Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
Multi-tenancy: workspaces, sign-up, invitations, usage budgets and Switch Cloud (#627)
Louis Amaudruzbad92802aa4e
diff --git a/.env.example b/.env.exampleindex 322406f60..af98b1932 100644--- a/.env.example+++ b/.env.example@@ -144,6 +144,11 @@ GATEWAY_ADMIN_PASSWORD=# docs/old/multi-tenancy-phase2-tenants.md, §4.# GATEWAY_TENANT_CHOICE_ENABLED=false+# Where a first-time IdP sign-in lands: `default_tenant` (the one pre-existing+# workspace), `invite_only` (no workspace until an invitation is accepted), or+# `open` (no workspace, and they may create their own, capped per person).+# GATEWAY_SIGNUP_MODE=default_tenant+# How many workspaces one person may own here. Creating a workspace is an# amplification vector rather than a row — every tenant adds a fan-out at boot# and to a sweep that runs every few seconds — so the route is bounded. Set it@@ -152,6 +157,19 @@ GATEWAY_ADMIN_PASSWORD=# exempt. See docs/old/multi-tenancy-phase2-tenants.md, §5.# GATEWAY_MAX_WORKSPACES_PER_USER=3+# Invitation e-mails. Set a host to send an invitation addressed to an e-mail+# through this SMTP relay; unset, the invitation is still created and the admin+# shares the link. Needs FRONTEND_BASE_URL (the link points there). TLS is+# `starttls` (587), `tls` (465) or `none` (a local relay only). Username and+# password go together or not at all.+# GATEWAY_SMTP_HOST=smtp.example.com+# GATEWAY_SMTP_PORT=587+# GATEWAY_SMTP_TLS=starttls+# GATEWAY_SMTP_USERNAME=+# GATEWAY_SMTP_PASSWORD=+# GATEWAY_SMTP_FROM=Switch <[email protected]>+# GATEWAY_INVITE_EMAILS_PER_DAY=50+# ── Frontend ─────────────────────────────────────────────────────────────────FRONTEND_BASE_URL=http://localhost:5173@@ -175,6 +193,21 @@ FRONTEND_BASE_URL=http://localhost:5173# SLACK_APP_CLIENT_SECRET=# SLACK_APP_SIGNING_SECRET=+# Credentials of the distributed Discord app — the one a customer adds to their+# server by clicking "Add to Server", not the self-registered app whose token an+# operator pastes in (DISCORD_SETUP.md). Set all four or none; setting some is+# refused at startup, and MESSAGING_PUBLIC_URL must be set with them. The bot+# token lives here, in deployment config, because a Discord install carries no+# per-install token. See docs/old/bridges/DISCORD_DISTRIBUTED_APP.md.+# DISCORD_APP_CLIENT_ID=+# DISCORD_APP_CLIENT_SECRET=+# DISCORD_APP_BOT_TOKEN=+# DISCORD_APP_APPLICATION_ID=+# Privileged intents on the shared connection, each off by default (mention-only+# / API member fetches) and requiring Discord verification past ~100 guilds.+# DISCORD_APP_MESSAGE_CONTENT=false+# DISCORD_APP_MEMBERS=false+# ── Mattermost (local dev) ───────────────────────────────────────────────────MATTERMOST_ADMIN_USER=adminMATTERMOST_ADMIN_PASSWORD=diff --git a/.github/workflows/pr-ci.yml b/.github/workflows/pr-ci.ymlindex 9df9d16ec..f28a8ed17 100644--- a/.github/workflows/pr-ci.yml+++ b/.github/workflows/pr-ci.yml@@ -267,6 +267,9 @@ jobs:- name: Build (tsc + vite)run: npm run build+ - name: Test (vitest)+ run: npm test+migration-heads-on-merge:name: Migration heads on merge# Only meaningful right after a new migration lands on main — a PR stilldiff --git a/.gitleaks.toml b/.gitleaks.tomlindex 3c56aee28..e9fec6c15 100644--- a/.gitleaks.toml+++ b/.gitleaks.toml@@ -44,6 +44,10 @@ regexes = [# Collaboration-adapter type registration; the mattermost-access-token# rule mistakes the identifier sequence for a token. No secret here.'''"mattermost", MattermostAdapter, MattermostConnectionConfig''',+ # A Discord client/application id is a *public* identifier, not a secret, and+ # these are obvious dummies in a config-validator test — but the default+ # `discord-client-id` rule flags any 17-19 digit number next to the keyword.+ '''discord_app_(?:client|application)_id="\d{17,19}"''',]paths = [# Log-redaction tests exercise deliberately fake vendor tokens. Both spellingsdiff --git a/CLAUDE.md b/CLAUDE.mdindex 5b56b6369..a74f1547f 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -169,8 +169,11 @@ Tests live in `core/tests/switch_core/` mirroring the module structure. Uses pyt`deploy/observability/`.- `docs/old/multi-tenancy.md` — why Switch is multi-tenant the way it is: thetenant model, sign-in and onboarding, one official messaging app per- platform, and the phased plan the work follows. Phases 0 and 1 are built;- read the code, not this, for what exists today.+ platform, and the phased plan the work follows. Phases 0 and 1 are built,+ and most of Phase 2; read the code, not this, for what exists today.+- `docs/old/multi-tenancy-phase2-tenants.md` — several workspaces per person:+ how a request picks its tenant, the tenant and invitation API, workspace+ roles, and how sign-up works (§9a)- `docs/old/multi-tenancy-phase1-db.md` — the Phase 1 database schema as built:tables, per-tenant uniqueness, and how a request's tenant is bound- `docs/old/rds-migration.md` — moving a deployment's Postgres to RDS: thediff --git a/NOTICE b/NOTICEindex 15d4239d0..d19a83c64 100644--- a/NOTICE+++ b/NOTICE@@ -258,3 +258,28 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.++--------------------------------------------------------------------------------++Agent Switch includes the following third-party data files, in+core/switch_core/gateway/email_domain_lists/.++freemail (https://github.com/willwhite/freemail), data/free.txt+Copyright (c) 2015, Will White++Permission to use, copy, modify, and/or distribute this software for any+purpose with or without fee is hereby granted, provided that the above+copyright notice and this permission notice appear in all copies.++THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF+OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.++disposable-email-domains+(https://github.com/disposable-email-domains/disposable-email-domains),+disposable_email_blocklist.conf+Dedicated to the public domain under CC0 1.0 Universal.diff --git a/console/AGENTS.md b/console/AGENTS.mdindex 4fc5dcc2f..416cae054 100644--- a/console/AGENTS.md+++ b/console/AGENTS.md@@ -128,6 +128,16 @@ pnpm run devpnpm run d```+Switch Cloud, the hosted deployment the first-run page and the Add server dialog+offer, has no URL in source. Point a run at one with `SWITCH_CLOUD_URL`, or bake+one into a build with `MAIN_VITE_SWITCH_CLOUD_URL` (inlined into the main+process by electron-vite). Either must be a bare https origin; with neither set+the Cloud choice reads "Coming soon".++```bash+SWITCH_CLOUD_URL=https://cloud.example.com pnpm run dev+```+Run main-process or renderer-only dev watches:```bashdiff --git a/console/agents/architecture/data-model.md b/console/agents/architecture/data-model.mdindex e071bffc5..2fd1788bc 100644--- a/console/agents/architecture/data-model.md+++ b/console/agents/architecture/data-model.md@@ -23,7 +23,8 @@ The schema is defined in `apps/switch-console-desktop/src/main/db/schema.ts`.| **session** | `conversation` | One instantiation/run of an agent. The unit shown under an agent in the sidebar. || **message** | `message` | A message in a session (was keyed by `conversationId`, now `sessionId`). || *(removed)* | `session` (worktree-era) | The upstream parallel-run grouping. Removed — Switch Console runs every session in the location's directory, so the grouping layer is gone. |-| *(removed)* | `workspace` | The upstream execution-location abstraction (worktree / SSH / BYOI remote). Removed — see below. |+| *(removed)* | `workspace` | The upstream execution-location abstraction (worktree / SSH / BYOI remote). Removed — see below. Switch Console has a `workspaces` table again, but it names something unrelated: a tenant on a Switch server. |+| **workspace** | *(none)* — new | A tenant on a Switch server, and what the window is scoped to. An agent belongs to one; every gateway call is made in its name. The table is `workspaces`. |### Tables with no upstream equivalent@@ -32,6 +33,7 @@ These carry the Switch- and remote-specific state that upstream had no concept o| Table | What it is ||---|---|| `switch_servers` | A Switch server Switch Console talks to, managed or external. |+| `workspaces` | A tenant on one of those servers. Registering a server creates its first, tenant-less and named after the server. Agents reference it, and the active selection (`kv`, `activeWorkspaceId`) names one. || `remote_hosts` | An SSH host (keyed by its `~/.ssh/config` alias) that can run agents. || `remote_host_reachability` | The last observed reachability of a host. Separate from the host record so a probe result never masquerades as configuration — see the reachability note below. || `remote_host_setup_plans` | A host's onboarding plan (CHOO-1809). See "Remote host setup". |@@ -52,6 +54,11 @@ location (a working directory, local or on an SSH host)A location that lives on an SSH host references a `remote_hosts` row; that host carriesits own reachability and setup-plan rows alongside, not inside, the location hierarchy.+An agent also references the workspace it belongs to, which is not part of this+hierarchy: a location is where an agent runs, a workspace is who it runs as. One+directory can hold agents belonging to different workspaces, and a workspace's+agents can be spread across directories and hosts.+A session's room connection is a row keyed by `session_id` with`ON DELETE CASCADE`, so it cannot outlive the session (or the agent above it).It was previously a JSON blob in `app_settings`, which referenced nothing and so@@ -60,12 +67,14 @@ agents whose Switch server had been destroyed.## What we deliberately dropped from upstream, and why-- **The `workspaces` table and the workspace abstraction.** Upstream modelled+- **The upstream workspace abstraction.** (Not to be confused with Switch+ Console's own `workspaces` table above, which reuses the name for a tenant on+ a Switch server and has nothing to do with this.) Upstream modelled*where* a session runs (git worktree, project-SSH, BYOI remote). Switch Console hadalready gutted this before the rework — `workspace-config` reached v3 with thenote *"Switch Console has no git worktrees, branches, PRs, or BYOI: every sessionruns in the project root directory."* A workspace was therefore just "the- project directory" plus lifecycle scripts. We dropped the table (and+ project directory" plus lifecycle scripts. We dropped it (and`project.repositoryWorkspaceId` / `session.workspaceId`) and keep lifecyclescripts / fs access as a service hung off the location's directory.diff --git a/console/apps/switch-console-desktop/drizzle/0051_workspaces.sql b/console/apps/switch-console-desktop/drizzle/0051_workspaces.sqlnew file mode 100644index 000000000..9ecb019bf--- /dev/null+++ b/console/apps/switch-console-desktop/drizzle/0051_workspaces.sql@@ -0,0 +1,71 @@+-- Workspaces: what the window is scoped to, one level below a server.+--+-- Each existing server gets exactly one workspace, and that workspace REUSES+-- THE SERVER'S ID. That is what makes the upgrade invisible: every server id+-- already persisted elsewhere — agents.server_id, the active-server kv value,+-- and the opaque navigation snapshots under `view-state:` — stays valid when+-- read as a workspace id, so nothing has to be rewritten or reconciled. New+-- workspaces discovered from a gateway get fresh ids.+--+-- tenant_id stays NULL for these rows: no gateway has been asked yet, and the+-- upgrade must not depend on one being reachable. The first reconcile matches+-- each row to a tenant, keeping the id so the agents pointing at it still do.+CREATE TABLE `workspaces` (+ `id` text PRIMARY KEY NOT NULL,+ `server_id` text NOT NULL,+ `name` text NOT NULL,+ `tenant_id` text,+ `slug` text,+ `role` text,+ `created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,+ `updated_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,+ FOREIGN KEY (`server_id`) REFERENCES `switch_servers`(`id`) ON UPDATE no action ON DELETE cascade+);+--> statement-breakpoint+CREATE INDEX `idx_workspaces_server_id` ON `workspaces` (`server_id`);--> statement-breakpoint+CREATE UNIQUE INDEX `idx_workspaces_server_tenant` ON `workspaces` (`server_id`,`tenant_id`);--> statement-breakpoint+CREATE UNIQUE INDEX `idx_workspaces_server_placeholder` ON `workspaces` (`server_id`) WHERE `tenant_id` IS NULL;--> statement-breakpoint+INSERT INTO `workspaces` (`id`, `server_id`, `name`, `tenant_id`, `slug`, `role`)+ SELECT `id`, `id`, `name`, NULL, NULL, NULL FROM `switch_servers`;+--> statement-breakpoint+-- Re-point agents at workspaces via the SQLite table-recreation dance rather+-- than DROP COLUMN: `server_id` carries a foreign key, and SQLite refuses to+-- drop a column named in one. Runs with foreign_keys=OFF inside the migration+-- transaction, so dropping and renaming does not disturb the sessions FK, which+-- tracks the table name. The workspace id equals the old server id, so the+-- carry-over is a straight copy — except that `server_id` was added by+-- ALTER TABLE ADD COLUMN, which in SQLite cannot carry an ON DELETE clause, so+-- its set-null was never enforced by the engine and a row may point at a server+-- that is gone. Copying such a value would seed the new, real foreign key with a+-- violation that foreign_keys=OFF lets straight through, so it is dropped to+-- NULL here — the same "unlinked" state the app already handles.+CREATE TABLE `__new_agents` (+ `id` text PRIMARY KEY NOT NULL,+ `location_id` text NOT NULL,+ `name` text NOT NULL,+ `provider_id` text NOT NULL,+ `switch_agent_id` text,+ `api_endpoint` text,+ `workspace_id` text,+ `status` text,+ `auto_approve` integer DEFAULT false NOT NULL,+ `owner_name` text,+ `provider_config` text,+ `created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,+ `updated_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,+ FOREIGN KEY (`location_id`) REFERENCES `locations`(`id`) ON UPDATE no action ON DELETE no action,+ FOREIGN KEY (`workspace_id`) REFERENCES `workspaces`(`id`) ON UPDATE no action ON DELETE set null+);--> statement-breakpoint+INSERT INTO `__new_agents` (`id`, `location_id`, `name`, `provider_id`, `switch_agent_id`, `api_endpoint`, `workspace_id`, `status`, `auto_approve`, `owner_name`, `provider_config`, `created_at`, `updated_at`)+ SELECT `id`, `location_id`, `name`, `provider_id`, `switch_agent_id`, `api_endpoint`,+ CASE WHEN `server_id` IN (SELECT `id` FROM `workspaces`) THEN `server_id` END,+ `status`, `auto_approve`, `owner_name`, `provider_config`, `created_at`, `updated_at` FROM `agents`;+--> statement-breakpoint+DROP TABLE `agents`;--> statement-breakpoint+ALTER TABLE `__new_agents` RENAME TO `agents`;--> statement-breakpoint+CREATE INDEX `idx_agents_location_id` ON `agents` (`location_id`);--> statement-breakpoint+CREATE INDEX `idx_agents_workspace_id` ON `agents` (`workspace_id`);--> statement-breakpoint+INSERT INTO `kv` (`key`, `value`)+ SELECT 'activeWorkspaceId', `value` FROM `kv` WHERE `key` = 'activeSwitchServerId';+--> statement-breakpoint+DELETE FROM `kv` WHERE `key` = 'activeSwitchServerId';diff --git a/console/apps/switch-console-desktop/drizzle/meta/0051_snapshot.json b/console/apps/switch-console-desktop/drizzle/meta/0051_snapshot.jsonnew file mode 100644index 000000000..5f301abe2--- /dev/null+++ b/console/apps/switch-console-desktop/drizzle/meta/0051_snapshot.json@@ -0,0 +1,978 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "a44f0db7-1021-46dc-90e6-810d28551f3a",+ "prevId": "9bf29a0b-5aea-41b1-8394-0475326b97f7",+ "tables": {+ "agents": {+ "name": "agents",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "location_id": {+ "name": "location_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider_id": {+ "name": "provider_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "switch_agent_id": {+ "name": "switch_agent_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "api_endpoint": {+ "name": "api_endpoint",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "auto_approve": {+ "name": "auto_approve",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "owner_name": {+ "name": "owner_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "provider_config": {+ "name": "provider_config",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "idx_agents_location_id": {+ "name": "idx_agents_location_id",+ "columns": ["location_id"],+ "isUnique": false+ },+ "idx_agents_workspace_id": {+ "name": "idx_agents_workspace_id",+ "columns": ["workspace_id"],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "agents_location_id_locations_id_fk": {+ "name": "agents_location_id_locations_id_fk",+ "tableFrom": "agents",+ "tableTo": "locations",+ "columnsFrom": ["location_id"],+ "columnsTo": ["id"],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "agents_workspace_id_workspaces_id_fk": {+ "name": "agents_workspace_id_workspaces_id_fk",+ "tableFrom": "agents",+ "tableTo": "workspaces",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "app_secrets": {+ "name": "app_secrets",+ "columns": {+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "secret": {+ "name": "secret",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_app_secrets_key": {+ "name": "idx_app_secrets_key",+ "columns": ["key"],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "app_settings": {+ "name": "app_settings",+ "columns": {+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "idx_app_settings_key": {+ "name": "idx_app_settings_key",+ "columns": ["key"],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "kv": {+ "name": "kv",+ "columns": {+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "idx_kv_key": {+ "name": "idx_kv_key",+ "columns": ["key"],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "location_settings": {+ "name": "location_settings",+ "columns": {+ "location_id": {+ "name": "location_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "base_settings_json": {+ "name": "base_settings_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "shareable_settings_json": {+ "name": "shareable_settings_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "legacy_config_migrated_at": {+ "name": "legacy_config_migrated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "location_settings_location_id_locations_id_fk": {+ "name": "location_settings_location_id_locations_id_fk",+ "tableFrom": "location_settings",+ "tableTo": "locations",+ "columnsFrom": ["location_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "locations": {+ "name": "locations",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ssh_host": {+ "name": "ssh_host",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "dir": {+ "name": "dir",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "idx_locations_host_dir": {+ "name": "idx_locations_host_dir",+ "columns": ["ssh_host", "dir"],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "messages": {+ "name": "messages",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "sender": {+ "name": "sender",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "timestamp": {+ "name": "timestamp",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_messages_session_id": {+ "name": "idx_messages_session_id",+ "columns": ["session_id"],+ "isUnique": false+ },+ "idx_messages_timestamp": {+ "name": "idx_messages_timestamp",+ "columns": ["timestamp"],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "messages_session_id_sessions_id_fk": {+ "name": "messages_session_id_sessions_id_fk",+ "tableFrom": "messages",+ "tableTo": "sessions",+ "columnsFrom": ["session_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "remote_host_reachability": {+ "name": "remote_host_reachability",+ "columns": {+ "ssh_host": {+ "name": "ssh_host",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'unknown'"+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_checked_at": {+ "name": "last_checked_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_reachable_at": {+ "name": "last_reachable_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "consecutive_failures": {+ "name": "consecutive_failures",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "remote_host_setup_plans": {+ "name": "remote_host_setup_plans",+ "columns": {+ "ssh_host": {+ "name": "ssh_host",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'idle'"+ },+ "steps": {+ "name": "steps",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "current_step_id": {+ "name": "current_step_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "remote_hosts": {+ "name": "remote_hosts",+ "columns": {+ "ssh_host": {+ "name": "ssh_host",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "session_room_connections": {+ "name": "session_room_connections",+ "columns": {+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "room_id": {+ "name": "room_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "room_name": {+ "name": "room_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "switch_agent_id": {+ "name": "switch_agent_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "session_room_connections_session_id_sessions_id_fk": {+ "name": "session_room_connections_session_id_sessions_id_fk",+ "tableFrom": "session_room_connections",+ "tableTo": "sessions",+ "columnsFrom": ["session_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "sessions": {+ "name": "sessions",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "agent_id": {+ "name": "agent_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "config": {+ "name": "config",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "agent_status": {+ "name": "agent_status",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "agent_status_seen": {+ "name": "agent_status_seen",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": 1+ },+ "is_initial_session": {+ "name": "is_initial_session",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "is_pinned": {+ "name": "is_pinned",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "archived_at": {+ "name": "archived_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_interacted_at": {+ "name": "last_interacted_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "status_changed_at": {+ "name": "status_changed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "idx_sessions_agent_id": {+ "name": "idx_sessions_agent_id",+ "columns": ["agent_id"],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "sessions_agent_id_agents_id_fk": {+ "name": "sessions_agent_id_agents_id_fk",+ "tableFrom": "sessions",+ "tableTo": "agents",+ "columnsFrom": ["agent_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "switch_servers": {+ "name": "switch_servers",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "gateway_url": {+ "name": "gateway_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "api_url": {+ "name": "api_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "managed": {+ "name": "managed",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "management_kind": {+ "name": "management_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "ssh_host": {+ "name": "ssh_host",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "idx_switch_servers_gateway_url": {+ "name": "idx_switch_servers_gateway_url",+ "columns": ["gateway_url"],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "workspaces": {+ "name": "workspaces",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "server_id": {+ "name": "server_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "tenant_id": {+ "name": "tenant_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "idx_workspaces_server_id": {+ "name": "idx_workspaces_server_id",+ "columns": ["server_id"],+ "isUnique": false+ },+ "idx_workspaces_server_tenant": {+ "name": "idx_workspaces_server_tenant",+ "columns": ["server_id", "tenant_id"],+ "isUnique": true+ },+ "idx_workspaces_server_placeholder": {+ "name": "idx_workspaces_server_placeholder",+ "columns": ["server_id"],+ "isUnique": true,+ "where": "`tenant_id` IS NULL"+ }+ },+ "foreignKeys": {+ "workspaces_server_id_switch_servers_id_fk": {+ "name": "workspaces_server_id_switch_servers_id_fk",+ "tableFrom": "workspaces",+ "tableTo": "switch_servers",+ "columnsFrom": ["server_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ }+ },+ "views": {},+ "enums": {},+ "_meta": {+ "schemas": {},+ "tables": {},+ "columns": {}+ },+ "internal": {+ "indexes": {}+ }+}diff --git a/console/apps/switch-console-desktop/drizzle/meta/_journal.json b/console/apps/switch-console-desktop/drizzle/meta/_journal.jsonindex dd2dfb96e..cb8a8591c 100644--- a/console/apps/switch-console-desktop/drizzle/meta/_journal.json+++ b/console/apps/switch-console-desktop/drizzle/meta/_journal.json@@ -358,6 +358,13 @@"when": 1790248865722,"tag": "0050_drop_session_shell_id","breakpoints": true+ },+ {+ "idx": 51,+ "version": "6",+ "when": 1790300000000,+ "tag": "0051_workspaces",+ "breakpoints": true}]}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.tsindex 444714b29..d7101562f 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.ts@@ -28,7 +28,7 @@ function fakeFs(seed: Record<string, string> = {}): PluginFs {const h = vi.hoisted(() => {const writeDefinition = vi.fn(async () => {});// A faithful-enough stand-in for a repo-agents provider: the config sync- // renders the definition and writes it through the workspace fs, so the mock+ // renders the definition and writes it through the workdir fs, so the mock// has to answer where it goes and what it looks like.const repoAgents = {writeDefinition,@@ -40,11 +40,11 @@ const h = vi.hoisted(() => {readDefinition: async () => null,};const state: {- workspace: PluginFs | null;+ workdir: PluginFs | null;repoAgents: object | null;nameTaken: boolean;} = {- workspace: null,+ workdir: null,repoAgents,nameTaken: false,};@@ -67,14 +67,17 @@ vi.mock('@main/core/providers/plugin-registry', () => ({}));vi.mock('./register-agent-identity', () => ({ registerAgentIdentity: h.registerAgentIdentity }));vi.mock('./createAgent', () => ({ createAgent: h.createAgent }));-vi.mock('./agent-workspace-fs', () => ({- resolveWorkspaceFsFor: vi.fn(async () => ({- fs: h.state.workspace as PluginFs,+vi.mock('./agent-workdir-fs', () => ({+ resolveWorkdirFsFor: vi.fn(async () => ({+ fs: h.state.workdir as PluginFs,close: vi.fn(),})),}));vi.mock('@main/core/switch-servers/servers-store', () => ({- getServer: vi.fn(async () => ({ id: 'srv-1', apiUrl: 'https://switch.example.com' })),+ getServer: vi.fn(async () => mockServer),+}));+vi.mock('@main/core/workspaces/workspace-session', () => ({+ withWorkspaceSession: (_workspaceId: string, fn: (server: unknown) => unknown) => fn(mockServer),}));vi.mock('@main/core/locations/store', () => ({ensureLocation: vi.fn(async () => ({ id: 'loc-1' })),@@ -104,6 +107,11 @@ vi.mock('@main/db/client', () => ({}));vi.mock('@main/db/schema', () => ({ agents: { id: 'id', switchAgentId: 'switchAgentId' } }));vi.mock('drizzle-orm', () => ({ eq: vi.fn() }));+vi.mock('@main/core/workspaces/workspaces-store', () => ({+ requireWorkspaceForServer: vi.fn(async (serverId: string) => ({ id: `ws-${serverId}` })),+}));++const mockServer = vi.hoisted(() => ({ id: 'srv-1', apiUrl: 'https://switch.example.com' }));const { addAgent } = await import('./add-agent');const { trackEvent } = await import('@main/core/telemetry/telemetry-service');@@ -138,7 +146,7 @@ describe('addAgent', () => {vi.clearAllMocks();h.state.nameTaken = false;h.state.repoAgents = h.repoAgents;- h.state.workspace = fakeFs();+ h.state.workdir = fakeFs();h.registerAgentIdentity.mockResolvedValue({ kind: 'created', id: 'sw-1', apiKey: 'tok-123' });// `clearAllMocks` resets call records but not implementations: without a// default, whichever test last set one decides the answer for the rest.@@ -184,7 +192,7 @@ describe('addAgent', () => {// unconditional it got no credentials on disk at all, so its sessions// authenticated to Switch as whatever was in settings.local.json.h.state.repoAgents = null;- const fs = h.state.workspace as PluginFs;+ const fs = h.state.workdir as PluginFs;const result = await addAgent(params());@@ -198,7 +206,7 @@ describe('addAgent', () => {});it('writes credentials and a config file, and no provider definition', async () => {- const fs = h.state.workspace as PluginFs;+ const fs = h.state.workdir as PluginFs;await addAgent(params({ providerId: 'claude', name: 'cc-hoot' }));@@ -210,7 +218,7 @@ describe('addAgent', () => {});it('records the agent’s instructions in its committed config file', async () => {- const fs = h.state.workspace as PluginFs;+ const fs = h.state.workdir as PluginFs;await addAgent(params({ providerId: 'claude', name: 'cc-hoot', instructions: 'Be careful.' }));@@ -221,7 +229,7 @@ describe('addAgent', () => {it('starts from what it was created with, whatever an earlier agent left behind', async () => {// A leftover definition under the same name used to be taken as a hand// edit, replacing everything typed into the form.- const fs = h.state.workspace as PluginFs;+ const fs = h.state.workdir as PluginFs;await fs.write('.claude/agents/cc-hoot.md','---\nname: cc-hoot\ndescription: Old\n---\n\nOld instructions.\n'@@ -235,7 +243,7 @@ describe('addAgent', () => {});it('git-ignores the credentials directory so the token never enters VCS', async () => {- const fs = h.state.workspace as PluginFs;+ const fs = h.state.workdir as PluginFs;await addAgent(params());expect(await fs.read('.switch/agents/.gitignore')).toBe('*\n');});@@ -254,9 +262,9 @@ describe('addAgent', () => {);});- it('writes nothing to the workspace when registration fails', async () => {+ it('writes nothing to the workdir when registration fails', async () => {h.registerAgentIdentity.mockResolvedValue({ kind: 'name-conflict' } as never);- const fs = h.state.workspace as PluginFs;+ const fs = h.state.workdir as PluginFs;expect((await addAgent(params())).kind).toBe('name-conflict');expect(await fs.read(agentSettingsRelativePath('codex-hoot'))).toBeNull();@@ -275,7 +283,7 @@ describe('addAgent', () => {SWITCH_AGENT_ID: 'their-agent',},});- h.state.workspace = fakeFs({ [agentSettingsRelativePath('codex-hoot')]: theirs });+ h.state.workdir = fakeFs({ [agentSettingsRelativePath('codex-hoot')]: theirs });const result = await addAgent(params());@@ -285,9 +293,9 @@ describe('addAgent', () => {});expect(h.registerAgentIdentity).not.toHaveBeenCalled();expect(h.createAgent).not.toHaveBeenCalled();- expect(- await (h.state.workspace as PluginFs).read(agentSettingsRelativePath('codex-hoot'))- ).toBe(theirs);+ expect(await (h.state.workdir as PluginFs).read(agentSettingsRelativePath('codex-hoot'))).toBe(+ theirs+ );});it('refuses when same-server credentials exist but the agent is unknown to this install (CHOO-2560)', async () => {@@ -302,7 +310,7 @@ describe('addAgent', () => {SWITCH_AGENT_ID: 'colleague-agent',},});- h.state.workspace = fakeFs({ [agentSettingsRelativePath('codex-hoot')]: colleague });+ h.state.workdir = fakeFs({ [agentSettingsRelativePath('codex-hoot')]: colleague });const result = await addAgent(params());@@ -310,9 +318,9 @@ describe('addAgent', () => {expect(h.registerAgentIdentity).not.toHaveBeenCalled();expect(h.createAgent).not.toHaveBeenCalled();// The colleague's file is intact.- expect(- await (h.state.workspace as PluginFs).read(agentSettingsRelativePath('codex-hoot'))- ).toBe(colleague);+ expect(await (h.state.workdir as PluginFs).read(agentSettingsRelativePath('codex-hoot'))).toBe(+ colleague+ );});it('refuses a name already taken in the location, without minting an identity', async () => {diff --git a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.ts b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.tsindex 9373e7865..7f0a7f09a 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.ts@@ -11,6 +11,8 @@ import { agentTypeOf } from '@main/core/telemetry/agent-type';import type { TelemetryAgentCreateFailure } from '@main/core/telemetry/events';import { entryPointOf } from '@main/core/telemetry/narrow';import { trackEvent } from '@main/core/telemetry/telemetry-service';+import { withWorkspaceSession } from '@main/core/workspaces/workspace-session';+import { requireWorkspaceForServer } from '@main/core/workspaces/workspaces-store';import { db } from '@main/db/client';import { agents as agentsTable } from '@main/db/schema';import { agentAvatarUrlForName } from '@shared/core/agents/agent-avatar';@@ -30,7 +32,7 @@ import type { AgentTemplateOrigin } from './agent-config-file';import { foreignCredentialsOwner, sameEndpointAgentId } from './agent-credentials-slot';import { agentEvents } from './agent-events';import { agentNameTaken } from './agent-name-taken';-import { resolveWorkspaceFsFor } from './agent-workspace-fs';+import { resolveWorkdirFsFor } from './agent-workdir-fs';import { createAgent } from './createAgent';import { acknowledgeDefinition } from './import-agent-config';import { knownAgentTypeForProvider } from './known-agent-type';@@ -189,6 +191,7 @@ async function runAddAgent(params: AddAgentParams): Promise<AddAgentResult> {message: `No Switch server with id ${params.serverId}`,});}+ const targetWorkspace = await requireWorkspaceForServer(params.serverId);// Before minting an identity: the gateway's uniqueness check is scoped to the// Switch server, so it cannot see a name already taken in this directory. Two@@ -254,23 +257,25 @@ async function runAddAgent(params: AddAgentParams): Promise<AddAgentResult> {}}- const registered = await registerAgentIdentity(server, {- name: params.name,- description: params.description,- displayName: params.displayName,- repoDir: params.dir,- agentType: knownAgentTypeForProvider(params.providerId),- iconUrl: params.iconUrl ?? agentAvatarUrlForName(params.name),- });+ const registered = await withWorkspaceSession(targetWorkspace.id, (target) =>+ registerAgentIdentity(target, {+ name: params.name,+ description: params.description,+ displayName: params.displayName,+ repoDir: params.dir,+ agentType: knownAgentTypeForProvider(params.providerId),+ iconUrl: params.iconUrl ?? agentAvatarUrlForName(params.name),+ })+ );if (registered.kind !== 'created') return reportFailedCreate(params, registered);- const workspace = await resolveWorkspaceFsFor(params.sshHost, params.dir);+ const workdir = await resolveWorkdirFsFor(params.sshHost, params.dir);try {// Writing the per-agent Switch credentials is unconditional core behavior for// every provider, keyed by the agent's `name` — the single key-space every// reader (launch path, auto-session watcher, notification poller) uses// (CHOO-1440).- await writeNeutralAgentSettingsFs(workspace.fs, {+ await writeNeutralAgentSettingsFs(workdir.fs, {slug: params.name,apiEndpoint: server.apiUrl,apiToken: registered.apiKey,@@ -282,10 +287,10 @@ async function runAddAgent(params: AddAgentParams): Promise<AddAgentResult> {// name left behind is recorded as accounted for, so nothing takes it for an// edit to this one.await writeAgentConfigFile(- workspace.fs,+ workdir.fs,params.name,await acknowledgeDefinition({- workspaceFs: workspace.fs,+ workdirFs: workdir.fs,repoAgents: getPlugin(params.providerId).behavior.repoAgents ?? null,name: params.name,config: {@@ -297,7 +302,7 @@ async function runAddAgent(params: AddAgentParams): Promise<AddAgentResult> {}));} finally {- workspace.close();+ workdir.close();}const location = await ensureLocation({@@ -313,7 +318,7 @@ async function runAddAgent(params: AddAgentParams): Promise<AddAgentResult> {providerId: params.providerId,switchAgentId: registered.id,apiEndpoint: server.apiUrl,- serverId: params.serverId,+ workspaceId: targetWorkspace.id,autoApprove: params.autoApprove,providerConfig: params.providerConfig ?? null,});diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-config-file.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-config-file.tsindex 5d2b636ae..0eb0ab237 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-config-file.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-config-file.ts@@ -64,14 +64,28 @@ export type AgentTemplateOrigin = {name: string;source: 'bundled' | 'server';serverId?: string;+ /**+ * The workspace the template was read from.+ *+ * A template registry belongs to a workspace, not to the server hosting it,+ * so the server alone does not say where to look again once an account holds+ * several on one. Absent on an origin written before this was recorded.+ */+ workspaceId?: string;};function parseTemplateOrigin(value: unknown): AgentTemplateOrigin | undefined {if (!isPlainObject(value)) return undefined;- const { id, name, source, serverId } = value;+ const { id, name, source, serverId, workspaceId } = value;if (typeof id !== 'string' || typeof name !== 'string') return undefined;if (source !== 'bundled' && source !== 'server') return undefined;- return { id, name, source, ...(typeof serverId === 'string' ? { serverId } : {}) };+ return {+ id,+ name,+ source,+ ...(typeof serverId === 'string' ? { serverId } : {}),+ ...(typeof workspaceId === 'string' ? { workspaceId } : {}),+ };}/**diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-config.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-config.test.tsindex f0e5a9694..74828e579 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-config.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-config.test.ts@@ -43,8 +43,8 @@ vi.mock('./getAgentById', () => ({vi.mock('./agent-location', () => ({getAgentLocation: async () => ({ id: 'loc-1', dir: '/repo', sshHost: 'vm-1' }),}));-vi.mock('./agent-workspace-fs', () => ({- resolveWorkspaceFsFor: async () => ({ fs: fakeFs(), close: () => {} }),+vi.mock('./agent-workdir-fs', () => ({+ resolveWorkdirFsFor: async () => ({ fs: fakeFs(), close: () => {} }),}));vi.mock('./setAgentProviderConfig', () => ({setAgentProviderConfig: (params: unknown) => setAgentProviderConfig(params),diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-config.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-config.tsindex eef9dfdb1..4c8cbfe1d 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-config.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-config.ts@@ -3,7 +3,7 @@ import { getPlugin } from '@main/core/providers/plugin-registry';import { providerConfigFromAttributes } from '@shared/core/agents/agent-provider-config';import type { AgentConfigFile } from './agent-config-file';import { writeAgentConfigFile, type AgentTemplateOrigin } from './agent-config-file';-import { readRequiredAgentConfig, withAgentWorkspace } from './agent-launch-config';+import { readRequiredAgentConfig, withAgentWorkdir } from './agent-launch-config';import { getAgentById } from './getAgentById';import { ensureRemoteWatcher } from './remote-watcher';import { setAgentProviderConfig } from './setAgentProviderConfig';@@ -19,7 +19,7 @@ import { setAgentProviderConfig } from './setAgentProviderConfig';*/export async function readAgentConfig(agentId: string): Promise<AgentConfigFile> {- return withAgentWorkspace(agentId, (agent, fs) => readRequiredAgentConfig(agent, fs));+ return withAgentWorkdir(agentId, (agent, fs) => readRequiredAgentConfig(agent, fs));}/** The template the agent was created from, or null for an agent created without one. */@@ -61,12 +61,12 @@ export async function setAgentSettings(params: {}));}-/** Read, change, write — in one workspace session. */+/** Read, change, write — in one workdir session. */async function updateAgentConfig(agentId: string,change: (config: AgentConfigFile) => AgentConfigFile): Promise<AgentConfigFile> {- const config = await withAgentWorkspace(agentId, async (agent, fs) => {+ const config = await withAgentWorkdir(agentId, async (agent, fs) => {const next = change(await readRequiredAgentConfig(agent, fs));await writeAgentConfigFile(fs, agent.name, next);return next;diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-credentials-slot.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-credentials-slot.tsindex 81bafcd68..1fcf30ba1 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-credentials-slot.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-credentials-slot.ts@@ -1,4 +1,4 @@-import { resolveWorkspaceFsFor } from './agent-workspace-fs';+import { resolveWorkdirFsFor } from './agent-workdir-fs';import { agentSettingsRelativePath } from './switch-settings-paths';import { existingAgentIdInSlot, foreignCredentialsOwnerFs } from './write-switch-settings';@@ -22,11 +22,11 @@ export async function foreignCredentialsOwner(slug: string,apiEndpoint: string): Promise<string | null> {- const workspace = await resolveWorkspaceFsFor(sshHost, dir);+ const workdir = await resolveWorkdirFsFor(sshHost, dir);try {- return await foreignCredentialsOwnerFs(workspace.fs, slug, apiEndpoint);+ return await foreignCredentialsOwnerFs(workdir.fs, slug, apiEndpoint);} finally {- workspace.close();+ workdir.close();}}@@ -46,11 +46,11 @@ export async function sameEndpointAgentId(slug: string,apiEndpoint: string): Promise<string | null> {- const workspace = await resolveWorkspaceFsFor(sshHost, dir);+ const workdir = await resolveWorkdirFsFor(sshHost, dir);try {- const existingRaw = await workspace.fs.read(agentSettingsRelativePath(slug));+ const existingRaw = await workdir.fs.read(agentSettingsRelativePath(slug));return existingAgentIdInSlot(existingRaw, apiEndpoint);} finally {- workspace.close();+ workdir.close();}}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-launch-config.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-launch-config.tsindex e079ebc82..068b016ac 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-launch-config.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-launch-config.ts@@ -13,7 +13,7 @@ import {isAgentUnmigrated,markAgentMigrated,} from './agent-storage-migration-ready';-import { resolveWorkspaceFsFor } from './agent-workspace-fs';+import { resolveWorkdirFsFor } from './agent-workdir-fs';import { getAgentById } from './getAgentById';import { importAgentConfig } from './import-agent-config';import { agentConfigRelativePath } from './switch-settings-paths';@@ -56,7 +56,7 @@ export async function readRequiredAgentConfig(await agentStorageMigrationReady();if (isAgentUnmigrated(agent.id)) {await importAgentConfig({- workspaceFs: fs,+ workdirFs: fs,repoAgents: getPlugin(agent.providerId).behavior.repoAgents ?? null,name: agent.name,providerConfig: agent.providerConfig,@@ -82,7 +82,7 @@ export type AgentLaunchConfig = {};export async function agentLaunchConfig(agentId: string): Promise<AgentLaunchConfig> {- return withAgentWorkspace(agentId, async (agent, fs) => {+ return withAgentWorkdir(agentId, async (agent, fs) => {const config = await readRequiredAgentConfig(agent, fs);const repoAgents = getPlugin(agent.providerId).behavior.repoAgents;return {@@ -126,7 +126,7 @@ function launchSpecialization(config: AgentConfigFile): SwitchLaunchSpecializati}/** Run `run` against the agent's working directory, local or over SFTP. */-export async function withAgentWorkspace<T>(+export async function withAgentWorkdir<T>(agentId: string,run: (agent: Agent, fs: PluginFs) => Promise<T>): Promise<T> {@@ -134,10 +134,10 @@ export async function withAgentWorkspace<T>(if (!agent) throw new Error(`No agent with id ${agentId}`);const location = await getAgentLocation(agent);- const workspace = await resolveWorkspaceFsFor(location.sshHost, location.dir);+ const workdir = await resolveWorkdirFsFor(location.sshHost, location.dir);try {- return await run(agent, workspace.fs);+ return await run(agent, workdir.fs);} finally {- workspace.close();+ workdir.close();}}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-storage-migration-marker.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-storage-migration-marker.tsindex 1a3b83e03..2e6a40a12 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-storage-migration-marker.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-storage-migration-marker.ts@@ -6,7 +6,7 @@ import { kv } from '@main/db/schema';* Persisted marker recording which generation of the CHOO-1440 agent-storage* migration has completed a full, error-free pass. Once current,* {@link migrateAgentStorage} short-circuits at boot instead of re-opening every- * agent's workspace filesystem (an SSH/SFTP round trip per remote agent, and a+ * agent's workdir filesystem (an SSH/SFTP round trip per remote agent, and a* 20s connect timeout per unreachable host) on every launch.*/const MARKER_KEY = 'agentStorageMigrationComplete';diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-workspace-fs.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-workdir-fs.tssimilarity index 90%rename from console/apps/switch-console-desktop/src/main/core/agents/agent-workspace-fs.tsrename to console/apps/switch-console-desktop/src/main/core/agents/agent-workdir-fs.tsindex 0697b8af9..a0c9e2002 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-workspace-fs.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-workdir-fs.ts@@ -12,7 +12,7 @@ import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';* Callers MUST invoke `close()` in a `finally` — a leaked SFTP channel* eventually exhausts the host's MaxSessions.*/-export type WorkspaceFs = {+export type WorkdirFs = {/** FS rooted at the working dir — local disk or the remote repo dir. */fs: PluginFs;/** FS for user-scoped (`~/.claude`) definitions; empty for remote agents. */@@ -34,15 +34,12 @@ const EMPTY_PLUGIN_FS: PluginFs = {};/**- * Open a {@link WorkspaceFs} for a working directory identified by run location+ * Open a {@link WorkdirFs} for a working directory identified by run location* (ssh host + dir) rather than an existing agent row — used at create/onboard* time before a row exists. Local dirs resolve on disk; remote dirs open an* SFTP channel to the host.*/-export async function resolveWorkspaceFsFor(- sshHost: string | null,- dir: string-): Promise<WorkspaceFs> {+export async function resolveWorkdirFsFor(sshHost: string | null, dir: string): Promise<WorkdirFs> {if (sshHost === null) {return { fs: createPluginFs(dir), homeFs: createPluginFs(homedir()), close: () => {} };}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/assignAgentServer.ts b/console/apps/switch-console-desktop/src/main/core/agents/assignAgentServer.tsindex d070f69de..cd7b884cc 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/assignAgentServer.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/assignAgentServer.ts@@ -1,5 +1,6 @@import { agentExistsOnServer, GatewayError } from '@main/core/switch-servers/gateway-client';-import { getServer } from '@main/core/switch-servers/servers-store';+import { withWorkspaceSession } from '@main/core/workspaces/workspace-session';+import { requireWorkspaceForServer } from '@main/core/workspaces/workspaces-store';import type { AgentVerifyResult } from '@shared/core/switch-servers/switch-servers';import { getAgentById } from './getAgentById';import { updateAgent } from './updateAgent';@@ -22,14 +23,19 @@ export async function assignAgentServer(params: {if (!agent.switchAgentId) {throw new Error(`Agent ${params.agentId} has no Switch agent id to verify`);}- const server = await getServer(params.serverId);- if (!server) {- throw new Error(`No Switch server with id ${params.serverId}`);- }+ // Resolved before the call, not after it: the workspace the agent would be+ // written into is the one the question has to be asked of, or a `found` here+ // means found somewhere else.+ const workspace = await requireWorkspaceForServer(params.serverId);+ const switchAgentId = agent.switchAgentId;let result: AgentVerifyResult;try {- result = (await agentExistsOnServer(server, agent.switchAgentId)) ? 'found' : 'not-found';+ result = (await withWorkspaceSession(workspace.id, (server) =>+ agentExistsOnServer(server, switchAgentId)+ ))+ ? 'found'+ : 'not-found';} catch (cause) {if (cause instanceof GatewayError && cause.kind === 'unauthorized') {return 'unauthenticated';@@ -38,7 +44,7 @@ export async function assignAgentServer(params: {}if (result === 'found') {- await updateAgent({ agentId: params.agentId, serverId: params.serverId });+ await updateAgent({ agentId: params.agentId, workspaceId: workspace.id });}return result;}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.test.tsindex bc7b30808..ff79b8655 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.test.ts@@ -14,12 +14,12 @@ function readOnlyFs(seed: Record<string, string>): PluginFs & { files: Map<strinread: (p) => Promise.resolve(files.get(p) ?? null),write: (p, content) => {if (!p.startsWith('.switch/config/')) {- return Promise.reject(new Error(`attach wrote to the workspace: ${p}`));+ return Promise.reject(new Error(`attach wrote to the workdir: ${p}`));}files.set(p, content);return Promise.resolve();},- delete: (p) => Promise.reject(new Error(`attach deleted from the workspace: ${p}`)),+ delete: (p) => Promise.reject(new Error(`attach deleted from the workdir: ${p}`)),exists: (p) => Promise.resolve(files.has(p)),list: (dir) => {const prefix = `${dir}/`;@@ -52,12 +52,12 @@ const h = vi.hoisted(() => {}}const state: {- workspace: PluginFs | null;+ workdir: PluginFs | null;/** Agent-row names already in the directory, per Switch server. */- agentNamesByServer: Record<string, string[]>;+ agentNamesByWorkdir: Record<string, string[]>;existsOnServer: boolean;existsThrows: Error | null;- } = { workspace: null, agentNamesByServer: {}, existsOnServer: true, existsThrows: null };+ } = { workdir: null, agentNamesByWorkdir: {}, existsOnServer: true, existsThrows: null };return {state,GatewayError,@@ -77,13 +77,25 @@ vi.mock('@main/core/locations/store', () => ({ensureLocation: vi.fn(async () => ({ id: 'loc-1' })),}));vi.mock('./getAgents', () => ({- getLocationAgentsOnServer: vi.fn(async (_locationId: string, serverId: string) =>- (h.state.agentNamesByServer[serverId] ?? []).map((name) => ({ name }))+ getLocationAgentsInWorkspace: vi.fn(async (_locationId: string, workspaceId: string) =>+ (h.state.agentNamesByWorkdir[workspaceId] ?? []).map((name) => ({ name }))),}));-vi.mock('./agent-workspace-fs', () => ({- resolveWorkspaceFsFor: vi.fn(async () => ({- fs: h.state.workspace as PluginFs,+vi.mock('@main/core/workspaces/workspaces-store', () => ({+ requireWorkspaceForServer: vi.fn(async (serverId: string) => ({ id: `ws-${serverId}` })),+}));++const mockServer = vi.hoisted(() => ({+ id: 'srv-1',+ name: 'Switch',+ apiUrl: 'https://switch.example.com',+}));+vi.mock('@main/core/workspaces/workspace-session', () => ({+ withWorkspaceSession: (_workspaceId: string, fn: (server: unknown) => unknown) => fn(mockServer),+}));+vi.mock('./agent-workdir-fs', () => ({+ resolveWorkdirFsFor: vi.fn(async () => ({+ fs: h.state.workdir as PluginFs,homeFs: null,close: vi.fn(),})),@@ -97,11 +109,7 @@ vi.mock('@main/core/switch-servers/gateway-client', () => ({GatewayError: h.GatewayError,}));vi.mock('@main/core/switch-servers/servers-store', () => ({- getServer: vi.fn(async () => ({- id: 'srv-1',- name: 'Switch',- apiUrl: 'https://switch.example.com',- })),+ getServer: vi.fn(async () => mockServer),}));vi.mock('./createAgent', () => ({ createAgent: h.createAgent }));vi.mock('@main/core/locations/path-utils', () => ({ checkIsValidDirectory: () => true }));@@ -124,10 +132,10 @@ function params(agents: Array<{ name: string; providerId: 'codex' | 'claude' }>)describe('attachConfiguredAgents', () => {beforeEach(() => {vi.clearAllMocks();- h.state.agentNamesByServer = {};+ h.state.agentNamesByWorkdir = {};h.state.existsOnServer = true;h.state.existsThrows = null;- h.state.workspace = readOnlyFs({ '.switch/agents/theirs.json': creds('sw-theirs') });+ h.state.workdir = readOnlyFs({ '.switch/agents/theirs.json': creds('sw-theirs') });});it('adopts the existing Switch identity instead of minting a new one', async () => {@@ -146,25 +154,25 @@ describe('attachConfiguredAgents', () => {});it('writes nothing to the working directory but a missing config file', async () => {- // The workspace belongs to whichever install set the agent up. Any other+ // The workdir belongs to whichever install set the agent up. Any other// write here rejects, so this passing means attach touched none of their// state — and every agent has a config file.await expect(attachConfiguredAgents(params([{ name: 'theirs', providerId: 'codex' }]))).resolves.toMatchObject({ success: true });- expect(await h.state.workspace?.read('.switch/config/theirs.json')).not.toBeNull();+ expect(await h.state.workdir?.read('.switch/config/theirs.json')).not.toBeNull();});it('leaves an existing config file alone', async () => {const existing = JSON.stringify({ instructions: 'Theirs.', rendered: { x: 'y' } });- h.state.workspace = readOnlyFs({+ h.state.workdir = readOnlyFs({'.switch/agents/theirs.json': creds('sw-theirs'),'.switch/config/theirs.json': existing,});await attachConfiguredAgents(params([{ name: 'theirs', providerId: 'codex' }]));- expect(await h.state.workspace.read('.switch/config/theirs.json')).toBe(existing);+ expect(await h.state.workdir.read('.switch/config/theirs.json')).toBe(existing);});it('fails loudly when the identity no longer exists on the server', async () => {@@ -198,7 +206,7 @@ describe('attachConfiguredAgents', () => {});it('skips an agent this Switch Console already has', async () => {- h.state.agentNamesByServer = { 'srv-1': ['theirs'] };+ h.state.agentNamesByWorkdir = { 'ws-srv-1': ['theirs'] };const result = await attachConfiguredAgents(params([{ name: 'theirs', providerId: 'codex' }]));@@ -208,13 +216,13 @@ describe('attachConfiguredAgents', () => {it('attaches an agent already attached to a different server (CHOO-2044)', async () => {// Same directory, same name, other server — a separate agent, not a duplicate.- h.state.agentNamesByServer = { 'srv-other': ['theirs'] };+ h.state.agentNamesByWorkdir = { 'ws-srv-other': ['theirs'] };const result = await attachConfiguredAgents(params([{ name: 'theirs', providerId: 'codex' }]));expect(result.success).toBe(true);expect(h.createAgent).toHaveBeenCalledWith(- expect.objectContaining({ name: 'theirs', serverId: 'srv-1' })+ expect.objectContaining({ name: 'theirs', workspaceId: 'ws-srv-1' }));});@@ -222,7 +230,7 @@ describe('attachConfiguredAgents', () => {// One Switch server can be reachable at two URLs. The launch path reads the// endpoint from the same file as the token, so the directory's value is what// the session will really use — surfaced, never corrected.- h.state.workspace = readOnlyFs({+ h.state.workdir = readOnlyFs({'.switch/agents/theirs.json': creds('sw-theirs', 'https://switch.internal:8443'),});diff --git a/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.ts b/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.tsindex c094e007e..0cc10a079 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.ts@@ -8,6 +8,8 @@ import { getPlugin } from '@main/core/providers/plugin-registry';import { autoSessionWatcher } from '@main/core/switch-rooms/auto-session-watcher';import { agentExistsOnServer, GatewayError } from '@main/core/switch-servers/gateway-client';import { getServer } from '@main/core/switch-servers/servers-store';+import { withWorkspaceSession } from '@main/core/workspaces/workspace-session';+import { requireWorkspaceForServer } from '@main/core/workspaces/workspaces-store';import { log } from '@main/lib/logger';import type { Agent } from '@shared/core/agents/agents';import type { OnboardAgentError } from '@shared/core/agents/onboarding';@@ -16,7 +18,7 @@ import { sameApiEndpoint } from '@shared/core/switch-servers/switch-servers';import { basenameFromAnyPath } from '@shared/path-name';import { readAgentConfigFile } from './agent-config-file';import { agentEvents } from './agent-events';-import { resolveWorkspaceFsFor } from './agent-workspace-fs';+import { resolveWorkdirFsFor } from './agent-workdir-fs';import { createAgent } from './createAgent';import { discoverConfiguredAgents } from './discover-configured-agents';import { importAgentConfig } from './import-agent-config';@@ -74,6 +76,7 @@ export async function attachConfiguredAgents(const server = await getServer(params.serverId);if (!server) throw new Error(`No Switch server with id ${params.serverId}`);+ const targetWorkspace = await requireWorkspaceForServer(params.serverId);const discovered = new Map((@@ -120,7 +123,10 @@ export async function attachConfiguredAgents(if (!found) continue;try {- if (!(await agentExistsOnServer(server, found.switchAgentId))) {+ const exists = await withWorkspaceSession(targetWorkspace.id, (target) =>+ agentExistsOnServer(target, found.switchAgentId)+ );+ if (!exists) {return err({type: 'switch-agent-not-on-server',dir: params.dir,@@ -164,7 +170,7 @@ export async function attachConfiguredAgents(providerId,switchAgentId: found.switchAgentId,apiEndpoint: found.apiEndpoint,- serverId: params.serverId,+ workspaceId: targetWorkspace.id,autoApprove: params.sshHost !== null,ownerName: ownerName ?? null,});@@ -201,16 +207,16 @@ async function ensureAgentConfig(params: {name: string;providerId: AgentProviderId;}): Promise<void> {- const workspace = await resolveWorkspaceFsFor(params.sshHost, params.dir);+ const workdir = await resolveWorkdirFsFor(params.sshHost, params.dir);try {- if ((await readAgentConfigFile(workspace.fs, params.name)) !== null) return;+ if ((await readAgentConfigFile(workdir.fs, params.name)) !== null) return;await importAgentConfig({- workspaceFs: workspace.fs,+ workdirFs: workdir.fs,repoAgents: getPlugin(params.providerId).behavior.repoAgents ?? null,name: params.name,providerConfig: null,});} finally {- workspace.close();+ workdir.close();}}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/controller.ts b/console/apps/switch-console-desktop/src/main/core/agents/controller.tsindex cdfc29779..e4b593467 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/controller.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/controller.ts@@ -77,7 +77,7 @@ export const agentsController = createRPCController({onboardAgent: (params: OnboardAgentParams) => onboardAgent(params),discoverLoadableAgentsOnHost: (params: DiscoverLoadableAgentsParams) =>discoverLoadableAgentsOnHost(params),- discoverLoadableAgentsInDir: (params: { sshHost: string; dir: string; serverId: string }) =>+ discoverLoadableAgentsInDir: (params: { sshHost: string; dir: string; workspaceId: string }) =>discoverLoadableAgentsInDir(params),attachConfiguredAgents: (params: AttachConfiguredAgentsParams) => attachConfiguredAgents(params),removeLoadableAgentConfig: (params: RemoveLoadableAgentConfigParams) =>diff --git a/console/apps/switch-console-desktop/src/main/core/agents/createAgent.ts b/console/apps/switch-console-desktop/src/main/core/agents/createAgent.tsindex d6a28b0c3..f2ade07ab 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/createAgent.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/createAgent.ts@@ -2,7 +2,7 @@ import { sql } from 'drizzle-orm';import { db } from '@main/db/client';import { agents } from '@main/db/schema';import type { Agent, CreateAgentParams } from '@shared/core/agents/agents';-import { mapAgentRowToAgent } from './utils';+import { mapAgentRow } from './utils';/*** Insert an agent row. Main-process internal, and deliberately not an RPC@@ -21,7 +21,7 @@ export async function createAgent(params: CreateAgentParams): Promise<Agent> {providerId: params.providerId,switchAgentId: params.switchAgentId,apiEndpoint: params.apiEndpoint,- serverId: params.serverId,+ workspaceId: params.workspaceId,autoApprove: params.autoApprove,ownerName: params.ownerName ?? null,providerConfig: params.providerConfig ?? null,@@ -29,5 +29,5 @@ export async function createAgent(params: CreateAgentParams): Promise<Agent> {}).returning();- return mapAgentRowToAgent(row);+ return mapAgentRow(row);}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.test.tsindex f27dce8dd..a60c23263 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.test.ts@@ -49,8 +49,8 @@ vi.mock('@main/core/sdk-host/shared-watcher', () => ({vi.mock('@main/core/providers/plugin-registry', () => ({getPlugin: () => ({ behavior: { repoAgents: h.state.repoAgents } }),}));-vi.mock('./agent-workspace-fs', () => ({- resolveWorkspaceFsFor: vi.fn(async () => ({ fs: h.state.fs, close: vi.fn() })),+vi.mock('./agent-workdir-fs', () => ({+ resolveWorkdirFsFor: vi.fn(async () => ({ fs: h.state.fs, close: vi.fn() })),}));vi.mock('./agent-location', () => ({getAgentLocation: vi.fn(async () => ({ sshHost: h.state.sshHost, dir: '/repo' })),@@ -85,7 +85,10 @@ vi.mock('@main/core/switch-servers/gateway-client', () => ({}},}));-vi.mock('@main/core/switch-servers/servers-store', () => ({ getServer: vi.fn() }));+vi.mock('@main/core/workspaces/workspace-session', () => ({+ withWorkspaceSession: (_workspaceId: string, fn: (server: { id: string }) => unknown) =>+ fn({ id: 'srv-1' }),+}));vi.mock('@main/core/view-state/view-state-service', () => ({viewStateService: { del: vi.fn(async () => {}) },}));@@ -255,10 +258,9 @@ describe('deleteAgent', () => {providerId: 'claude',locationId: 'loc',serverId: 'srv-1',+ workspaceId: 'ws-1',switchAgentId: 'sw-1',};- const { getServer } = await import('@main/core/switch-servers/servers-store');- vi.mocked(getServer).mockResolvedValue({ id: 'srv-1' } as never);const fs = fakeFs({[agentSettingsRelativePath('cc-hoot')]: CREDS,'.claude/agents/cc-hoot.md': '# cc-hoot',@@ -429,10 +431,9 @@ describe('deleteAgent', () => {providerId: 'claude',locationId: 'loc',serverId: 'srv-1',+ workspaceId: 'ws-1',switchAgentId: 'sw-1',};- const { getServer } = await import('@main/core/switch-servers/servers-store');- vi.mocked(getServer).mockResolvedValue({ id: 'srv-1' } as never);await expect(deleteAgent('agent-1', {@@ -455,6 +456,7 @@ describe('deleteAgent', () => {providerId: 'claude',locationId: 'loc',serverId: null,+ workspaceId: null,switchAgentId: null,};diff --git a/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.ts b/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.tsindex 72eff6d91..0421dcd80 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.ts@@ -8,7 +8,6 @@ import {deleteAgent as gatewayDeleteAgent,GatewayError,} from '@main/core/switch-servers/gateway-client';-import { getServer } from '@main/core/switch-servers/servers-store';import { agentTypeOf } from '@main/core/telemetry/agent-type';import type {TelemetryAgentRemoveFailure,@@ -18,6 +17,7 @@ import type {import { agentRemoveTriggerOf } from '@main/core/telemetry/narrow';import { trackEvent } from '@main/core/telemetry/telemetry-service';import { viewStateService } from '@main/core/view-state/view-state-service';+import { withWorkspaceSession } from '@main/core/workspaces/workspace-session';import { db } from '@main/db/client';import { agents, sessions } from '@main/db/schema';import { log } from '@main/lib/logger';@@ -26,7 +26,7 @@ import type { Location } from '@shared/core/locations/locations';import { sessionRuntimeManager } from '../sessions/session-runtime-manager';import { agentEvents } from './agent-events';import { getAgentLocation } from './agent-location';-import { resolveWorkspaceFsFor } from './agent-workspace-fs';+import { resolveWorkdirFsFor } from './agent-workdir-fs';import { getAgentById } from './getAgentById';import { stopRemoteWatcher } from './remote-watcher';import { removeAgentLaunchProfile } from './remove-launch-profile';@@ -99,17 +99,14 @@ function locationKindOfRow(location: Location | null): TelemetryLocationKind {* rather than leaving the row gone but the Switch identity orphaned.*/async function deleteAgentInSwitch(agent: Agent): Promise<void> {- if (!agent.serverId || !agent.switchAgentId) {+ const { workspaceId, switchAgentId } = agent;+ if (!workspaceId || !switchAgentId) {throw new AgentNotLinkedToSwitchError(- `Agent ${agent.id} is not linked to a Switch server, so it cannot be deleted in Switch.`+ `Agent ${agent.id} is not linked to a Switch workspace, so it cannot be deleted in Switch.`);}- const server = await getServer(agent.serverId);- if (!server) {- throw new AgentNotLinkedToSwitchError(`No Switch server with id ${agent.serverId}`);- }- await gatewayDeleteAgent(server, agent.switchAgentId);+ await withWorkspaceSession(workspaceId, (server) => gatewayDeleteAgent(server, switchAgentId));}/**@@ -124,7 +121,7 @@ async function deleteAgentInSwitch(agent: Agent): Promise<void> {* (visibly) rather than thrown — the credentials being torn down are already dead.*/async function removeProvisionedFiles(agent: Agent, location: Location): Promise<void> {- const ctx = await resolveWorkspaceFsFor(location.sshHost, location.dir);+ const ctx = await resolveWorkdirFsFor(location.sshHost, location.dir);try {const behavior = getPlugin(agent.providerId).behavior.repoAgents;if (behavior && agent.name) {diff --git a/console/apps/switch-console-desktop/src/main/core/agents/discover-configured-agents.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/discover-configured-agents.test.tsindex e00083211..453b32007 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/discover-configured-agents.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/discover-configured-agents.test.ts@@ -50,12 +50,17 @@ function launchSpec(providerId: string) {const h = vi.hoisted(() => {const state: {- workspace: PluginFs | null;+ workdir: PluginFs | null;location: { id: string } | undefined;/** Agent-row names already in the directory, per Switch server. */- agentNamesByServer: Record<string, string[]>;+ agentNamesByWorkdir: Record<string, string[]>;claudeDefinitions: Array<{ name: string; description: string | null }>;- } = { workspace: null, location: { id: 'loc-1' }, agentNamesByServer: {}, claudeDefinitions: [] };+ } = {+ workdir: null,+ location: { id: 'loc-1' },+ agentNamesByWorkdir: {},+ claudeDefinitions: [],+ };return { state, warn: vi.fn() };});@@ -63,13 +68,16 @@ vi.mock('@main/core/locations/store', () => ({getLocationByHostDir: vi.fn(async () => h.state.location),}));vi.mock('./getAgents', () => ({- getLocationAgentsOnServer: vi.fn(async (_locationId: string, serverId: string) =>- (h.state.agentNamesByServer[serverId] ?? []).map((name) => ({ name }))+ getLocationAgentsInWorkspace: vi.fn(async (_locationId: string, workspaceId: string) =>+ (h.state.agentNamesByWorkdir[workspaceId] ?? []).map((name) => ({ name }))),}));-vi.mock('./agent-workspace-fs', () => ({- resolveWorkspaceFsFor: vi.fn(async () => ({- fs: h.state.workspace as PluginFs,+vi.mock('@main/core/workspaces/workspaces-store', () => ({+ requireWorkspaceForServer: vi.fn(async (serverId: string) => ({ id: `ws-${serverId}` })),+}));+vi.mock('./agent-workdir-fs', () => ({+ resolveWorkdirFsFor: vi.fn(async () => ({+ fs: h.state.workdir as PluginFs,homeFs: null,close: vi.fn(),})),@@ -96,16 +104,16 @@ describe('discoverConfiguredAgents', () => {beforeEach(() => {vi.clearAllMocks();h.state.location = { id: 'loc-1' };- h.state.agentNamesByServer = {};+ h.state.agentNamesByWorkdir = {};h.state.claudeDefinitions = [];- h.state.workspace = fakeFs();+ h.state.workdir = fakeFs();});it('finds a Codex agent from credentials alone', async () => {// The gap this feature closes: Codex has no repo-agent definitions, so the// definition-based scan sees nothing. The provider-neutral credentials file// is written for every provider, so it finds the agent anyway.- h.state.workspace = fakeFs({+ h.state.workdir = fakeFs({'.switch/agents/.gitignore': '*\n','.switch/agents/codex-hoot.json': creds('sw-codex'),'.switchdash/agents/codex-hoot/agent-launch-spec.json': launchSpec('codex'),@@ -125,7 +133,7 @@ describe('discoverConfiguredAgents', () => {it('never surfaces the API token', async () => {// Attaching must not need the secret: it stays on disk for the launch path.- h.state.workspace = fakeFs({+ h.state.workdir = fakeFs({'.switch/agents/hoot.json': creds('sw-1', 'https://switch.example.com', 'tok-do-not-leak'),});@@ -134,7 +142,7 @@ describe('discoverConfiguredAgents', () => {it('falls back to the owning provider definition, then to unknown', async () => {h.state.claudeDefinitions = [{ name: 'cc-hoot', description: null }];- h.state.workspace = fakeFs({+ h.state.workdir = fakeFs({'.switch/agents/cc-hoot.json': creds('sw-cc'),'.switch/agents/mystery.json': creds('sw-my'),});@@ -152,7 +160,7 @@ describe('discoverConfiguredAgents', () => {it('uses the provider definition and ignores obsolete sidecar launch specs', async () => {h.state.claudeDefinitions = [{ name: 'hoot', description: null }];- h.state.workspace = fakeFs({+ h.state.workdir = fakeFs({'.switch/agents/hoot.json': creds('sw-1'),'.switchdash/agents/hoot/agent-launch-spec.json': launchSpec('codex'),});@@ -161,8 +169,8 @@ describe('discoverConfiguredAgents', () => {});it('marks agents this Switch Console already has a row for', async () => {- h.state.agentNamesByServer = { 'srv-a': ['mine'] };- h.state.workspace = fakeFs({+ h.state.agentNamesByWorkdir = { 'ws-srv-a': ['mine'] };+ h.state.workdir = fakeFs({'.switch/agents/mine.json': creds('sw-mine'),'.switch/agents/theirs.json': creds('sw-theirs'),});@@ -176,8 +184,8 @@ describe('discoverConfiguredAgents', () => {// The directory is a place on disk, not one server's territory. An agent row// for server A says nothing about server B, and treating it as "already got// this" is what silently emptied the onboarding list.- h.state.agentNamesByServer = { 'srv-a': ['shared'] };- h.state.workspace = fakeFs({ '.switch/agents/shared.json': creds('sw-shared') });+ h.state.agentNamesByWorkdir = { 'ws-srv-a': ['shared'] };+ h.state.workdir = fakeFs({ '.switch/agents/shared.json': creds('sw-shared') });expect((await scan('srv-a'))[0]).toMatchObject({ name: 'shared', alreadyAgent: true });expect((await scan('srv-b'))[0]).toMatchObject({ name: 'shared', alreadyAgent: false });@@ -189,13 +197,13 @@ describe('discoverConfiguredAgents', () => {it('reports nothing for an unknown location rather than failing', async () => {h.state.location = undefined;- h.state.workspace = fakeFs({ '.switch/agents/hoot.json': creds('sw-1') });+ h.state.workdir = fakeFs({ '.switch/agents/hoot.json': creds('sw-1') });expect((await scan())[0]).toMatchObject({ name: 'hoot', alreadyAgent: false });});it('skips unusable credentials files instead of inventing an identity', async () => {- h.state.workspace = fakeFs({+ h.state.workdir = fakeFs({'.switch/agents/broken.json': '{ not json','.switch/agents/no-id.json': JSON.stringify({ env: { SWITCH_API_ENDPOINT: 'https://x' } }),'.switch/agents/good.json': creds('sw-good'),@@ -206,7 +214,7 @@ describe('discoverConfiguredAgents', () => {});it('ignores non-JSON entries such as the .gitignore', async () => {- h.state.workspace = fakeFs({+ h.state.workdir = fakeFs({'.switch/agents/.gitignore': '*\n','.switch/agents/hoot.json': creds('sw-1'),});diff --git a/console/apps/switch-console-desktop/src/main/core/agents/discover-configured-agents.ts b/console/apps/switch-console-desktop/src/main/core/agents/discover-configured-agents.tsindex 1dd4d01d8..28fa66159 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/discover-configured-agents.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/discover-configured-agents.ts@@ -1,13 +1,14 @@import type { PluginFs } from '@switch-console/core/agents/plugins';import { getLocationByHostDir } from '@main/core/locations/store';import { listPlugins } from '@main/core/providers/plugin-registry';+import { requireWorkspaceForServer } from '@main/core/workspaces/workspaces-store';import { log } from '@main/lib/logger';import {isValidProviderId,type AgentProviderId,} from '@shared/core/providers/agent-provider-registry';-import { resolveWorkspaceFsFor } from './agent-workspace-fs';-import { getLocationAgentsOnServer } from './getAgents';+import { resolveWorkdirFsFor } from './agent-workdir-fs';+import { getLocationAgentsInWorkspace } from './getAgents';import { SWITCH_AGENTS_DIR_RELATIVE } from './switch-settings-paths';/** How an agent's provider was inferred, so the UI can say whether to trust it. */@@ -73,13 +74,13 @@ function parseCredentialIdentity(raw: string | null, name: string): CredentialId* concept at all. Built once per scan: each provider answers with its own* discovery rather than this module hardcoding any provider's on-disk layout.*/-async function definitionOwners(workspaceFs: PluginFs): Promise<Map<string, AgentProviderId>> {+async function definitionOwners(workdirFs: PluginFs): Promise<Map<string, AgentProviderId>> {const owners = new Map<string, AgentProviderId>();for (const plugin of listPlugins()) {const behavior = plugin.behavior.repoAgents;if (!behavior) continue;try {- for (const def of await behavior.discoverDefinitions(workspaceFs)) {+ for (const def of await behavior.discoverDefinitions(workdirFs)) {if (!owners.has(def.name) && isValidProviderId(plugin.metadata.id)) {owners.set(def.name, plugin.metadata.id);}@@ -118,26 +119,29 @@ export async function discoverConfiguredAgents(params: {* attached here already and still be attachable to another (CHOO-2044). */serverId: string;}): Promise<DiscoveredConfiguredAgent[]> {+ const targetWorkspace = await requireWorkspaceForServer(params.serverId);const location = await getLocationByHostDir(params.sshHost, params.dir);const existing = location- ? new Set((await getLocationAgentsOnServer(location.id, params.serverId)).map((a) => a.name))+ ? new Set(+ (await getLocationAgentsInWorkspace(location.id, targetWorkspace.id)).map((a) => a.name)+ ): new Set<string>();- const workspace = await resolveWorkspaceFsFor(params.sshHost, params.dir);+ const workdir = await resolveWorkdirFsFor(params.sshHost, params.dir);try {- const names = (await workspace.fs.list(SWITCH_AGENTS_DIR_RELATIVE))+ const names = (await workdir.fs.list(SWITCH_AGENTS_DIR_RELATIVE)).filter((entry) => entry.endsWith('.json')).map((entry) => entry.slice(0, -'.json'.length)).filter((name) => name.length > 0).sort((a, b) => a.localeCompare(b));if (names.length === 0) return [];- const owners = await definitionOwners(workspace.fs);+ const owners = await definitionOwners(workdir.fs);const discovered: DiscoveredConfiguredAgent[] = [];for (const name of names) {const identity = parseCredentialIdentity(- await workspace.fs.read(`${SWITCH_AGENTS_DIR_RELATIVE}/${name}.json`),+ await workdir.fs.read(`${SWITCH_AGENTS_DIR_RELATIVE}/${name}.json`),name);if (!identity) continue;@@ -156,6 +160,6 @@ export async function discoverConfiguredAgents(params: {}return discovered;} finally {- workspace.close();+ workdir.close();}}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/discover-loadable-agents.ts b/console/apps/switch-console-desktop/src/main/core/agents/discover-loadable-agents.tsindex b43e7a13b..c622c1803 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/discover-loadable-agents.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/discover-loadable-agents.ts@@ -2,7 +2,7 @@ import { SshExecutionContext } from '@main/core/execution-context/ssh-execution-import { sshConnectionIdForHost } from '@main/core/locations/location-transport';import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';import { fetchAgents, fetchMe } from '@main/core/switch-servers/gateway-client';-import { getServer } from '@main/core/switch-servers/servers-store';+import { withWorkspaceSession, workspaceServer } from '@main/core/workspaces/workspace-session';import { log } from '@main/lib/logger';import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';import { sameApiEndpoint } from '@shared/core/switch-servers/switch-servers';@@ -41,7 +41,7 @@ export type LoadableAgent = {export type DiscoverLoadableAgentsParams = {sshHost: string;- serverId: string;+ workspaceId: string;/** When true, run a depth-limited `find` over `$HOME` in addition to the* cheap server-assisted discovery. Off by default — the walk can be slow* on large VMs. */@@ -68,17 +68,22 @@ export type DiscoverLoadableAgentsResult = {export async function discoverLoadableAgentsOnHost(params: DiscoverLoadableAgentsParams): Promise<DiscoverLoadableAgentsResult> {- const server = await getServer(params.serverId);- if (!server) throw new Error(`No Switch server with id ${params.serverId}`);+ const server = await workspaceServer(params.workspaceId);// Key: "dir\0name" → LoadableAgent. Server entries inserted first win.const seen = new Map<string, LoadableAgent>();// --- Source 1: Server-assisted discovery ---try {- const remoteAgents = await fetchAgents(server);- // Marks rows the signed-in user owns; an auth failure degrades to not-owner.- const me = await fetchMe(server).catch(() => null);+ // Leased together: `GET /agents` answers for the selected tenant, and the+ // owner marks below are only meaningful against the same one. The on-host+ // scans that follow are SSH and need no session, so the lease ends here+ // rather than being held across them.+ const { remoteAgents, me } = await withWorkspaceSession(params.workspaceId, async () => ({+ remoteAgents: await fetchAgents(server),+ // Marks rows the signed-in user owns; an auth failure degrades to not-owner.+ me: await fetchMe(server).catch(() => null),+ }));// Collect distinct repo_dirs from agents whose known_agent_options carry one.type ServerAgentInfo = {@@ -109,7 +114,7 @@ export async function discoverLoadableAgentsOnHost(const discovered = await discoverConfiguredAgents({sshHost: params.sshHost,dir,- serverId: params.serverId,+ serverId: server.id,});for (const agent of discovered) {const key = `${dir}\0${agent.name}`;@@ -140,7 +145,7 @@ export async function discoverLoadableAgentsOnHost(}} catch (error) {log.warn('discoverLoadableAgentsOnHost: server-assisted discovery failed', {- serverId: params.serverId,+ workspaceId: params.workspaceId,error: error instanceof Error ? error.message : String(error),});}@@ -154,7 +159,7 @@ export async function discoverLoadableAgentsOnHost(const discovered = await discoverConfiguredAgents({sshHost: params.sshHost,dir,- serverId: params.serverId,+ serverId: server.id,});for (const agent of discovered) {const key = `${dir}\0${agent.name}`;@@ -250,15 +255,16 @@ async function findSwitchAgentDirsOnHost(sshHost: string): Promise<string[]> {export async function discoverLoadableAgentsInDir(params: {sshHost: string;dir: string;- serverId: string;+ workspaceId: string;}): Promise<{ agents: LoadableAgent[]; serverApiUrl: string }> {- const server = await getServer(params.serverId);- if (!server) throw new Error(`No Switch server with id ${params.serverId}`);+ // The server only, with no lease: this path makes no gateway call — the scan+ // is on-host and the server is here for its API URL.+ const server = await workspaceServer(params.workspaceId);const discovered = await discoverConfiguredAgents({sshHost: params.sshHost,dir: params.dir,- serverId: params.serverId,+ serverId: server.id,});const agents = discovered.map((agent) => ({diff --git a/console/apps/switch-console-desktop/src/main/core/agents/getAgentById.ts b/console/apps/switch-console-desktop/src/main/core/agents/getAgentById.tsindex 9aeab349b..334f898e4 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/getAgentById.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/getAgentById.ts@@ -2,10 +2,10 @@ import { eq } from 'drizzle-orm';import { db } from '@main/db/client';import { agents } from '@main/db/schema';import type { Agent } from '@shared/core/agents/agents';-import { mapAgentRowToAgent } from './utils';+import { mapAgentRow } from './utils';export async function getAgentById(agentId: string): Promise<Agent | undefined> {const [row] = await db.select().from(agents).where(eq(agents.id, agentId)).limit(1);if (!row) return undefined;- return mapAgentRowToAgent(row);+ return mapAgentRow(row);}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/getAgents.ts b/console/apps/switch-console-desktop/src/main/core/agents/getAgents.tsindex 51edb0773..ef3e64ca6 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/getAgents.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/getAgents.ts@@ -1,37 +1,45 @@import { and, desc, eq } from 'drizzle-orm';import { db } from '@main/db/client';-import { agents } from '@main/db/schema';+import { agents, workspaces } from '@main/db/schema';import type { Agent } from '@shared/core/agents/agents';import { mapAgentRowToAgent } from './utils';+/**+ * Agents with the server hosting each one's workspace. Left-joined, because an+ * unlinked agent has no workspace and still has to be listed.+ */+function agentsWithServer() {+ return db+ .select({ agent: agents, serverId: workspaces.serverId })+ .from(agents)+ .leftJoin(workspaces, eq(agents.workspaceId, workspaces.id));+}+export async function getAgents(locationId?: string): Promise<Agent[]> {+ const query = agentsWithServer();const rows = locationId- ? await db- .select()- .from(agents)- .where(eq(agents.locationId, locationId))- .orderBy(desc(agents.updatedAt))- : await db.select().from(agents).orderBy(desc(agents.updatedAt));- return rows.map(mapAgentRowToAgent);+ ? await query.where(eq(agents.locationId, locationId)).orderBy(desc(agents.updatedAt))+ : await query.orderBy(desc(agents.updatedAt));+ return rows.map((row) => mapAgentRowToAgent(row.agent, row.serverId));}/**- * A directory's agents that belong to one Switch server.+ * A directory's agents that belong to one workspace.*- * A directory is a place on disk, not a server's territory: the same folder can- * hold agents registered against several servers. Anything answering "do I- * already have this agent" must therefore ask per server — asking per directory- * reports an agent on server A as already onboarded when the target is server B,- * and the candidate is silently dropped (CHOO-2044).+ * A directory is a place on disk, not a workspace's territory: the same folder+ * can hold agents belonging to several. Anything answering "do I already have+ * this agent" must therefore ask per workspace — asking per directory reports+ * an agent in workspace A as already onboarded when the target is workspace B,+ * and the candidate is silently dropped (CHOO-2044). Per workspace rather than+ * per server because an agent's name is unique per tenant on the gateway, so+ * two workspaces on one server can each hold a different agent of that name.*/-export async function getLocationAgentsOnServer(+export async function getLocationAgentsInWorkspace(locationId: string,- serverId: string+ workspaceId: string): Promise<Agent[]> {- const rows = await db- .select()- .from(agents)- .where(and(eq(agents.locationId, locationId), eq(agents.serverId, serverId)))+ const rows = await agentsWithServer()+ .where(and(eq(agents.locationId, locationId), eq(agents.workspaceId, workspaceId))).orderBy(desc(agents.updatedAt));- return rows.map(mapAgentRowToAgent);+ return rows.map((row) => mapAgentRowToAgent(row.agent, row.serverId));}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/import-agent-config.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/import-agent-config.test.tsindex 1cccb1c9c..79dcac350 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/import-agent-config.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/import-agent-config.test.ts@@ -35,7 +35,7 @@ const claudeRepoAgents = getPlugin('claude').behavior.repoAgents!;function importClaude(pluginFs = createPluginFs(dir)) {return importAgentConfig({- workspaceFs: pluginFs,+ workdirFs: pluginFs,repoAgents: claudeRepoAgents,name: NAME,providerConfig: null,@@ -161,7 +161,7 @@ describe('importAgentConfig', () => {pluginFs,NAME,await acknowledgeDefinition({- workspaceFs: pluginFs,+ workdirFs: pluginFs,repoAgents: claudeRepoAgents,name: NAME,config: { description: 'Mine', instructions: 'Mine.' },@@ -229,7 +229,7 @@ describe('importAgentConfig', () => {it('seeds a config file from the agent row for a provider without definitions', async () => {const pluginFs = createPluginFs(dir);await importAgentConfig({- workspaceFs: pluginFs,+ workdirFs: pluginFs,repoAgents: null,name: NAME,providerConfig: {@@ -250,7 +250,7 @@ describe('importAgentConfig', () => {expect(await importAgentConfig({- workspaceFs: pluginFs,+ workdirFs: pluginFs,repoAgents: null,name: NAME,providerConfig: {diff --git a/console/apps/switch-console-desktop/src/main/core/agents/import-agent-config.ts b/console/apps/switch-console-desktop/src/main/core/agents/import-agent-config.tsindex 27c7be4d1..078b4e37a 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/import-agent-config.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/import-agent-config.ts@@ -46,23 +46,23 @@ import { agentConfigRelativePath } from './switch-settings-paths';* file cannot be parsed — writing over it would lose what it holds.*/export async function importAgentConfig(params: {- workspaceFs: PluginFs;+ workdirFs: PluginFs;/** Null for a provider with no repository definitions. */repoAgents: IRepoAgentsBehavior | null;name: string;providerConfig: AgentProviderConfig | null;}): Promise<boolean> {- const { workspaceFs, repoAgents, name, providerConfig } = params;- const existing = await readAgentConfigFile(workspaceFs, name);+ const { workdirFs, repoAgents, name, providerConfig } = params;+ const existing = await readAgentConfigFile(workdirFs, name);const imported = repoAgents- ? await importDefinition({ workspaceFs, repoAgents, name, existing })+ ? await importDefinition({ workdirFs, repoAgents, name, existing }): (existing ?? fromProviderConfig(providerConfig));if (existing && serialiseAgentConfigFile(imported) === serialiseAgentConfigFile(existing)) {return false;}- await writeAgentConfigFile(workspaceFs, name, imported);+ await writeAgentConfigFile(workdirFs, name, imported);return true;}@@ -76,15 +76,15 @@ export async function importAgentConfig(params: {* a definition it generated itself and regenerates it from the config instead.*/export async function acknowledgeDefinition(params: {- workspaceFs: PluginFs;+ workdirFs: PluginFs;repoAgents: IRepoAgentsBehavior | null;name: string;config: AgentConfigFile;}): Promise<AgentConfigFile> {- const { workspaceFs, repoAgents, name, config } = params;+ const { workdirFs, repoAgents, name, config } = params;if (!repoAgents) return config;const definitionPath = repoAgents.definitionPath(name);- const current = await workspaceFs.read(definitionPath);+ const current = await workdirFs.read(definitionPath);if (current === null) return config;return {...config,@@ -93,21 +93,21 @@ export async function acknowledgeDefinition(params: {}async function importDefinition(params: {- workspaceFs: PluginFs;+ workdirFs: PluginFs;repoAgents: IRepoAgentsBehavior;name: string;existing: AgentConfigFile | null;}): Promise<AgentConfigFile> {- const { workspaceFs, repoAgents, name, existing } = params;+ const { workdirFs, repoAgents, name, existing } = params;const config = existing ?? {};const acknowledge = (next: AgentConfigFile) =>- acknowledgeDefinition({ workspaceFs, repoAgents, name, config: next });+ acknowledgeDefinition({ workdirFs, repoAgents, name, config: next });const definitionPath = repoAgents.definitionPath(name);- const current = await workspaceFs.read(definitionPath);+ const current = await workdirFs.read(definitionPath);if (current === null) return config;- const attributes = await repoAgents.readDefinition(workspaceFs, name);+ const attributes = await repoAgents.readDefinition(workdirFs, name);if (attributes === null || !hasFrontmatter(current)) {log.warn('importAgentConfig: agent definition has no frontmatter; not importing it', {name,diff --git a/console/apps/switch-console-desktop/src/main/core/agents/migrate-agent-storage.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/migrate-agent-storage.test.tsindex 7cd9842d6..faf7f2436 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/migrate-agent-storage.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/migrate-agent-storage.test.ts@@ -40,7 +40,7 @@ function credsJson(agentId: string): string {}// Shared mock state + spies. Hoisted so the vi.mock factories (which are lifted-// above imports) can reference them. `agents`/`workspace` are set per test.+// above imports) can reference them. `agents`/`workdir` are set per test.// `repoAgents` is the behavior `getPlugin` returns — set it to null in a test to// simulate a provider without repo-agent definitions (e.g. Codex).const h = vi.hoisted(() => {@@ -65,11 +65,11 @@ const h = vi.hoisted(() => {};const state: {agents: Array<Record<string, unknown>>;- workspace: PluginFs | null;+ workdir: PluginFs | null;repoAgents: object | null;} = {agents: [],- workspace: null,+ workdir: null,repoAgents: defaultRepoAgents,};return {@@ -92,10 +92,10 @@ vi.mock('@main/core/providers/plugin-registry', () => ({vi.mock('@main/core/locations/store', () => ({getLocationById: vi.fn(async () => ({ id: 'loc', sshHost: null, dir: '/repo' })),}));-vi.mock('./agent-workspace-fs', () => ({- resolveWorkspaceFsFor: vi.fn(async () => ({- fs: h.state.workspace,- homeFs: h.state.workspace,+vi.mock('./agent-workdir-fs', () => ({+ resolveWorkdirFsFor: vi.fn(async () => ({+ fs: h.state.workdir,+ homeFs: h.state.workdir,close: () => {},})),}));@@ -136,7 +136,7 @@ describe('migrateAgentStorage', () => {'.switch/agents/agent-id-1.json': credsJson('sw-1'),'.claude/agents/cc-hoot-main.md': '# def',});- h.state.workspace = ws;+ h.state.workdir = ws;await migrateAgentStorage();@@ -154,7 +154,7 @@ describe('migrateAgentStorage', () => {h.state.agents = [{ ...baseAgent, providerId: 'codex', name: 'codex-hoot' }];h.state.repoAgents = null;const ws = fakeFs({ '.switch/agents/agent-id-1.json': credsJson('sw-1') });- h.state.workspace = ws;+ h.state.workdir = ws;await migrateAgentStorage();@@ -174,7 +174,7 @@ describe('migrateAgentStorage', () => {'.claude/settings.local.json': credsJson('sw-1'),'.claude/agents/cc-hoot-main.md': '# def',});- h.state.workspace = ws;+ h.state.workdir = ws;await migrateAgentStorage();@@ -197,7 +197,7 @@ describe('migrateAgentStorage', () => {h.state.repoAgents = null;const ws = fakeFs({ '.claude/settings.local.json': credsJson('sw-CLAUDE-MAIN') });const read = vi.spyOn(ws, 'read');- h.state.workspace = ws;+ h.state.workdir = ws;await migrateAgentStorage();@@ -214,7 +214,7 @@ describe('migrateAgentStorage', () => {];h.state.repoAgents = null;const ws = fakeFs({ '.claude/settings.local.json': credsJson('sw-CLAUDE-MAIN') });- h.state.workspace = ws;+ h.state.workdir = ws;await migrateAgentStorage();@@ -228,7 +228,7 @@ describe('migrateAgentStorage', () => {'.claude/settings.local.json': credsJson('sw-other'),'.claude/agents/cc-hoot-main.md': '# def',});- h.state.workspace = ws;+ h.state.workdir = ws;await migrateAgentStorage();@@ -250,7 +250,7 @@ describe('migrateAgentStorage', () => {h.state.agents = [{ ...baseAgent, providerId: 'codex', name: 'codex-hoot' }];h.state.repoAgents = null;const ws = fakeFs({ '.switch/agents/agent-id-1.json': credsJson('sw-other') });- h.state.workspace = ws;+ h.state.workdir = ws;await migrateAgentStorage();@@ -271,7 +271,7 @@ describe('migrateAgentStorage', () => {'.claude/agents/cc-hoot-main.md': '# def',};const ws = fakeFs({ ...seed });- h.state.workspace = ws;+ h.state.workdir = ws;await migrateAgentStorage();@@ -283,31 +283,31 @@ describe('migrateAgentStorage', () => {it('writes no credentials when none exist anywhere (unrecoverable token)', async () => {const ws = fakeFs({ '.claude/agents/cc-hoot-main.md': '# def' });- h.state.workspace = ws;+ h.state.workdir = ws;await migrateAgentStorage();expect(await ws.exists('.switch/agents/cc-hoot-main.json')).toBe(false);});- it('skips the whole pass (no workspace opened) once the current generation is latched', async () => {+ it('skips the whole pass (no workdir opened) once the current generation is latched', async () => {h.completedGeneration.mockResolvedValueOnce(3);- const resolveWorkspaceFsFor = (await import('./agent-workspace-fs')).resolveWorkspaceFsFor;+ const resolveWorkdirFsFor = (await import('./agent-workdir-fs')).resolveWorkdirFsFor;await migrateAgentStorage();- expect(resolveWorkspaceFsFor).not.toHaveBeenCalled();+ expect(resolveWorkdirFsFor).not.toHaveBeenCalled();expect(h.markComplete).not.toHaveBeenCalled();});it('re-running after generation 2 skips the credential step but gives every agent a config file', async () => {h.completedGeneration.mockResolvedValueOnce(2);- h.state.workspace = fakeFs({ '.claude/settings.local.json': credsJson('sw-1') });+ h.state.workdir = fakeFs({ '.claude/settings.local.json': credsJson('sw-1') });await migrateAgentStorage();expect(h.readLaunchEnv).not.toHaveBeenCalled();- expect(await h.state.workspace.exists('.switch/agents/cc-hoot-main.json')).toBe(false);+ expect(await h.state.workdir.exists('.switch/agents/cc-hoot-main.json')).toBe(false);expect(h.importAgentConfig).toHaveBeenCalledTimes(1);expect(h.markComplete).toHaveBeenCalledTimes(1);});@@ -315,7 +315,7 @@ describe('migrateAgentStorage', () => {it('imports each agent’s config from its definition, or from the row without one', async () => {const providerConfig = { version: '2', providerId: 'codex', values: { model: 'gpt-5' } };h.state.agents = [{ ...baseAgent, providerConfig: null }];- h.state.workspace = fakeFs({});+ h.state.workdir = fakeFs({});await migrateAgentStorage();@@ -339,12 +339,12 @@ describe('migrateAgentStorage', () => {});it('never writes a provider definition, even for an agent without one', async () => {- h.state.workspace = fakeFs({ '.switch/agents/cc-hoot-main.json': credsJson('sw-1') });+ h.state.workdir = fakeFs({ '.switch/agents/cc-hoot-main.json': credsJson('sw-1') });await migrateAgentStorage();expect(h.writeDefinition).not.toHaveBeenCalled();- expect(await h.state.workspace.exists('.claude/agents/cc-hoot-main.md')).toBe(false);+ expect(await h.state.workdir.exists('.claude/agents/cc-hoot-main.md')).toBe(false);});it('re-running for generation 2 still migrates a provider generation 1 skipped', async () => {@@ -352,7 +352,7 @@ describe('migrateAgentStorage', () => {h.state.agents = [{ ...baseAgent, providerId: 'codex', name: 'codex-hoot' }];h.state.repoAgents = null;const ws = fakeFs({ '.switch/agents/agent-id-1.json': credsJson('sw-1') });- h.state.workspace = ws;+ h.state.workdir = ws;await migrateAgentStorage();@@ -360,7 +360,7 @@ describe('migrateAgentStorage', () => {});it('latches the marker after a clean pass', async () => {- h.state.workspace = fakeFs({+ h.state.workdir = fakeFs({'.switch/agents/cc-hoot-main.json': credsJson('sw-1'),'.claude/agents/cc-hoot-main.md': '# def',});@@ -371,7 +371,7 @@ describe('migrateAgentStorage', () => {});it('does not latch the marker when an agent migration throws', async () => {- h.state.workspace = fakeFs({+ h.state.workdir = fakeFs({'.switch/agents/cc-hoot-main.json': credsJson('sw-1'),'.claude/agents/cc-hoot-main.md': '# def',});diff --git a/console/apps/switch-console-desktop/src/main/core/agents/migrate-agent-storage.ts b/console/apps/switch-console-desktop/src/main/core/agents/migrate-agent-storage.tsindex 173e72957..2b3ae4946 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/migrate-agent-storage.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/migrate-agent-storage.ts@@ -13,7 +13,7 @@ import {markAgentStorageMigrationComplete,} from './agent-storage-migration-marker';import { markAgentUnmigrated } from './agent-storage-migration-ready';-import { resolveWorkspaceFsFor } from './agent-workspace-fs';+import { resolveWorkdirFsFor } from './agent-workdir-fs';import { getAgents } from './getAgents';import { importAgentConfig } from './import-agent-config';import { agentSettingsRelativePath, SWITCH_SETTINGS_RELATIVE_PATH } from './switch-settings-paths';@@ -35,7 +35,7 @@ import { writeNeutralAgentSettingsFs } from './write-switch-settings';*/export async function migrateAgentStorage(): Promise<void> {// Once a full pass has migrated every agent, never re-run: the steady-state- // migration re-opens each agent's workspace filesystem (an SSH/SFTP round trip+ // migration re-opens each agent's workdir filesystem (an SSH/SFTP round trip// per remote agent) on every boot for no benefit.const completed = await completedAgentStorageMigrationGeneration();if (completed >= AGENT_STORAGE_MIGRATION_GENERATION) return;@@ -69,7 +69,7 @@ export async function migrateAgentStorage(): Promise<void> {** `completedGeneration` is the generation this install already finished, so a* re-run can skip agents the new generation cannot change — the check happens- * before the workspace filesystem is opened, which for a remote agent is an SSH+ * before the workdir filesystem is opened, which for a remote agent is an SSH* connect and an SFTP channel.*/async function migrateOne(agent: Agent, completedGeneration: number): Promise<boolean> {@@ -87,7 +87,7 @@ async function migrateOne(agent: Agent, completedGeneration: number): Promise<boconst location = await getLocationById(agent.locationId);if (!location) return false;- const workspace = await resolveWorkspaceFsFor(location.sshHost, location.dir);+ const workdir = await resolveWorkdirFsFor(location.sshHost, location.dir);try {// The agent's identity is its single `name` (CHOO-1440): the creds/definition// stem on disk. It is authoritative — earlier migrations, and the 0041 SQL@@ -95,7 +95,7 @@ async function migrateOne(agent: Agent, completedGeneration: number): Promise<boconst name = agent.name;let changed = false;- if (!credentialsDone && (await migrateCredentials(agent, workspace.fs, behavior))) {+ if (!credentialsDone && (await migrateCredentials(agent, workdir.fs, behavior))) {changed = true;}@@ -103,7 +103,7 @@ async function migrateOne(agent: Agent, completedGeneration: number): Promise<bo// in its provider definition or on its row.if (await importAgentConfig({- workspaceFs: workspace.fs,+ workdirFs: workdir.fs,repoAgents: behavior ?? null,name,providerConfig: agent.providerConfig,@@ -114,7 +114,7 @@ async function migrateOne(agent: Agent, completedGeneration: number): Promise<boreturn changed;} finally {- workspace.close();+ workdir.close();}}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/onboard-agent.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/onboard-agent.test.tsindex 3438387da..d3ed6dc4e 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/onboard-agent.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/onboard-agent.test.ts@@ -45,6 +45,12 @@ vi.mock('@main/core/switch-rooms/switch-credentials', () => ({vi.mock('@main/core/switch-servers/servers-store', () => ({getServer: vi.fn(async () => h.server),}));+vi.mock('@main/core/workspaces/workspaces-store', () => ({+ requireWorkspaceForServer: vi.fn(async (serverId: string) => ({ id: `ws-${serverId}` })),+}));+vi.mock('@main/core/workspaces/workspace-session', () => ({+ withWorkspaceSession: (_workspaceId: string, fn: (server: unknown) => unknown) => fn(h.server),+}));vi.mock('@main/core/switch-servers/gateway-client', () => {class GatewayError extends Error {constructor(readonly kind: string) {@@ -72,8 +78,8 @@ vi.mock('@main/core/switch-rooms/auto-session-watcher', () => ({autoSessionWatcher: { bringUp: vi.fn(async () => {}) },}));vi.mock('./write-switch-settings', () => ({ writeAgentNeutralSettings: vi.fn(async () => {}) }));-vi.mock('./agent-workspace-fs', () => ({- resolveWorkspaceFsFor: vi.fn(async () => ({ fs: {}, close: () => {} })),+vi.mock('./agent-workdir-fs', () => ({+ resolveWorkdirFsFor: vi.fn(async () => ({ fs: {}, close: () => {} })),}));vi.mock('./import-agent-config', () => ({ importAgentConfig: h.importAgentConfig }));vi.mock('@main/core/providers/plugin-registry', () => ({diff --git a/console/apps/switch-console-desktop/src/main/core/agents/onboard-agent.ts b/console/apps/switch-console-desktop/src/main/core/agents/onboard-agent.tsindex e6641f9b2..aff258b67 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/onboard-agent.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/onboard-agent.ts@@ -11,6 +11,8 @@ import { getServer } from '@main/core/switch-servers/servers-store';import { agentTypeOf } from '@main/core/telemetry/agent-type';import type { TelemetryAgentCreateFailure } from '@main/core/telemetry/events';import { trackEvent } from '@main/core/telemetry/telemetry-service';+import { withWorkspaceSession } from '@main/core/workspaces/workspace-session';+import { requireWorkspaceForServer } from '@main/core/workspaces/workspaces-store';import { log } from '@main/lib/logger';import type {OnboardAgentError,@@ -21,7 +23,7 @@ import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';import type { UiEntryPoint } from '@shared/core/telemetry/reporting';import { basenameFromAnyPath } from '@shared/path-name';import { agentEvents } from './agent-events';-import { resolveWorkspaceFsFor } from './agent-workspace-fs';+import { resolveWorkdirFsFor } from './agent-workdir-fs';import { createAgent } from './createAgent';import { detectSwitchAgent } from './detect';import { detectSwitchAgentRemote } from './detect-remote';@@ -87,33 +89,32 @@ async function verifyAgentOnServer(agentId: string,dir: string): Promise<OnboardAgentError | null> {- const server = await getServer(serverId);- if (!server) {- throw new Error(`No Switch server with id ${serverId}`);- }- try {- const exists = await agentExistsOnServer(server, agentId);- if (!exists) {- return {- type: 'switch-agent-not-on-server',- dir,- serverId: server.id,- serverName: server.name,- agentId,- };- }- return null;- } catch (cause) {- if (cause instanceof GatewayError && cause.kind === 'unauthorized') {- return {- type: 'switch-server-unauthenticated',- dir,- serverId: server.id,- serverName: server.name,- };+ const workspace = await requireWorkspaceForServer(serverId);+ return withWorkspaceSession(workspace.id, async (server) => {+ try {+ const exists = await agentExistsOnServer(server, agentId);+ if (!exists) {+ return {+ type: 'switch-agent-not-on-server',+ dir,+ serverId: server.id,+ serverName: server.name,+ agentId,+ };+ }+ return null;+ } catch (cause) {+ if (cause instanceof GatewayError && cause.kind === 'unauthorized') {+ return {+ type: 'switch-server-unauthenticated',+ dir,+ serverId: server.id,+ serverName: server.name,+ };+ }+ throw cause;}- throw cause;- }+ });}/**@@ -188,22 +189,24 @@ export async function onboardAgent(params: OnboardAgentParams): Promise<OnboardA}}+ const targetWorkspace = await requireWorkspaceForServer(params.serverId);+const name = basenameFromAnyPath(params.dir) || params.providerId;// Every agent has a config file. This directory was set up outside this// Console, so whatever its Claude Code definition holds becomes the config.// Written before the agent row, so a failure here leaves no agent behind that// has none.- const workspace = await resolveWorkspaceFsFor(sshHost, params.dir);+ const workdir = await resolveWorkdirFsFor(sshHost, params.dir);try {await importAgentConfig({- workspaceFs: workspace.fs,+ workdirFs: workdir.fs,repoAgents: getPlugin(params.providerId).behavior.repoAgents ?? null,name,providerConfig: null,});} finally {- workspace.close();+ workdir.close();}const location = await ensureLocation({ sshHost, dir: params.dir, name: params.name });@@ -215,7 +218,7 @@ export async function onboardAgent(params: OnboardAgentParams): Promise<OnboardAproviderId: params.providerId,switchAgentId: switchAgent.agentId,apiEndpoint: switchAgent.apiEndpoint,- serverId: params.serverId,+ workspaceId: targetWorkspace.id,// Honor an explicit choice from the add-agent modal; otherwise default by// run location — remote agents run unattended on their VM with no operator// to answer permission prompts, so default them to bypass, local off.diff --git a/console/apps/switch-console-desktop/src/main/core/agents/propagate-server-api-url.db.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/propagate-server-api-url.db.test.tsindex 39b884bd7..b943590f5 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/propagate-server-api-url.db.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/propagate-server-api-url.db.test.ts@@ -5,7 +5,7 @@ import { openFixture } from '@tooling/utils/db';import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { AppDb } from '@main/db/client';-import { agents, locations, switchServers } from '@main/db/schema';+import { agents, locations, switchServers, workspaces } from '@main/db/schema';import { propagateServerApiUrl } from './propagate-server-api-url';import { agentSettingsRelativePath, SWITCH_SETTINGS_RELATIVE_PATH } from './switch-settings-paths';@@ -69,6 +69,13 @@ describe('propagateServerApiUrl', () => {apiUrl: 'https://other-api.example.com',},]);++ // Deliberately not the servers' ids: the cascade has to find agents through+ // their workspace, and identical ids would hide it not doing so.+ await fixture.db.insert(workspaces).values([+ { id: 'ws-pilot', serverId: 'pilot', name: 'Pilot' },+ { id: 'ws-other', serverId: 'other', name: 'Other' },+ ]);});afterEach(async () => {@@ -96,7 +103,7 @@ describe('propagateServerApiUrl', () => {switchAgentId: 'switch-agent-1',providerId: 'claude',apiEndpoint: 'https://old-api.example.com',- serverId: 'pilot',+ workspaceId: 'ws-pilot',});const results = await propagateServerApiUrl('pilot', 'https://new-api.example.com');@@ -152,7 +159,7 @@ describe('propagateServerApiUrl', () => {locationId: 'named-location',name: 'named-agent',providerId,- serverId: 'pilot',+ workspaceId: 'ws-pilot',apiEndpoint: env.SWITCH_API_ENDPOINT,});expect(await propagateServerApiUrl('pilot', 'https://new-api.example.com')).toMatchObject([@@ -185,7 +192,7 @@ describe('propagateServerApiUrl', () => {locationId: 'broken-location',name: 'broken-agent',providerId: 'codex',- serverId: 'pilot',+ workspaceId: 'ws-pilot',});expect(await propagateServerApiUrl('pilot', 'https://new-api.example.com')).toMatchObject([{ agentId: 'broken-agent', outcome: 'failed', error: expect.stringContaining('invalid') },@@ -211,7 +218,7 @@ describe('propagateServerApiUrl', () => {locationId: 'shared-location',name: 'agent-a',providerId: 'codex',- serverId: 'pilot',+ workspaceId: 'ws-pilot',switchAgentId: 'agent-a-identity',},{@@ -219,7 +226,7 @@ describe('propagateServerApiUrl', () => {locationId: 'shared-location',name: 'agent-b',providerId: 'claude',- serverId: 'other',+ workspaceId: 'ws-other',switchAgentId: 'agent-b-identity',},]);@@ -239,7 +246,7 @@ describe('propagateServerApiUrl', () => {name: 'bare-agent',providerId: 'claude',apiEndpoint: null,- serverId: 'pilot',+ workspaceId: 'ws-pilot',});const results = await propagateServerApiUrl('pilot', 'https://new-api.example.com');@@ -272,7 +279,7 @@ describe('propagateServerApiUrl', () => {name: 'other-agent',providerId: 'claude',apiEndpoint: 'https://other-api.example.com',- serverId: 'other',+ workspaceId: 'ws-other',});const results = await propagateServerApiUrl('pilot', 'https://new-api.example.com');diff --git a/console/apps/switch-console-desktop/src/main/core/agents/propagate-server-api-url.ts b/console/apps/switch-console-desktop/src/main/core/agents/propagate-server-api-url.tsindex 0e8d166a1..d98378ee8 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/propagate-server-api-url.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/propagate-server-api-url.ts@@ -6,7 +6,7 @@ import { FileSystemError, FileSystemErrorCodes } from '@main/core/fs/types';import { sshConnectionIdForHost } from '@main/core/locations/location-transport';import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';import { db } from '@main/db/client';-import { agents } from '@main/db/schema';+import { agents, workspaces } from '@main/db/schema';import { log } from '@main/lib/logger';import type { Agent } from '@shared/core/agents/agents';import type { AgentApiUrlPropagation } from '@shared/core/switch-servers/switch-servers';@@ -155,7 +155,8 @@ async function propagateToAgent(}/**- * Cascade a server's new API URL to every agent linked to it, rewriting each+ * Cascade a server's new API URL to every agent in any of its workspaces —+ * the URL is the server's, so all of them move together. Rewrites each* agent's on-disk `SWITCH_API_ENDPOINT` (local dir or remote SSH host) and the* DB mirror. Agents keep their token; unprovisioned agents are skipped, not* clobbered. Returns a per-agent summary — failures are reported, never@@ -166,10 +167,14 @@ export async function propagateServerApiUrl(serverId: string,apiEndpoint: string): Promise<AgentApiUrlPropagation[]> {- const rows = await db.select().from(agents).where(eq(agents.serverId, serverId));+ const rows = await db+ .select({ agent: agents })+ .from(agents)+ .innerJoin(workspaces, eq(agents.workspaceId, workspaces.id))+ .where(eq(workspaces.serverId, serverId));const results: AgentApiUrlPropagation[] = [];for (const row of rows) {- results.push(await propagateToAgent(mapAgentRowToAgent(row), apiEndpoint));+ results.push(await propagateToAgent(mapAgentRowToAgent(row.agent, serverId), apiEndpoint));}return results;}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/remote-session-reconciler.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/remote-session-reconciler.test.tsindex 87e14f0f7..92567f7f6 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/remote-session-reconciler.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/remote-session-reconciler.test.ts@@ -11,7 +11,6 @@ import {const mocks = vi.hoisted(() => ({list: vi.fn(),- server: vi.fn(async () => ({ id: 'server', gatewayUrl: 'https://example.test' })),snapshot: vi.fn(),room: vi.fn(),create: vi.fn(async () => ({ success: true })),@@ -29,12 +28,14 @@ vi.mock('./getAgentById', () => ({id: 'local',switchAgentId: 'agent',serverId: 'server',+ workspaceId: 'workspace',providerId: 'codex',autoApprove: false,}),}));-vi.mock('@main/core/switch-servers/servers-store', () => ({- getServer: mocks.server,+vi.mock('@main/core/workspaces/workspace-session', () => ({+ withWorkspaceSession: (_workspaceId: string, fn: (server: { id: string }) => Promise<unknown>) =>+ fn({ id: 'server' }),}));vi.mock('@main/core/switch-servers/gateway-client', () => ({fetchRoomDetail: mocks.room,diff --git a/console/apps/switch-console-desktop/src/main/core/agents/remote-session-reconciler.ts b/console/apps/switch-console-desktop/src/main/core/agents/remote-session-reconciler.tsindex 3c55d10a9..f743d8e22 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/remote-session-reconciler.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/remote-session-reconciler.ts@@ -6,7 +6,7 @@ import { sessionWasDeleted } from '@main/core/sessions/deleted-sessions';import { sessionService } from '@main/core/sessions/session-service';import { switchRoomService } from '@main/core/switch-rooms/switch-room-service';import { fetchRoomDetail } from '@main/core/switch-servers/gateway-client';-import { getServer } from '@main/core/switch-servers/servers-store';+import { withWorkspaceSession } from '@main/core/workspaces/workspace-session';import { db } from '@main/db/client';import { sessions } from '@main/db/schema';import { events } from '@main/lib/events';@@ -74,9 +74,8 @@ class RemoteSessionReconciler {this.stop(agentId);return;}- if (!agent.serverId) throw new Error('This linked agent has no Switch server configured.');- const server = await getServer(agent.serverId);- if (!server) throw new Error('The session discovery server is missing.');+ if (!agent.workspaceId) throw new Error('This linked agent has no workspace configured.');+ const workspaceId = agent.workspaceId;const remote: unknown[] = await listHostSessions(agentId);const failures: string[] = [];const local = new Map(@@ -146,7 +145,7 @@ class RemoteSessionReconciler {id: session.sessionId,agentId,title: roomId- ? `Session for ${(await fetchRoomDetail(server, roomId)).name}`+ ? `Session for ${(await withWorkspaceSession(workspaceId, (server) => fetchRoomDetail(server, roomId))).name}`: 'Shared session',attach: false,startSource: 'adopted',diff --git a/console/apps/switch-console-desktop/src/main/core/agents/remove-launch-profile.ts b/console/apps/switch-console-desktop/src/main/core/agents/remove-launch-profile.tsindex 42da7f49e..b3b4dd2ee 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/remove-launch-profile.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/remove-launch-profile.ts@@ -15,7 +15,7 @@ import { connectRemoteAgent } from './connect-remote-agent';** The profile lives in the home scope, not the working dir, so it is reached* through the same home filesystem that wrote it: local disk for a local agent,- * and the exec-backed remote home for a remote one (the repo-dir `WorkspaceFs`+ * and the exec-backed remote home for a remote one (the repo-dir `WorkdirFs`* used elsewhere in teardown deliberately has no writable home for remote* agents). Best-effort and isolated: a filesystem or connection failure is* logged, not thrown, so the rest of the agent's teardown still runs — but it isdiff --git a/console/apps/switch-console-desktop/src/main/core/agents/remove-loadable-agent-config.ts b/console/apps/switch-console-desktop/src/main/core/agents/remove-loadable-agent-config.tsindex dafa03c4e..931491e8e 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/remove-loadable-agent-config.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/remove-loadable-agent-config.ts@@ -1,5 +1,5 @@import { log } from '@main/lib/logger';-import { resolveWorkspaceFsFor } from './agent-workspace-fs';+import { resolveWorkdirFsFor } from './agent-workdir-fs';import { agentSettingsRelativePath } from './switch-settings-paths';export type RemoveLoadableAgentConfigParams = {@@ -27,7 +27,7 @@ export async function removeLoadableAgentConfig(params: RemoveLoadableAgentConfigParams): Promise<RemoveLoadableAgentConfigResult> {const relPath = agentSettingsRelativePath(params.name);- const ctx = await resolveWorkspaceFsFor(params.sshHost, params.dir);+ const ctx = await resolveWorkdirFsFor(params.sshHost, params.dir);try {const existing = await ctx.fs.read(relPath);if (existing === null) return { removed: false, reason: 'not-found' };diff --git a/console/apps/switch-console-desktop/src/main/core/agents/reset-remote-agent.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/reset-remote-agent.test.tsindex 3a36e47c8..95738d2c1 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/reset-remote-agent.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/reset-remote-agent.test.ts@@ -10,10 +10,11 @@ const mocks = vi.hoisted(() => ({teardown: vi.fn(async () => ({ success: true })),}));vi.mock('./getAgentById', () => ({- getAgentById: async () => ({ id: 'local', serverId: 'server', switchAgentId: 'agent' }),+ getAgentById: async () => ({ id: 'local', workspaceId: 'workspace', switchAgentId: 'agent' }),}));-vi.mock('@main/core/switch-servers/servers-store', () => ({- getServer: async () => ({ id: 'server' }),+vi.mock('@main/core/workspaces/workspace-session', () => ({+ withWorkspaceSession: (_workspaceId: string, fn: (server: { id: string }) => Promise<unknown>) =>+ fn({ id: 'server' }),}));vi.mock('@main/core/sdk-host/host-sessions', () => ({ listHostSessions: mocks.list }));vi.mock('@main/core/sdk-host/shared-agent-runtime', () => ({ stopSharedSession: mocks.stop }));diff --git a/console/apps/switch-console-desktop/src/main/core/agents/reset-remote-agent.ts b/console/apps/switch-console-desktop/src/main/core/agents/reset-remote-agent.tsindex 199b2d4de..aeebeb943 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/reset-remote-agent.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/reset-remote-agent.ts@@ -6,7 +6,6 @@ import { manageAgentSidecar } from '@main/core/sdk-host/sidecar-management';import { sessionHooks } from '@main/core/sessions/session-hooks';import { sessionRuntimeManager } from '@main/core/sessions/session-runtime-manager';import { switchRoomService } from '@main/core/switch-rooms/switch-room-service';-import { getServer } from '@main/core/switch-servers/servers-store';import { viewStateService } from '@main/core/view-state/view-state-service';import { db } from '@main/db/client';import { sessions } from '@main/db/schema';@@ -19,10 +18,8 @@ import { startRemoteDiscovery } from './remote-watcher';export async function resetRemoteAgent(agentId: string): Promise<void> {const agent = await getAgentById(agentId);- if (!agent?.serverId || !agent.switchAgentId)+ if (!agent?.workspaceId || !agent.switchAgentId)throw new Error('The agent is not linked to Switch.');- const server = await getServer(agent.serverId);- if (!server) throw new Error('The agent’s Switch server is missing.');await configureSharedWatcher(agentId, { connected: false, spawning: false }, 'explicit');remoteSessionReconciler.stop(agentId);const remote = await listHostSessions(agentId);diff --git a/console/apps/switch-console-desktop/src/main/core/agents/resolve-servers.db.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/resolve-servers.db.test.tsdeleted file mode 100644index 1bf6f9f3f..000000000--- a/console/apps/switch-console-desktop/src/main/core/agents/resolve-servers.db.test.ts+++ /dev/null@@ -1,128 +0,0 @@-import { openFixture } from '@tooling/utils/db';-import { eq } from 'drizzle-orm';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import type { AppDb } from '@main/db/client';-import { agents, locations, switchServers } from '@main/db/schema';-import { resolveAgentServers } from './resolve-servers';--const mocks = vi.hoisted(() => ({- db: undefined as AppDb | undefined,-}));--vi.mock('@main/db/client', () => ({- get db() {- if (!mocks.db) throw new Error('Test database not initialized');- return mocks.db;- },-}));--// servers-store transitively constructs the encrypted-secrets singleton (which-// touches the real db at import). resolveAgentServers never reads cookies, so-// stub it out to keep this test to the agent↔server reconciliation path.-vi.mock('@main/core/secrets/encrypted-app-secrets-store', () => ({- encryptedAppSecretsStore: {- getSecret: vi.fn(),- setSecret: vi.fn(),- deleteSecret: vi.fn(),- },-}));--async function serverIdOf(db: AppDb, agentId: string): Promise<string | null> {- const [row] = await db- .select({ serverId: agents.serverId })- .from(agents)- .where(eq(agents.id, agentId))- .limit(1);- return row?.serverId ?? null;-}--describe('resolveAgentServers', () => {- let fixture: Awaited<ReturnType<typeof openFixture>>;-- beforeEach(async () => {- fixture = await openFixture('empty');- mocks.db = fixture.db;- // Mirror production: the app's main connection does not enforce foreign- // keys, so an agent can reference a server that has since been removed —- // exactly the dangling state resolveAgentServers cleans up.- fixture.sqlite.pragma('foreign_keys = OFF');-- await fixture.db- .insert(locations)- .values({ id: 'location-1', name: 'Location', sshHost: '', dir: '/repo/location-1' });- await fixture.db.insert(switchServers).values([- {- id: 'pilot',- name: 'Pilot',- gatewayUrl: 'https://pilot-gateway.example.com',- apiUrl: 'https://pilot-api.example.com',- },- {- id: 'local',- name: 'Local',- gatewayUrl: 'http://localhost:8080',- apiUrl: 'http://localhost:8081',- },- ]);- });-- afterEach(() => {- fixture.close();- mocks.db = undefined;- });-- it('keeps links to registered servers, unlinks dangling, leaves unassigned alone', async () => {- await fixture.db.insert(agents).values([- // Explicitly linked to a registered server -> kept (not re-derived).- {- id: 'agent-pilot',- locationId: 'location-1',- name: 'pilot',- providerId: 'claude',- apiEndpoint: 'https://pilot.example.com/agent-bridge',- serverId: 'pilot',- },- // Linked to a server that is no longer registered -> unlinked.- {- id: 'agent-dangling',- locationId: 'location-1',- name: 'dangling',- providerId: 'claude',- apiEndpoint: 'https://gone.example.com',- serverId: 'removed-server',- },- // Never assigned -> stays null.- {- id: 'agent-none',- locationId: 'location-1',- name: 'none',- providerId: 'claude',- apiEndpoint: null,- serverId: null,- },- ]);-- await resolveAgentServers();-- expect(await serverIdOf(fixture.db, 'agent-pilot')).toBe('pilot');- expect(await serverIdOf(fixture.db, 'agent-dangling')).toBeNull();- expect(await serverIdOf(fixture.db, 'agent-none')).toBeNull();- });-- it('does not re-link by endpoint origin (links are explicit, never inferred)', async () => {- // Endpoint origin matches the local server, but serverId is null: the old- // behavior would auto-link; the new behavior must leave it unassigned.- await fixture.db.insert(agents).values({- id: 'agent-origin-match',- locationId: 'location-1',- name: 'origin-match',- providerId: 'claude',- apiEndpoint: 'http://localhost:8080',- serverId: null,- });-- await resolveAgentServers();-- expect(await serverIdOf(fixture.db, 'agent-origin-match')).toBeNull();- });-});diff --git a/console/apps/switch-console-desktop/src/main/core/agents/resolve-servers.ts b/console/apps/switch-console-desktop/src/main/core/agents/resolve-servers.tsdeleted file mode 100644index 962379f33..000000000--- a/console/apps/switch-console-desktop/src/main/core/agents/resolve-servers.ts+++ /dev/null@@ -1,42 +0,0 @@-import { isNotNull, notInArray } from 'drizzle-orm';-import { listServers } from '@main/core/switch-servers/servers-store';-import { db } from '@main/db/client';-import { agents } from '@main/db/schema';-import { log } from '@main/lib/logger';--/**- * Drop agent → server links that point at a server no longer in the registry,- * so an agent never references a server that has been removed.- *- * Links are otherwise authoritative: an agent's `serverId` is chosen and- * verified explicitly at onboarding (or via the assign-server action), not- * inferred. This reconciliation only *unlinks* dangling references — it never- * re-derives or re-assigns a server — so an explicit choice is never clobbered.- * An agent left with a null `serverId` surfaces in the UI as "needs a server".- *- * Run at boot and whenever the server registry changes.- */-export async function resolveAgentServers(): Promise<void> {- const servers = await listServers();- const registeredIds = servers.map((s) => s.id);-- // No registered servers → every linked agent is dangling. Otherwise unlink- // only agents whose serverId is set and not among the registered ids.- // (`NOT IN` already excludes null rows, so unassigned agents stay untouched.)- const where =- registeredIds.length === 0- ? isNotNull(agents.serverId)- : notInArray(agents.serverId, registeredIds);-- const result = await db- .update(agents)- .set({ serverId: null })- .where(where)- .returning({ id: agents.id });-- if (result.length > 0) {- log.info('switch-agents: unlinked agents pointing at removed servers', {- unlinked: result.length,- });- }-}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/stop-shared-agent-sessions.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/stop-shared-agent-sessions.test.tsindex 782f44938..0cf2792ba 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/stop-shared-agent-sessions.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/stop-shared-agent-sessions.test.ts@@ -16,8 +16,9 @@ vi.mock('@main/core/sdk-host/session-commands', () => ({submitSessionCommand: mocks.submit,sessionCommandStatus: mocks.status,}));-vi.mock('@main/core/switch-servers/servers-store', () => ({- getServer: async () => ({ id: 'server' }),+vi.mock('@main/core/workspaces/workspace-session', () => ({+ withWorkspaceSession: (_workspaceId: string, fn: (server: { id: string }) => Promise<unknown>) =>+ fn({ id: 'server' }),}));const { stopSharedAgentSessions } = await import('./stop-shared-agent-sessions');const session = {@@ -40,7 +41,7 @@ const session = {attachmentMimeTypes: [],},};-const agent = { id: 'local-agent', serverId: 'server', switchAgentId: 'agent' } as Agent;+const agent = { id: 'local-agent', workspaceId: 'workspace', switchAgentId: 'agent' } as Agent;const receipt = {type: 'command.status',commandId: 'stop-epoch',@@ -90,3 +91,8 @@ it('does not stop other agents or retired sessions', async () => {await stopSharedAgentSessions(agent);expect(mocks.submit).not.toHaveBeenCalled();});++it('does nothing for an agent with no workspace to address', async () => {+ await stopSharedAgentSessions({ ...agent, workspaceId: null } as Agent);+ expect(mocks.list).not.toHaveBeenCalled();+});diff --git a/console/apps/switch-console-desktop/src/main/core/agents/stop-shared-agent-sessions.ts b/console/apps/switch-console-desktop/src/main/core/agents/stop-shared-agent-sessions.tsindex b308523cb..d6743f137 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/stop-shared-agent-sessions.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/stop-shared-agent-sessions.ts@@ -1,12 +1,9 @@import { listHostSessions } from '@main/core/sdk-host/host-sessions';import { stopSharedSession } from '@main/core/sdk-host/stop-shared-session';-import { getServer } from '@main/core/switch-servers/servers-store';import type { Agent } from '@shared/core/agents/agents';export async function stopSharedAgentSessions(agent: Agent): Promise<void> {- if (!agent.serverId || !agent.switchAgentId) return;- const server = await getServer(agent.serverId);- if (!server) throw new Error('Cannot stop SDK sessions: the Switch server is missing.');+ if (!agent.workspaceId || !agent.switchAgentId) return;const sessions = await listHostSessions(agent.id);for (const session of sessions.filter((session) =>diff --git a/console/apps/switch-console-desktop/src/main/core/agents/updateAgent.ts b/console/apps/switch-console-desktop/src/main/core/agents/updateAgent.tsindex 89073bec4..2285bb0af 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/updateAgent.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/updateAgent.ts@@ -4,14 +4,14 @@ import { agents } from '@main/db/schema';import type { AgentProviderConfig } from '@shared/core/agents/agent-provider-config';import type { Agent } from '@shared/core/agents/agents';import { agentEvents } from './agent-events';-import { mapAgentRowToAgent } from './utils';+import { mapAgentRow } from './utils';export type UpdateAgentParams = {agentId: string;status?: string | null;switchAgentId?: string | null;apiEndpoint?: string | null;- serverId?: string;+ workspaceId?: string;autoApprove?: boolean;/** Null clears the agent's specialization, putting it back on provider defaults. */providerConfig?: AgentProviderConfig | null;@@ -24,13 +24,13 @@ export async function updateAgent(params: UpdateAgentParams): Promise<Agent | unif (params.status !== undefined) set.status = params.status;if (params.switchAgentId !== undefined) set.switchAgentId = params.switchAgentId;if (params.apiEndpoint !== undefined) set.apiEndpoint = params.apiEndpoint;- if (params.serverId !== undefined) set.serverId = params.serverId;+ if (params.workspaceId !== undefined) set.workspaceId = params.workspaceId;if (params.autoApprove !== undefined) set.autoApprove = params.autoApprove;if (params.providerConfig !== undefined) set.providerConfig = params.providerConfig;const [row] = await db.update(agents).set(set).where(eq(agents.id, params.agentId)).returning();if (!row) return undefined;- const agent = mapAgentRowToAgent(row);+ const agent = await mapAgentRow(row);agentEvents._emit('agent:updated', agent);return agent;}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/utils.ts b/console/apps/switch-console-desktop/src/main/core/agents/utils.tsindex 801b36b72..7f8455a05 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/utils.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/utils.ts@@ -1,8 +1,14 @@+import { serverIdForWorkspace } from '@main/core/workspaces/workspaces-store';import type { AgentRow } from '@main/db/schema';import { noteAgentName } from '@main/lib/log-name-cache';import type { Agent } from '@shared/core/agents/agents';-export function mapAgentRowToAgent(row: AgentRow): Agent {+/**+ * `serverId` is the server hosting the agent's workspace. It is a join away+ * from the row rather than on it, so the caller resolves it — the list reads+ * join, the single-row reads use {@link mapAgentRow}.+ */+export function mapAgentRowToAgent(row: AgentRow, serverId: string | null): Agent {// Every read and write of an agent passes through here, so the log sink can// name an agent id without ever querying for it.noteAgentName(row.id, row.name);@@ -14,7 +20,8 @@ export function mapAgentRowToAgent(row: AgentRow): Agent {providerId: row.providerId,switchAgentId: row.switchAgentId ?? null,apiEndpoint: row.apiEndpoint ?? null,- serverId: row.serverId ?? null,+ workspaceId: row.workspaceId ?? null,+ serverId,status: row.status ?? null,autoApprove: row.autoApprove,ownerName: row.ownerName ?? null,@@ -23,3 +30,8 @@ export function mapAgentRowToAgent(row: AgentRow): Agent {updatedAt: row.updatedAt,};}++/** {@link mapAgentRowToAgent} for one row, looking its server up. */+export async function mapAgentRow(row: AgentRow): Promise<Agent> {+ return mapAgentRowToAgent(row, await serverIdForWorkspace(row.workspaceId));+}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.test.tsindex 9a5794bd3..c4dc881e8 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.test.ts@@ -259,19 +259,15 @@ describe('writeNeutralAgentSettingsFs, against another install of Switch Consoleit('reports the owning server through foreignCredentialsOwnerFs, for a caller checking before it registers', async () => {await seed('shared-name', otherInstall);- const workspaceFs = createPluginFs(dir);+ const workdirFs = createPluginFs(dir);expect(- await foreignCredentialsOwnerFs(workspaceFs, 'shared-name', 'https://switch.example.com')+ await foreignCredentialsOwnerFs(workdirFs, 'shared-name', 'https://switch.example.com')).toBe('https://other-switch.example.com');expect(- await foreignCredentialsOwnerFs(- workspaceFs,- 'shared-name',- 'https://other-switch.example.com'- )+ await foreignCredentialsOwnerFs(workdirFs, 'shared-name', 'https://other-switch.example.com')).toBeNull();- expect(await foreignCredentialsOwnerFs(workspaceFs, 'absent', 'https://switch.example.com')) //+ expect(await foreignCredentialsOwnerFs(workdirFs, 'absent', 'https://switch.example.com')) //.toBeNull();});});diff --git a/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.ts b/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.tsindex 943d90c17..4336f9f52 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.ts@@ -413,11 +413,11 @@ export class ExistingAgentCredentialsError extends Error {* below re-checks, so a path that skips this one still cannot clobber.*/export async function foreignCredentialsOwnerFs(- workspaceFs: PluginFs,+ workdirFs: PluginFs,slug: string,apiEndpoint: string): Promise<string | null> {- const existingRaw = await workspaceFs.read(agentSettingsRelativePath(slug));+ const existingRaw = await workdirFs.read(agentSettingsRelativePath(slug));return foreignCredentialsEndpoint(existingRaw, apiEndpoint);}@@ -482,11 +482,11 @@ export function existingAgentIdInSlot(* before the token reaches disk.*/export async function writeNeutralAgentSettingsFs(- workspaceFs: PluginFs,+ workdirFs: PluginFs,params: { slug: string; expectedAgentId?: string } & SwitchSettingsCredentials): Promise<void> {const relPath = agentSettingsRelativePath(params.slug);- const existingRaw = await workspaceFs.read(relPath);+ const existingRaw = await workdirFs.read(relPath);const existingEndpoint = foreignCredentialsEndpoint(existingRaw, params.apiEndpoint);if (existingEndpoint !== null) {throw new ForeignAgentCredentialsError({@@ -516,8 +516,8 @@ export async function writeNeutralAgentSettingsFs(});}- if (!(await workspaceFs.exists(SWITCH_AGENTS_GITIGNORE_RELATIVE))) {- await workspaceFs.write(SWITCH_AGENTS_GITIGNORE_RELATIVE, '*\n');+ if (!(await workdirFs.exists(SWITCH_AGENTS_GITIGNORE_RELATIVE))) {+ await workdirFs.write(SWITCH_AGENTS_GITIGNORE_RELATIVE, '*\n');}- await workspaceFs.write(relPath, mergeAgentCredentials(existingRaw, params));+ await workdirFs.write(relPath, mergeAgentCredentials(existingRaw, params));}diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.test.tsindex b23f90ceb..943a96b73 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.test.ts@@ -94,20 +94,29 @@ describe('buildEnvFile', () => {// An entry here must say why the stack is correct without it — leaving a// var unset is a decision, not a default.const intentionallyUnset = new Set<string>([- // The four below configure switch-core as a distributed messaging app —- // one app we own, installed by a customer into their own workspace, with- // the platform posting events to URLs declared once in the app manifest.- // A managed stack cannot be one of those and is not meant to be: it binds- // to loopback, so no platform can reach its callback or event URLs, and- // the credentials are the app owner's rather than anything this machine- // could hold. switch-core registers no installer without them and the- // operator UI says so rather than offering a button that would fail at- // Slack. Connecting a workspace from here is the other path — an operator- // registering a bridge with their own app's token.+ // The vars below configure switch-core as a distributed messaging app —+ // one app we own, installed by a customer into their own workspace. A+ // managed stack cannot be one of those and is not meant to be: it binds+ // to loopback, so no platform can reach the OAuth redirect the install+ // needs (and switch-core makes MESSAGING_PUBLIC_URL a startup requirement+ // the moment a distributed app is configured, so setting the credentials+ // without it would fail boot), and the credentials are the app owner's+ // rather than anything this machine could hold. switch-core registers no+ // installer without them and the operator UI says so rather than offering+ // a button that would fail at the platform. Connecting a workspace from+ // here is the other path — an operator registering a bridge with their+ // own app's token.'MESSAGING_PUBLIC_URL','SLACK_APP_CLIENT_ID','SLACK_APP_CLIENT_SECRET','SLACK_APP_SIGNING_SECRET',+ // Discord grants no per-install token, so its four are deployment config+ // rather than per-workspace secrets. None can be held by a loopback stack+ // (see above), so all are unset here.+ 'DISCORD_APP_CLIENT_ID',+ 'DISCORD_APP_CLIENT_SECRET',+ 'DISCORD_APP_BOT_TOKEN',+ 'DISCORD_APP_APPLICATION_ID',]);const missing = [...interpolated]diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline-matrix-migration.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline-matrix-migration.test.tsindex 49a344f8a..b8c8fd5d5 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline-matrix-migration.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline-matrix-migration.test.ts@@ -64,10 +64,13 @@ vi.mock('@main/core/switch-servers/servers-store', () => ({ensureManagedServer: () => Promise.resolve({ id: 'srv-1' }),setActiveServerId: vi.fn(),}));+// Reads this install's own workspace rows, and through them the database client.+vi.mock('@main/core/workspaces/reconcile-workspaces', () => ({+ reconcileServerWorkspaces: () => Promise.resolve(),+}));vi.mock('@main/core/switch-servers/auth', () => ({passwordLogin: () => Promise.resolve({ success: true }),}));-vi.mock('@main/core/agents/resolve-servers', () => ({ resolveAgentServers: vi.fn() }));vi.mock('./managed-upgrade', () => ({prepareUpgrade: prepareUpgradeMock,finishUpgrade: finishUpgradeMock,diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline-shared-host.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline-shared-host.test.tsindex efb8db229..5f21634c1 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline-shared-host.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline-shared-host.test.ts@@ -95,7 +95,9 @@ vi.mock('@main/core/switch-servers/servers-store', () => ({setActiveServerId: vi.fn(() => Promise.resolve()),}));vi.mock('@main/core/switch-servers/auth', () => ({ passwordLogin: passwordLoginMock }));-vi.mock('@main/core/agents/resolve-servers', () => ({ resolveAgentServers: vi.fn() }));+vi.mock('@main/core/workspaces/reconcile-workspaces', () => ({+ reconcileServerWorkspaces: vi.fn(async () => {}),+}));vi.mock('./matrix-migration', () => ({crossesMatrixBoundary: () => false,runBackfill: vi.fn(),diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline.test.tsindex 36fbbb6c5..278caaccf 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline.test.ts@@ -70,10 +70,13 @@ vi.mock('@main/core/switch-servers/servers-store', () => ({ensureManagedServer: () => Promise.resolve({ id: 'srv-1' }),setActiveServerId: setActiveServerIdMock,}));+// Reads this install's own workspace rows, and through them the database client.+vi.mock('@main/core/workspaces/reconcile-workspaces', () => ({+ reconcileServerWorkspaces: () => Promise.resolve(),+}));vi.mock('@main/core/switch-servers/auth', () => ({passwordLogin: () => Promise.resolve({ success: true }),}));-vi.mock('@main/core/agents/resolve-servers', () => ({ resolveAgentServers: vi.fn() }));vi.mock('./managed-upgrade', () => ({prepareUpgrade: prepareUpgradeMock,finishUpgrade: finishUpgradeMock,diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline.tsindex ce6af3bf6..f46886a1f 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline.ts@@ -1,10 +1,10 @@-import { resolveAgentServers } from '@main/core/agents/resolve-servers';import { passwordLogin } from '@main/core/switch-servers/auth';import {assertManagedServerUrlFree,ensureManagedServer,setActiveServerId,} from '@main/core/switch-servers/servers-store';+import { reconcileServerWorkspaces } from '@main/core/workspaces/reconcile-workspaces';import { log } from '@main/lib/logger';import { COMPATIBLE_SWITCH_VERSION, RELEASE_REPO_OWNER } from '@shared/app-identity';import {@@ -446,9 +446,18 @@ async function registerAndSignIn(log.warn('managed-switch-server: auto sign-in failed; server will show a sign-in prompt', {error: login.error,});+ } else {+ // The user never sees a login form for a managed stack, so this is the only+ // sign-in it will ever have — without matching the workspaces here, its+ // placeholder one would stay unmatched until some later launch happened to.+ await reconcileServerWorkspaces(server.id).catch((error: unknown) => {+ log.warn('managed-switch-server: signed in, but could not read the account’s workspaces', {+ server: server.id,+ error: String(error),+ });+ });}- await resolveAgentServers();return server.id;}diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.ymlindex 5d1d13f64..eaa2eab12 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml@@ -224,6 +224,14 @@ services:SLACK_APP_CLIENT_ID: ${SLACK_APP_CLIENT_ID:-}SLACK_APP_CLIENT_SECRET: ${SLACK_APP_CLIENT_SECRET:-}SLACK_APP_SIGNING_SECRET: ${SLACK_APP_SIGNING_SECRET:-}+ DISCORD_APP_CLIENT_ID: ${DISCORD_APP_CLIENT_ID:-}+ DISCORD_APP_CLIENT_SECRET: ${DISCORD_APP_CLIENT_SECRET:-}+ DISCORD_APP_BOT_TOKEN: ${DISCORD_APP_BOT_TOKEN:-}+ DISCORD_APP_APPLICATION_ID: ${DISCORD_APP_APPLICATION_ID:-}+ # True/false flags, so bare keys for the reason given under LOG_FORMAT+ # below: `${VAR:-}` would hand them an empty string, which fails boot.+ DISCORD_APP_MESSAGE_CONTENT:+ DISCORD_APP_MEMBERS:# Observability and log format. Forwarded because this service names# every variable it passes, so without them here, setting any of these# in `.env` does nothing and the Helm chart is the only way to turndiff --git a/console/apps/switch-console-desktop/src/main/core/onboarding/controller.ts b/console/apps/switch-console-desktop/src/main/core/onboarding/controller.tsnew file mode 100644index 000000000..5bef6e6e8--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/onboarding/controller.ts@@ -0,0 +1,6 @@+import { createRPCController } from '@shared/lib/ipc/rpc';+import { installIsEmpty } from './install-contents';++export const onboardingController = createRPCController({+ installIsEmpty,+});diff --git a/console/apps/switch-console-desktop/src/main/core/onboarding/install-contents.ts b/console/apps/switch-console-desktop/src/main/core/onboarding/install-contents.tsnew file mode 100644index 000000000..f59a08805--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/onboarding/install-contents.ts@@ -0,0 +1,27 @@+import { db } from '@main/db/client';+import { agents, locations, switchServers } from '@main/db/schema';++/**+ * Whether this install holds nothing of its own — the fresh-install question the+ * shell asks before it puts the first-run page over the whole window.+ *+ * Deliberately not "has no Switch server". Agents, locations and the sessions+ * running in them outlive a server on purpose: removing one says in as many+ * words that its agents are kept and can be re-linked elsewhere. Reading an+ * empty server list as a fresh install would answer that promise by replacing+ * the window with a welcome page — permanently, across relaunches, with those+ * sessions still running behind it.+ *+ * Answered here rather than assembled in the renderer because the counts are+ * three rows the database already has, and the alternative is the shell waiting+ * on stores that mount agents and open SSH connections to tell it whether to+ * draw a sidebar at all.+ */+export async function installIsEmpty(): Promise<boolean> {+ const [server] = await db.select({ id: switchServers.id }).from(switchServers).limit(1);+ if (server) return false;+ const [location] = await db.select({ id: locations.id }).from(locations).limit(1);+ if (location) return false;+ const [agent] = await db.select({ id: agents.id }).from(agents).limit(1);+ return agent === undefined;+}diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.test.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.test.tsindex 2cb0acec4..7cd68e600 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.test.ts@@ -4,7 +4,7 @@ import { adoptSubagent } from './adopt-subagent';const mocks = vi.hoisted(() => ({local: vi.fn(),- server: vi.fn(),+ session: vi.fn(),remote: vi.fn(),create: vi.fn(),emit: vi.fn(),@@ -13,26 +13,28 @@ const mocks = vi.hoisted(() => ({}));vi.mock('@main/core/agents/agent-events', () => ({ agentEvents: { _emit: mocks.emit } }));vi.mock('@main/core/agents/createAgent', () => ({ createAgent: mocks.create }));-vi.mock('@main/core/agents/getAgents', () => ({ getLocationAgentsOnServer: mocks.local }));+vi.mock('@main/core/agents/getAgents', () => ({ getLocationAgentsInWorkspace: mocks.local }));vi.mock('@main/core/agents/remote-session-reconciler', () => ({remoteSessionReconciler: { start: mocks.start },}));vi.mock('@main/core/switch-servers/gateway-client', () => ({ fetchAgentDetail: mocks.remote }));-vi.mock('@main/core/switch-servers/servers-store', () => ({ getServer: mocks.server }));vi.mock('@main/core/agents/agent-location', () => ({getAgentLocation: async () => ({ id: 'location', dir: '/repo', sshHost: 'vm-1' }),}));-vi.mock('@main/core/agents/agent-workspace-fs', () => ({- resolveWorkspaceFsFor: async () => ({ fs: {}, close: () => {} }),+vi.mock('@main/core/agents/agent-workdir-fs', () => ({+ resolveWorkdirFsFor: async () => ({ fs: {}, close: () => {} }),}));vi.mock('@main/core/agents/import-agent-config', () => ({ importAgentConfig: mocks.importConfig }));vi.mock('@main/core/providers/plugin-registry', () => ({getPlugin: () => ({ behavior: { repoAgents: { definitionPath: () => '' } } }),}));+vi.mock('@main/core/workspaces/workspace-session', () => ({+ withWorkspaceSession: mocks.session,+}));const parent = {id: 'parent',locationId: 'location',- serverId: 'server',+ workspaceId: 'workspace',apiEndpoint: 'https://example.test/agent',providerId: 'claude',autoApprove: false,@@ -42,7 +44,9 @@ const parent = {beforeEach(() => {vi.resetAllMocks();mocks.local.mockResolvedValue([]);- mocks.server.mockResolvedValue({ id: 'server' });+ mocks.session.mockImplementation(+ (_workspaceId: string, fn: (server: { id: string }) => Promise<unknown>) => fn({ id: 'server' })+ );mocks.remote.mockResolvedValue({ id: 'child', ownerName: 'Owner' });mocks.create.mockImplementation(async (value) => ({ ...value, id: 'local-child' }));});@@ -55,7 +59,7 @@ it('adopts the child identity and discovers its sessions using its own credentianame: 'reviewer',switchAgentId: 'child',providerId: 'claude',- serverId: 'server',+ workspaceId: 'workspace',autoApprove: false,providerConfig: parent.providerConfig,})diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.tsindex 5babc8c3b..5ec84ad44 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.ts@@ -1,14 +1,14 @@import { randomUUID } from 'node:crypto';import { agentEvents } from '@main/core/agents/agent-events';import { getAgentLocation } from '@main/core/agents/agent-location';-import { resolveWorkspaceFsFor } from '@main/core/agents/agent-workspace-fs';+import { resolveWorkdirFsFor } from '@main/core/agents/agent-workdir-fs';import { createAgent } from '@main/core/agents/createAgent';-import { getLocationAgentsOnServer } from '@main/core/agents/getAgents';+import { getLocationAgentsInWorkspace } from '@main/core/agents/getAgents';import { importAgentConfig } from '@main/core/agents/import-agent-config';import { remoteSessionReconciler } from '@main/core/agents/remote-session-reconciler';import { getPlugin } from '@main/core/providers/plugin-registry';import { fetchAgentDetail } from '@main/core/switch-servers/gateway-client';-import { getServer } from '@main/core/switch-servers/servers-store';+import { withWorkspaceSession } from '@main/core/workspaces/workspace-session';import type { Agent } from '@shared/core/agents/agents';export async function adoptSubagent(@@ -16,8 +16,8 @@ export async function adoptSubagent(name: string,switchAgentId: string): Promise<void> {- if (!parent.serverId) throw new Error('The subagent’s Switch server is missing.');- const local = await getLocationAgentsOnServer(parent.locationId, parent.serverId);+ if (!parent.workspaceId) throw new Error('The subagent’s Switch workspace is missing.');+ const local = await getLocationAgentsInWorkspace(parent.locationId, parent.workspaceId);const existing = local.find((agent) => agent.switchAgentId === switchAgentId);if (existing) {if (existing.name !== name || existing.providerId !== parent.providerId)@@ -27,24 +27,24 @@ export async function adoptSubagent(}if (local.some((agent) => agent.name === name))throw new Error('This subagent name is already linked to a different Switch identity.');- const server = await getServer(parent.serverId);- if (!server) throw new Error('The subagent’s Switch server is missing.');- const remote = await fetchAgentDetail(server, switchAgentId);+ const remote = await withWorkspaceSession(parent.workspaceId, (server) =>+ fetchAgentDetail(server, switchAgentId)+ );if (remote.id !== switchAgentId)throw new Error('Switch returned a different subagent identity.');// Every agent has a config file; a subagent's comes from its own definition.// Written before the row, so a failure leaves no agent behind that has none.const location = await getAgentLocation(parent);- const workspace = await resolveWorkspaceFsFor(location.sshHost, location.dir);+ const workdir = await resolveWorkdirFsFor(location.sshHost, location.dir);try {await importAgentConfig({- workspaceFs: workspace.fs,+ workdirFs: workdir.fs,repoAgents: getPlugin(parent.providerId).behavior.repoAgents ?? null,name,providerConfig: parent.providerConfig,});} finally {- workspace.close();+ workdir.close();}const agent = await createAgent({id: randomUUID(),@@ -53,7 +53,7 @@ export async function adoptSubagent(providerId: parent.providerId,switchAgentId,apiEndpoint: parent.apiEndpoint,- serverId: parent.serverId,+ workspaceId: parent.workspaceId,autoApprove: parent.autoApprove,ownerName: remote.ownerName,providerConfig: parent.providerConfig,diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/controller.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/controller.tsindex a02061e52..a6df2edc4 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/controller.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/controller.ts@@ -29,10 +29,10 @@ export const sdkHostController = createRPCController({agentLogs: sharedAgentLogs,manageSidecar: async (agentId: string, action: 'update' | 'restart' | 'stop' | 'start') =>manageAgentSidecar(agentId, z.enum(['update', 'restart', 'stop', 'start']).parse(action)),- serverForAgent: async (agentId: string) => {+ workspaceForAgent: async (agentId: string) => {const agent = await getAgentById(agentId);- if (!agent?.serverId) throw new Error('This agent has no Switch server.');- return agent.serverId;+ if (!agent?.workspaceId) throw new Error('This agent has no Switch workspace.');+ return agent.workspaceId;},transcriptSource,transcriptOpen: (agentId: string, sessionId: string) => openTranscript(agentId, sessionId),diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/diagnostics.test.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/diagnostics.test.tsindex 4cbaa2496..888c261ed 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/diagnostics.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/diagnostics.test.ts@@ -5,7 +5,11 @@ vi.mock('@main/core/agent-runtime/impl/resolve-sidecar-bundle', () => ({resolveSharedHostBundlePath: () => import.meta.filename,}));vi.mock('@main/core/agents/getAgentById', () => ({- getAgentById: async () => ({ id: 'agent', switchAgentId: 'remote-agent', serverId: 'server' }),+ getAgentById: async () => ({+ id: 'agent',+ switchAgentId: 'remote-agent',+ workspaceId: 'workspace',+ }),}));vi.mock('@main/core/agents/agent-location', () => ({getAgentLocation: async () => ({ sshHost: 'host', dir: '/work' }),@@ -16,8 +20,9 @@ vi.mock('@main/core/agents/connect-remote-agent', () => ({vi.mock('@main/core/execution-context/local-execution-context', () => ({LocalExecutionContext: class {},}));-vi.mock('@main/core/switch-servers/servers-store', () => ({- getServer: async () => ({ id: 'server' }),+vi.mock('@main/core/workspaces/workspace-session', () => ({+ withWorkspaceSession: (_workspaceId: string, fn: (server: { id: string }) => Promise<unknown>) =>+ fn({ id: 'server' }),}));vi.mock('./host-sessions', () => ({ listHostSessions: mocks.sessions }));vi.mock('./host-watcher-snapshot', () => ({ hostWatcherStatus: mocks.watcher }));diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/diagnostics.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/diagnostics.tsindex b2909b602..a3241295b 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/diagnostics.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/diagnostics.ts@@ -6,7 +6,6 @@ import { getAgentLocation } from '@main/core/agents/agent-location';import { connectRemoteAgent } from '@main/core/agents/connect-remote-agent';import { getAgentById } from '@main/core/agents/getAgentById';import { LocalExecutionContext } from '@main/core/execution-context/local-execution-context';-import { getServer } from '@main/core/switch-servers/servers-store';import { redactSecrets } from '@main/lib/file-logger';import { listHostSessions } from './host-sessions';import { hostWatcherStatus } from './host-watcher-snapshot';@@ -29,7 +28,7 @@ const watcherSchema = z.object({async function agentHost(agentId: string) {const agent = await getAgentById(agentId);- if (!agent?.serverId || !agent.switchAgentId)+ if (!agent?.workspaceId || !agent.switchAgentId)throw new Error('The agent is not linked to Switch.');const location = await getAgentLocation(agent);const ctx = location.sshHost@@ -60,8 +59,6 @@ async function remoteWatchers(agentId: string): Promise<z.infer<typeof watcherScexport async function sharedAgentDiagnostics(agentId: string) {const { agent, location, ctx } = await agentHost(agentId);- const server = await getServer(agent.serverId!);- if (!server) throw new Error('The agent’s Switch server is missing.');const [watchers, bundle, remote] = await Promise.all([location.sshHost? remoteWatchers(agentId)diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.initial-prompt.test.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.initial-prompt.test.tsindex 8945e499f..66c10cedf 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.initial-prompt.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.initial-prompt.test.ts@@ -42,7 +42,7 @@ vi.mock('@main/core/switch-rooms/session-room-store', () => ({getPersistedRoomConnection: mocks.persistedRoom,}));vi.mock('@main/core/agents/getAgentById', () => ({ getAgentById: mocks.agent }));-vi.mock('@main/core/switch-servers/servers-store', () => ({ getServer: mocks.server }));+vi.mock('@main/core/workspaces/workspace-session', () => ({ workspaceServer: mocks.server }));class FakeNotRecorded extends Error {}vi.mock('./session-commands', () => ({CommandNotRecordedError: FakeNotRecorded,@@ -122,7 +122,7 @@ beforeEach(() => {id: 'agent-1',name: 'scout',switchAgentId: 'remote-agent',- serverId: 'server-1',+ workspaceId: 'workspace-1',});mocks.server.mockResolvedValue({ id: 'server-1' });mocks.ready.mockResolvedValue(undefined);@@ -416,7 +416,7 @@ it('reports restart progress through host replacement and authentication until rrelease = resolve;}));- mocks.loadSession.mockResolvedValue({ serverId: 'server-1', row: { config: {} } });+ mocks.loadSession.mockResolvedValue({ workspaceId: 'workspace-1', row: { config: {} } });mocks.snapshot.mockResolvedValueOnce({session: { epoch: 'old', connectivity: 'online', status: 'ready' },diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.tsindex a63e43c81..c36df3240 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.ts@@ -41,11 +41,10 @@ import { controllerConnectionId } from '@main/core/switch-rooms/session-connectiimport { getPersistedRoomConnection } from '@main/core/switch-rooms/session-room-store';import { switchNotificationPoller } from '@main/core/switch-rooms/switch-notification-poller';import { switchRoomService } from '@main/core/switch-rooms/switch-room-service';-import { getServer } from '@main/core/switch-servers/servers-store';+import { workspaceServer } from '@main/core/workspaces/workspace-session';import { log } from '@main/lib/logger';import { makeHookSessionId } from '@shared/core/providers/hook-session-id';import type { Session } from '@shared/core/sessions/sessions';-import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';import { JournalUnavailableError } from './host-journal';import { currentSnapshot } from './transcripts';@@ -67,7 +66,7 @@ function launchSettled(snapshot: Snapshot): boolean {}export class SharedAgentRuntime implements AgentRuntimeProvider {- private server: SwitchServer | null = null;+ private workspaceId: string | null = null;private starting: Promise<void> | null = null;private opened: Promise<void> | null = null;private startupError: string | null = null;@@ -150,12 +149,11 @@ export class SharedAgentRuntime implements AgentRuntimeProvider {): Promise<void> {this.startupStage = 'Preparing the session on its host…';const agent = await getAgentById(session.agentId);- if (!agent?.switchAgentId || !agent.serverId)- throw new Error('Link this agent to a Switch server before starting a session.');- this.server = await getServer(agent.serverId);- if (!this.server) throw new Error('The agent’s Switch server is missing.');+ if (!agent?.switchAgentId || !agent.workspaceId)+ throw new Error('Link this agent to a Switch workspace before starting a session.');+ this.workspaceId = agent.workspaceId;this.startupStage = 'Waiting for the Switch server to be ready…';- await ensureServerSessionReady(this.server);+ await ensureServerSessionReady(await workspaceServer(agent.workspaceId));this.startupStage = 'Preparing the session on its host…';const intended = switchNotificationPoller.getSharedIntent(session.id, agent.switchAgentId);const config = await buildSharedHostConfig(session, this.params, this.transport);@@ -353,7 +351,7 @@ export class SharedAgentRuntime implements AgentRuntimeProvider {}async restart(session: Session): Promise<void> {- await this.resolveServer();+ await this.resolveWorkspace();if (this.starting) await this.starting;this.setStartupError(null);this.starting = this.open(session, undefined, true, true, null, () => {});@@ -378,11 +376,12 @@ export class SharedAgentRuntime implements AgentRuntimeProvider {if (!joined) throw new Error('The session is no longer recorded in Console.');await stopSharedSession(joined.row.agentId, this.params.sessionId);}- private async resolveServer(): Promise<void> {- if (this.server) return;+ private async resolveWorkspace(): Promise<string> {+ if (this.workspaceId) return this.workspaceId;const session = await loadSessionWithAgent(this.params.sessionId);- this.server = session?.serverId ? await getServer(session.serverId) : null;- if (!this.server) throw new Error('The session’s Switch server is missing.');+ if (!session?.workspaceId) throw new Error('The session’s Switch workspace is missing.');+ this.workspaceId = session.workspaceId;+ return this.workspaceId;}}diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/stop-saved-session.test.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/stop-saved-session.test.tsindex 9c881fff1..b6a6b18de 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/stop-saved-session.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/stop-saved-session.test.ts@@ -12,7 +12,7 @@ vi.mock('./local-host', () => ({ stopLocalSession: mocks.stopLocal }));beforeEach(() => {vi.resetAllMocks();- mocks.agent.mockResolvedValue({ switchAgentId: 'remote-agent', serverId: 'server' });+ mocks.agent.mockResolvedValue({ switchAgentId: 'remote-agent', workspaceId: 'workspace' });mocks.stop.mockResolvedValue(undefined);mocks.stopLocal.mockResolvedValue(undefined);});diff --git a/console/apps/switch-console-desktop/src/main/core/sessions/session-join.ts b/console/apps/switch-console-desktop/src/main/core/sessions/session-join.tsindex 21ab50987..716c94524 100644--- a/console/apps/switch-console-desktop/src/main/core/sessions/session-join.ts+++ b/console/apps/switch-console-desktop/src/main/core/sessions/session-join.ts@@ -1,6 +1,6 @@import { eq } from 'drizzle-orm';import { db } from '@main/db/client';-import { agents, sessions, type SessionRow } from '@main/db/schema';+import { agents, sessions, type SessionRow, workspaces } from '@main/db/schema';import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';export type SessionWithAgent = {@@ -10,9 +10,13 @@ export type SessionWithAgent = {/** The owning agent's `name` — the session's identity source. The creds slug* and `--agent` launch name derive from it, read live, not from a frozen tag. */name: string;- /** The registered Switch server the agent belongs to; null once that server- * has been removed, which leaves the agent's endpoint and token pointing at- * something that no longer exists. */+ /** The workspace the owning agent belongs to; null for an agent not linked to+ * Switch. This is what a call about the session is addressed with — a server+ * can host several workspaces and answers for only the selected one. */+ workspaceId: string | null;+ /** The server hosting the agent's workspace; null once that server has been+ * removed, which leaves the agent's endpoint and token pointing at something+ * that no longer exists. */serverId: string | null;};@@ -29,10 +33,13 @@ export async function loadSessionWithAgent(locationId: agents.locationId,providerId: agents.providerId,name: agents.name,- serverId: agents.serverId,+ workspaceId: agents.workspaceId,+ serverId: workspaces.serverId,}).from(sessions).innerJoin(agents, eq(sessions.agentId, agents.id))+ // Left: an unlinked agent has no workspace and its sessions still load.+ .leftJoin(workspaces, eq(agents.workspaceId, workspaces.id)).where(eq(sessions.id, sessionId)).limit(1);if (!joined) return undefined;@@ -41,6 +48,7 @@ export async function loadSessionWithAgent(locationId: joined.locationId,providerId: joined.providerId,name: joined.name,+ workspaceId: joined.workspaceId,serverId: joined.serverId,};}diff --git a/console/apps/switch-console-desktop/src/main/core/switch-rooms/switch-credentials.ts b/console/apps/switch-console-desktop/src/main/core/switch-rooms/switch-credentials.tsindex 1e53e273f..d3986f655 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-rooms/switch-credentials.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-rooms/switch-credentials.ts@@ -102,12 +102,12 @@ export async function readAgentSwitchEnv(* the agent, so the miss is warned about here rather than at each call site.*/export async function readAgentSwitchEnvFromFs(- workspaceFs: PluginFs,+ workdirFs: PluginFs,slug: string,log: CredentialsLogger): Promise<Record<string, string>> {const relPath = agentSettingsRelativePath(slug);- const env = credentialsAsEnv(parseSwitchAgentCredentials(await workspaceFs.read(relPath), log));+ const env = credentialsAsEnv(parseSwitchAgentCredentials(await workdirFs.read(relPath), log));if (Object.keys(env).length === 0) {log.warn('readAgentSwitchEnvFromFs: no Switch identity for agent; session will not authenticate as it',diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/auth.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/auth.tsindex ca8db7e51..8fe2cee51 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/auth.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/auth.ts@@ -22,7 +22,7 @@ function gatewayUrl(server: SwitchServer, path: string): string {}/** Pull the `switch_auth` value out of the response's Set-Cookie headers. */-function extractAuthCookie(setCookies: string[]): string | null {+export function extractAuthCookie(setCookies: string[]): string | null {for (const raw of setCookies) {const [pair] = raw.split(';');const eq = pair.indexOf('=');diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.test.tsindex 90aee30fa..f285bbe7b 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.test.ts@@ -55,20 +55,25 @@ function server(id: string): SwitchServer {}/**- * Set up a server's agent list and which of them this install manages locally.- * `managed` defaults to all of them — the ordinary case of a machine looking at- * its own agents.+ * Set up a workspace's agent list and which of them this install manages+ * locally. `managed` defaults to all of them — the ordinary case of a machine+ * looking at its own agents.*/function given(remote: RemoteAgentSummary[], managed?: string[]) {const ids = managed ?? remote.map((a) => a.id);fetchAgents.mockResolvedValue(remote);getAgents.mockResolvedValue(- ids.map((switchAgentId) => ({ id: `local-${switchAgentId}`, switchAgentId, serverId: 's-1' }))+ ids.map((switchAgentId) => ({+ id: `local-${switchAgentId}`,+ switchAgentId,+ workspaceId: 'ws-1',+ })));}-/** Re-imported per test: the module remembers which servers it has done, which- * is the behaviour under test in one case and interference in every other. */+/** Re-imported per test: the module remembers which workspaces it has done,+ * which is the behaviour under test in one case and interference in every+ * other. */async function loadFresh() {vi.resetModules();return (await import('./backfill-agent-icons')).backfillAgentIcons;@@ -85,7 +90,7 @@ describe('backfillAgentIcons', () => {given([agent({ id: 'a-1', name: 'switch_worker' })]);const backfill = await loadFresh();- expect(await backfill(server('s-1'))).toEqual({ kind: 'written', written: 1 });+ expect(await backfill('ws-1', server('s-1'))).toEqual({ kind: 'written', written: 1 });expect(updateAgentIcon).toHaveBeenCalledWith(expect.anything(),'a-1',@@ -101,7 +106,7 @@ describe('backfillAgentIcons', () => {given([agent({ id: 'a-1', name: 'ancient', ownerId: null })]);const backfill = await loadFresh();- expect(await backfill(server('s-1'))).toEqual({ kind: 'written', written: 1 });+ expect(await backfill('ws-1', server('s-1'))).toEqual({ kind: 'written', written: 1 });expect(updateAgentIcon).toHaveBeenCalledOnce();});@@ -111,7 +116,7 @@ describe('backfillAgentIcons', () => {given([agent({ iconUrl: 'https://example.com/mine.png' })]);const backfill = await loadFresh();- expect(await backfill(server('s-1'))).toEqual({ kind: 'written', written: 0 });+ expect(await backfill('ws-1', server('s-1'))).toEqual({ kind: 'written', written: 0 });expect(updateAgentIcon).not.toHaveBeenCalled();});@@ -121,18 +126,18 @@ describe('backfillAgentIcons', () => {given([agent({ id: 'a-1' }), agent({ id: 'someone-elses' })], ['a-1']);const backfill = await loadFresh();- expect(await backfill(server('s-1'))).toEqual({ kind: 'written', written: 1 });+ expect(await backfill('ws-1', server('s-1'))).toEqual({ kind: 'written', written: 1 });expect(updateAgentIcon).toHaveBeenCalledWith(expect.anything(), 'a-1', expect.any(String));});- it('ignores a local agent belonging to a different server', async () => {+ it('ignores a local agent belonging to a different workspace', async () => {fetchAgents.mockResolvedValue([agent({ id: 'a-1' })]);getAgents.mockResolvedValue([- { id: 'local-1', switchAgentId: 'a-1', serverId: 'another-server' },+ { id: 'local-1', switchAgentId: 'a-1', workspaceId: 'another-workspace' },]);const backfill = await loadFresh();- expect(await backfill(server('s-1'))).toEqual({ kind: 'written', written: 0 });+ expect(await backfill('ws-1', server('s-1'))).toEqual({ kind: 'written', written: 0 });expect(updateAgentIcon).not.toHaveBeenCalled();});@@ -141,7 +146,7 @@ describe('backfillAgentIcons', () => {updateAgentIcon.mockRejectedValueOnce(new FakeGatewayError('http', 'forbidden', 403));const backfill = await loadFresh();- expect(await backfill(server('s-1'))).toEqual({ kind: 'written', written: 0 });+ expect(await backfill('ws-1', server('s-1'))).toEqual({ kind: 'written', written: 0 });});it('reports a server with no icon endpoint', async () => {@@ -152,7 +157,7 @@ describe('backfillAgentIcons', () => {updateAgentIcon.mockRejectedValue(new FakeGatewayError('http', 'not found', 404));const backfill = await loadFresh();- expect(await backfill(server('s-1'))).toEqual({ kind: 'unsupported' });+ expect(await backfill('ws-1', server('s-1'))).toEqual({ kind: 'unsupported' });});it('reports the agents that kept the old icon', async () => {@@ -160,17 +165,21 @@ describe('backfillAgentIcons', () => {updateAgentIcon.mockRejectedValueOnce(new Error('boom'));const backfill = await loadFresh();- expect(await backfill(server('s-1'))).toEqual({ kind: 'partial', written: 2, failed: 1 });+ expect(await backfill('ws-1', server('s-1'))).toEqual({+ kind: 'partial',+ written: 2,+ failed: 1,+ });expect(updateAgentIcon).toHaveBeenCalledTimes(3);});- it('asks the gateway once per server however often it is called', async () => {+ it('asks the gateway once per workspace however often it is called', async () => {given([agent({})]);const backfill = await loadFresh();- await backfill(server('s-1'));- await backfill(server('s-1'));- await backfill(server('s-1'));+ await backfill('ws-1', server('s-1'));+ await backfill('ws-1', server('s-1'));+ await backfill('ws-1', server('s-1'));expect(updateAgentIcon).toHaveBeenCalledTimes(1);expect(fetchAgents).toHaveBeenCalledTimes(1);@@ -180,7 +189,7 @@ describe('backfillAgentIcons', () => {// Two sidebar refreshes can land together on startup; without this each// would see no icons yet and write every agent twice.let release = (_: RemoteAgentSummary[]) => {};- getAgents.mockResolvedValue([{ id: 'local-1', switchAgentId: 'a-1', serverId: 's-1' }]);+ getAgents.mockResolvedValue([{ id: 'local-1', switchAgentId: 'a-1', workspaceId: 'ws-1' }]);fetchAgents.mockReturnValue(new Promise<RemoteAgentSummary[]>((resolve) => {release = resolve;@@ -188,8 +197,8 @@ describe('backfillAgentIcons', () => {);const backfill = await loadFresh();- const first = backfill(server('s-1'));- const second = backfill(server('s-1'));+ const first = backfill('ws-1', server('s-1'));+ const second = backfill('ws-1', server('s-1'));release([agent({ id: 'a-1' })]);await Promise.all([first, second]);@@ -203,23 +212,45 @@ describe('backfillAgentIcons', () => {fetchAgents.mockRejectedValueOnce(new Error('offline'));const backfill = await loadFresh();- await expect(backfill(server('s-1'))).rejects.toThrow('offline');+ await expect(backfill('ws-1', server('s-1'))).rejects.toThrow('offline');given([agent({})]);- expect(await backfill(server('s-1'))).toEqual({ kind: 'written', written: 1 });+ expect(await backfill('ws-1', server('s-1'))).toEqual({ kind: 'written', written: 1 });});- it('handles each server separately', async () => {+ it('handles each workspace separately', async () => {fetchAgents.mockResolvedValue([agent({ id: 'a-1' })]);getAgents.mockResolvedValue([- { id: 'local-1', switchAgentId: 'a-1', serverId: 's-1' },- { id: 'local-2', switchAgentId: 'a-1', serverId: 's-2' },+ { id: 'local-1', switchAgentId: 'a-1', workspaceId: 'ws-1' },+ { id: 'local-2', switchAgentId: 'a-1', workspaceId: 'ws-2' },]);const backfill = await loadFresh();- await backfill(server('s-1'));- await backfill(server('s-2'));+ await backfill('ws-1', server('s-1'));+ await backfill('ws-2', server('s-2'));expect(updateAgentIcon).toHaveBeenCalledTimes(2);});++ /**+ * Two workspaces on one server are two different agent lists: `GET /agents`+ * answers for whichever tenant the session has selected. Remembering the pass+ * against the server would have the first workspace's result stand in for the+ * second's — its agents never written, and its report describing a pass that+ * never looked at them.+ */+ it('does a second workspace on the same server rather than reusing the first', async () => {+ fetchAgents.mockResolvedValue([agent({ id: 'a-1' })]);+ getAgents.mockResolvedValue([+ { id: 'local-1', switchAgentId: 'a-1', workspaceId: 'ws-1' },+ { id: 'local-2', switchAgentId: 'a-1', workspaceId: 'ws-2' },+ ]);+ const backfill = await loadFresh();++ await backfill('ws-1', server('s-1'));+ await backfill('ws-2', server('s-1'));++ expect(fetchAgents).toHaveBeenCalledTimes(2);+ expect(updateAgentIcon).toHaveBeenCalledTimes(2);+ });});diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.tsindex 3f6427268..fa6d64e26 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.ts@@ -29,37 +29,51 @@ import { fetchAgents, GatewayError, updateAgentIcon } from './gateway-client';* server — still show the lettered avatar. Nothing on screen would say why, so* the caller is handed what happened and tells the user.*/-export function backfillAgentIcons(server: SwitchServer): Promise<AgentIconBackfill> {- const settled = completed.get(server.id);+export function backfillAgentIcons(+ workspaceId: string,+ server: SwitchServer+): Promise<AgentIconBackfill> {+ const settled = completed.get(workspaceId);if (settled !== undefined) return Promise.resolve(settled);- const running = inFlight.get(server.id);+ const running = inFlight.get(workspaceId);if (running) return running;- const run = writeMissingIcons(server)+ const run = writeMissingIcons(workspaceId, server).then((outcome) => {- completed.set(server.id, outcome);+ completed.set(workspaceId, outcome);return outcome;})- .finally(() => inFlight.delete(server.id));+ .finally(() => inFlight.delete(workspaceId));- inFlight.set(server.id, run);+ inFlight.set(workspaceId, run);return run;}-/** Servers already done this run, and what happened to each. Kept so opening- * the agents page repeatedly does not re-ask the gateway; a server that threw- * is deliberately absent, so the next refresh tries again. */+/**+ * Workspaces already done this run, and what happened to each. Kept so opening+ * the agents page repeatedly does not re-ask the gateway; a workspace whose+ * pass threw is deliberately absent, so the next refresh tries again.+ *+ * Per workspace and not per server: `GET /agents` answers for the tenant the+ * session has selected, so one server's two workspaces are two different lists.+ * Keying on the server would let the first workspace's pass stand in for the+ * second's — the second's agents never written, and the first's outcome+ * reported under the second's name.+ */const completed = new Map<string, AgentIconBackfill>();const inFlight = new Map<string, Promise<AgentIconBackfill>>();-async function writeMissingIcons(server: SwitchServer): Promise<AgentIconBackfill> {+async function writeMissingIcons(+ workspaceId: string,+ server: SwitchServer+): Promise<AgentIconBackfill> {const [agents, local] = await Promise.all([fetchAgents(server), getAgents()]);- // `GET /agents` lists the whole server, most of which is nothing to do with- // this computer.+ // `GET /agents` lists the whole workspace, most of which is nothing to do+ // with this computer.const managed = new Set(local- .filter((agent) => agent.serverId === server.id && agent.switchAgentId !== null)+ .filter((agent) => agent.workspaceId === workspaceId && agent.switchAgentId !== null).map((agent) => agent.switchAgentId as string));const missing = agents.filter((agent) => agent.iconUrl === null && managed.has(agent.id));@@ -94,6 +108,7 @@ async function writeMissingIcons(server: SwitchServer): Promise<AgentIconBackfilif (written === 0 && notFound > 0 && notFound === missing.length) {log.warn('agent icon backfill: this server has no agent-icon endpoint', {event: 'agent_icon_backfill',+ workspaceId,serverId: server.id,agents: missing.length,});@@ -103,6 +118,7 @@ async function writeMissingIcons(server: SwitchServer): Promise<AgentIconBackfilif (failures.length > 0) {log.warn('agent icon backfill: some agents kept the lettered avatar', {event: 'agent_icon_backfill',+ workspaceId,serverId: server.id,written,failed: failures.length,@@ -113,6 +129,7 @@ async function writeMissingIcons(server: SwitchServer): Promise<AgentIconBackfillog.info('agent icon backfill: done', {event: 'agent_icon_backfill',+ workspaceId,serverId: server.id,written,});diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.test.tsindex 44875ad81..06bb4bb5a 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.test.ts@@ -8,12 +8,12 @@ const managedServerHostBlocked = vi.hoisted(() => vi.fn((): unknown => null));const fetchAuthConfig = vi.hoisted(() => vi.fn());const trackEvent = vi.hoisted(() => vi.fn());const addServer = vi.hoisted(() => vi.fn());-const resolveAgentServers = vi.hoisted(() => vi.fn());+const findServerByGatewayUrl = vi.hoisted(() => vi.fn());const passwordLogin = vi.hoisted(() => vi.fn());-const createRoomOnServer = vi.hoisted(() => vi.fn());-const deleteBridge = vi.hoisted(() => vi.fn());-const deleteRoom = vi.hoisted(() => vi.fn());-const fetchBridges = vi.hoisted(() => vi.fn());+const reconcileServerWorkspaces = vi.hoisted(() => vi.fn());+const listWorkspacesForServer = vi.hoisted(() => vi.fn());+const createTenant = vi.hoisted(() => vi.fn());+const acceptInvitation = vi.hoisted(() => vi.fn());// Stubbed rather than reimplemented: what the tests below assert is that the// kind reaches the event, not how a row is read as one.const serverKindOf = vi.hoisted(() => vi.fn(() => 'remote_managed'));@@ -22,7 +22,6 @@ const serverKindOf = vi.hoisted(() => vi.fn(() => 'remote_managed'));// ssh / agent side effects at load.vi.mock('@main/core/agents/agent-defaults', () => ({ suggestAgentDefaults: vi.fn() }));vi.mock('@main/core/agents/propagate-server-api-url', () => ({ propagateServerApiUrl: vi.fn() }));-vi.mock('@main/core/agents/resolve-servers', () => ({ resolveAgentServers }));vi.mock('@main/core/agents/write-remote-switch-settings', () => ({writeRemoteSwitchSettings: vi.fn(),}));@@ -36,6 +35,11 @@ vi.mock('@main/core/managed-switch-server/managed-server-status', () => ({isManagedServerRunning,managedServerHostBlocked,}));+// Reads this install's own workspace rows, and through them the database client.+vi.mock('@main/core/workspaces/reconcile-workspaces', () => ({+ reconcileServerWorkspaces,+}));+vi.mock('@main/core/workspaces/workspaces-store', () => ({ listWorkspacesForServer }));// Writes to the app's log file, which a test has no business creating.vi.mock('@main/lib/logger', () => ({log: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() },@@ -45,18 +49,16 @@ vi.mock('./auth', () => ({ oidcLogin: vi.fn(), passwordLogin }));vi.mock('./backfill-agent-icons', () => ({ backfillAgentIcons: vi.fn() }));// Reaches the encrypted secrets store, and through it the database client.vi.mock('./bundled-chat-sign-in', () => ({ bundledChatSignInFor: vi.fn() }));-vi.mock('./create-room', () => ({ createRoomOnServer }));vi.mock('./gateway-web', () => ({ openAuthenticatedGatewayPage: vi.fn() }));vi.mock('./gateway-client', () => ({fetchMe,agentExistsOnServer: vi.fn(),- deleteBridge,- deleteRoom,fetchAgentDetail: vi.fn(),fetchAgentRooms: vi.fn(),fetchAgents: vi.fn(),fetchAuthConfig,- fetchBridges,+ createTenant,+ acceptInvitation,fetchRoomRoles: vi.fn(),fetchRooms: vi.fn(),registerKnownAgent: vi.fn(),@@ -65,8 +67,8 @@ vi.mock('./gateway-client', () => ({vi.mock('./servers-store', () => ({getServer,addServer,+ findServerByGatewayUrl,deleteSessionCookie: vi.fn(),- getActiveServerId: vi.fn(),listServers: vi.fn(),removeServer: vi.fn(),renameServer: vi.fn(),@@ -155,43 +157,6 @@ describe('gateway calls on an unreachable host', () => {});});-describe('disconnecting a bridge', () => {- beforeEach(() => {- vi.clearAllMocks();- managedServerHostBlocked.mockReturnValue(null);- getServer.mockResolvedValue(server({}));- fetchBridges.mockResolvedValue([{ id: 'b1', type: 'slack' }]);- });-- it('reports a disconnection the gateway carried out', async () => {- deleteBridge.mockResolvedValue({ kind: 'deleted' });-- await switchServersController.deleteBridge({ serverId: 'srv', bridgeId: 'b1' });-- await vi.waitFor(() =>- expect(trackEvent).toHaveBeenCalledWith('bridge_disconnected', {- bridge_platform: 'slack',- outcome: 'success',- })- );- });-- it('reports a refusal as a failure rather than as a disconnection', async () => {- // Admin-only, and the gateway hands back the refusal instead of throwing- // it — so the await returns exactly as it does for a bridge that went.- deleteBridge.mockResolvedValue({ kind: 'forbidden' });-- await switchServersController.deleteBridge({ serverId: 'srv', bridgeId: 'b1' });-- await vi.waitFor(() =>- expect(trackEvent).toHaveBeenCalledWith('bridge_disconnected', {- bridge_platform: 'slack',- outcome: 'failure',- })- );- });-});-describe('an action a server whose host has gone down cannot take', () => {const blocked = {sshHost: 'h',@@ -204,45 +169,6 @@ describe('an action a server whose host has gone down cannot take', () => {vi.clearAllMocks();getServer.mockResolvedValue(server({ managed: true, managementKind: 'remote', sshHost: 'h' }));managedServerHostBlocked.mockReturnValue(blocked);- // What the gateway does on a host that cannot be reached: the platform is- // then unknowable rather than absent.- fetchBridges.mockRejectedValue(new Error('no route to host'));- });-- it('reports the room it refused to create', async () => {- await expect(- switchServersController.createRoom({- serverId: 'srv',- name: 'Room',- description: '',- bridgeId: 'b1',- agentIds: ['a1'],- })- ).rejects.toBeInstanceOf(HostUnreachableError);-- expect(createRoomOnServer).not.toHaveBeenCalled();- await vi.waitFor(() =>- expect(trackEvent).toHaveBeenCalledWith('room_created', {- server_kind: 'remote_managed',- bridge_platform: 'unknown',- agent_count: 1,- has_instructions: false,- outcome: 'failure',- failure_reason: 'unreachable',- })- );- });-- it('reports the room it refused to delete', async () => {- await expect(- switchServersController.deleteRoom({ serverId: 'srv', roomId: 'r1' })- ).rejects.toBeInstanceOf(HostUnreachableError);-- expect(deleteRoom).not.toHaveBeenCalled();- expect(trackEvent).toHaveBeenCalledWith('room_deleted', {- server_kind: 'remote_managed',- outcome: 'failure',- });});it('reports the sign-in that never left this machine', async () => {@@ -282,21 +208,250 @@ describe('an action a server whose host has gone down cannot take', () => {});});+/**+ * Signing in is the first moment the gateway will say which workspaces the+ * account belongs to — before it, the server's only workspace is the+ * placeholder its registration created.+ */+describe('reading the account’s workspaces once it is signed in', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ getServer.mockResolvedValue(server({}));+ managedServerHostBlocked.mockReturnValue(null);+ });++ it('matches the workspaces after a sign-in that succeeded', async () => {+ passwordLogin.mockResolvedValue({ success: true, value: { id: 'u1' } });++ await switchServersController.passwordLogin({+ serverId: 'srv',+ email: '[email protected]',+ password: 'hunter2',+ });++ expect(reconcileServerWorkspaces).toHaveBeenCalledWith('srv');+ });++ it('does not after one that failed', async () => {+ passwordLogin.mockResolvedValue({ success: false, error: { kind: 'invalid_credentials' } });++ await switchServersController.passwordLogin({+ serverId: 'srv',+ email: '[email protected]',+ password: 'hunter2',+ });++ expect(reconcileServerWorkspaces).not.toHaveBeenCalled();+ });++ // The sign-in itself worked; reporting it as a failure would send the user+ // back to a form with nothing left to do.+ it('still reports the sign-in when the workspaces cannot be read', async () => {+ passwordLogin.mockResolvedValue({ success: true, value: { id: 'u1' } });+ reconcileServerWorkspaces.mockRejectedValue(new Error('gateway too old'));++ const result = await switchServersController.passwordLogin({+ serverId: 'srv',+ email: '[email protected]',+ password: 'hunter2',+ });++ expect(result.success).toBe(true);+ });+});++function workspaceRow(overrides: Record<string, unknown>) {+ return {+ id: 'ws',+ serverId: 'srv',+ name: 'W',+ tenantId: 'tenant-1',+ slug: 'w',+ role: 'member',+ createdAt: '',+ updatedAt: '',+ ...overrides,+ };+}++describe('resolveWorkspaces', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ // Reset rather than cleared: an earlier test leaves a rejection standing on+ // it, and `clearAllMocks` forgets the calls but keeps the behaviour.+ reconcileServerWorkspaces.mockReset().mockResolvedValue(undefined);+ getServer.mockResolvedValue(server({}));+ managedServerHostBlocked.mockReturnValue(null);+ });++ it('answers with the memberships the server confirmed', async () => {+ listWorkspacesForServer.mockResolvedValue([+ workspaceRow({ id: 'ws-1', tenantId: 't1' }),+ workspaceRow({ id: 'ws-2', tenantId: 't2' }),+ ]);++ const found = await switchServersController.resolveWorkspaces('srv');++ expect(reconcileServerWorkspaces).toHaveBeenCalledWith('srv');+ expect(found.map((w) => w.id)).toEqual(['ws-1', 'ws-2']);+ });++ // The placeholder a registration creates is not a membership, and offering it+ // would scope the window to a workspace the gateway has never heard of.+ it('leaves out the row that was never matched to a tenant', async () => {+ listWorkspacesForServer.mockResolvedValue([+ workspaceRow({ id: 'ws-1', tenantId: null, slug: null, role: null }),+ ]);++ await expect(switchServersController.resolveWorkspaces('srv')).resolves.toEqual([]);+ });++ /**+ * The row is kept locally so its agents are not silently detached, but every+ * call scoped to it is refused. Offering it puts the refusal after the click;+ * worse, left as the only answer it is the one the caller enters without+ * asking.+ */+ it('leaves out a membership the account has been removed from', async () => {+ listWorkspacesForServer.mockResolvedValue([+ workspaceRow({ id: 'ws-1', tenantId: 't1' }),+ workspaceRow({ id: 'ws-gone', tenantId: 't2', role: null }),+ ]);++ const found = await switchServersController.resolveWorkspaces('srv');++ expect(found.map((w) => w.id)).toEqual(['ws-1']);+ });++ // "You belong to nothing" and "nobody could be asked" are different answers,+ // and a caller that received the empty list for both would offer to create a+ // second workspace to someone who already has one.+ it('raises rather than answering empty when the server cannot be asked', async () => {+ reconcileServerWorkspaces.mockRejectedValue(new Error('gateway unreachable'));++ await expect(switchServersController.resolveWorkspaces('srv')).rejects.toThrow(+ 'gateway unreachable'+ );+ });+});++describe('createWorkspace', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ reconcileServerWorkspaces.mockReset().mockResolvedValue(undefined);+ getServer.mockResolvedValue(server({}));+ managedServerHostBlocked.mockReturnValue(null);+ });++ it('returns the local row for the workspace the gateway minted', async () => {+ createTenant.mockResolvedValue({ id: 't9', slug: 'acme', name: 'Acme', role: 'owner' });+ listWorkspacesForServer.mockResolvedValue([+ workspaceRow({ id: 'ws-1', tenantId: 't1' }),+ workspaceRow({ id: 'ws-9', tenantId: 't9', name: 'Acme', role: 'owner' }),+ ]);++ const created = await switchServersController.createWorkspace({+ serverId: 'srv',+ name: 'Acme',+ });++ expect(createTenant).toHaveBeenCalledWith(expect.objectContaining({ id: 'srv' }), 'Acme');+ expect(created.id).toBe('ws-9');+ });++ /**+ * The reconcile is what records the workspace, name included — so one that+ * failed has recorded nothing. Answering anyway would hand back whichever row+ * happened to be there, under a name the user did not type, and report a+ * success the install has no trace of.+ */+ it('raises when the reconcile that records the workspace fails', async () => {+ createTenant.mockResolvedValue({ id: 't9', slug: 'acme', name: 'Acme', role: 'owner' });+ reconcileServerWorkspaces.mockRejectedValue(new Error('the gateway stopped answering'));++ await expect(+ switchServersController.createWorkspace({ serverId: 'srv', name: 'Acme' })+ ).rejects.toThrow('the gateway stopped answering');+ expect(listWorkspacesForServer).not.toHaveBeenCalled();+ });++ // The workspace exists on the server either way. Returning something else, or+ // nothing, would leave the app scoped to a workspace that is not the one just+ // made — so it says so instead.+ it('raises when the new workspace did not land locally', async () => {+ createTenant.mockResolvedValue({ id: 't9', slug: 'acme', name: 'Acme', role: 'owner' });+ listWorkspacesForServer.mockResolvedValue([workspaceRow({ id: 'ws-1', tenantId: 't1' })]);++ await expect(+ switchServersController.createWorkspace({ serverId: 'srv', name: 'Acme' })+ ).rejects.toThrow('did not record it');+ });++ it('does not ask a server whose host is down to create anything', async () => {+ getServer.mockResolvedValue(server({ managed: true, managementKind: 'remote', sshHost: 'h' }));+ managedServerHostBlocked.mockReturnValue({ sshHost: 'h', status: 'unreachable' });++ await expect(+ switchServersController.createWorkspace({ serverId: 'srv', name: 'Acme' })+ ).rejects.toThrow();+ expect(createTenant).not.toHaveBeenCalled();+ });+});++describe('acceptInvitation', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ reconcileServerWorkspaces.mockReset().mockResolvedValue(undefined);+ getServer.mockResolvedValue(server({}));+ managedServerHostBlocked.mockReturnValue(null);+ });++ it('returns the local row for the workspace the invitation joined', async () => {+ acceptInvitation.mockResolvedValue({ id: 't5', slug: 'cryo', name: 'Cryo', role: 'member' });+ listWorkspacesForServer.mockResolvedValue([+ workspaceRow({ id: 'ws-1', tenantId: 't1' }),+ workspaceRow({ id: 'ws-5', tenantId: 't5', name: 'Cryo', role: 'member' }),+ ]);++ const joined = await switchServersController.acceptInvitation({+ serverId: 'srv',+ token: 'tok',+ });++ expect(acceptInvitation).toHaveBeenCalledWith(expect.objectContaining({ id: 'srv' }), 'tok');+ expect(reconcileServerWorkspaces).toHaveBeenCalledWith('srv');+ expect(joined.id).toBe('ws-5');+ });++ it('raises when the joined workspace did not land locally', async () => {+ acceptInvitation.mockResolvedValue({ id: 't5', slug: 'cryo', name: 'Cryo', role: 'member' });+ listWorkspacesForServer.mockResolvedValue([workspaceRow({ id: 'ws-1', tenantId: 't1' })]);++ await expect(+ switchServersController.acceptInvitation({ serverId: 'srv', token: 'tok' })+ ).rejects.toThrow('did not record it');+ });++ it('passes a refusal through untouched', async () => {+ acceptInvitation.mockRejectedValue(new Error('This invitation has expired'));++ await expect(+ switchServersController.acceptInvitation({ serverId: 'srv', token: 'tok' })+ ).rejects.toThrow('This invitation has expired');+ expect(reconcileServerWorkspaces).not.toHaveBeenCalled();+ });+});+describe('adding a server by URL', () => {const params = { name: 'S', gatewayUrl: 'http://gateway', apiUrl: 'http://api' };beforeEach(() => {vi.clearAllMocks();- resolveAgentServers.mockResolvedValue(undefined);});- it('keeps the add that worked when reconciling the agent links does not', async () => {- // The row is in; unlinking agents from servers that are gone is bookkeeping- // after the fact. Rejecting here would show the user a failure for a server- // they now have, and a second press would register it twice.+ it('reports the add that worked', async () => {const added = server({ id: 'new' });addServer.mockResolvedValue(added);- resolveAgentServers.mockRejectedValue(new Error('database is locked'));await expect(switchServersController.addServer(params)).resolves.toBe(added);expect(trackEvent).toHaveBeenCalledExactlyOnceWith('server_added', {@@ -316,3 +471,109 @@ describe('adding a server by URL', () => {});});});++describe('connecting to Switch Cloud', () => {+ const CLOUD = server({+ id: 'cloud',+ name: 'Switch Cloud',+ gatewayUrl: 'https://cloud.example.com',+ });++ beforeEach(() => {+ vi.unstubAllEnvs();+ vi.stubEnv('SWITCH_CLOUD_URL', 'https://cloud.example.com');+ vi.stubEnv('MAIN_VITE_SWITCH_CLOUD_URL', undefined);+ addServer.mockReset();+ findServerByGatewayUrl.mockReset();+ trackEvent.mockReset();+ });++ it('registers the Cloud once, on its one origin', async () => {+ findServerByGatewayUrl.mockResolvedValue(null);+ addServer.mockResolvedValue(CLOUD);++ await expect(switchServersController.connectToSwitchCloud()).resolves.toBe(CLOUD);++ expect(addServer).toHaveBeenCalledWith({+ name: 'Switch Cloud',+ gatewayUrl: 'https://cloud.example.com',+ apiUrl: 'https://cloud.example.com',+ });+ expect(trackEvent).toHaveBeenCalledWith('server_added', {+ server_kind: 'external',+ outcome: 'success',+ });+ });++ it('hands back the row already registered rather than adding another', async () => {+ findServerByGatewayUrl.mockResolvedValue(CLOUD);++ await expect(switchServersController.connectToSwitchCloud()).resolves.toBe(CLOUD);++ expect(addServer).not.toHaveBeenCalled();+ expect(trackEvent).not.toHaveBeenCalled();+ });++ it('raises when no Cloud is named', async () => {+ vi.stubEnv('SWITCH_CLOUD_URL', undefined);++ await expect(switchServersController.connectToSwitchCloud()).rejects.toThrow(+ 'Switch Cloud is not configured'+ );+ expect(addServer).not.toHaveBeenCalled();+ });+});++describe('finding the server an invite link is for', () => {+ const CLOUD = server({+ id: 'cloud',+ name: 'Switch Cloud',+ gatewayUrl: 'https://cloud.example.com',+ });+ const OWN = server({ id: 'own', gatewayUrl: 'https://switch.example.org' });++ beforeEach(() => {+ vi.unstubAllEnvs();+ vi.stubEnv('SWITCH_CLOUD_URL', 'https://cloud.example.com');+ vi.stubEnv('MAIN_VITE_SWITCH_CLOUD_URL', undefined);+ addServer.mockReset();+ findServerByGatewayUrl.mockReset();+ });++ it('registers Switch Cloud when the link is for it', async () => {+ findServerByGatewayUrl.mockResolvedValue(null);+ addServer.mockResolvedValue(CLOUD);++ await expect(+ switchServersController.serverForInvite('https://cloud.example.com')+ ).resolves.toEqual({ kind: 'known', server: CLOUD, via: 'cloud' });+ expect(addServer).toHaveBeenCalledOnce();+ });++ it('hands back a server already registered here', async () => {+ findServerByGatewayUrl.mockResolvedValue(OWN);++ await expect(+ switchServersController.serverForInvite('https://switch.example.org')+ ).resolves.toEqual({ kind: 'known', server: OWN, via: 'external' });+ expect(addServer).not.toHaveBeenCalled();+ });++ it('says a server it has never heard of is unknown, and registers nothing', async () => {+ findServerByGatewayUrl.mockResolvedValue(null);++ await expect(+ switchServersController.serverForInvite('https://switch.example.org')+ ).resolves.toEqual({ kind: 'unknown', origin: 'https://switch.example.org' });+ expect(addServer).not.toHaveBeenCalled();+ });++ it('does not treat a link as the Cloud when this build names none', async () => {+ vi.stubEnv('SWITCH_CLOUD_URL', undefined);+ findServerByGatewayUrl.mockResolvedValue(null);++ await expect(+ switchServersController.serverForInvite('https://cloud.example.com')+ ).resolves.toEqual({ kind: 'unknown', origin: 'https://cloud.example.com' });+ });+});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.tsindex ad69b5054..c5ada10f9 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@@ -1,177 +1,60 @@import type { Result } from '@switch-console/shared';import { propagateServerApiUrl } from '@main/core/agents/propagate-server-api-url';-import { resolveAgentServers } from '@main/core/agents/resolve-servers';import { appService } from '@main/core/app/service';-import {- isManagedServerRunning,- managedServerHostBlocked,-} from '@main/core/managed-switch-server/managed-server-status';-import { bridgePlatformOfType } from '@main/core/telemetry/bridge-platform';-import type {- TelemetryAuthMethod,- TelemetryBridgeFailure,- TelemetryBridgePlatform,- TelemetryOutcome,- TelemetryRoomAgentsDirection,- TelemetryRoomCreateFailure,- TelemetryServerKind,- TelemetrySignInFailure,-} from '@main/core/telemetry/events';-import { roomAgentsDirectionOf } from '@main/core/telemetry/narrow';+import { isManagedServerRunning } from '@main/core/managed-switch-server/managed-server-status';+import type { TelemetryAuthMethod, TelemetrySignInFailure } from '@main/core/telemetry/events';import { trackEvent } from '@main/core/telemetry/telemetry-service';+import { reconcileServerWorkspaces } from '@main/core/workspaces/reconcile-workspaces';+import { listWorkspacesForServer } from '@main/core/workspaces/workspaces-store';import { log } from '@main/lib/logger';-import { HostUnreachableError } from '@shared/core/remote-hosts/reachability';+import {+ type InviteServer,+ SWITCH_CLOUD_NAME,+ type SwitchCloudEndpoint,+} from '@shared/core/switch-servers/switch-cloud';import type {- AddressingPolicy,AddServerParams,- AgentVerifyResult,- BridgeDirectorySearchResult,- AgentIconBackfill,BundledChatSignIn,- ClaimIdentityParams,- ClaimIdentityResult,- CreateBridgeParams,- CreateBridgeResult,- CreateRoomParams,- CreateRoomResult,- DeleteBridgeParams,- DeleteBridgeResult,- LinkedIdentity,PasswordLoginParams,- RemoteAgentRoom,- RemoteAgentSummary,- RemoteBridge,- RemoteBridgeType,- RemoteExternalUser,- RemoteRoomDetail,- RemoteRoomGroup,- RemoteRoomRole,- RemoteRoomSummary,RenameServerParams,ServerConnectionStatus,SwitchAuthConfig,SwitchServer,- UpdateBridgeParams,- UpdateBridgeResult,- UpdateRoomParams,UpdateServerParams,UpdateServerResult,} from '@shared/core/switch-servers/switch-servers';+import type { JoinableWorkspaces, PendingInvitations } from '@shared/core/workspaces/invitations';+import { isWithdrawnWorkspace, type Workspace } from '@shared/core/workspaces/workspaces';import { createRPCController } from '@shared/lib/ipc/rpc';import { type LoginError, oidcLogin, passwordLogin } from './auth';-import { backfillAgentIcons } from './backfill-agent-icons';-import { withResolvedHomeUrls } from './bridge-home-url';import { bundledChatSignInFor } from './bundled-chat-sign-in';-import { createBridgeOnServer } from './create-bridge';-import { createRoomOnServer } from './create-room';import {- addRoomAgents,- agentExistsOnServer,- deleteBridge,- deleteRoom,- fetchAddressingPolicy,- fetchAgentRooms,- fetchAgents,- fetchAllExternalUsers,+ acceptInvitation,+ acceptPendingInvitation,+ joinWorkspaceByDomain,+ createTenant,fetchAuthConfig,- fetchBridges,- fetchBridgeTypes,fetchMe,- fetchMyIdentities,- fetchRoomAgentIds,- fetchRoomDetail,- fetchRoomGroups,- fetchRoomRoles,- fetchRooms,- createTemplate,- deleteTemplate,- updateTemplate,- fetchTemplateDetail,- fetchTemplateRuns,- fetchTemplates,+ fetchJoinableWorkspaces,+ fetchPendingInvitations,GatewayError,- ownsOwnerAddressedAgent,- releaseBridgeIdentity,- changeTemplateRun,- createRoomFromTemplate,- exportRoomYaml,- fetchTemplateSchema,- removeRoomAgent,- type StoredTemplateDetail,- type StoredTemplateSummary,- type TemplateVisibility,- type ProvisionFromTemplateResult,- type TemplateRun,- updateAddressingPolicy,- updateAgentIcon,- updateRoom,+ type RemoteTenant,} from './gateway-client';import { openAuthenticatedGatewayPage } from './gateway-web';-import { claimIdentityOnServer, searchDirectoryOnServer } from './identities';+import { hostUnreachable, requireReachableServer, requireServer } from './require-server';import {addServer,deleteSessionCookie,- getActiveServerId,+ findServerByGatewayUrl,getServer,listServers,removeServer,renameServer,+ serverKindOf,setActiveServerId,updateServer,- serverKindOf,} from './servers-store';-import { updateBridgeOnServer } from './update-bridge';--async function requireServer(serverId: string): Promise<SwitchServer> {- const server = await getServer(serverId);- if (!server) {- throw new Error(`No Switch server with id ${serverId}`);- }- return server;-}--/**- * The refusal a managed server's host being down produces, or null while it is- * up.- *- * Returned rather than thrown so a path that reports its own outcome can count- * the refusal before it propagates: the server is what an event describes- * itself with, and a helper that throws leaves the caller holding nothing.- */-function hostUnreachable(server: SwitchServer): HostUnreachableError | null {- const blocked = managedServerHostBlocked(server);- return blocked ? new HostUnreachableError(blocked) : null;-}--/**- * Resolve a server and refuse to touch its gateway while the host it is managed- * on is unreachable (CHOO-1780). `gatewayFetch` enforces the same rule at the- * transport, so this is for the paths that reach the gateway some other way —- * sign-in and the dashboard window — and for failing before the side effects a- * write would otherwise start.- */-async function requireReachableServer(serverId: string): Promise<SwitchServer> {- const server = await requireServer(serverId);- const unreachable = hostUnreachable(server);- if (unreachable) throw unreachable;- return server;-}--/** A bridge result's discriminant as a code. Never the message beside it. */-function bridgeFailureReason(kind: string): TelemetryBridgeFailure {- switch (kind) {- case 'created':- return 'none';- case 'unauthenticated':- return 'unauthenticated';- case 'forbidden':- return 'forbidden';- case 'invalid':- return 'invalid';- default:- return 'error';- }-}+import { requireSwitchCloudEndpoint, switchCloudEndpoint } from './switch-cloud';/** A sign-in's own error union, as a reportable code. Never its message. */const SIGN_IN_FAILURE: Record<LoginError['kind'], TelemetrySignInFailure> = {@@ -184,11 +67,49 @@ function signInFailureReason(result: Result<unknown, LoginError>): TelemetrySignreturn result.success ? 'none' : SIGN_IN_FAILURE[result.error.kind];}+/**+ * Match the server's workspaces to the memberships the account turns out to+ * have. Signing in is the first moment the gateway will answer that, and the+ * renderer reloads its workspace list straight afterwards — so it is awaited,+ * to be there when it does.+ *+ * Logged rather than raised: the sign-in itself succeeded, and reporting it as+ * a failure would send the user back to a form that has nothing left to do.+ */+async function adoptWorkspaces(server: SwitchServer): Promise<void> {+ try {+ await reconcileServerWorkspaces(server.id);+ } catch (error) {+ log.warn('workspaces: signed in, but could not read the account’s workspaces', {+ server: server.id,+ error: String(error),+ });+ }+}+/*** Reported by reason rather than by outcome: the two are the same fact, and a* sign-in that never left this machine — the server's host is down — has a* reason of its own but no result to read one from.*/+/**+ * The local row for a workspace a server has just added the account to.+ *+ * Reconciled rather than inserted here, the same as `createWorkspace`: which+ * local row a membership belongs to is decided in one place.+ */+async function recordJoined(server: SwitchServer, tenant: RemoteTenant): Promise<Workspace> {+ await reconcileServerWorkspaces(server.id);+ const workspaces = await listWorkspacesForServer(server.id);+ const joined = workspaces.find((workspace) => workspace.tenantId === tenant.id);+ if (!joined) {+ throw new Error(+ `${server.name} added you to ${tenant.name}, but this install did not record it.`+ );+ }+ return joined;+}+function reportSignIn(method: TelemetryAuthMethod,server: SwitchServer,@@ -202,76 +123,26 @@ function reportSignIn(});}-/** A room-create result's discriminant as a code. */-function roomCreateFailureReason(result: CreateRoomResult): TelemetryRoomCreateFailure {- switch (result.kind) {- case 'created':- return 'none';- case 'unauthenticated':- return 'unauthenticated';- case 'bridge-unavailable':- return 'bridge_unavailable';- case 'invalid':- return 'invalid';- default:- return 'error';- }-}--/**- * Which platform a bridge id is on.- *- * A lookup rather than a field: these operations take a bridge id, and the type- * either never appears (a delete) or appears only on success (a room). Best- * effort — an unreachable server yields `unknown` rather than failing the- * operation it is only describing.- *- * **Never awaited by a caller doing real work.** It asks the gateway, and making- * someone wait on a network round trip so we can describe what they did would- * put reporting in the path of the thing being reported. `reportWithBridge` is- * how the answer is used once it arrives.- */-function bridgePlatformOf(- server: SwitchServer,- bridgeId: string | null | undefined-): Promise<TelemetryBridgePlatform> {- if (!bridgeId) return Promise.resolve('unknown');- return fetchBridges(server)- .then((bridges) => bridgePlatformOfType(bridges.find((b) => b.id === bridgeId)?.type))- .catch((): TelemetryBridgePlatform => 'unknown');-}-/**- * Report once the platform is known, without anyone waiting for it.+ * Register Switch Cloud as a server, or hand back the one already registered.*- * The event arrives a moment after the action rather than with it, which costs- * nothing: it carries its own timestamp, taken when the work happened.+ * Idempotent because the first-run flow walks back and forth over it: going+ * back from sign-in and choosing the Cloud again must land on the same row,+ * and the gateway URL is unique, so a second insert would fail rather than+ * duplicate. Reported only when a row is actually added.*/-function reportWithBridge(- platform: Promise<TelemetryBridgePlatform>,- emit: (platform: TelemetryBridgePlatform) => void-): void {- void platform.then(emit).catch(() => {});-}--/** The same, for a room create whose other properties are already known. */-function reportRoomCreated(- server: SwitchServer,- bridgeId: string | null | undefined,- rest: {- server_kind: TelemetryServerKind;- agent_count: number;- has_instructions: boolean;- failure_reason: TelemetryRoomCreateFailure;+async function registerSwitchCloud({ url }: SwitchCloudEndpoint): Promise<SwitchServer> {+ const existing = await findServerByGatewayUrl(url);+ if (existing) return existing;+ let server: SwitchServer;+ try {+ server = await addServer({ name: SWITCH_CLOUD_NAME, gatewayUrl: url, apiUrl: url });+ } catch (error) {+ trackEvent('server_added', { server_kind: 'external', outcome: 'failure' });+ throw error;}-): void {- reportWithBridge(bridgePlatformOf(server, bridgeId), (bridge_platform) =>- trackEvent('room_created', {- ...rest,- bridge_platform,- outcome: rest.failure_reason === 'none' ? 'success' : 'failure',- })- );+ trackEvent('server_added', { server_kind: 'external', outcome: 'success' });+ return server;}export const switchServersController = createRPCController({@@ -290,23 +161,38 @@ export const switchServersController = createRPCController({throw error;}trackEvent('server_added', { server_kind: 'external', outcome: 'success' });- // The row has landed, so the server is added whatever happens next — this- // reconciliation only unlinks agents pointing at servers that are gone.- // Rejecting for it would tell the user their add failed while the store has- // already reported it as done, and leave them to press Add again, which- // registers the same server a second time rather than retrying the first.- try {- await resolveAgentServers();- } catch (error) {- log.warn('switch-servers: could not reconcile agent links after adding a server', { error });- }return server;},+ /** Where Switch Cloud is, or null when this build or run has not been told. */+ switchCloud: async (): Promise<SwitchCloudEndpoint | null> => switchCloudEndpoint(),++ /** Register Switch Cloud as a server, or hand back the one already registered. */+ connectToSwitchCloud: async (): Promise<SwitchServer> =>+ registerSwitchCloud(requireSwitchCloudEndpoint()),++ /**+ * The server an invite link points at, as far as this install can reach it.+ *+ * A server already registered here is handed back as it is. Switch Cloud is+ * registered on the spot when the link is for it, since its addresses are the+ * build's and there is nothing to ask. Any other server is unknown: an invite+ * link names the server's web address and nothing else, and where its agents+ * connect is not something to guess, so the caller has to ask.+ */+ serverForInvite: async (origin: string): Promise<InviteServer> => {+ const cloud = switchCloudEndpoint();+ if (cloud && new URL(cloud.url).origin === new URL(origin).origin) {+ return { kind: 'known', server: await registerSwitchCloud(cloud), via: 'cloud' };+ }+ const existing = await findServerByGatewayUrl(origin);+ if (existing) return { kind: 'known', server: existing, via: 'external' };+ return { kind: 'unknown', origin };+ },+updateServer: async (params: UpdateServerParams): Promise<UpdateServerResult> => {const previous = await requireServer(params.id);const server = await updateServer(params);- await resolveAgentServers();// The API URL is what an agent's SWITCH_API_ENDPOINT points at. When it// changes, cascade it to every member agent's stored config so they don't@@ -324,10 +210,113 @@ export const switchServersController = createRPCController({removeServer: (serverId: string): Promise<void> => removeServer(serverId),- getActiveServerId: (): Promise<string | null> => getActiveServerId(),-setActiveServer: (serverId: string): Promise<void> => setActiveServerId(serverId),+ /**+ * Ask a server which workspaces this account belongs to, and return the local+ * rows for them.+ *+ * Local rows rather than the gateway's answer directly, because what a caller+ * does next is scope the window to one, and that is addressed by the row's+ * id. Reconciling first is what guarantees there is a row for each.+ *+ * An empty list means the server answered and the account belongs to nothing+ * — a real answer, and the one the first-run flow turns into "create your+ * workspace". A server that cannot be asked raises instead, because the two+ * are not the same and a caller that treated them alike would offer to create+ * a second workspace to someone who already has one.+ */+ resolveWorkspaces: async (serverId: string): Promise<Workspace[]> => {+ await reconcileServerWorkspaces(serverId);+ const workspaces = await listWorkspacesForServer(serverId);+ // A withdrawn membership is a row this install still holds for a workspace+ // the account has been removed from. It is kept so its agents are not+ // silently detached, but it is not somewhere to work: every call scoped to+ // it is refused, and with exactly one of them the caller would take it+ // without asking.+ return workspaces.filter(+ (workspace) => workspace.tenantId !== null && !isWithdrawnWorkspace(workspace)+ );+ },++ /**+ * Create a workspace on a server, owned by the signed-in user.+ *+ * Addressed by server rather than by workspace — the exception the split+ * allows itself, because the thing being created is the workspace: there is+ * no id to address it by until the gateway has minted one, and on a fresh+ * install there is no other workspace to address it from either.+ *+ * Reconciling afterwards rather than inserting a row here keeps one+ * implementation of "which local row is this membership": the new workspace+ * may claim the tenant-less row a freshly registered server starts with, and+ * deciding that twice is how the two answers come to differ. It is also what+ * carries the typed name onto the row, since a matched workspace takes its+ * name from the gateway — so a reconcile that fails here leaves the name to+ * the next one rather than stranding it on the server forever, which is what+ * a rename issued from this call site would have done.+ */+ createWorkspace: async (params: { serverId: string; name: string }): Promise<Workspace> => {+ const server = await requireReachableServer(params.serverId);+ const tenant = await createTenant(server, params.name);+ await reconcileServerWorkspaces(params.serverId);++ const workspaces = await listWorkspacesForServer(params.serverId);+ const created = workspaces.find((workspace) => workspace.tenantId === tenant.id);+ if (!created) {+ throw new Error(+ `${server.name} created the workspace ${tenant.name}, but this install did not record it.`+ );+ }+ return created;+ },++ /**+ * Accept an invitation on a server, and return the local row for the+ * workspace it joined.+ */+ acceptInvitation: async (params: { serverId: string; token: string }): Promise<Workspace> => {+ const server = await requireReachableServer(params.serverId);+ return recordJoined(server, await acceptInvitation(server, params.token));+ },++ /** The invitations waiting for the signed-in account on a server. */+ listPendingInvitations: async (serverId: string): Promise<PendingInvitations> =>+ fetchPendingInvitations(await requireReachableServer(serverId)),++ /**+ * Accept an invitation addressed to the signed-in account, and return the+ * local row for the workspace it joined — the same as `acceptInvitation`,+ * with the account's address in place of the link.+ */+ acceptPendingInvitation: async (params: {+ serverId: string;+ tenantId: string;+ invitationId: string;+ }): Promise<Workspace> => {+ const server = await requireReachableServer(params.serverId);+ return recordJoined(+ server,+ await acceptPendingInvitation(server, params.tenantId, params.invitationId)+ );+ },++ /** The workspaces open to the signed-in account's domain on a server. */+ listJoinableWorkspaces: async (serverId: string): Promise<JoinableWorkspaces> =>+ fetchJoinableWorkspaces(await requireReachableServer(serverId)),++ /**+ * Join a workspace open to the signed-in account's domain, and return the+ * local row for it.+ */+ joinWorkspaceByDomain: async (params: {+ serverId: string;+ tenantId: string;+ }): Promise<Workspace> => {+ const server = await requireReachableServer(params.serverId);+ return recordJoined(server, await joinWorkspaceByDomain(server, params.tenantId));+ },+getAuthConfig: async (serverId: string): Promise<SwitchAuthConfig> =>fetchAuthConfig(await requireReachableServer(serverId)),@@ -343,6 +332,7 @@ export const switchServersController = createRPCController({}const result = await passwordLogin(server, params.email, params.password);reportSignIn('password', server, signInFailureReason(result));+ if (result.success) await adoptWorkspaces(server);return result;},@@ -355,6 +345,7 @@ export const switchServersController = createRPCController({}const result = await oidcLogin(server);reportSignIn('oidc', server, signInFailureReason(result));+ if (result.success) await adoptWorkspaces(server);return result;},@@ -404,20 +395,6 @@ export const switchServersController = createRPCController({}},- listRemoteAgents: async (serverId: string): Promise<RemoteAgentSummary[]> =>- fetchAgents(await requireServer(serverId)),-- listRemoteRooms: async (serverId: string): Promise<RemoteRoomSummary[]> =>- fetchRooms(await requireServer(serverId)),-- listRemoteBridges: async (serverId: string): Promise<RemoteBridge[]> => {- const server = await requireReachableServer(serverId);- return withResolvedHomeUrls(server, await fetchBridges(server));- },-- listRemoteBridgeTypes: async (serverId: string): Promise<RemoteBridgeType[]> =>- fetchBridgeTypes(await requireReachableServer(serverId)),-/*** The bundled chat's address and sign-in for a managed server (CHOO-1787).*@@ -427,381 +404,4 @@ export const switchServersController = createRPCController({*/getBundledChatSignIn: async (serverId: string): Promise<BundledChatSignIn> =>bundledChatSignInFor(await getServer(serverId)),-- /**- * Attach a collaboration bridge to the chosen server (CHOO-1784).- *- * `params.connectionConfig` carries platform credentials. They cross the IPC- * boundary once, on the way out, and are never written to Switch Console's disk- * or returned to the renderer — the server stores them. Keep it that way: do- * not log `params` here.- */- createBridge: async (params: CreateBridgeParams): Promise<CreateBridgeResult> => {- const server = await requireReachableServer(params.serverId);- const platform = bridgePlatformOfType(params.bridgeType);- let result: CreateBridgeResult;- try {- result = await createBridgeOnServer(server, {- bridgeType: params.bridgeType,- displayName: params.displayName,- connectionConfig: params.connectionConfig,- setAsDefault: params.setAsDefault,- channelCreationEnabled: params.channelCreationEnabled,- });- } catch (error) {- trackEvent('bridge_connected', {- bridge_platform: platform,- outcome: 'failure',- failure_reason: 'error',- });- throw error;- }- trackEvent('bridge_connected', {- bridge_platform: platform,- outcome: result.kind === 'created' ? 'success' : 'failure',- failure_reason: bridgeFailureReason(result.kind),- });- return result;- },-- /**- * Edit a bridge's operator-controlled switches — today, only whether the- * connection may create channels. Admin-only, like registering one; see- * `updateBridgeOnServer` for the recoverable-failure mapping.- */- updateBridge: async (params: UpdateBridgeParams): Promise<UpdateBridgeResult> => {- const server = await requireReachableServer(params.serverId);- return updateBridgeOnServer(server, {- bridgeId: params.bridgeId,- channelCreationEnabled: params.channelCreationEnabled,- });- },-- /**- * Disconnect a messaging app from the chosen server. Admin-only, and the- * gateway deletes every Switch room on the bridge on the way — see- * `deleteBridge`. The renderer owns the confirmation; by the time this runs- * the rooms are being given up deliberately.- */- deleteBridge: async (params: DeleteBridgeParams): Promise<DeleteBridgeResult> => {- const server = await requireReachableServer(params.serverId);- // Started before the delete, because afterwards there is no bridge left to- // read a platform from — but never waited on: see `reportWithBridge`.- const platform = bridgePlatformOf(server, params.bridgeId);- const result = await deleteBridge(server, params.bridgeId);- reportWithBridge(platform, (bridge_platform) =>- trackEvent('bridge_disconnected', {- bridge_platform,- outcome: result.kind === 'deleted' ? 'success' : 'failure',- })- );- return result;- },-- /**- * Create a room on the chosen server, owned by the signed-in user. Room- * provisioning stays server-side (`POST /gateway/rooms`); this only maps- * recoverable failures onto a typed result the modal can act on.- */- createRoom: async (params: CreateRoomParams): Promise<CreateRoomResult> => {- const server = await requireServer(params.serverId);- const report = (failure_reason: TelemetryRoomCreateFailure) =>- reportRoomCreated(server, params.bridgeId, {- server_kind: serverKindOf(server),- agent_count: params.agentIds.length,- has_instructions: (params.instructions?.trim().length ?? 0) > 0,- failure_reason,- });-- const unreachable = hostUnreachable(server);- if (unreachable) {- report('unreachable');- throw unreachable;- }-- let result: CreateRoomResult;- try {- result = await createRoomOnServer(server, {- name: params.name,- description: params.description,- instructions: params.instructions,- bridgeId: params.bridgeId,- agentIds: params.agentIds,- });- } catch (error) {- report('error');- throw error;- }-- report(roomCreateFailureReason(result));- return result;- },-- createRoomFromTemplate: async (- serverId: string,- yamlText: string,- inputs: Record<string, string | number | boolean>,- templateName?: string- ): Promise<ProvisionFromTemplateResult> =>- createRoomFromTemplate(await requireServer(serverId), yamlText, inputs, templateName),-- /** The runs the user may see, or null when the server does not record runs. */- listTemplateRuns: async (params: { serverId: string }): Promise<TemplateRun[] | null> =>- fetchTemplateRuns(await requireServer(params.serverId)),-- stopTemplateRun: async (params: { serverId: string; rootRoomId: string }): Promise<TemplateRun> =>- changeTemplateRun(await requireServer(params.serverId), params.rootRoomId, 'stop'),-- continueTemplateRun: async (params: {- serverId: string;- rootRoomId: string;- }): Promise<TemplateRun> =>- changeTemplateRun(await requireServer(params.serverId), params.rootRoomId, 'continue'),-- listTemplates: async (params: {- serverId: string;- kind?: string;- /** Narrows to templates whose name or description contains it. */- q?: string;- }): Promise<StoredTemplateSummary[]> =>- fetchTemplates(await requireServer(params.serverId), { kind: params.kind, q: params.q }),-- getTemplateDetail: async (params: {- serverId: string;- templateId: string;- }): Promise<StoredTemplateDetail> =>- fetchTemplateDetail(await requireServer(params.serverId), params.templateId),-- deleteTemplate: async (params: { serverId: string; templateId: string }): Promise<void> =>- deleteTemplate(await requireServer(params.serverId), params.templateId),-- updateTemplate: async (params: {- serverId: string;- templateId: string;- name?: string;- description?: string;- kind?: string;- content?: string;- readVisibility?: TemplateVisibility;- writeVisibility?: TemplateVisibility;- }): Promise<StoredTemplateDetail> => {- const { serverId, templateId, ...changes } = params;- return updateTemplate(await requireServer(serverId), templateId, changes);- },-- saveTemplate: async (params: {- serverId: string;- name: string;- description: string;- kind: string;- content: string;- readVisibility?: TemplateVisibility;- writeVisibility?: TemplateVisibility;- }): Promise<StoredTemplateDetail> => {- const { serverId, ...template } = params;- return createTemplate(await requireServer(serverId), template);- },-- fetchTemplateSchema: async (serverId: string): Promise<Record<string, unknown> | null> =>- fetchTemplateSchema(await requireServer(serverId)),-- exportRoomYaml: async (params: { serverId: string; roomId: string }): Promise<string> =>- exportRoomYaml(await requireServer(params.serverId), params.roomId),-- listAgentRooms: async (params: {- serverId: string;- agentId: string;- }): Promise<RemoteAgentRoom[]> =>- fetchAgentRooms(await requireServer(params.serverId), params.agentId),-- listRoomRoles: async (params: { serverId: string; roomId: string }): Promise<RemoteRoomRole[]> =>- fetchRoomRoles(await requireServer(params.serverId), params.roomId),-- listRoomAgentIds: async (params: { serverId: string; roomId: string }): Promise<string[]> =>- fetchRoomAgentIds(await requireServer(params.serverId), params.roomId),-- /** One room in full, for its configuration page. */- getRoomDetail: async (params: { serverId: string; roomId: string }): Promise<RemoteRoomDetail> =>- fetchRoomDetail(await requireServer(params.serverId), params.roomId),-- /**- * Change a room's own settings. Failures propagate as-is — a user without- * write access to the room needs the gateway's refusal, not a saved-looking- * field holding a value the server never took.- */- updateRoom: async (params: UpdateRoomParams): Promise<RemoteRoomDetail> =>- updateRoom(await requireReachableServer(params.serverId), params.roomId, {- description: params.description,- instructions: params.instructions,- }),-- /**- * Add agents to a room. Failures propagate as-is: the caller shows the- * gateway's own words (e.g. an agent whose server-side client is not running,- * which the gateway rejects) rather than a generic message.- */- addRoomAgents: async (params: {- serverId: string;- roomId: string;- agentIds: string[];- /**- * Which screen this came from. The same call serves both, and the- * one-agent-to-many-rooms screen loops it once per room — so without this,- * adding an agent to five rooms is indistinguishable from five people each- * adding one agent.- */- direction: TelemetryRoomAgentsDirection;- }): Promise<void> => {- await addRoomAgents(- await requireReachableServer(params.serverId),- params.roomId,- params.agentIds- );- trackEvent('room_agents_added', {- agent_count: params.agentIds.length,- direction: roomAgentsDirectionOf(params.direction),- });- },-- /** Remove one agent from a room. Membership only — the agent is not deleted. */- removeRoomAgent: async (params: {- serverId: string;- roomId: string;- agentId: string;- }): Promise<void> =>- removeRoomAgent(await requireReachableServer(params.serverId), params.roomId, params.agentId),-- /** Delete a room and everything in it. The gateway enforces who may. */- deleteRoom: async (params: { serverId: string; roomId: string }): Promise<void> => {- const server = await requireServer(params.serverId);- const report = (outcome: TelemetryOutcome) =>- trackEvent('room_deleted', { server_kind: serverKindOf(server), outcome });-- // A host that has gone down refuses the deletion as surely as the gateway- // can, and the event has an outcome precisely so a refusal is counted.- const unreachable = hostUnreachable(server);- if (unreachable) {- report('failure');- throw unreachable;- }-- try {- await deleteRoom(server, params.roomId);- } catch (error) {- report('failure');- throw error;- }- report('success');- },-- listRemoteRoomGroups: async (serverId: string): Promise<RemoteRoomGroup[]> =>- fetchRoomGroups(await requireServer(serverId)),-- listRemoteExternalUsers: async (serverId: string): Promise<RemoteExternalUser[]> =>- fetchAllExternalUsers(await requireServer(serverId)),-- /**- * Search a bridge's own user directory so the signed-in user can find- * themselves before they have ever posted in the workspace (CHOO-2137).- */- searchBridgeDirectory: async (params: {- serverId: string;- bridgeId: string;- query: string;- }): Promise<BridgeDirectorySearchResult> =>- searchDirectoryOnServer(- await requireReachableServer(params.serverId),- params.bridgeId,- params.query- ),-- /** Claim a messaging-app account as the signed-in Switch user's own. */- claimBridgeIdentity: async (params: ClaimIdentityParams): Promise<ClaimIdentityResult> => {- const server = await requireReachableServer(params.serverId);- const result = await claimIdentityOnServer(server, {- bridgeId: params.bridgeId,- externalUserId: params.externalUserId,- username: params.username,- });- reportWithBridge(bridgePlatformOf(server, params.bridgeId), (bridge_platform) =>- trackEvent('bridge_identity_claimed', {- bridge_platform,- outcome: result.kind === 'claimed' ? 'success' : 'failure',- })- );- return result;- },-- /** Give up a claim on a messaging-app account, leaving any other user's claim- * on it in place. `userId` is whose claim to drop — null for the signed-in- * user, which is the only one this app offers. Failures propagate: unclaiming- * is a deliberate act, and reporting success for one that did not happen- * would leave the user thinking an agent is no longer reachable by them when- * it still is. */- releaseBridgeIdentity: async (params: {- serverId: string;- bridgeId: string;- identityId: string;- userId: string | null;- }): Promise<void> =>- releaseBridgeIdentity(- await requireReachableServer(params.serverId),- params.bridgeId,- params.identityId,- params.userId- ),-- /** The messaging accounts the signed-in user has claimed on this server. */- listMyIdentities: async (serverId: string): Promise<LinkedIdentity[]> =>- fetchMyIdentities(await requireServer(serverId)),-- /** Whether the signed-in user owns an agent here that is set to answer its- * owner, which is what makes an unlinked messaging account worth warning- * about. One agent-list read, so callers need not ration it. */- ownsOwnerAddressedAgent: async (serverId: string): Promise<boolean> =>- ownsOwnerAddressedAgent(await requireServer(serverId)),-- getAddressingPolicy: async (params: {- serverId: string;- agentId: string;- }): Promise<AddressingPolicy | null> =>- fetchAddressingPolicy(await requireServer(params.serverId), params.agentId),-- updateAddressingPolicy: async (params: {- serverId: string;- agentId: string;- policy: AddressingPolicy | null;- }): Promise<void> =>- updateAddressingPolicy(await requireServer(params.serverId), params.agentId, params.policy),-- /** Give this user's icon-less agents the avatar their name generates. Runs- * once per server per app run; reports what happened so the caller can say- * when the icons did not reach the server. */- backfillAgentIcons: async (serverId: string): Promise<AgentIconBackfill> =>- backfillAgentIcons(await requireServer(serverId)),-- /** Set or clear an agent's icon. Returns the agent as the server now holds- * it, so the caller refreshes from the stored value rather than the one it- * hoped for. */- updateAgentIcon: async (params: {- serverId: string;- agentId: string;- iconUrl: string | null;- }): Promise<RemoteAgentSummary> =>- updateAgentIcon(await requireServer(params.serverId), params.agentId, params.iconUrl),-- verifyAgent: async (params: {- serverId: string;- agentId: string;- }): Promise<AgentVerifyResult> => {- const server = await requireServer(params.serverId);- try {- return (await agentExistsOnServer(server, params.agentId)) ? 'found' : 'not-found';- } catch (cause) {- if (cause instanceof GatewayError && cause.kind === 'unauthorized') {- return 'unauthenticated';- }- throw cause;- }- },});diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.tsindex 8b34fab8f..4226079fd 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.ts@@ -18,7 +18,7 @@ import type {*/export async function createBridgeOnServer(server: SwitchServer,- params: Omit<CreateBridgeParams, 'serverId'>+ params: Omit<CreateBridgeParams, 'workspaceId'>): Promise<CreateBridgeResult> {try {const bridge = await createBridge(server, {diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/create-room.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/create-room.tsindex c1bc0b288..276f7c679 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/create-room.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/create-room.ts@@ -33,7 +33,7 @@ function isBridgeFailure(detail: string): boolean {*/export async function createRoomOnServer(server: SwitchServer,- params: Omit<CreateRoomParams, 'serverId'>+ params: Omit<CreateRoomParams, 'workspaceId'>): Promise<CreateRoomResult> {try {const room = await createRoom(server, {diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/delete-server-agents.db.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/delete-server-agents.db.test.tsindex 12c9aa201..d4a78cab5 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/delete-server-agents.db.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/delete-server-agents.db.test.ts@@ -2,7 +2,7 @@ import { openFixture } from '@tooling/utils/db';import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { AppDb } from '@main/db/client';-import { agents, locations, switchServers } from '@main/db/schema';+import { agents, locations, switchServers, workspaces } from '@main/db/schema';const mocks = vi.hoisted(() => ({db: undefined as AppDb | undefined,@@ -44,6 +44,11 @@ describe('deleteAgentsForServer', () => {gatewayUrl: `https://${id}.example.com`,apiUrl: `https://api-${id}.example.com`,});+ // Deliberately not the server's id: the query has to reach the server+ // through the workspace, and identical ids would hide it not doing so.+ await fixture.db+ .insert(workspaces)+ .values({ id: `ws-${id}`, serverId: id, name: `Workspace ${id}` });}});@@ -53,9 +58,13 @@ describe('deleteAgentsForServer', () => {});async function seedAgent(id: string, serverId: string | null): Promise<void> {- await fixture.db- .insert(agents)- .values({ id, locationId: 'loc-1', name: id, providerId: 'claude', serverId });+ await fixture.db.insert(agents).values({+ id,+ locationId: 'loc-1',+ name: id,+ providerId: 'claude',+ workspaceId: serverId ? `ws-${serverId}` : null,+ });}it('deletes only the agents belonging to the given server', async () => {@@ -121,7 +130,7 @@ describe('deleteAgentsForServer', () => {const remaining = await fixture.db.select({ id: agents.id }).from(agents)- .where(eq(agents.serverId, 'other-1'));+ .where(eq(agents.workspaceId, 'ws-other-1'));expect(remaining).toEqual([{ id: 'agent-other' }]);});});diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/delete-server-agents.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/delete-server-agents.tsindex 6fd47dbde..2f0a08cf5 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/delete-server-agents.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/delete-server-agents.ts@@ -1,11 +1,11 @@import { eq } from 'drizzle-orm';import { deleteAgent } from '@main/core/agents/deleteAgent';import { db } from '@main/db/client';-import { agents } from '@main/db/schema';+import { agents, workspaces } from '@main/db/schema';import { log } from '@main/lib/logger';/**- * Delete every agent that belongs to a managed Switch server, as part of+ * Delete every agent in every workspace of a managed Switch server, as part of* destroying that server's stack.** Wiping a managed stack destroys the server-side identity behind each of its@@ -33,7 +33,8 @@ export async function deleteAgentsForServer(const rows = await db.select({ id: agents.id, name: agents.name }).from(agents)- .where(eq(agents.serverId, serverId));+ .innerJoin(workspaces, eq(agents.workspaceId, workspaces.id))+ .where(eq(workspaces.serverId, serverId));const deleted: string[] = [];const failed: { agentId: string; error: string }[] = [];diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.tsindex 374b18f79..b2a4880c7 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts@@ -13,6 +13,17 @@ import { ownerOnlyPolicy } from '@shared/core/switch-servers/owner-policy';const getSessionCookie = vi.hoisted(() => vi.fn());const refreshSession = vi.hoisted(() => vi.fn());const reauthenticateManagedServer = vi.hoisted(() => vi.fn());+const setSessionCookie = vi.hoisted(() => vi.fn());+/** The real cookie parse, so a missing cookie is read the way the client reads it. */+const extractAuthCookie = vi.hoisted(() =>+ vi.fn((setCookies: string[]) => {+ for (const raw of setCookies) {+ const [pair] = raw.split(';');+ if (pair?.startsWith('switch_auth=')) return pair.slice('switch_auth='.length);+ }+ return null;+ })+);const managedServerHostBlocked = vi.hoisted(() => vi.fn<() => HostReachability | null>(() => null));const managedServerStoppedPhase = vi.hoisted(() =>@@ -26,8 +37,8 @@ vi.mock('@main/core/managed-switch-server/managed-server-status', () => ({noteManagedServerUnanswered,}));-vi.mock('./servers-store', () => ({ getSessionCookie }));-vi.mock('./auth', () => ({ refreshSession, reauthenticateManagedServer }));+vi.mock('./servers-store', () => ({ getSessionCookie, setSessionCookie }));+vi.mock('./auth', () => ({ refreshSession, reauthenticateManagedServer, extractAuthCookie }));vi.mock('./console-identity', () => ({consoleIdentityHeaders: async (server: { managed: boolean }) =>server.managed@@ -36,6 +47,19 @@ vi.mock('./console-identity', () => ({}));const {+ acceptInvitation,+ acceptPendingInvitation,+ beginMessagingAppInstall,+ fetchInstallablePlatforms,+ fetchPendingInvitations,+ fetchJoinableWorkspaces,+ joinWorkspaceByDomain,+ fetchJoinDomains,+ addJoinDomain,+ removeJoinDomain,+ createInvitation,+ fetchInvitations,+ fetchInviteEmailEnabled,createRoom,deleteBridge,fetchBridges,@@ -820,3 +844,415 @@ describe('deleteBridge', () => {await expect(deleteBridge(SERVER, 'b1')).rejects.toMatchObject({ status: 500 });});});++describe('acceptInvitation', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.stubGlobal('fetch', fetchMock);+ getSessionCookie.mockResolvedValue(makeJwt(24 * 60 * 60));+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ function acceptedResponse(setCookies: string[]): Response {+ return {+ status: 200,+ ok: true,+ json: async () => ({ id: 't1', slug: 'cryo', name: 'Cryo Team', role: 'member' }),+ headers: { getSetCookie: () => setCookies },+ text: async () => '',+ } as unknown as Response;+ }++ it('sends the token in the body and keeps the workspace-scoped cookie', async () => {+ fetchMock.mockResolvedValue(+ acceptedResponse(['switch_auth=scoped; Path=/; HttpOnly']) as never+ );++ const tenant = await acceptInvitation(SERVER, 'tok-1');++ const [url, init] = fetchMock.mock.calls[0] as unknown as [+ string,+ { method: string; body: string },+ ];+ expect(url).toBe('https://switch.example.com/gateway/invitations/accept');+ expect(init.method).toBe('POST');+ expect(JSON.parse(init.body)).toEqual({ token: 'tok-1' });+ expect(setSessionCookie).toHaveBeenCalledExactlyOnceWith('srv-1', 'scoped');+ expect(tenant).toEqual({ id: 't1', slug: 'cryo', name: 'Cryo Team', role: 'member' });+ });++ it('raises when the server joins the workspace but sends no cookie', async () => {+ fetchMock.mockResolvedValue(acceptedResponse([]) as never);++ await expect(acceptInvitation(SERVER, 'tok-1')).rejects.toThrow(/no session cookie/);+ expect(setSessionCookie).not.toHaveBeenCalled();+ });++ it("surfaces the server's reason for refusing", async () => {+ fetchMock.mockResolvedValue(+ errorResponse(403, JSON.stringify({ detail: 'This invitation has expired' })) as never+ );++ await expect(acceptInvitation(SERVER, 'tok-1')).rejects.toMatchObject({+ status: 403,+ detail: 'This invitation has expired',+ });+ });+});++describe("installing the deployment's own messaging app", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.stubGlobal('fetch', fetchMock);+ getSessionCookie.mockResolvedValue(makeJwt(24 * 60 * 60));+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('lists the platforms the deployment has an app for', async () => {+ fetchMock.mockResolvedValue(jsonResponse({ platforms: ['slack'] }) as never);++ await expect(fetchInstallablePlatforms(SERVER)).resolves.toEqual(['slack']);+ expect((fetchMock.mock.calls[0] as unknown as [string])[0]).toBe(+ 'https://switch.example.com/gateway/messaging-apps'+ );+ });++ it('reads a server without the route as having no app to install', async () => {+ fetchMock.mockResolvedValue(errorResponse(404, '{"detail":"Not Found"}') as never);++ await expect(fetchInstallablePlatforms(SERVER)).resolves.toEqual([]);+ });++ it('raises on any other failure', async () => {+ fetchMock.mockResolvedValue(errorResponse(403, '{"detail":"Forbidden"}') as never);++ await expect(fetchInstallablePlatforms(SERVER)).rejects.toMatchObject({ status: 403 });+ });++ it('starts an install and returns the consent URL', async () => {+ fetchMock.mockResolvedValue(+ jsonResponse({ authorize_url: 'https://slack.example/oauth?state=s' }) as never+ );++ await expect(beginMessagingAppInstall(SERVER, 'slack')).resolves.toBe(+ 'https://slack.example/oauth?state=s'+ );+ const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];+ expect(url).toBe('https://switch.example.com/gateway/messaging-apps/slack/install');+ expect(init.method).toBe('POST');+ });++ it('raises when the deployment has no app for the platform', async () => {+ fetchMock.mockResolvedValue(errorResponse(501, '{"detail":"no app"}') as never);++ await expect(beginMessagingAppInstall(SERVER, 'slack')).rejects.toMatchObject({ status: 501 });+ });+});++describe('invitations addressed to the signed-in account', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.stubGlobal('fetch', fetchMock);+ getSessionCookie.mockResolvedValue(makeJwt(24 * 60 * 60));+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('lists them with the workspace and who invited you', async () => {+ fetchMock.mockResolvedValue(+ jsonResponse([+ {+ id: 'inv-1',+ tenant_id: 't1',+ tenant_slug: 'cryo',+ tenant_name: 'Cryo Team',+ role: 'admin',+ expires_at: '2026-12-01T00:00:00+00:00',+ invited_by: 'Ada',+ created_at: '2026-11-24T00:00:00+00:00',+ },+ ]) as never+ );++ const listed = await fetchPendingInvitations(SERVER);++ expect((fetchMock.mock.calls[0] as unknown as [string])[0]).toBe(+ 'https://switch.example.com/gateway/invitations/mine'+ );+ expect(listed).toEqual({+ kind: 'listed',+ invitations: [+ {+ id: 'inv-1',+ tenantId: 't1',+ workspaceName: 'Cryo Team',+ role: 'admin',+ expiresAt: '2026-12-01T00:00:00.000Z',+ invitedBy: 'Ada',+ },+ ],+ });+ });++ it('reads a server without the route as unable to say, not as none', async () => {+ fetchMock.mockResolvedValue(errorResponse(404, '{"detail":"Not Found"}') as never);++ await expect(fetchPendingInvitations(SERVER)).resolves.toEqual({ kind: 'unsupported' });+ });++ it('raises on any other failure', async () => {+ fetchMock.mockResolvedValue(errorResponse(500, 'boom') as never);++ await expect(fetchPendingInvitations(SERVER)).rejects.toMatchObject({ status: 500 });+ });++ it('accepts one by its workspace and id and keeps the workspace-scoped cookie', async () => {+ fetchMock.mockResolvedValue({+ status: 200,+ ok: true,+ json: async () => ({ id: 't1', slug: 'cryo', name: 'Cryo Team', role: 'member' }),+ headers: { getSetCookie: () => ['switch_auth=scoped; Path=/; HttpOnly'] },+ text: async () => '',+ } as never);++ const tenant = await acceptPendingInvitation(SERVER, 't1', 'inv-1');++ const [url, init] = fetchMock.mock.calls[0] as unknown as [+ string,+ { method: string; body: string },+ ];+ expect(url).toBe('https://switch.example.com/gateway/invitations/mine/accept');+ expect(init.method).toBe('POST');+ expect(JSON.parse(init.body)).toEqual({ tenant_id: 't1', invitation_id: 'inv-1' });+ expect(setSessionCookie).toHaveBeenCalledExactlyOnceWith('srv-1', 'scoped');+ expect(tenant).toEqual({ id: 't1', slug: 'cryo', name: 'Cryo Team', role: 'member' });+ });+});++describe('joining a workspace by e-mail domain', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.stubGlobal('fetch', fetchMock);+ getSessionCookie.mockResolvedValue(makeJwt(24 * 60 * 60));+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('lists the workspaces open to your domain', async () => {+ fetchMock.mockResolvedValue(+ jsonResponse([+ {+ tenant_id: 't9',+ tenant_slug: 'skunk',+ tenant_name: 'Skunkworks',+ domain: 'acme.example',+ },+ ]) as never+ );++ const listed = await fetchJoinableWorkspaces(SERVER);++ expect((fetchMock.mock.calls[0] as unknown as [string])[0]).toBe(+ 'https://switch.example.com/gateway/joinable-tenants'+ );+ expect(listed).toEqual({+ kind: 'listed',+ workspaces: [{ tenantId: 't9', workspaceName: 'Skunkworks', domain: 'acme.example' }],+ });+ });++ it('reads a server without the route as unable to say, not as none', async () => {+ fetchMock.mockResolvedValue(errorResponse(404, '{"detail":"Not Found"}') as never);++ await expect(fetchJoinableWorkspaces(SERVER)).resolves.toEqual({ kind: 'unsupported' });+ await expect(fetchJoinDomains(SERVER, 't1')).resolves.toEqual({ kind: 'unsupported' });+ });++ it('joins one and keeps the workspace-scoped cookie', async () => {+ fetchMock.mockResolvedValue({+ status: 200,+ ok: true,+ json: async () => ({ id: 't9', slug: 'skunk', name: 'Skunkworks', role: 'member' }),+ headers: { getSetCookie: () => ['switch_auth=scoped; Path=/; HttpOnly'] },+ text: async () => '',+ } as never);++ const tenant = await joinWorkspaceByDomain(SERVER, 't9');++ const [url, init] = fetchMock.mock.calls[0] as unknown as [string, { method: string }];+ expect(url).toBe('https://switch.example.com/gateway/joinable-tenants/t9/join');+ expect(init.method).toBe('POST');+ expect(setSessionCookie).toHaveBeenCalledExactlyOnceWith('srv-1', 'scoped');+ expect(tenant).toEqual({ id: 't9', slug: 'skunk', name: 'Skunkworks', role: 'member' });+ });++ it("reads a workspace's domains and the admin's own", async () => {+ fetchMock.mockResolvedValue(+ jsonResponse({+ domains: [+ { domain: 'acme.example', created_by: 'u1', created_at: '2026-11-24T00:00:00+00:00' },+ ],+ own_domain: 'acme.example',+ own_domain_refusal: null,+ }) as never+ );++ await expect(fetchJoinDomains(SERVER, 't1')).resolves.toEqual({+ kind: 'listed',+ domains: ['acme.example'],+ ownDomain: 'acme.example',+ ownDomainRefusal: null,+ });+ expect((fetchMock.mock.calls[0] as unknown as [string])[0]).toBe(+ 'https://switch.example.com/gateway/tenants/t1/join-domains'+ );+ });++ it('adds and removes a domain', async () => {+ fetchMock.mockResolvedValue(jsonResponse({}) as never);++ await addJoinDomain(SERVER, 't1', 'acme.example');+ await removeJoinDomain(SERVER, 't1', 'acme.example');++ const calls = fetchMock.mock.calls as unknown as [string, { method: string; body?: string }][];+ expect(calls[0]![0]).toBe('https://switch.example.com/gateway/tenants/t1/join-domains');+ expect(calls[0]![1].method).toBe('POST');+ expect(JSON.parse(calls[0]![1].body!)).toEqual({ domain: 'acme.example' });+ expect(calls[1]![0]).toBe(+ 'https://switch.example.com/gateway/tenants/t1/join-domains/acme.example'+ );+ expect(calls[1]![1].method).toBe('DELETE');+ });++ it("surfaces the server's refusal of another domain", async () => {+ fetchMock.mockResolvedValue(+ errorResponse(+ 400,+ JSON.stringify({+ detail: 'You can only open the workspace to the domain of your own address, acme.example',+ })+ ) as never+ );++ await expect(addJoinDomain(SERVER, 't1', 'other.example')).rejects.toMatchObject({+ status: 400,+ });+ });+});++describe('workspace invitations', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.stubGlobal('fetch', fetchMock);+ getSessionCookie.mockResolvedValue(makeJwt(24 * 60 * 60));+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ function jsonResponse(body: unknown): Response {+ return {+ status: 200,+ ok: true,+ json: async () => body,+ headers: { getSetCookie: () => [] },+ text: async () => '',+ } as unknown as Response;+ }++ const ROW = {+ id: 'inv-1',+ role: 'admin',+ email: '[email protected]',+ expires_at: '2026-10-05 12:00:00.123456+00:00',+ uses_remaining: 1,+ revoked_at: null,+ created_by: 'u1',+ created_at: '2026-09-28 12:00:00+00:00',+ };++ it("reads the server's timestamps as ISO, whatever separator it writes", async () => {+ fetchMock.mockResolvedValue(jsonResponse([ROW]) as never);++ const [invitation] = await fetchInvitations(SERVER, 'tenant 1');++ expect((fetchMock.mock.calls[0] as unknown as [string])[0]).toBe(+ 'https://switch.example.com/gateway/tenants/tenant%201/invitations'+ );+ expect(invitation).toEqual({+ id: 'inv-1',+ role: 'admin',+ email: '[email protected]',+ expiresAt: '2026-10-05T12:00:00.123Z',+ usesRemaining: 1,+ revokedAt: null,+ createdAt: '2026-09-28T12:00:00.000Z',+ });+ });++ it('raises on a timestamp it cannot read rather than showing an invalid date', async () => {+ fetchMock.mockResolvedValue(jsonResponse([{ ...ROW, expires_at: 'soon' }]) as never);++ await expect(fetchInvitations(SERVER, 't1')).rejects.toThrow(/unreadable timestamp/);+ });++ it('posts the invitation and returns the token and what became of the e-mail', async () => {+ fetchMock.mockResolvedValue(+ jsonResponse({ ...ROW, token: 'tok-1', email_delivery: 'not_configured' }) as never+ );++ const created = await createInvitation(SERVER, 't1', {+ role: 'admin',+ email: '[email protected]',+ expiresInHours: 48,+ usesRemaining: 1,+ });++ const [, init] = fetchMock.mock.calls[0] as unknown as [+ string,+ { method: string; body: string },+ ];+ expect(init.method).toBe('POST');+ expect(JSON.parse(init.body)).toEqual({+ role: 'admin',+ email: '[email protected]',+ expires_in_hours: 48,+ uses_remaining: 1,+ });+ expect(created.token).toBe('tok-1');+ expect(created.emailDelivery).toBe('not_configured');+ });++ it('reads a server older than e-mailed invitations as not sending them', async () => {+ fetchMock.mockResolvedValue(jsonResponse({ state: 'ready' }) as never);+ await expect(fetchInviteEmailEnabled(SERVER)).resolves.toBeNull();++ fetchMock.mockResolvedValue(errorResponse(404, '{"detail":"Not Found"}') as never);+ await expect(fetchInviteEmailEnabled(SERVER)).resolves.toBeNull();+ });++ it('keeps the link when an older server says nothing about the e-mail', async () => {+ fetchMock.mockResolvedValue(jsonResponse({ ...ROW, token: 'tok-1' }) as never);++ const created = await createInvitation(SERVER, 't1', {+ role: 'member',+ email: '[email protected]',+ expiresInHours: 48,+ usesRemaining: 1,+ });++ expect(created.token).toBe('tok-1');+ expect(created.emailDelivery).toBe('unsupported');+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.tsindex c5467bbd2..bcf3d96df 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@@ -4,6 +4,7 @@ import {managedServerStoppedPhase,noteManagedServerUnanswered,} from '@main/core/managed-switch-server/managed-server-status';+import { assertedTenant } from '@main/core/workspaces/asserted-tenant';import { ManagedServerStoppedError } from '@shared/core/managed-switch-server/managed-switch-server';import { HostUnreachableError } from '@shared/core/remote-hosts/reachability';import { policyNamesOwner } from '@shared/core/switch-servers/owner-policy';@@ -27,9 +28,17 @@ import type {SwitchServerDeclaration,SwitchUser,} from '@shared/core/switch-servers/switch-servers';-import { reauthenticateManagedServer, refreshSession } from './auth';+import type {+ Invitation,+ InvitationEmailDelivery,+ JoinableWorkspaces,+ PendingInvitations,+ WorkspaceJoinDomains,+} from '@shared/core/workspaces/invitations';+import type { WorkspaceRole } from '@shared/core/workspaces/workspaces';+import { extractAuthCookie, reauthenticateManagedServer, refreshSession } from './auth';import { consoleIdentityHeaders } from './console-identity';-import { getSessionCookie } from './servers-store';+import { getSessionCookie, setSessionCookie } from './servers-store';/** The gateway management API is mounted under `/gateway` on the server. */function gatewayUrl(server: SwitchServer, path: string): string {@@ -60,6 +69,30 @@ function decodeJwtExpMs(jwt: string): number | null {}}+/**+ * Read the `tenant_id` claim out of a JWT without verifying it. Returns null+ * for a malformed token, and for a session that has selected no tenant — the+ * gateway mints the claim as null until `/tenants/{id}/switch` is called.+ *+ * Unverified is the right level here: the claim only ever *selects* which+ * workspace a call is scoped to, and the gateway re-checks membership against+ * a live row on every request, so nothing this reads can grant access. It is+ * read to know whether the selection already matches the workspace being+ * addressed, or whether a switch has to happen first.+ */+export function decodeJwtTenantId(jwt: string): string | null {+ const parts = jwt.split('.');+ if (parts.length !== 3) return null;+ try {+ const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8')) as {+ tenant_id?: unknown;+ };+ return typeof payload.tenant_id === 'string' ? payload.tenant_id : null;+ } catch {+ return null;+ }+}+/** Dedupe concurrent renewals per server so a burst of authenticated calls* triggers at most one refresh round-trip (and one cookie write). */const inflightRefresh = new Map<string, Promise<string | null>>();@@ -141,12 +174,42 @@ async function resolveAuthCookie(server: SwitchServer): Promise<string> {return renewIfExpiring(server, stored);}if (server.managed) {- const minted = await reauthenticateManagedServer(server);+ const minted = await silentLogin(server);if (minted) return minted;}throw new GatewayError('unauthorized', 'Not signed in to this Switch server.');}+/**+ * Servers whose silent re-login is putting a tenant back, so the switch it makes+ * does not try to re-login its way out of its own 401.+ */+const restoringTenant = new Set<string>();++/**+ * Log a managed server back in silently, and re-select the workspace the calls+ * in flight on it were addressing.+ *+ * A login cookie names no tenant. Handed back on its own it would answer the+ * rest of a workspace-scoped call with the account's default workspace —+ * succeeding, and looking exactly like the answer that was asked for.+ */+async function silentLogin(server: SwitchServer): Promise<string | null> {+ const minted = await reauthenticateManagedServer(server);+ if (!minted) return null;+ const tenantId = assertedTenant(server.id);+ if (tenantId === null || restoringTenant.has(server.id)) return minted;+ restoringTenant.add(server.id);+ try {+ await switchTenant(server, tenantId);+ } finally {+ restoringTenant.delete(server.id);+ }+ // `switchTenant` stores the scoped cookie; the minted one it replaced would+ // send this very call to the wrong workspace.+ return (await getSessionCookie(server.id)) ?? minted;+}+async function gatewayFetch(server: SwitchServer,path: string,@@ -203,7 +266,7 @@ async function gatewayFetch(// We hold its admin creds, so re-login and retry the call once rather than// bouncing the user to a sign-in screen for a password they never saw.if (response.status === 401 && options.authenticated && server.managed) {- const renewed = await reauthenticateManagedServer(server);+ const renewed = await silentLogin(server);if (renewed) {response = await sendOnce(renewed);}@@ -281,6 +344,396 @@ export async function fetchMe(server: SwitchServer): Promise<SwitchUser> {return mapUser((await res.json()) as UserResponseJson);}+/** A tenant the signed-in user belongs to, as `GET /tenants` reports it. */+export type RemoteTenant = {+ id: string;+ slug: string;+ name: string;+ role: WorkspaceRole;+};++function mapRole(raw: unknown): WorkspaceRole {+ if (raw === 'owner' || raw === 'admin' || raw === 'member') return raw;+ throw new GatewayError('http', `Switch server reported an unknown workspace role: ${raw}`);+}++/**+ * The tenants the signed-in user belongs to. Answered without a tenant being+ * selected on the session, which is what makes it the entry point: a user with+ * several memberships has none selected until they pick one.+ */+export async function fetchTenants(server: SwitchServer): Promise<RemoteTenant[]> {+ const res = await gatewayFetch(server, '/tenants', { authenticated: true });+ const json = (await res.json()) as Array<{+ id: string;+ slug: string;+ name: string;+ role: string;+ }>;+ return json.map((t) => ({ id: t.id, slug: t.slug, name: t.name, role: mapRole(t.role) }));+}++/**+ * Create a workspace on this server, owned by the signed-in user.+ *+ * The gateway derives the slug from the name and refuses a name whose slug is+ * already taken, so the caller shows that refusal rather than retrying under a+ * name the user did not choose.+ */+export async function createTenant(server: SwitchServer, name: string): Promise<RemoteTenant> {+ const res = await gatewayFetch(server, '/tenants', {+ authenticated: true,+ method: 'POST',+ body: { name },+ });+ const json = (await res.json()) as { id: string; slug: string; name: string; role: string };+ return { id: json.id, slug: json.slug, name: json.name, role: mapRole(json.role) };+}++/**+ * Select a tenant for this server's session, persisting the re-minted cookie.+ *+ * One session holds one selected tenant, so this is what makes a call scoped to+ * a particular workspace rather than to whichever one was picked last. The+ * gateway verifies membership before it mints, so a refusal here is a real+ * answer — it is raised rather than swallowed, because the alternative is+ * issuing the caller's next request against somebody else's workspace.+ */+export async function switchTenant(server: SwitchServer, tenantId: string): Promise<void> {+ const res = await gatewayFetch(server, `/tenants/${encodeURIComponent(tenantId)}/switch`, {+ authenticated: true,+ method: 'POST',+ });+ const cookie = extractAuthCookie(res.headers.getSetCookie());+ if (!cookie) {+ throw new GatewayError(+ 'http',+ `${server.name} accepted the workspace selection but returned no session cookie.`+ );+ }+ await setSessionCookie(server.id, cookie);+}++/**+ * Accept an invitation to a workspace, joining it.+ *+ * The token goes in the body, never the path: it is a bearer credential. The+ * gateway answers with a session cookie scoped to the workspace joined, which+ * is kept for the same reason `switchTenant` keeps its own — the next call made+ * for that workspace has to reach it, not whichever one was selected before.+ *+ * Accepting an invitation to a workspace the account is already in is not an+ * error: the gateway returns the existing membership and spends nothing.+ */+export async function acceptInvitation(server: SwitchServer, token: string): Promise<RemoteTenant> {+ const res = await gatewayFetch(server, '/invitations/accept', {+ authenticated: true,+ method: 'POST',+ body: { token },+ });+ return joinedTenant(server, res);+}++/**+ * Accept an invitation addressed to the signed-in account, by id.+ *+ * Answers exactly as {@link acceptInvitation} does, session cookie included:+ * the server switches the session into the workspace it joined.+ */+export async function acceptPendingInvitation(+ server: SwitchServer,+ tenantId: string,+ invitationId: string+): Promise<RemoteTenant> {+ const res = await gatewayFetch(server, '/invitations/mine/accept', {+ authenticated: true,+ method: 'POST',+ body: { tenant_id: tenantId, invitation_id: invitationId },+ });+ return joinedTenant(server, res);+}++type PendingInvitationJson = {+ id: string;+ tenant_id: string;+ tenant_slug: string;+ tenant_name: string;+ role: string;+ expires_at: string;+ invited_by: string;+ created_at: string;+};++/**+ * The invitations addressed to the signed-in account, in workspaces it is not in.+ *+ * A 404 is a server from before the route existed, and is answered as+ * `unsupported` rather than raised: the account is signed in and the rest of+ * the server works, so it is a feature the server lacks, not a failure. Every+ * other refusal is raised.+ */+export async function fetchPendingInvitations(server: SwitchServer): Promise<PendingInvitations> {+ let res: Response;+ try {+ res = await gatewayFetch(server, '/invitations/mine', { authenticated: true });+ } catch (cause) {+ if (cause instanceof GatewayError && cause.status === 404) return { kind: 'unsupported' };+ throw cause;+ }+ const json = (await res.json()) as PendingInvitationJson[];+ return {+ kind: 'listed',+ invitations: json.map((i) => ({+ id: i.id,+ tenantId: i.tenant_id,+ workspaceName: i.tenant_name,+ role: mapRole(i.role),+ expiresAt: isoTimestamp(i.expires_at),+ invitedBy: i.invited_by,+ })),+ };+}++async function joinedTenant(server: SwitchServer, res: Response): Promise<RemoteTenant> {+ const json = (await res.json()) as { id: string; slug: string; name: string; role: string };+ const cookie = extractAuthCookie(res.headers.getSetCookie());+ if (!cookie) {+ throw new GatewayError(+ 'http',+ `${server.name} accepted the invitation but returned no session cookie.`+ );+ }+ await setSessionCookie(server.id, cookie);+ return { id: json.id, slug: json.slug, name: json.name, role: mapRole(json.role) };+}++type InvitationJson = {+ id: string;+ role: string;+ email: string | null;+ expires_at: string;+ uses_remaining: number;+ revoked_at: string | null;+ created_at: string;+};++/**+ * A gateway timestamp as ISO 8601.+ *+ * The invitation routes write Python's `str(datetime)`, with a space where ISO+ * has a `T`. Normalised here so every reader downstream can hand it to `Date`;+ * one that still does not parse is raised, since showing an expiry of "Invalid+ * Date" would leave an admin unable to tell a live invitation from a dead one.+ */+function isoTimestamp(raw: string): string {+ const parsed = new Date(raw.replace(' ', 'T'));+ if (Number.isNaN(parsed.getTime())) {+ throw new GatewayError('http', `Switch server reported an unreadable timestamp: ${raw}`);+ }+ return parsed.toISOString();+}++function mapInvitation(json: InvitationJson): Invitation {+ return {+ id: json.id,+ role: mapRole(json.role),+ email: json.email,+ expiresAt: isoTimestamp(json.expires_at),+ usesRemaining: json.uses_remaining,+ revokedAt: json.revoked_at === null ? null : isoTimestamp(json.revoked_at),+ createdAt: isoTimestamp(json.created_at),+ };+}++function mapDelivery(raw: unknown): InvitationEmailDelivery {+ // A server older than e-mailed invitations leaves the field out. Refusing it+ // would lose the link of an invitation the server has already made.+ if (raw === undefined) return 'unsupported';+ if (raw === 'sent' || raw === 'not_configured' || raw === 'failed' || raw === 'not_requested') {+ return raw;+ }+ throw new GatewayError('http', `Switch server reported an unknown e-mail delivery: ${raw}`);+}++/**+ * The workspaces open to the domain of the signed-in account's address.+ *+ * A server without the route answers 404, which is read as unable to say+ * rather than as none.+ */+export async function fetchJoinableWorkspaces(server: SwitchServer): Promise<JoinableWorkspaces> {+ let res: Response;+ try {+ res = await gatewayFetch(server, '/joinable-tenants', { authenticated: true });+ } catch (cause) {+ if (cause instanceof GatewayError && cause.status === 404) return { kind: 'unsupported' };+ throw cause;+ }+ const json = (await res.json()) as { tenant_id: string; tenant_name: string; domain: string }[];+ return {+ kind: 'listed',+ workspaces: json.map((w) => ({+ tenantId: w.tenant_id,+ workspaceName: w.tenant_name,+ domain: w.domain,+ })),+ };+}++/**+ * Join a workspace open to the account's domain, and switch the session into+ * it — the same scoped cookie accepting an invitation stores.+ */+export async function joinWorkspaceByDomain(+ server: SwitchServer,+ tenantId: string+): Promise<RemoteTenant> {+ const res = await gatewayFetch(server, `/joinable-tenants/${encodeURIComponent(tenantId)}/join`, {+ authenticated: true,+ method: 'POST',+ });+ return joinedTenant(server, res);+}++function joinDomainsPath(tenantId: string): string {+ return `/tenants/${encodeURIComponent(tenantId)}/join-domains`;+}++/** The domains a workspace is open to. Admins and owners only. */+export async function fetchJoinDomains(+ server: SwitchServer,+ tenantId: string+): Promise<WorkspaceJoinDomains> {+ let res: Response;+ try {+ res = await gatewayFetch(server, joinDomainsPath(tenantId), { authenticated: true });+ } catch (cause) {+ if (cause instanceof GatewayError && cause.status === 404) return { kind: 'unsupported' };+ throw cause;+ }+ const json = (await res.json()) as {+ domains: { domain: string }[];+ own_domain: string;+ own_domain_refusal: string | null;+ };+ return {+ kind: 'listed',+ domains: json.domains.map((d) => d.domain),+ ownDomain: json.own_domain,+ ownDomainRefusal: json.own_domain_refusal,+ };+}++export async function addJoinDomain(+ server: SwitchServer,+ tenantId: string,+ domain: string+): Promise<void> {+ await gatewayFetch(server, joinDomainsPath(tenantId), {+ authenticated: true,+ method: 'POST',+ body: { domain },+ });+}++export async function removeJoinDomain(+ server: SwitchServer,+ tenantId: string,+ domain: string+): Promise<void> {+ await gatewayFetch(server, `${joinDomainsPath(tenantId)}/${encodeURIComponent(domain)}`, {+ authenticated: true,+ method: 'DELETE',+ });+}++function invitationsPath(tenantId: string): string {+ return `/tenants/${encodeURIComponent(tenantId)}/invitations`;+}++/** Every invitation to a workspace, revoked and spent ones included. Admins and owners only. */+export async function fetchInvitations(+ server: SwitchServer,+ tenantId: string+): Promise<Invitation[]> {+ const res = await gatewayFetch(server, invitationsPath(tenantId), { authenticated: true });+ return ((await res.json()) as InvitationJson[]).map(mapInvitation);+}++/**+ * Mint an invitation to a workspace, and e-mail it when it names an address+ * and the server has mail set up.+ *+ * The token comes back once, here, and never again: the server stores a hash.+ */+export async function createInvitation(+ server: SwitchServer,+ tenantId: string,+ params: {+ role: WorkspaceRole;+ email: string | null;+ expiresInHours: number;+ usesRemaining: number;+ }+): Promise<{ invitation: Invitation; token: string; emailDelivery: InvitationEmailDelivery }> {+ const res = await gatewayFetch(server, invitationsPath(tenantId), {+ authenticated: true,+ method: 'POST',+ body: {+ role: params.role,+ email: params.email,+ expires_in_hours: params.expiresInHours,+ uses_remaining: params.usesRemaining,+ },+ });+ const json = (await res.json()) as InvitationJson & { token: string; email_delivery?: string };+ return {+ invitation: mapInvitation(json),+ token: json.token,+ emailDelivery: mapDelivery(json.email_delivery),+ };+}++export async function revokeInvitation(+ server: SwitchServer,+ tenantId: string,+ invitationId: string+): Promise<Invitation> {+ const res = await gatewayFetch(+ server,+ `${invitationsPath(tenantId)}/${encodeURIComponent(invitationId)}`,+ { authenticated: true, method: 'DELETE' }+ );+ return mapInvitation((await res.json()) as InvitationJson);+}++/**+ * Whether this server e-mails an invitation that names an address, or only+ * mints the link for the admin to send.+ *+ * Null on a server older than e-mailed invitations: one without the session+ * route answers 404, and one with it but without the field predates the+ * feature. Neither sends an e-mail.+ */+export async function fetchInviteEmailEnabled(server: SwitchServer): Promise<boolean | null> {+ let res: Response;+ try {+ res = await gatewayFetch(server, '/auth/session', { authenticated: true });+ } catch (cause) {+ if (cause instanceof GatewayError && cause.status === 404) return null;+ throw cause;+ }+ const json = (await res.json()) as { invite_email_enabled?: unknown };+ if (json.invite_email_enabled === undefined) return null;+ if (typeof json.invite_email_enabled !== 'boolean') {+ throw new GatewayError(+ 'http',+ `${server.name} reported an unreadable invite_email_enabled: ${String(json.invite_email_enabled)}`+ );+ }+ return json.invite_email_enabled;+}+/** Options for `registerKnownAgent`, matching the gateway's* `RegisterKnownAgentRequest.options`. The gateway validates these against the* options schema of the `agent_type` being registered and ignores keys that type@@ -579,6 +1032,47 @@ export async function fetchBridges(server: SwitchServer): Promise<RemoteBridge[]return json.map(mapBridge);}+/**+ * The messaging platforms this deployment has its own app for, which a+ * workspace can install with the platform's OAuth consent screen instead of+ * registering an app and pasting its tokens. Empty on a deployment that+ * registered none.+ *+ * A 404 is a server from before the route existed; it has no app to install+ * either, so it answers empty rather than failing the connect dialog.+ */+export async function fetchInstallablePlatforms(server: SwitchServer): Promise<string[]> {+ let res: Response;+ try {+ res = await gatewayFetch(server, '/messaging-apps', { authenticated: true });+ } catch (cause) {+ if (cause instanceof GatewayError && cause.status === 404) return [];+ throw cause;+ }+ const json = (await res.json()) as { platforms: string[] };+ return json.platforms;+}++/**+ * Start installing the deployment's app for `platform` into the workspace the+ * session is bound to. Returns the platform's consent URL, which must be+ * opened in a real browser: the platform refuses to render it in a frame, and+ * the server finishes the install on its own public callback, so nothing comes+ * back to Switch Console but the new bridge.+ */+export async function beginMessagingAppInstall(+ server: SwitchServer,+ platform: string+): Promise<string> {+ const res = await gatewayFetch(+ server,+ `/messaging-apps/${encodeURIComponent(platform)}/install`,+ { authenticated: true, method: 'POST' }+ );+ const json = (await res.json()) as { authorize_url: string };+ return json.authorize_url;+}+/** Field names that hold a credential and must be masked on input. Mirrors the* operator dashboard's `isSecretField`, widened to catch `*_private_key` (the* Teams bridge's Graph encryption key), which its bare `api_key` alternationdiff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/identities.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/identities.tsindex 920157230..dd231daeb 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/identities.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/identities.ts@@ -68,7 +68,7 @@ export async function searchDirectoryOnServer(*/export async function claimIdentityOnServer(server: SwitchServer,- params: Omit<ClaimIdentityParams, 'serverId'>+ params: Omit<ClaimIdentityParams, 'workspaceId'>): Promise<ClaimIdentityResult> {try {const claimed = await claimBridgeIdentity(server, params.bridgeId, {diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/require-server.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/require-server.tsnew file mode 100644index 000000000..ed42d6b84--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/require-server.ts@@ -0,0 +1,39 @@+import { managedServerHostBlocked } from '@main/core/managed-switch-server/managed-server-status';+import { HostUnreachableError } from '@shared/core/remote-hosts/reachability';+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';+import { getServer } from './servers-store';++export async function requireServer(serverId: string): Promise<SwitchServer> {+ const server = await getServer(serverId);+ if (!server) {+ throw new Error(`No Switch server with id ${serverId}`);+ }+ return server;+}++/**+ * The refusal a managed server's host being down produces, or null while it is+ * up.+ *+ * Returned rather than thrown so a path that reports its own outcome can count+ * the refusal before it propagates: the server is what an event describes+ * itself with, and a helper that throws leaves the caller holding nothing.+ */+export function hostUnreachable(server: SwitchServer): HostUnreachableError | null {+ const blocked = managedServerHostBlocked(server);+ return blocked ? new HostUnreachableError(blocked) : null;+}++/**+ * Resolve a server and refuse to touch its gateway while the host it is managed+ * on is unreachable (CHOO-1780). `gatewayFetch` enforces the same rule at the+ * transport, so this is for the paths that reach the gateway some other way —+ * sign-in and the dashboard window — and for failing before the side effects a+ * write would otherwise start.+ */+export async function requireReachableServer(serverId: string): Promise<SwitchServer> {+ const server = await requireServer(serverId);+ const unreachable = hostUnreachable(server);+ if (unreachable) throw unreachable;+ return server;+}diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/servers-store.db.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/servers-store.db.test.tsindex 7a746c190..7338c8a65 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/servers-store.db.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/servers-store.db.test.ts@@ -2,7 +2,7 @@ import { openFixture } from '@tooling/utils/db';import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { AppDb } from '@main/db/client';-import { agents, kv, locations, switchServers } from '@main/db/schema';+import { agents, kv, locations, switchServers, workspaces } from '@main/db/schema';const mocks = vi.hoisted(() => ({db: undefined as AppDb | undefined,@@ -37,8 +37,15 @@ vi.mock('@main/core/telemetry/telemetry-service', () => ({}));// Imported after the mocks so the module binds to the mocked db + secrets store.-const { addServer, assertManagedServerUrlFree, ensureManagedServer, removeServer, renameServer } =- await import('./servers-store');+const {+ addServer,+ assertManagedServerUrlFree,+ ensureManagedServer,+ removeServer,+ renameServer,+ setActiveServerId,+} = await import('./servers-store');+const { getActiveWorkspaceId } = await import('@main/core/workspaces/workspaces-store');describe('servers-store: rename & delete', () => {let fixture: Awaited<ReturnType<typeof openFixture>>;@@ -391,6 +398,10 @@ describe('servers-store: rename & delete', () => {});it('unlinks the server’s agents (keeps them), deletes the row, and clears the active pointer', async () => {+ // The unlink is two foreign keys deep — the server's workspaces cascade,+ // and their agents are set null — so this one test needs the engine to be+ // enforcing them.+ fixture.sqlite.pragma('foreign_keys = ON');await fixture.db.insert(locations).values({ id: 'loc-1', name: 'Loc', sshHost: '', dir: '/repo/loc-1' });@@ -400,28 +411,163 @@ describe('servers-store: rename & delete', () => {gatewayUrl: 'https://gw.example.com',apiUrl: 'https://api.example.com',});+ await fixture.db.insert(workspaces).values({ id: 'ws-1', serverId: 'srv-1', name: 'Server' });await fixture.db.insert(agents).values([- { id: 'agent-1', locationId: 'loc-1', name: 'A', providerId: 'claude', serverId: 'srv-1' },- { id: 'agent-2', locationId: 'loc-1', name: 'B', providerId: 'claude', serverId: 'srv-1' },+ {+ id: 'agent-1',+ locationId: 'loc-1',+ name: 'A',+ providerId: 'claude',+ workspaceId: 'ws-1',+ },+ {+ id: 'agent-2',+ locationId: 'loc-1',+ name: 'B',+ providerId: 'claude',+ workspaceId: 'ws-1',+ },]);- await fixture.db.insert(kv).values({ key: 'activeSwitchServerId', value: 'srv-1' });+ await fixture.db.insert(kv).values({ key: 'activeWorkspaceId', value: 'ws-1' });await removeServer('srv-1');const remainingServers = await fixture.db.select().from(switchServers);expect(remainingServers).toHaveLength(0);+ const remainingWorkspaces = await fixture.db.select().from(workspaces);+ expect(remainingWorkspaces).toHaveLength(0);+const remainingAgents = await fixture.db.select().from(agents);expect(remainingAgents).toHaveLength(2);- expect(remainingAgents.every((a) => a.serverId === null)).toBe(true);+ expect(remainingAgents.every((a) => a.workspaceId === null)).toBe(true);const [activePointer] = await fixture.db.select().from(kv)- .where(eq(kv.key, 'activeSwitchServerId'));+ .where(eq(kv.key, 'activeWorkspaceId'));expect(activePointer).toBeUndefined();expect(secretMocks.deleteSecret).toHaveBeenCalledWith('switch-server-cookie:srv-1');});});});++describe('selecting a server', () => {+ let fixture: Awaited<ReturnType<typeof openFixture>>;++ beforeEach(async () => {+ fixture = await openFixture('empty');+ mocks.db = fixture.db;+ fixture.sqlite.pragma('foreign_keys = OFF');+ await fixture.db.insert(switchServers).values({+ id: 'srv-1',+ name: 'Local dev',+ gatewayUrl: 'https://srv-1.example.com',+ apiUrl: 'https://api-srv-1.example.com',+ });+ });++ afterEach(() => {+ fixture.close();+ mocks.db = undefined;+ });++ async function seedWorkspace(+ id: string,+ tenantId: string | null,+ role: 'owner' | 'member' | null = 'member'+ ): Promise<void> {+ await fixture.db.insert(workspaces).values({ id, serverId: 'srv-1', name: id, tenantId, role });+ }++ it('selects the one workspace a server has', async () => {+ await seedWorkspace('ws-1', 't-1');++ await setActiveServerId('srv-1');++ expect(await getActiveWorkspaceId()).toBe('ws-1');+ });++ /**+ * Refusing would fail the managed stack start this runs inside, taking a+ * healthy server down over a question about which of its workspaces to show.+ */+ it('picks one rather than refusing when the account has several there', async () => {+ await seedWorkspace('ws-1', 't-1');+ await seedWorkspace('ws-2', 't-2');++ await setActiveServerId('srv-1');++ expect(await getActiveWorkspaceId()).toBe('ws-1');+ });++ // Re-selecting the server the user is already in must not move them to+ // another of its workspaces; a managed stack start does exactly that.+ it('leaves the selection alone when it is already on that server', async () => {+ await seedWorkspace('ws-1', 't-1');+ await seedWorkspace('ws-2', 't-2');+ await setActiveServerId('srv-1');+ await fixture.db.update(kv).set({ value: 'ws-2' }).where(eq(kv.key, 'activeWorkspaceId'));++ await setActiveServerId('srv-1');++ const [pointer] = await fixture.db.select().from(kv).where(eq(kv.key, 'activeWorkspaceId'));+ expect(pointer!.value).toBe('ws-2');+ });++ /**+ * The oldest row is the one a withdrawn membership is most likely to be —+ * the server's original workspace, whose membership was the first to be+ * given up. Landing on it would scope the window to something the gateway+ * refuses every call for.+ */+ it('skips a workspace this account is no longer a member of', async () => {+ await seedWorkspace('ws-1', 't-gone', null);+ await seedWorkspace('ws-2', 't-2');++ await setActiveServerId('srv-1');++ expect(await getActiveWorkspaceId()).toBe('ws-2');+ });++ /**+ * The row the server was registered with, before the gateway was asked which+ * workspaces the account has. It names no tenant, so a call scoped to it+ * selects none and the gateway answers with whichever workspace the session+ * last selected — under this one's name. On an upgraded install it is also+ * the oldest row, and holds every agent.+ */+ it('skips a placeholder the reconcile could not match', async () => {+ await seedWorkspace('ws-1', null, null);+ await seedWorkspace('ws-2', 't-2');++ await setActiveServerId('srv-1');++ expect(await getActiveWorkspaceId()).toBe('ws-2');+ });++ // Every server's first workspace starts out like this and is matched to a+ // membership afterwards; on its own there is nothing to confuse it with.+ it('selects a lone workspace that has no tenant yet', async () => {+ await seedWorkspace('ws-1', null, null);++ await setActiveServerId('srv-1');++ expect(await getActiveWorkspaceId()).toBe('ws-1');+ });++ // Nothing else to fall back to, and refusing here takes a healthy managed+ // stack start down; the seam says why on the first call instead.+ it('still picks one when every workspace on the server is withdrawn', async () => {+ await seedWorkspace('ws-1', 't-gone', null);++ await setActiveServerId('srv-1');++ expect(await getActiveWorkspaceId()).toBe('ws-1');+ });++ it('refuses a server with no workspace at all', async () => {+ await expect(setActiveServerId('srv-1')).rejects.toThrow('no workspace');+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/servers-store.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/servers-store.tsindex 164f2d2ee..0f4af1b2d 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/servers-store.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/servers-store.ts@@ -3,8 +3,18 @@ import { and, desc, eq, isNull, ne, or, sql } from 'drizzle-orm';import { encryptedAppSecretsStore } from '@main/core/secrets/encrypted-app-secrets-store';import type { TelemetryEventMap } from '@main/core/telemetry/events';import { trackEvent } from '@main/core/telemetry/telemetry-service';+import { forgetServerSession } from '@main/core/workspaces/workspace-session';+import {+ clearActiveWorkspaceOnServer,+ ensureServerWorkspace,+ getActiveWorkspaceId,+ insertServerWorkspace,+ listWorkspacesForServer,+ renameServerWorkspaces,+ setActiveWorkspaceId,+} from '@main/core/workspaces/workspaces-store';import { db } from '@main/db/client';-import { agents, kv, type SwitchServerRow, switchServers } from '@main/db/schema';+import { type SwitchServerRow, switchServers } from '@main/db/schema';import {urlOrigin,type AddServerParams,@@ -13,9 +23,10 @@ import {type SwitchServer,type UpdateServerParams,} from '@shared/core/switch-servers/switch-servers';+import { workspaceUnavailability } from '@shared/core/workspaces/workspaces';-const ACTIVE_SERVER_KV_KEY = 'activeSwitchServerId';-+// Keyed to the server, not the workspace: one gateway session cookie covers+// every workspace on a server.function cookieSecretKey(serverId: string): string {return `switch-server-cookie:${serverId}`;}@@ -196,7 +207,9 @@ export async function ensureManagedServer(}).where(eq(switchServers.id, existing.id)).returning();- return mapRow(row);+ const server = mapRow(row);+ await ensureServerWorkspace(server);+ return server;}const [row] = await db.insert(switchServers)@@ -211,13 +224,20 @@ export async function ensureManagedServer(updatedAt: sql`CURRENT_TIMESTAMP`,}).returning();+ const server = mapRow(row);+ await ensureServerWorkspace(server);// Only the insert: this function also runs on every restart of a stack that// already exists, and that is not a server being added.trackEvent('server_added', {server_kind: ref.kind === 'remote' ? 'remote_managed' : 'local',outcome: 'success',});- return mapRow(row);+ return server;+}++/** The server registered at a gateway URL, compared the way it was stored. */+export async function findServerByGatewayUrl(gatewayUrl: string): Promise<SwitchServer | null> {+ return getServerByGatewayUrl(normaliseUrl(gatewayUrl));}async function getServerByGatewayUrl(gatewayUrl: string): Promise<SwitchServer | null> {@@ -230,22 +250,28 @@ async function getServerByGatewayUrl(gatewayUrl: string): Promise<SwitchServer |}export async function addServer(params: AddServerParams): Promise<SwitchServer> {- const [row] = await db- .insert(switchServers)- .values({- id: randomUUID(),- name: params.name.trim(),- gatewayUrl: normaliseUrl(params.gatewayUrl),- apiUrl: normaliseUrl(params.apiUrl),- updatedAt: sql`CURRENT_TIMESTAMP`,- })- .returning();+ const server = db.transaction((tx) => {+ const [row] = tx+ .insert(switchServers)+ .values({+ id: randomUUID(),+ name: params.name.trim(),+ gatewayUrl: normaliseUrl(params.gatewayUrl),+ apiUrl: normaliseUrl(params.apiUrl),+ updatedAt: sql`CURRENT_TIMESTAMP`,+ })+ .returning()+ .all();+ const inserted = mapRow(row!);+ insertServerWorkspace(tx, inserted);+ return inserted;+ });// Not reported here, unlike the managed insert above: registering a URL is a// discrete action with one caller, so the controller reports both of its// outcomes together and a single Add cannot produce two events. The managed// kinds have no such single owner — two services call that path and so does// every restart — which is why it is reported at the insert instead.- return mapRow(row);+ return server;}export async function updateServer(params: UpdateServerParams): Promise<SwitchServer> {@@ -262,6 +288,7 @@ export async function updateServer(params: UpdateServerParams): Promise<SwitchSeif (!row) {throw new Error(`No Switch server with id ${params.id}`);}+ await renameServerWorkspaces(params.id, params.name.trim());return mapRow(row);}@@ -274,6 +301,7 @@ export async function renameServer(params: RenameServerParams): Promise<SwitchSeif (!row) {throw new Error(`No Switch server with id ${params.id}`);}+ await renameServerWorkspaces(params.id, params.name.trim());return mapRow(row);}@@ -283,13 +311,12 @@ export async function removeServer(id: string): Promise<void> {const server = await getServer(id).catch(() => null);await deleteSessionCookie(id);- // Unlink agents explicitly: SQLite's ALTER TABLE ADD COLUMN can't carry an- // ON DELETE clause, so the FK's set-null isn't enforced by the engine.- await db.update(agents).set({ serverId: null }).where(eq(agents.serverId, id));+ // Before the delete, while the server's workspaces are still readable.+ await clearActiveWorkspaceOnServer(id);+ // Deleting the server takes its workspaces with it and unlinks their agents,+ // both by foreign key: workspaces cascade, agents are set null.await db.delete(switchServers).where(eq(switchServers.id, id));- if ((await getActiveServerId()) === id) {- await db.delete(kv).where(eq(kv.key, ACTIVE_SERVER_KV_KEY));- }+ forgetServerSession(id);// Removing an already-absent server is not a server being removed.if (server) trackEvent('server_removed', { server_kind: serverKindOf(server) });@@ -303,23 +330,36 @@ export function serverKindOf(return server.managementKind === 'remote' ? 'remote_managed' : 'local';}-export async function getActiveServerId(): Promise<string | null> {- const [row] = await db.select().from(kv).where(eq(kv.key, ACTIVE_SERVER_KV_KEY)).limit(1);- return row?.value ?? null;-}-+/**+ * Select a server by selecting one of its workspaces.+ *+ * Picks the first when the account turns out to belong to several on that+ * server, rather than refusing the way the paths that attach an agent do. The+ * risks are not the same: showing the wrong workspace is visible and one click+ * from being corrected, while attaching an agent to it is neither. Refusing+ * here would instead fail the managed stack start this runs inside, taking a+ * healthy server down over a question about which of its workspaces to show.+ *+ * "First" means the first that can actually be opened, where there is one: a+ * withdrawn membership and an unmatched placeholder are both refused by the+ * gateway, and landing on either is not a wrong guess a click corrects. Where+ * there is no such workspace it still picks, for the same reason it does not+ * refuse a choice between several — the seam says why on the first call.+ */export async function setActiveServerId(id: string): Promise<void> {const server = await getServer(id);- if (!server) {- throw new Error(`No Switch server with id ${id}`);- }- await db- .insert(kv)- .values({ key: ACTIVE_SERVER_KV_KEY, value: id, updatedAt: sql`CURRENT_TIMESTAMP` })- .onConflictDoUpdate({- target: kv.key,- set: { value: id, updatedAt: sql`CURRENT_TIMESTAMP` },- });+ if (!server) throw new Error(`No Switch server with id ${id}`);+ const found = await listWorkspacesForServer(id);+ if (found.length === 0) throw new Error(`Switch server ${id} has no workspace`);+ const active = await getActiveWorkspaceId();+ if (found.some((candidate) => candidate.id === active)) return;+ // The rows are oldest first, and the oldest is exactly the one a withdrawn+ // membership or an unmatched placeholder is most likely to be — the row the+ // server was registered with, before the gateway was ever asked.+ const openable = found.find(+ (candidate) => workspaceUnavailability(candidate, found.length) === null+ );+ await setActiveWorkspaceId((openable ?? found[0]!).id);}// ---------------------------------------------------------------------------diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/switch-cloud.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/switch-cloud.test.tsnew file mode 100644index 000000000..1571e584a--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/switch-cloud.test.ts@@ -0,0 +1,76 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { requireSwitchCloudEndpoint, switchCloudEndpoint } from './switch-cloud';++afterEach(() => {+ vi.unstubAllEnvs();+});++function runWith(value: string | undefined) {+ vi.stubEnv('SWITCH_CLOUD_URL', value);+ vi.stubEnv('MAIN_VITE_SWITCH_CLOUD_URL', undefined);+}++describe('switchCloudEndpoint', () => {+ it('is null when nothing names a Cloud', () => {+ runWith(undefined);+ expect(switchCloudEndpoint()).toBeNull();+ });++ it('treats a blank value as unset', () => {+ runWith(' ');+ expect(switchCloudEndpoint()).toBeNull();+ });++ it('returns the origin of an https URL', () => {+ runWith(' https://cloud.example.com/ ');+ expect(switchCloudEndpoint()).toEqual({ url: 'https://cloud.example.com' });+ });++ it('falls back to the build-time value', () => {+ vi.stubEnv('SWITCH_CLOUD_URL', undefined);+ vi.stubEnv('MAIN_VITE_SWITCH_CLOUD_URL', 'https://built.example.com');+ expect(switchCloudEndpoint()).toEqual({ url: 'https://built.example.com' });+ });++ it('prefers the run-time value over the build-time one', () => {+ vi.stubEnv('SWITCH_CLOUD_URL', 'https://run.example.com');+ vi.stubEnv('MAIN_VITE_SWITCH_CLOUD_URL', 'https://built.example.com');+ expect(switchCloudEndpoint()).toEqual({ url: 'https://run.example.com' });+ });++ it('raises on a value that is not a URL', () => {+ runWith('not a url');+ expect(() => switchCloudEndpoint()).toThrow('SWITCH_CLOUD_URL is not a URL');+ });++ it('raises on plain http', () => {+ runWith('http://cloud.example.com');+ expect(() => switchCloudEndpoint()).toThrow('must be an https URL');+ });++ it('accepts plain http to this machine, for a local stand-in', () => {+ runWith('http://localhost:8000');+ expect(switchCloudEndpoint()).toEqual({ url: 'http://localhost:8000' });+ runWith('http://127.0.0.1:8000');+ expect(switchCloudEndpoint()).toEqual({ url: 'http://127.0.0.1:8000' });+ runWith('http://[::1]:8000');+ expect(switchCloudEndpoint()).toEqual({ url: 'http://[::1]:8000' });+ });++ it('does not take a host that only starts like localhost', () => {+ runWith('http://localhost.example.com');+ expect(() => switchCloudEndpoint()).toThrow('must be an https URL');+ });++ it('raises on a URL with a path', () => {+ runWith('https://cloud.example.com/gateway');+ expect(() => switchCloudEndpoint()).toThrow('must be an origin with no path');+ });+});++describe('requireSwitchCloudEndpoint', () => {+ it('raises when nothing names a Cloud', () => {+ runWith(undefined);+ expect(() => requireSwitchCloudEndpoint()).toThrow('Switch Cloud is not configured');+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/switch-cloud.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/switch-cloud.tsnew file mode 100644index 000000000..050dacdb8--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/switch-cloud.ts@@ -0,0 +1,55 @@+import type { SwitchCloudEndpoint } from '@shared/core/switch-servers/switch-cloud';++/** Read at run time, so a dev run can be pointed at a deployment without a rebuild. */+const RUNTIME_VARIABLE = 'SWITCH_CLOUD_URL';+/** Inlined by electron-vite at build time, so a packaged build carries its own. */+const BUILD_VARIABLE = 'MAIN_VITE_SWITCH_CLOUD_URL';++/**+ * Where Switch Cloud is, or null when neither this run nor this build names it.+ *+ * Supplied from outside rather than written here, because this repository is+ * public and which deployment a build treats as the Cloud is a choice made per+ * build, not part of the source. Unset is a real answer — the Cloud choice then+ * says it is not open yet — but a value that is not an https URL is a broken+ * build or launch, and raised as one rather than treated as unset. The one+ * exception is plain http to this machine, so a server run from a checkout can+ * stand in for the Cloud while testing (`just local-cloud`).+ */+export function switchCloudEndpoint(): SwitchCloudEndpoint | null {+ const fromRun = process.env[RUNTIME_VARIABLE]?.trim();+ if (fromRun) return { url: parseCloudUrl(fromRun, RUNTIME_VARIABLE) };+ const fromBuild = import.meta.env.MAIN_VITE_SWITCH_CLOUD_URL?.trim();+ if (fromBuild) return { url: parseCloudUrl(fromBuild, BUILD_VARIABLE) };+ return null;+}++export function requireSwitchCloudEndpoint(): SwitchCloudEndpoint {+ const endpoint = switchCloudEndpoint();+ if (!endpoint) {+ throw new Error(+ `Switch Cloud is not configured for this build. Set ${RUNTIME_VARIABLE} to its https URL.`+ );+ }+ return endpoint;+}++const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);++/** The origin alone: the Console appends `/gateway` itself, so a path would double up. */+function parseCloudUrl(value: string, variable: string): string {+ let url: URL;+ try {+ url = new URL(value);+ } catch {+ throw new Error(`${variable} is not a URL: ${value}`);+ }+ const loopbackHttp = url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname);+ if (url.protocol !== 'https:' && !loopbackHttp) {+ throw new Error(`${variable} must be an https URL, or http to localhost: ${value}`);+ }+ if (url.pathname !== '/' || url.search || url.hash) {+ throw new Error(`${variable} must be an origin with no path, like https://host: ${value}`);+ }+ return url.origin;+}diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/update-bridge.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/update-bridge.tsindex 9b3e03d35..d1e3fa08a 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/update-bridge.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/update-bridge.ts@@ -15,7 +15,7 @@ import type {*/export async function updateBridgeOnServer(server: SwitchServer,- params: Omit<UpdateBridgeParams, 'serverId'>+ params: Omit<UpdateBridgeParams, 'workspaceId'>): Promise<UpdateBridgeResult> {try {const bridge = await updateBridge(server, params.bridgeId, {diff --git a/console/apps/switch-console-desktop/src/main/core/telemetry/catalogue.test.ts b/console/apps/switch-console-desktop/src/main/core/telemetry/catalogue.test.tsindex 9fd7600dd..ac0975a66 100644--- a/console/apps/switch-console-desktop/src/main/core/telemetry/catalogue.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/telemetry/catalogue.test.ts@@ -46,7 +46,8 @@ function sampleFor(property: string): string | number | boolean {property === 'connected_to_room' ||property === 'delete_in_switch' ||property === 'resolved' ||- property === 'cold_start'+ property === 'cold_start' ||+ property === 'first_run') {return true;}diff --git a/console/apps/switch-console-desktop/src/main/core/telemetry/events.ts b/console/apps/switch-console-desktop/src/main/core/telemetry/events.tsindex a8b03b05f..23bcadd3c 100644--- a/console/apps/switch-console-desktop/src/main/core/telemetry/events.ts+++ b/console/apps/switch-console-desktop/src/main/core/telemetry/events.ts@@ -651,7 +651,7 @@ export const TELEMETRY_EVENT_PROPERTIES = {onboarding_step_started: ['step_id'],onboarding_checklist_dismissed: [],onboarding_completed: [],- add_server_step: ['step', 'choice'],+ add_server_step: ['step', 'choice', 'first_run'],renderer_crashed: [],telemetry_consent_changed: ['source'],session_attached: ['agent_type', 'outcome'],diff --git a/console/apps/switch-console-desktop/src/main/core/telemetry/renderer-events.ts b/console/apps/switch-console-desktop/src/main/core/telemetry/renderer-events.tsindex 844be6f70..abfb66ec2 100644--- a/console/apps/switch-console-desktop/src/main/core/telemetry/renderer-events.ts+++ b/console/apps/switch-console-desktop/src/main/core/telemetry/renderer-events.ts@@ -53,6 +53,7 @@ const RENDERER_TELEMETRY_SCHEMAS = {add_server_step: z.object({step: z.enum(ADD_SERVER_STEPS),choice: z.enum(ADD_SERVER_CHOICES),+ first_run: z.boolean(),}),renderer_crashed: z.object({}),} as const satisfies {diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/asserted-tenant.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/asserted-tenant.tsnew file mode 100644index 000000000..5843c48bd--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/asserted-tenant.ts@@ -0,0 +1,36 @@+/**+ * Which tenant a server's session is currently selecting on behalf of the calls+ * holding a lease on it.+ *+ * The session seam owns this; it lives in a module of its own so the gateway+ * client can read it without importing the seam that switches tenants through+ * the gateway client.+ *+ * Every lease outstanding on a server at one moment names the same tenant — a+ * switch waits for every lease to be given up first — so there is one answer per+ * server rather than one per call.+ */+const asserted = new Map<string, string>();++/** Record the tenant `serverId`'s first outstanding lease was taken against. */+export function setAssertedTenant(serverId: string, tenantId: string): void {+ asserted.set(serverId, tenantId);+}++/** Forget it once nothing is leasing the server. */+export function clearAssertedTenant(serverId: string): void {+ asserted.delete(serverId);+}++/**+ * The tenant that has to hold for the calls in flight on `serverId`, or null+ * when nothing is leasing it or the lease named no tenant.+ *+ * Read by anything that replaces the session cookie underneath those calls: a+ * cookie minted by a fresh login selects no tenant, and handing it back+ * unchanged would answer the rest of the lease with the account's default+ * workspace while the caller still believes it is addressing the one it named.+ */+export function assertedTenant(serverId: string): string | null {+ return asserted.get(serverId) ?? null;+}diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.test.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.test.tsnew file mode 100644index 000000000..e6b84d82b--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.test.ts@@ -0,0 +1,261 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { HostUnreachableError } from '@shared/core/remote-hosts/reachability';++const managedServerHostBlocked = vi.hoisted(() => vi.fn((): unknown => null));+const trackEvent = vi.hoisted(() => vi.fn());+const createRoomOnServer = vi.hoisted(() => vi.fn());+const deleteBridge = vi.hoisted(() => vi.fn());+const deleteRoom = vi.hoisted(() => vi.fn());+const fetchBridges = vi.hoisted(() => vi.fn());+const getServer = vi.hoisted(() => vi.fn());+const getSessionCookie = vi.hoisted(() => vi.fn());+const requireWorkspace = vi.hoisted(() => vi.fn());+const listWorkspacesForServer = vi.hoisted(() => vi.fn(async () => [{ id: 'ws' }]));+const switchTenant = vi.hoisted(() => vi.fn());+// Stubbed rather than reimplemented: what the tests below assert is that the+// kind reaches the event, not how a row is read as one.+const serverKindOf = vi.hoisted(() => vi.fn(() => 'remote_managed'));++// Stub the modules the controller imports that would otherwise pull electron /+// ssh / agent side effects at load.+vi.mock('@main/core/agents/agent-credentials-slot', () => ({ foreignCredentialsOwner: vi.fn() }));+vi.mock('@main/core/agents/agent-workdir-fs', () => ({ resolveWorkdirFsFor: vi.fn() }));+vi.mock('@main/core/agents/known-agent-type', () => ({ knownAgentTypeForProvider: vi.fn() }));+vi.mock('@main/core/agents/register-agent-identity', () => ({ registerAgentIdentity: vi.fn() }));+vi.mock('@main/core/agents/write-remote-switch-settings', () => ({+ writeRemoteSwitchSettings: vi.fn(),+}));+vi.mock('@main/core/agents/write-switch-settings', () => ({+ writeNeutralAgentSettingsFs: vi.fn(),+ writeSwitchSettings: vi.fn(),+}));+vi.mock('@main/core/fs/impl/ssh-fs', () => ({ SshFileSystem: vi.fn() }));+vi.mock('@main/core/locations/location-transport', () => ({ sshConnectionIdForHost: vi.fn() }));+vi.mock('@main/core/ssh/connect/connect-agent-ssh', () => ({ ensureSshConnected: vi.fn() }));+vi.mock('@main/core/telemetry/telemetry-service', () => ({ trackEvent }));+vi.mock('@main/core/managed-switch-server/managed-server-status', () => ({+ isManagedServerRunning: vi.fn(() => true),+ managedServerHostBlocked,+}));+// Writes to the app's log file, which a test has no business creating.+vi.mock('@main/lib/logger', () => ({+ log: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() },+}));+// Reads this install's own agent rows, and through them the database client.+vi.mock('@main/core/switch-servers/backfill-agent-icons', () => ({ backfillAgentIcons: vi.fn() }));+vi.mock('@main/core/switch-servers/bridge-home-url', () => ({ withResolvedHomeUrls: vi.fn() }));+vi.mock('@main/core/switch-servers/create-bridge', () => ({ createBridgeOnServer: vi.fn() }));+vi.mock('@main/core/switch-servers/create-room', () => ({ createRoomOnServer }));+vi.mock('@main/core/switch-servers/identities', () => ({+ claimIdentityOnServer: vi.fn(),+ searchDirectoryOnServer: vi.fn(),+}));+vi.mock('@main/core/switch-servers/update-bridge', () => ({ updateBridgeOnServer: vi.fn() }));+vi.mock('@main/core/switch-servers/gateway-client', () => ({+ addRoomAgents: vi.fn(),+ agentExistsOnServer: vi.fn(),+ createRoomFromTemplate: vi.fn(),+ decodeJwtTenantId: vi.fn(() => null),+ deleteBridge,+ deleteRoom,+ fetchAddressingPolicy: vi.fn(),+ fetchAgentDetail: vi.fn(),+ fetchAgentRooms: vi.fn(),+ fetchAgents: vi.fn(),+ fetchAllExternalUsers: vi.fn(),+ fetchBridges,+ fetchBridgeTypes: vi.fn(),+ fetchMyIdentities: vi.fn(),+ fetchRoomAgentIds: vi.fn(),+ fetchRoomDetail: vi.fn(),+ fetchRoomGroups: vi.fn(),+ fetchRoomRoles: vi.fn(),+ fetchRooms: vi.fn(),+ fetchTemplateSchema: vi.fn(),+ GatewayError: class GatewayError extends Error {},+ ownsOwnerAddressedAgent: vi.fn(),+ releaseBridgeIdentity: vi.fn(),+ removeRoomAgent: vi.fn(),+ switchTenant,+ updateAddressingPolicy: vi.fn(),+ updateAgentIcon: vi.fn(),+ updateRoom: vi.fn(),+}));+vi.mock('@main/core/switch-servers/servers-store', () => ({+ getServer,+ getSessionCookie,+ serverKindOf,+}));+vi.mock('./workspaces-store', () => ({+ getActiveWorkspaceId: vi.fn(),+ listWorkspaces: vi.fn(),+ listWorkspacesForServer,+ requireWorkspace,+ setActiveWorkspaceId: vi.fn(),+}));++const { workspacesController } = await import('./controller');++function server(overrides: Record<string, unknown>) {+ return {+ id: 'srv',+ name: 'S',+ gatewayUrl: 'http://localhost:3300',+ apiUrl: 'http://localhost:8000',+ managed: false,+ managementKind: null,+ sshHost: null,+ createdAt: '',+ updatedAt: '',+ ...overrides,+ };+}++/** The workspace every call below names, on the server the test set up. */+function workspace(tenantId: string | null = null) {+ return { id: 'ws', serverId: 'srv', name: 'S', tenantId, createdAt: '', updatedAt: '' };+}++describe('disconnecting a bridge', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ managedServerHostBlocked.mockReturnValue(null);+ getServer.mockResolvedValue(server({}));+ requireWorkspace.mockResolvedValue(workspace());+ fetchBridges.mockResolvedValue([{ id: 'b1', type: 'slack' }]);+ });++ it('reports a disconnection the gateway carried out', async () => {+ deleteBridge.mockResolvedValue({ kind: 'deleted' });++ await workspacesController.deleteBridge({ workspaceId: 'ws', bridgeId: 'b1' });++ await vi.waitFor(() =>+ expect(trackEvent).toHaveBeenCalledWith('bridge_disconnected', {+ bridge_platform: 'slack',+ outcome: 'success',+ })+ );+ });++ it('reports a refusal as a failure rather than as a disconnection', async () => {+ // Admin-only, and the gateway hands back the refusal instead of throwing+ // it — so the await returns exactly as it does for a bridge that went.+ deleteBridge.mockResolvedValue({ kind: 'forbidden' });++ await workspacesController.deleteBridge({ workspaceId: 'ws', bridgeId: 'b1' });++ await vi.waitFor(() =>+ expect(trackEvent).toHaveBeenCalledWith('bridge_disconnected', {+ bridge_platform: 'slack',+ outcome: 'failure',+ })+ );+ });+});++describe('an action a workspace whose host has gone down cannot take', () => {+ const blocked = {+ sshHost: 'h',+ status: 'unreachable',+ lastError: 'no route to host',+ lastCheckedAt: null,+ };++ beforeEach(() => {+ vi.clearAllMocks();+ getServer.mockResolvedValue(server({ managed: true, managementKind: 'remote', sshHost: 'h' }));+ requireWorkspace.mockResolvedValue(workspace());+ managedServerHostBlocked.mockReturnValue(blocked);+ // What the gateway does on a host that cannot be reached: the platform is+ // then unknowable rather than absent.+ fetchBridges.mockRejectedValue(new Error('no route to host'));+ });++ it('reports the room it refused to create', async () => {+ await expect(+ workspacesController.createRoom({+ workspaceId: 'ws',+ name: 'Room',+ description: '',+ bridgeId: 'b1',+ agentIds: ['a1'],+ })+ ).rejects.toBeInstanceOf(HostUnreachableError);++ expect(createRoomOnServer).not.toHaveBeenCalled();+ await vi.waitFor(() =>+ expect(trackEvent).toHaveBeenCalledWith('room_created', {+ server_kind: 'remote_managed',+ bridge_platform: 'unknown',+ agent_count: 1,+ has_instructions: false,+ outcome: 'failure',+ failure_reason: 'unreachable',+ })+ );+ });++ it('reports the room it refused to delete', async () => {+ await expect(+ workspacesController.deleteRoom({ workspaceId: 'ws', roomId: 'r1' })+ ).rejects.toBeInstanceOf(HostUnreachableError);++ expect(deleteRoom).not.toHaveBeenCalled();+ expect(trackEvent).toHaveBeenCalledWith('room_deleted', {+ server_kind: 'remote_managed',+ outcome: 'failure',+ });+ });+});++/**+ * The seam's whole point: a call names a workspace, and the session it goes out+ * on must be selecting that workspace's tenant. A read that answered from the+ * previously selected tenant would succeed and look right.+ */+describe('selecting the workspace’s tenant before the call', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ managedServerHostBlocked.mockReturnValue(null);+ getServer.mockResolvedValue(server({}));+ fetchBridges.mockResolvedValue([]);+ });++ it('switches when the session is selecting another tenant', async () => {+ requireWorkspace.mockResolvedValue(workspace('tenant-b'));+ getSessionCookie.mockResolvedValue('cookie-for-tenant-a');++ await workspacesController.listBridges('ws');++ expect(switchTenant).toHaveBeenCalledWith(expect.objectContaining({ id: 'srv' }), 'tenant-b');+ });++ it('does not switch when the session already selects it', async () => {+ const { decodeJwtTenantId } = await import('@main/core/switch-servers/gateway-client');+ vi.mocked(decodeJwtTenantId).mockReturnValue('tenant-b');+ requireWorkspace.mockResolvedValue(workspace('tenant-b'));+ getSessionCookie.mockResolvedValue('cookie-for-tenant-b');++ await workspacesController.listBridges('ws');++ expect(switchTenant).not.toHaveBeenCalled();+ });++ it('asserts nothing for a workspace with no tenant, where its server has only the one', async () => {+ requireWorkspace.mockResolvedValue(workspace(null));++ await workspacesController.listBridges('ws');++ expect(switchTenant).not.toHaveBeenCalled();+ expect(getSessionCookie).not.toHaveBeenCalled();+ });++ it('refuses a workspace with no tenant where its server has several', async () => {+ requireWorkspace.mockResolvedValue(workspace(null));+ listWorkspacesForServer.mockResolvedValueOnce([{ id: 'ws' }, { id: 'ws-2' }]);++ await expect(workspacesController.listBridges('ws')).rejects.toThrow('has not been matched');+ expect(fetchBridges).not.toHaveBeenCalled();+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.tsnew file mode 100644index 000000000..173412811--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts@@ -0,0 +1,674 @@+import { backfillAgentIcons } from '@main/core/switch-servers/backfill-agent-icons';+import { withResolvedHomeUrls } from '@main/core/switch-servers/bridge-home-url';+import { createBridgeOnServer } from '@main/core/switch-servers/create-bridge';+import { createRoomOnServer } from '@main/core/switch-servers/create-room';+import {+ addRoomAgents,+ agentExistsOnServer,+ changeTemplateRun,+ createRoomFromTemplate,+ createTemplate,+ deleteBridge,+ deleteRoom,+ deleteTemplate,+ exportRoomYaml,+ fetchAddressingPolicy,+ fetchAgentRooms,+ fetchAgents,+ fetchAllExternalUsers,+ fetchBridges,+ beginMessagingAppInstall,+ fetchBridgeTypes,+ fetchInstallablePlatforms,+ fetchMyIdentities,+ fetchRoomAgentIds,+ fetchRoomDetail,+ fetchRoomGroups,+ fetchRoomRoles,+ fetchRooms,+ fetchTemplateDetail,+ fetchTemplateRuns,+ fetchTemplates,+ fetchTemplateSchema,+ GatewayError,+ ownsOwnerAddressedAgent,+ releaseBridgeIdentity,+ removeRoomAgent,+ type StoredTemplateDetail,+ type StoredTemplateSummary,+ type ProvisionFromTemplateResult,+ type TemplateRun,+ type TemplateVisibility,+ updateAddressingPolicy,+ updateAgentIcon,+ updateRoom,+ updateTemplate,+} from '@main/core/switch-servers/gateway-client';+import {+ claimIdentityOnServer,+ searchDirectoryOnServer,+} from '@main/core/switch-servers/identities';+import { hostUnreachable } from '@main/core/switch-servers/require-server';+import { serverKindOf } from '@main/core/switch-servers/servers-store';+import { updateBridgeOnServer } from '@main/core/switch-servers/update-bridge';+import { bridgePlatformOfType } from '@main/core/telemetry/bridge-platform';+import type {+ TelemetryBridgeFailure,+ TelemetryBridgePlatform,+ TelemetryOutcome,+ TelemetryRoomAgentsDirection,+ TelemetryRoomCreateFailure,+ TelemetryServerKind,+} from '@main/core/telemetry/events';+import { roomAgentsDirectionOf } from '@main/core/telemetry/narrow';+import { trackEvent } from '@main/core/telemetry/telemetry-service';+import type {+ AddressingPolicy,+ AgentIconBackfill,+ AgentVerifyResult,+ BridgeDirectorySearchResult,+ ClaimIdentityParams,+ ClaimIdentityResult,+ CreateBridgeParams,+ CreateBridgeResult,+ CreateRoomParams,+ CreateRoomResult,+ DeleteBridgeParams,+ DeleteBridgeResult,+ LinkedIdentity,+ RemoteAgentRoom,+ RemoteAgentSummary,+ RemoteBridge,+ RemoteBridgeType,+ RemoteExternalUser,+ RemoteRoomDetail,+ RemoteRoomGroup,+ RemoteRoomRole,+ RemoteRoomSummary,+ SwitchServer,+ UpdateBridgeParams,+ UpdateBridgeResult,+ UpdateRoomParams,+} from '@shared/core/switch-servers/switch-servers';+import type { Workspace } from '@shared/core/workspaces/workspaces';+import { createRPCController } from '@shared/lib/ipc/rpc';+import {+ addWorkspaceJoinDomain,+ createWorkspaceInvitation,+ listWorkspaceInvitations,+ listWorkspaceJoinDomains,+ removeWorkspaceJoinDomain,+ revokeWorkspaceInvitation,+} from './invitations';+import {+ withReachableWorkspaceSession,+ withWorkspaceSession,+ workspaceServer,+} from './workspace-session';+import { getActiveWorkspaceId, listWorkspaces, setActiveWorkspaceId } from './workspaces-store';++/** A bridge result's discriminant as a code. Never the message beside it. */+function bridgeFailureReason(kind: string): TelemetryBridgeFailure {+ switch (kind) {+ case 'created':+ return 'none';+ case 'unauthenticated':+ return 'unauthenticated';+ case 'forbidden':+ return 'forbidden';+ case 'invalid':+ return 'invalid';+ default:+ return 'error';+ }+}++/** A room-create result's discriminant as a code. */+function roomCreateFailureReason(result: CreateRoomResult): TelemetryRoomCreateFailure {+ switch (result.kind) {+ case 'created':+ return 'none';+ case 'unauthenticated':+ return 'unauthenticated';+ case 'bridge-unavailable':+ return 'bridge_unavailable';+ case 'invalid':+ return 'invalid';+ default:+ return 'error';+ }+}++/**+ * Which platform a bridge id is on.+ *+ * A lookup rather than a field: these operations take a bridge id, and the type+ * either never appears (a delete) or appears only on success (a room). Best+ * effort — an unreachable server yields `unknown` rather than failing the+ * operation it is only describing.+ *+ * **Never awaited by a caller doing real work.** It asks the gateway, and making+ * someone wait on a network round trip so we can describe what they did would+ * put reporting in the path of the thing being reported. `reportWithBridge` is+ * how the answer is used once it arrives.+ *+ * It takes its own lease, so it must be started outside one: unawaited inside+ * another call's lease it would be left addressing whatever workspace the+ * session had moved on to. Where the answer is only readable before the work —+ * a delete — read it in that call's lease with+ * {@link bridgePlatformOnServer} instead.+ */+function bridgePlatformOf(+ workspaceId: string,+ bridgeId: string | null | undefined+): Promise<TelemetryBridgePlatform> {+ if (!bridgeId) return Promise.resolve('unknown');+ return withWorkspaceSession(workspaceId, fetchBridges)+ .then((bridges) => bridgePlatformOfType(bridges.find((b) => b.id === bridgeId)?.type))+ .catch((): TelemetryBridgePlatform => 'unknown');+}++/** {@link bridgePlatformOf} against a server already leased by the caller. */+function bridgePlatformOnServer(+ server: SwitchServer,+ bridgeId: string | null | undefined+): Promise<TelemetryBridgePlatform> {+ if (!bridgeId) return Promise.resolve('unknown');+ return fetchBridges(server)+ .then((bridges) => bridgePlatformOfType(bridges.find((b) => b.id === bridgeId)?.type))+ .catch((): TelemetryBridgePlatform => 'unknown');+}++/**+ * Report once the platform is known, without anyone waiting for it.+ *+ * The event arrives a moment after the action rather than with it, which costs+ * nothing: it carries its own timestamp, taken when the work happened.+ */+function reportWithBridge(+ platform: Promise<TelemetryBridgePlatform>,+ emit: (platform: TelemetryBridgePlatform) => void+): void {+ void platform.then(emit).catch(() => {});+}++/** The same, for a room create whose other properties are already known. */+function reportRoomCreated(+ workspaceId: string,+ bridgeId: string | null | undefined,+ rest: {+ server_kind: TelemetryServerKind;+ agent_count: number;+ has_instructions: boolean;+ failure_reason: TelemetryRoomCreateFailure;+ }+): void {+ reportWithBridge(bridgePlatformOf(workspaceId, bridgeId), (bridge_platform) =>+ trackEvent('room_created', {+ ...rest,+ bridge_platform,+ outcome: rest.failure_reason === 'none' ? 'success' : 'failure',+ })+ );+}++/**+ * Everything that reads or writes what a workspace owns — its rooms, agents,+ * bridges and identities.+ *+ * Every one of these is addressed by workspace rather than by server, because+ * that is what the data belongs to: a server can host several workspaces, and+ * the same call against the same server means a different thing in each. The+ * server is resolved from the workspace, and the session's selected tenant is+ * made to match it, inside `withWorkspaceSession` — see there for why that is+ * the seam and not a courtesy at each call site.+ *+ * Registering a server, signing in to one and asking whether it can be reached+ * are not workspace-scoped and stay in `switch-servers/controller.ts`.+ */+export const workspacesController = createRPCController({+ list: (): Promise<Workspace[]> => listWorkspaces(),++ getActiveId: (): Promise<string | null> => getActiveWorkspaceId(),++ setActive: (workspaceId: string): Promise<void> => setActiveWorkspaceId(workspaceId),++ listAgents: (workspaceId: string): Promise<RemoteAgentSummary[]> =>+ withWorkspaceSession(workspaceId, fetchAgents),++ listRooms: (workspaceId: string): Promise<RemoteRoomSummary[]> =>+ withWorkspaceSession(workspaceId, fetchRooms),++ /** Admins and owners only; the gateway refuses anyone else with a 403. */+ listInvitations: listWorkspaceInvitations,++ createInvitation: createWorkspaceInvitation,++ revokeInvitation: revokeWorkspaceInvitation,++ /**+ * The e-mail domains anyone may join the workspace from. Admins and owners+ * only, and an admin may add only the domain of their own address.+ */+ listJoinDomains: listWorkspaceJoinDomains,++ addJoinDomain: addWorkspaceJoinDomain,++ removeJoinDomain: removeWorkspaceJoinDomain,++ listBridges: (workspaceId: string): Promise<RemoteBridge[]> =>+ withReachableWorkspaceSession(workspaceId, async (server) =>+ withResolvedHomeUrls(server, await fetchBridges(server))+ ),++ listBridgeTypes: (workspaceId: string): Promise<RemoteBridgeType[]> =>+ withReachableWorkspaceSession(workspaceId, fetchBridgeTypes),++ listInstallablePlatforms: (workspaceId: string): Promise<string[]> =>+ withReachableWorkspaceSession(workspaceId, fetchInstallablePlatforms),++ /** Returns the platform's consent URL for the renderer to open in the browser. */+ beginMessagingAppInstall: (params: { workspaceId: string; platform: string }): Promise<string> =>+ withReachableWorkspaceSession(params.workspaceId, (server) =>+ beginMessagingAppInstall(server, params.platform)+ ),++ /**+ * Attach a collaboration bridge to the chosen workspace (CHOO-1784).+ *+ * `params.connectionConfig` carries platform credentials. They cross the IPC+ * boundary once, on the way out, and are never written to Switch Console's disk+ * or returned to the renderer — the server stores them. Keep it that way: do+ * not log `params` here.+ */+ createBridge: (params: CreateBridgeParams): Promise<CreateBridgeResult> =>+ withReachableWorkspaceSession(params.workspaceId, async (server) => {+ const platform = bridgePlatformOfType(params.bridgeType);+ let result: CreateBridgeResult;+ try {+ result = await createBridgeOnServer(server, {+ bridgeType: params.bridgeType,+ displayName: params.displayName,+ connectionConfig: params.connectionConfig,+ setAsDefault: params.setAsDefault,+ channelCreationEnabled: params.channelCreationEnabled,+ });+ } catch (error) {+ trackEvent('bridge_connected', {+ bridge_platform: platform,+ outcome: 'failure',+ failure_reason: 'error',+ });+ throw error;+ }+ trackEvent('bridge_connected', {+ bridge_platform: platform,+ outcome: result.kind === 'created' ? 'success' : 'failure',+ failure_reason: bridgeFailureReason(result.kind),+ });+ return result;+ }),++ /**+ * Edit a bridge's operator-controlled switches — today, only whether the+ * connection may create channels. Admin-only, like registering one; see+ * `updateBridgeOnServer` for the recoverable-failure mapping.+ */+ updateBridge: (params: UpdateBridgeParams): Promise<UpdateBridgeResult> =>+ withReachableWorkspaceSession(params.workspaceId, (server) =>+ updateBridgeOnServer(server, {+ bridgeId: params.bridgeId,+ channelCreationEnabled: params.channelCreationEnabled,+ })+ ),++ /**+ * Disconnect a messaging app from the chosen workspace. Admin-only, and the+ * gateway deletes every Switch room on the bridge on the way — see+ * `deleteBridge`. The renderer owns the confirmation; by the time this runs+ * the rooms are being given up deliberately.+ */+ deleteBridge: (params: DeleteBridgeParams): Promise<DeleteBridgeResult> =>+ withReachableWorkspaceSession(params.workspaceId, async (server) => {+ // Read before the delete, because afterwards there is no bridge left to+ // read a platform from — and awaited, unlike every other report: left to+ // resolve on its own it would outlive the lease that scopes it to this+ // workspace. A disconnect is a confirmed, destructive action, not a hot+ // path, so it can afford the round trip.+ const platform = await bridgePlatformOnServer(server, params.bridgeId);+ const result = await deleteBridge(server, params.bridgeId);+ trackEvent('bridge_disconnected', {+ bridge_platform: platform,+ outcome: result.kind === 'deleted' ? 'success' : 'failure',+ });+ return result;+ }),++ /**+ * Create a room in the chosen workspace, owned by the signed-in user. Room+ * provisioning stays server-side (`POST /gateway/rooms`); this only maps+ * recoverable failures onto a typed result the modal can act on.+ */+ createRoom: async (params: CreateRoomParams): Promise<CreateRoomResult> => {+ // A host that has gone down is counted before it is raised, which is why+ // this is here rather than left to the session seam.+ const known = await workspaceServer(params.workspaceId);++ // Every report is made out here, after the lease rather than inside it: the+ // platform lookup behind it takes a lease of its own, and one started from+ // within this call's would be left addressing whichever workspace the+ // session had moved on to by the time it ran.+ const report = (failure_reason: TelemetryRoomCreateFailure) =>+ reportRoomCreated(params.workspaceId, params.bridgeId, {+ server_kind: serverKindOf(known),+ agent_count: params.agentIds.length,+ has_instructions: (params.instructions?.trim().length ?? 0) > 0,+ failure_reason,+ });++ const unreachable = hostUnreachable(known);+ if (unreachable) {+ report('unreachable');+ throw unreachable;+ }++ let result: CreateRoomResult;+ try {+ result = await withWorkspaceSession(params.workspaceId, (server) =>+ createRoomOnServer(server, {+ name: params.name,+ description: params.description,+ instructions: params.instructions,+ bridgeId: params.bridgeId,+ agentIds: params.agentIds,+ })+ );+ } catch (error) {+ report('error');+ throw error;+ }++ report(roomCreateFailureReason(result));+ return result;+ },++ createRoomFromTemplate: (+ workspaceId: string,+ yamlText: string,+ inputs: Record<string, string | number | boolean>,+ templateName: string+ ): Promise<ProvisionFromTemplateResult> =>+ withWorkspaceSession(workspaceId, (server) =>+ createRoomFromTemplate(server, yamlText, inputs, templateName)+ ),++ /** The runs the user may see, or null when the server does not record runs. */+ listTemplateRuns: (params: { workspaceId: string }): Promise<TemplateRun[] | null> =>+ withWorkspaceSession(params.workspaceId, fetchTemplateRuns),++ stopTemplateRun: (params: { workspaceId: string; rootRoomId: string }): Promise<TemplateRun> =>+ withWorkspaceSession(params.workspaceId, (server) =>+ changeTemplateRun(server, params.rootRoomId, 'stop')+ ),++ continueTemplateRun: (params: {+ workspaceId: string;+ rootRoomId: string;+ }): Promise<TemplateRun> =>+ withWorkspaceSession(params.workspaceId, (server) =>+ changeTemplateRun(server, params.rootRoomId, 'continue')+ ),++ fetchTemplateSchema: (workspaceId: string): Promise<Record<string, unknown> | null> =>+ withWorkspaceSession(workspaceId, fetchTemplateSchema),++ listTemplates: (params: {+ workspaceId: string;+ kind?: string;+ q?: string;+ }): Promise<StoredTemplateSummary[]> =>+ withWorkspaceSession(params.workspaceId, (server) =>+ fetchTemplates(server, { kind: params.kind, q: params.q })+ ),++ getTemplateDetail: (params: {+ workspaceId: string;+ templateId: string;+ }): Promise<StoredTemplateDetail> =>+ withWorkspaceSession(params.workspaceId, (server) =>+ fetchTemplateDetail(server, params.templateId)+ ),++ deleteTemplate: (params: { workspaceId: string; templateId: string }): Promise<void> =>+ withWorkspaceSession(params.workspaceId, (server) => deleteTemplate(server, params.templateId)),++ saveTemplate: (params: {+ workspaceId: string;+ name: string;+ description: string;+ kind: string;+ content: string;+ readVisibility?: TemplateVisibility;+ writeVisibility?: TemplateVisibility;+ }): Promise<StoredTemplateDetail> => {+ const { workspaceId, ...template } = params;+ return withWorkspaceSession(workspaceId, (server) => createTemplate(server, template));+ },++ updateTemplate: (params: {+ workspaceId: string;+ templateId: string;+ name?: string;+ description?: string;+ kind?: string;+ content?: string;+ readVisibility?: TemplateVisibility;+ writeVisibility?: TemplateVisibility;+ }): Promise<StoredTemplateDetail> => {+ const { workspaceId, templateId, ...changes } = params;+ return withWorkspaceSession(workspaceId, (server) =>+ updateTemplate(server, templateId, changes)+ );+ },++ exportRoomYaml: (params: { workspaceId: string; roomId: string }): Promise<string> =>+ withWorkspaceSession(params.workspaceId, (server) => exportRoomYaml(server, params.roomId)),++ listAgentRooms: (params: { workspaceId: string; agentId: string }): Promise<RemoteAgentRoom[]> =>+ withWorkspaceSession(params.workspaceId, (server) => fetchAgentRooms(server, params.agentId)),++ listRoomRoles: (params: { workspaceId: string; roomId: string }): Promise<RemoteRoomRole[]> =>+ withWorkspaceSession(params.workspaceId, (server) => fetchRoomRoles(server, params.roomId)),++ listRoomAgentIds: (params: { workspaceId: string; roomId: string }): Promise<string[]> =>+ withWorkspaceSession(params.workspaceId, (server) => fetchRoomAgentIds(server, params.roomId)),++ /** One room in full, for its configuration page. */+ getRoomDetail: (params: { workspaceId: string; roomId: string }): Promise<RemoteRoomDetail> =>+ withWorkspaceSession(params.workspaceId, (server) => fetchRoomDetail(server, params.roomId)),++ /**+ * Change a room's own settings. Failures propagate as-is — a user without+ * write access to the room needs the gateway's refusal, not a saved-looking+ * field holding a value the server never took.+ */+ updateRoom: (params: UpdateRoomParams): Promise<RemoteRoomDetail> =>+ withReachableWorkspaceSession(params.workspaceId, (server) =>+ updateRoom(server, params.roomId, {+ description: params.description,+ instructions: params.instructions,+ })+ ),++ /**+ * Add agents to a room. Failures propagate as-is: the caller shows the+ * gateway's own words (e.g. an agent whose server-side client is not running,+ * which the gateway rejects) rather than a generic message.+ */+ addRoomAgents: (params: {+ workspaceId: string;+ roomId: string;+ agentIds: string[];+ /**+ * Which screen this came from. The same call serves both, and the+ * one-agent-to-many-rooms screen loops it once per room — so without this,+ * adding an agent to five rooms is indistinguishable from five people each+ * adding one agent.+ */+ direction: TelemetryRoomAgentsDirection;+ }): Promise<void> =>+ withReachableWorkspaceSession(params.workspaceId, async (server) => {+ await addRoomAgents(server, params.roomId, params.agentIds);+ trackEvent('room_agents_added', {+ agent_count: params.agentIds.length,+ direction: roomAgentsDirectionOf(params.direction),+ });+ }),++ /** Remove one agent from a room. Membership only — the agent is not deleted. */+ removeRoomAgent: (params: {+ workspaceId: string;+ roomId: string;+ agentId: string;+ }): Promise<void> =>+ withReachableWorkspaceSession(params.workspaceId, (server) =>+ removeRoomAgent(server, params.roomId, params.agentId)+ ),++ /** Delete a room and everything in it. The gateway enforces who may. */+ deleteRoom: async (params: { workspaceId: string; roomId: string }): Promise<void> => {+ const known = await workspaceServer(params.workspaceId);+ const report = (outcome: TelemetryOutcome) =>+ trackEvent('room_deleted', { server_kind: serverKindOf(known), outcome });++ // A host that has gone down refuses the deletion as surely as the gateway+ // can, and the event has an outcome precisely so a refusal is counted.+ const unreachable = hostUnreachable(known);+ if (unreachable) {+ report('failure');+ throw unreachable;+ }++ await withWorkspaceSession(params.workspaceId, async (server) => {+ try {+ await deleteRoom(server, params.roomId);+ } catch (error) {+ report('failure');+ throw error;+ }+ report('success');+ });+ },++ listRoomGroups: (workspaceId: string): Promise<RemoteRoomGroup[]> =>+ withWorkspaceSession(workspaceId, fetchRoomGroups),++ listExternalUsers: (workspaceId: string): Promise<RemoteExternalUser[]> =>+ withWorkspaceSession(workspaceId, fetchAllExternalUsers),++ /**+ * Search a bridge's own user directory so the signed-in user can find+ * themselves before they have ever posted in the chat workspace (CHOO-2137).+ */+ searchBridgeDirectory: (params: {+ workspaceId: string;+ bridgeId: string;+ query: string;+ }): Promise<BridgeDirectorySearchResult> =>+ withReachableWorkspaceSession(params.workspaceId, (server) =>+ searchDirectoryOnServer(server, params.bridgeId, params.query)+ ),++ /** Claim a messaging-app account as the signed-in Switch user's own. */+ claimBridgeIdentity: async (params: ClaimIdentityParams): Promise<ClaimIdentityResult> => {+ const result = await withReachableWorkspaceSession(params.workspaceId, (server) =>+ claimIdentityOnServer(server, {+ bridgeId: params.bridgeId,+ externalUserId: params.externalUserId,+ username: params.username,+ })+ );+ // Reported after the lease, not inside it: the platform lookup takes a lease+ // of its own, and the bridge is still there to read afterwards.+ reportWithBridge(bridgePlatformOf(params.workspaceId, params.bridgeId), (bridge_platform) =>+ trackEvent('bridge_identity_claimed', {+ bridge_platform,+ outcome: result.kind === 'claimed' ? 'success' : 'failure',+ })+ );+ return result;+ },++ /** Give up a claim on a messaging-app account, leaving any other user's claim+ * on it in place. `userId` is whose claim to drop — null for the signed-in+ * user, which is the only one this app offers. Failures propagate: unclaiming+ * is a deliberate act, and reporting success for one that did not happen+ * would leave the user thinking an agent is no longer reachable by them when+ * it still is. */+ releaseBridgeIdentity: (params: {+ workspaceId: string;+ bridgeId: string;+ identityId: string;+ userId: string | null;+ }): Promise<void> =>+ withReachableWorkspaceSession(params.workspaceId, (server) =>+ releaseBridgeIdentity(server, params.bridgeId, params.identityId, params.userId)+ ),++ /** The messaging accounts the signed-in user has claimed in this workspace. */+ listMyIdentities: (workspaceId: string): Promise<LinkedIdentity[]> =>+ withWorkspaceSession(workspaceId, fetchMyIdentities),++ /** Whether the signed-in user owns an agent here that is set to answer its+ * owner, which is what makes an unlinked messaging account worth warning+ * about. One agent-list read, so callers need not ration it. */+ ownsOwnerAddressedAgent: (workspaceId: string): Promise<boolean> =>+ withWorkspaceSession(workspaceId, ownsOwnerAddressedAgent),++ getAddressingPolicy: (params: {+ workspaceId: string;+ agentId: string;+ }): Promise<AddressingPolicy | null> =>+ withWorkspaceSession(params.workspaceId, (server) =>+ fetchAddressingPolicy(server, params.agentId)+ ),++ updateAddressingPolicy: (params: {+ workspaceId: string;+ agentId: string;+ policy: AddressingPolicy | null;+ }): Promise<void> =>+ withWorkspaceSession(params.workspaceId, (server) =>+ updateAddressingPolicy(server, params.agentId, params.policy)+ ),++ /** Give this user's icon-less agents the avatar their name generates. Runs+ * once per workspace per app run; reports what happened so the caller can say+ * when the icons did not reach the server. */+ backfillAgentIcons: (workspaceId: string): Promise<AgentIconBackfill> =>+ withWorkspaceSession(workspaceId, (server) => backfillAgentIcons(workspaceId, server)),++ /** Set or clear an agent's icon. Returns the agent as the server now holds+ * it, so the caller refreshes from the stored value rather than the one it+ * hoped for. */+ updateAgentIcon: (params: {+ workspaceId: string;+ agentId: string;+ iconUrl: string | null;+ }): Promise<RemoteAgentSummary> =>+ withWorkspaceSession(params.workspaceId, (server) =>+ updateAgentIcon(server, params.agentId, params.iconUrl)+ ),++ verifyAgent: (params: { workspaceId: string; agentId: string }): Promise<AgentVerifyResult> =>+ withWorkspaceSession(params.workspaceId, async (server) => {+ try {+ return (await agentExistsOnServer(server, params.agentId)) ? 'found' : 'not-found';+ } catch (cause) {+ if (cause instanceof GatewayError && cause.kind === 'unauthorized') {+ return 'unauthenticated';+ }+ throw cause;+ }+ }),+});diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/invitations.test.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/invitations.test.tsnew file mode 100644index 000000000..3182066b6--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/invitations.test.ts@@ -0,0 +1,109 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const requireWorkspace = vi.hoisted(() => vi.fn());+const fetchInvitations = vi.hoisted(() => vi.fn());+const fetchInviteEmailEnabled = vi.hoisted(() => vi.fn());+const createInvitation = vi.hoisted(() => vi.fn());+const revokeInvitation = vi.hoisted(() => vi.fn());+const leased = vi.hoisted(() => [] as string[]);++const SERVER = vi.hoisted(() => ({+ id: 'srv-1',+ name: 'switch.example.com',+ gatewayUrl: 'https://switch.example.com/',+ apiUrl: 'https://switch.example.com',+}));++vi.mock('./workspaces-store', () => ({ requireWorkspace }));+vi.mock('./workspace-session', () => ({+ withReachableWorkspaceSession: (workspaceId: string, fn: (server: unknown) => unknown) => {+ leased.push(workspaceId);+ return fn(SERVER);+ },+}));+vi.mock('@main/core/switch-servers/gateway-client', () => ({+ fetchInvitations,+ fetchInviteEmailEnabled,+ createInvitation,+ revokeInvitation,+}));++import {+ createWorkspaceInvitation,+ listWorkspaceInvitations,+ revokeWorkspaceInvitation,+} from './invitations';++const INVITATION = {+ id: 'inv-1',+ role: 'member',+ email: null,+ expiresAt: '2026-10-05T00:00:00.000Z',+ usesRemaining: 1,+ revokedAt: null,+ createdAt: '2026-09-28T00:00:00.000Z',+};++beforeEach(() => {+ vi.clearAllMocks();+ leased.length = 0;+ requireWorkspace.mockResolvedValue({ id: 'ws-1', name: 'Acme', tenantId: 'tenant-1' });+});++describe('workspace invitations', () => {+ it('lists them for the workspace tenant, with whether e-mail is on', async () => {+ fetchInvitations.mockResolvedValue([INVITATION]);+ fetchInviteEmailEnabled.mockResolvedValue(true);++ await expect(listWorkspaceInvitations('ws-1')).resolves.toEqual({+ invitations: [INVITATION],+ emailEnabled: true,+ });+ expect(fetchInvitations).toHaveBeenCalledWith(SERVER, 'tenant-1');+ expect(leased).toEqual(['ws-1']);+ });++ it('hands back the link built from the gateway address, never the bare token', async () => {+ createInvitation.mockResolvedValue({+ invitation: INVITATION,+ token: 'a+b/c',+ emailDelivery: 'not_requested',+ });++ const created = await createWorkspaceInvitation({+ workspaceId: 'ws-1',+ role: 'member',+ email: null,+ expiresInHours: 168,+ usesRemaining: 1,+ });++ expect(createInvitation).toHaveBeenCalledWith(SERVER, 'tenant-1', {+ role: 'member',+ email: null,+ expiresInHours: 168,+ usesRemaining: 1,+ });+ expect(created).toEqual({+ invitation: INVITATION,+ link: 'https://switch.example.com/invite#token=a%2Bb%2Fc',+ emailDelivery: 'not_requested',+ });+ });++ it('revokes one by id on the workspace tenant', async () => {+ revokeInvitation.mockResolvedValue({ ...INVITATION, revokedAt: '2026-09-28T01:00:00.000Z' });++ await revokeWorkspaceInvitation({ workspaceId: 'ws-1', invitationId: 'inv-1' });++ expect(revokeInvitation).toHaveBeenCalledWith(SERVER, 'tenant-1', 'inv-1');+ });++ it('refuses a workspace not matched to a tenant, before touching the server', async () => {+ requireWorkspace.mockResolvedValue({ id: 'ws-1', name: 'Acme', tenantId: null });++ await expect(listWorkspaceInvitations('ws-1')).rejects.toThrow(/not matched/);+ expect(leased).toEqual([]);+ expect(fetchInvitations).not.toHaveBeenCalled();+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/invitations.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/invitations.tsnew file mode 100644index 000000000..7c0348d0d--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/invitations.ts@@ -0,0 +1,105 @@+import {+ addJoinDomain,+ createInvitation,+ fetchInvitations,+ fetchInviteEmailEnabled,+ fetchJoinDomains,+ removeJoinDomain,+ revokeInvitation,+} from '@main/core/switch-servers/gateway-client';+import {+ inviteLink,+ type CreatedInvitation,+ type CreateInvitationParams,+ type Invitation,+ type WorkspaceInvitations,+ type WorkspaceJoinDomains,+} from '@shared/core/workspaces/invitations';+import { withReachableWorkspaceSession } from './workspace-session';+import { requireWorkspace } from './workspaces-store';++/**+ * The gateway's id for a workspace, which the invitation routes are addressed by.+ *+ * A workspace not yet matched to a tenant has none, and there is nothing to+ * invite anyone to until it has: the call would name no workspace at all.+ */+async function requireTenantId(workspaceId: string): Promise<string> {+ const workspace = await requireWorkspace(workspaceId);+ if (workspace.tenantId === null) {+ throw new Error(+ `${workspace.name} is not matched to a workspace on its server yet, so there is nothing to invite anyone to. Sign in to the server again and retry.`+ );+ }+ return workspace.tenantId;+}++export async function listWorkspaceInvitations(workspaceId: string): Promise<WorkspaceInvitations> {+ const tenantId = await requireTenantId(workspaceId);+ return withReachableWorkspaceSession(workspaceId, async (server) => {+ const [invitations, emailEnabled] = await Promise.all([+ fetchInvitations(server, tenantId),+ fetchInviteEmailEnabled(server),+ ]);+ return { invitations, emailEnabled };+ });+}++export async function createWorkspaceInvitation({+ workspaceId,+ ...params+}: CreateInvitationParams): Promise<CreatedInvitation> {+ const tenantId = await requireTenantId(workspaceId);+ return withReachableWorkspaceSession(workspaceId, async (server) => {+ const created = await createInvitation(server, tenantId, params);+ return {+ invitation: created.invitation,+ link: inviteLink(server.gatewayUrl, created.token),+ emailDelivery: created.emailDelivery,+ };+ });+}++export async function revokeWorkspaceInvitation({+ workspaceId,+ invitationId,+}: {+ workspaceId: string;+ invitationId: string;+}): Promise<Invitation> {+ const tenantId = await requireTenantId(workspaceId);+ return withReachableWorkspaceSession(workspaceId, (server) =>+ revokeInvitation(server, tenantId, invitationId)+ );+}++export async function listWorkspaceJoinDomains(workspaceId: string): Promise<WorkspaceJoinDomains> {+ const tenantId = await requireTenantId(workspaceId);+ return withReachableWorkspaceSession(workspaceId, (server) => fetchJoinDomains(server, tenantId));+}++export async function addWorkspaceJoinDomain({+ workspaceId,+ domain,+}: {+ workspaceId: string;+ domain: string;+}): Promise<void> {+ const tenantId = await requireTenantId(workspaceId);+ return withReachableWorkspaceSession(workspaceId, (server) =>+ addJoinDomain(server, tenantId, domain)+ );+}++export async function removeWorkspaceJoinDomain({+ workspaceId,+ domain,+}: {+ workspaceId: string;+ domain: string;+}): Promise<void> {+ const tenantId = await requireTenantId(workspaceId);+ return withReachableWorkspaceSession(workspaceId, (server) =>+ removeJoinDomain(server, tenantId, domain)+ );+}diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.db.test.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.db.test.tsnew file mode 100644index 000000000..e897efd62--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.db.test.ts@@ -0,0 +1,487 @@+import { openFixture } from '@tooling/utils/db';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { AppDb } from '@main/db/client';+import { agents, locations, switchServers } from '@main/db/schema';+import { workspacesChangedChannel } from '@shared/core/workspaces/workspaceEvents';+import { isWithdrawnWorkspace } from '@shared/core/workspaces/workspaces';++const mocks = vi.hoisted(() => ({+ db: undefined as AppDb | undefined,+}));++const fetchTenants = vi.hoisted(() => vi.fn());+const decodeJwtTenantId = vi.hoisted(() => vi.fn((_jwt: string): string | null => null));+const getSessionCookie = vi.hoisted(() => vi.fn(async (): Promise<string | null> => null));+const listServers = vi.hoisted(() => vi.fn(async (): Promise<{ id: string }[]> => []));+const warn = vi.hoisted(() => vi.fn());+const emit = vi.hoisted(() => vi.fn());++vi.mock('@main/db/client', () => ({+ get db() {+ if (!mocks.db) throw new Error('Test database not initialized');+ return mocks.db;+ },+}));+vi.mock('@main/core/managed-switch-server/managed-server-status', () => ({+ isManagedServerRunning: () => true,+}));+vi.mock('@main/core/switch-servers/gateway-client', () => ({ decodeJwtTenantId, fetchTenants }));+vi.mock('@main/core/switch-servers/require-server', () => ({+ requireServer: async (id: string) => ({ id, name: id }),+}));+vi.mock('@main/lib/events', () => ({ events: { emit } }));+vi.mock('@main/lib/logger', () => {+ const logger = { debug: vi.fn(), info: vi.fn(), warn, error: vi.fn(), child: () => logger };+ return { log: logger };+});++// Mocked whole rather than in part: the module builds the encrypted secrets+// store at import, which a test has no key for.+vi.mock('@main/core/switch-servers/servers-store', () => ({ getSessionCookie, listServers }));++const { reconcileAllWorkspaces, reconcileServerWorkspaces } =+ await import('./reconcile-workspaces');+const {+ createTenantWorkspace,+ ensureServerWorkspace,+ getActiveWorkspaceId,+ listWorkspacesForServer,+ setActiveWorkspaceId,+} = await import('./workspaces-store');++function tenant(id: string, name: string, role = 'member') {+ return { id, slug: id, name, role };+}++describe('reconcile-workspaces', () => {+ let fixture: Awaited<ReturnType<typeof openFixture>>;++ beforeEach(async () => {+ vi.clearAllMocks();+ decodeJwtTenantId.mockReturnValue(null);+ getSessionCookie.mockResolvedValue(null);+ fixture = await openFixture('empty');+ mocks.db = fixture.db;+ fixture.sqlite.pragma('foreign_keys = ON');+ await fixture.db.insert(switchServers).values({+ id: 'srv-1',+ name: 'Local dev',+ gatewayUrl: 'https://srv-1.example.com',+ apiUrl: 'https://api-srv-1.example.com',+ });+ listServers.mockResolvedValue([{ id: 'srv-1' }]);+ });++ afterEach(() => {+ fixture.close();+ mocks.db = undefined;+ });++ /** An agent in a workspace, which is the one thing that makes it unguessable. */+ async function attachAgent(workspaceId: string): Promise<void> {+ await fixture.db+ .insert(locations)+ .values({ id: 'loc-1', name: 'repo', dir: '/repo' })+ .onConflictDoNothing();+ await fixture.db.insert(agents).values({+ id: `agent-${workspaceId}`,+ locationId: 'loc-1',+ name: 'a',+ providerId: 'claude',+ workspaceId,+ });+ }++ /**+ * The case every install upgrading into tenancy is in: one workspace carrying+ * every agent, and one membership it turns out to be.+ */+ it('claims the server’s existing workspace for its sole membership', async () => {+ const before = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });+ fetchTenants.mockResolvedValue([tenant('t-1', 'Default', 'owner')]);++ await reconcileServerWorkspaces('srv-1');++ const found = await listWorkspacesForServer('srv-1');+ expect(found).toHaveLength(1);+ // Same row: the agents, the active selection and the saved navigation all+ // name this id, and a replacement would detach every one of them.+ expect(found[0]!.id).toBe(before.id);+ expect(found[0]!.tenantId).toBe('t-1');+ expect(found[0]!.role).toBe('owner');+ });++ /**+ * A row is named after its server only until it is matched. After that the+ * workspace is a tenant, the gateway is the only place it can be named or+ * renamed, and nothing in this app offers to name one — so a local label kept+ * here is one neither side can ever correct.+ */+ it('takes the gateway’s name for a workspace it has matched', async () => {+ await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });+ fetchTenants.mockResolvedValue([tenant('t-1', 'Default')]);++ await reconcileServerWorkspaces('srv-1');++ expect((await listWorkspacesForServer('srv-1'))[0]!.name).toBe('Default');+ });++ /**+ * Also how a name typed into the create form survives the round trip that+ * records it failing. The workspace exists on the gateway under that name and+ * the local row does not have it yet; the next reconcile is what closes the+ * gap, so the name is late rather than lost.+ */+ it('carries a later rename on the gateway onto the row it already matched', async () => {+ await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });+ fetchTenants.mockResolvedValue([tenant('t-1', 'Default')]);+ await reconcileServerWorkspaces('srv-1');++ fetchTenants.mockResolvedValue([tenant('t-1', 'Acme Robotics')]);+ await reconcileServerWorkspaces('srv-1');++ expect((await listWorkspacesForServer('srv-1'))[0]!.name).toBe('Acme Robotics');+ });++ it('adds a workspace for a membership this install has no row for', async () => {+ await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });+ getSessionCookie.mockResolvedValue('cookie');+ decodeJwtTenantId.mockReturnValue('t-1');+ fetchTenants.mockResolvedValue([tenant('t-1', 'Default'), tenant('t-2', 'Research')]);++ await reconcileServerWorkspaces('srv-1');++ const found = await listWorkspacesForServer('srv-1');+ expect(found).toHaveLength(2);+ expect(found.find((w) => w.tenantId === 't-1')!.name).toBe('Default');+ expect(found.find((w) => w.tenantId === 't-2')!.name).toBe('Research');+ });++ /**+ * What every multi-membership sign-in used to produce: the gateway refuses a+ * scoped call from a session with several memberships and no selection, so+ * this server has never answered one and its row holds nothing. Left behind+ * while a row was added per membership, it appeared in the switcher as a+ * workspace belonging to no membership at all.+ */+ it('gives the registration row a membership rather than leaving it belonging to none', async () => {+ const before = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });+ fetchTenants.mockResolvedValue([tenant('t-1', 'Default')]);++ await reconcileServerWorkspaces('srv-1');++ const found = await listWorkspacesForServer('srv-1');+ expect(found).toHaveLength(1);+ // The same row, so the active selection and the saved navigation still name+ // something that exists.+ expect(found[0]!.id).toBe(before.id);+ expect(found[0]!.tenantId).toBe('t-1');+ });++ /**+ * Which membership inherits the id the agents, the active selection and the+ * saved navigation point at is not something to decide by coin toss. Every+ * membership gets its own row instead, and the placeholder nothing was ever+ * put in is dropped — the same list, arrived at the same way every time.+ */+ it('refuses to pick one of several memberships for the registration row', async () => {+ const before = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });+ fetchTenants.mockResolvedValue([tenant('t-1', 'Default'), tenant('t-2', 'Research')]);++ await reconcileServerWorkspaces('srv-1');++ const found = await listWorkspacesForServer('srv-1');+ expect(found).toHaveLength(2);+ expect(found.some((w) => w.id === before.id)).toBe(false);+ expect(found.map((w) => w.name).toSorted()).toEqual(['Default', 'Research']);+ });++ /**+ * The cookie says which membership this row's calls have been reaching, so+ * there is nothing to guess and the row keeps its agents and its id.+ */+ it('adopts the membership the session already resolves to', async () => {+ const before = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });+ getSessionCookie.mockResolvedValue('cookie');+ decodeJwtTenantId.mockReturnValue('t-2');+ fetchTenants.mockResolvedValue([tenant('t-1', 'Default'), tenant('t-2', 'Research')]);++ await reconcileServerWorkspaces('srv-1');++ const found = await listWorkspacesForServer('srv-1');+ expect(found).toHaveLength(2);+ expect(found.find((w) => w.id === before.id)!.tenantId).toBe('t-2');+ });++ /**+ * The one case that cannot be answered: agents were registered through this+ * row, so it stands for wherever they live, and naming it the wrong+ * membership would move them somewhere the user cannot see.+ */+ it('refuses to guess which membership a workspace with agents holds', async () => {+ const before = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });+ await attachAgent(before.id);+ fetchTenants.mockResolvedValue([tenant('t-1', 'Default'), tenant('t-2', 'Research')]);++ await reconcileServerWorkspaces('srv-1');++ const found = await listWorkspacesForServer('srv-1');+ expect(found.find((w) => w.id === before.id)!.tenantId).toBeNull();+ // Both memberships are still recorded — only the question of which one the+ // existing row holds is left open.+ expect(found).toHaveLength(3);+ expect(found.some((w) => w.tenantId === 't-1')).toBe(true);+ expect(found.some((w) => w.tenantId === 't-2')).toBe(true);+ expect(warn).toHaveBeenCalled();+ });++ /**+ * The repair the short-circuit used to make impossible: once every membership+ * has a row, the leftover registration row could never be revisited, and no+ * later boot or sign-in could clear it.+ */+ it('drops an empty registration row left over once every membership has one', async () => {+ const before = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });+ await createTenantWorkspace('srv-1', {+ id: 't-1',+ slug: 't-1',+ name: 'Default',+ role: 'owner',+ });+ await createTenantWorkspace('srv-1', {+ id: 't-2',+ slug: 't-2',+ name: 'Research',+ role: 'member',+ });+ fetchTenants.mockResolvedValue([tenant('t-1', 'Default'), tenant('t-2', 'Research')]);++ await reconcileServerWorkspaces('srv-1');++ const found = await listWorkspacesForServer('srv-1');+ expect(found).toHaveLength(2);+ expect(found.some((w) => w.id === before.id)).toBe(false);+ });++ /**+ * The boot sweep runs behind an open window that read its list before it+ * started, and nothing else tells that window the list moved. Without this a+ * membership gained or lost between launches stays invisible for the whole+ * session, and the row dropped above goes on being offered in the switcher+ * after it has gone.+ */+ it('announces the change so an open window re-reads the list', async () => {+ await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });+ fetchTenants.mockResolvedValue([tenant('t-1', 'Default')]);++ await reconcileServerWorkspaces('srv-1');++ expect(emit).toHaveBeenCalledWith(workspacesChangedChannel, undefined);+ });++ /**+ * The boot sweep is not awaited, so a sign-in lands in the middle of it. Read+ * together, both passes see a membership with no row and both create one; the+ * unique index then turns the loser into an error that abandons the rest of+ * its pass, leaving the tenants it had not reached yet unmatched.+ */+ it('runs two passes on one server one after the other', async () => {+ await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });+ getSessionCookie.mockResolvedValue('cookie');+ decodeJwtTenantId.mockReturnValue('t-1');+ fetchTenants.mockResolvedValue([+ tenant('t-1', 'Default'),+ tenant('t-2', 'Research'),+ tenant('t-3', 'Ops'),+ ]);++ await Promise.all([reconcileServerWorkspaces('srv-1'), reconcileServerWorkspaces('srv-1')]);++ const found = await listWorkspacesForServer('srv-1');+ expect(found).toHaveLength(3);+ expect(found.map((w) => w.tenantId).toSorted((a, b) => a!.localeCompare(b!))).toEqual([+ 't-1',+ 't-2',+ 't-3',+ ]);+ });++ it('carries a role change on a workspace it already matched', async () => {+ const existing = await createTenantWorkspace('srv-1', {+ id: 't-1',+ slug: 't-1',+ name: 'Research',+ role: 'member',+ });+ fetchTenants.mockResolvedValue([tenant('t-1', 'Research', 'admin')]);++ await reconcileServerWorkspaces('srv-1');++ const found = await listWorkspacesForServer('srv-1');+ expect(found).toHaveLength(1);+ expect(found[0]!.id).toBe(existing.id);+ expect(found[0]!.role).toBe('admin');+ });++ /**+ * Deleting it would silently detach that workspace's agents. Kept, so the+ * next call scoped to it fails and says why — and said out loud now.+ */+ it('keeps a workspace whose membership has been withdrawn, and says so', async () => {+ await createTenantWorkspace('srv-1', {+ id: 't-gone',+ slug: 't-gone',+ name: 'Research',+ role: 'member',+ });+ fetchTenants.mockResolvedValue([tenant('t-1', 'Default')]);++ await reconcileServerWorkspaces('srv-1');++ const found = await listWorkspacesForServer('srv-1');+ const gone = found.find((w) => w.tenantId === 't-gone');+ expect(gone).toBeDefined();+ // The role is what the switcher reads to say so before the click, rather+ // than leaving the log file as the only place it is said.+ expect(gone!.role).toBeNull();+ expect(isWithdrawnWorkspace(gone!)).toBe(true);+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('no longer a member'), {+ server: 'srv-1',+ workspace: expect.any(String),+ });+ });++ it('restores the role when a withdrawn membership is granted again', async () => {+ await createTenantWorkspace('srv-1', {+ id: 't-back',+ slug: 't-back',+ name: 'Research',+ role: 'admin',+ });+ fetchTenants.mockResolvedValue([tenant('t-1', 'Default')]);+ await reconcileServerWorkspaces('srv-1');++ fetchTenants.mockResolvedValue([tenant('t-1', 'Default'), tenant('t-back', 'Research')]);+ await reconcileServerWorkspaces('srv-1');++ const back = (await listWorkspacesForServer('srv-1')).find((w) => w.tenantId === 't-back');+ expect(isWithdrawnWorkspace(back!)).toBe(false);+ });++ /**+ * Signing in to a server as a different account withdraws every workspace+ * the previous account held. A window left on one is refused on every read.+ */+ it('moves the selection off a withdrawn workspace onto one this account can open', async () => {+ const previous = await createTenantWorkspace('srv-1', {+ id: 't-previous',+ slug: 't-previous',+ name: 'Previous account’s',+ role: 'owner',+ });+ await setActiveWorkspaceId(previous.id);+ fetchTenants.mockResolvedValue([tenant('t-1', 'Default', 'owner')]);++ await reconcileServerWorkspaces('srv-1');++ const found = await listWorkspacesForServer('srv-1');+ expect(await getActiveWorkspaceId()).toBe(found.find((w) => w.tenantId === 't-1')!.id);+ });++ it('leaves the selection on a withdrawn workspace when nothing else can be opened', async () => {+ const held = await createTenantWorkspace('srv-1', {+ id: 't-gone',+ slug: 't-gone',+ name: 'Research',+ role: 'member',+ });+ await setActiveWorkspaceId(held.id);+ fetchTenants.mockResolvedValue([]);++ await reconcileServerWorkspaces('srv-1');++ expect(await getActiveWorkspaceId()).toBe(held.id);+ });++ // An account in no workspace at all is a server the user cannot use; saying+ // nothing and deleting the local row would look like it had never been set up.+ it('leaves the rows alone when the gateway reports no membership', async () => {+ const before = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });+ fetchTenants.mockResolvedValue([]);++ await reconcileServerWorkspaces('srv-1');++ const found = await listWorkspacesForServer('srv-1');+ expect(found).toEqual([before]);+ expect(warn).toHaveBeenCalled();+ });++ /**+ * The short-circuit for "no memberships" used to return before the withdrawal+ * pass, so the one case where every row has been withdrawn was the one case+ * that never marked any. The switcher and the first-run picker went on+ * offering them, and the refusal only arrived after the click.+ */+ it('marks every row withdrawn when the account is left in no workspace', async () => {+ const held = await createTenantWorkspace('srv-1', {+ id: 't-gone',+ slug: 't-gone',+ name: 'Research',+ role: 'member',+ });+ fetchTenants.mockResolvedValue([]);++ await reconcileServerWorkspaces('srv-1');++ const found = await listWorkspacesForServer('srv-1');+ expect(found.find((w) => w.id === held.id)!.role).toBeNull();+ expect(found.find((w) => w.id === held.id)!.tenantId).toBe('t-gone');+ });++ it('is idempotent across launches', async () => {+ const before = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });+ fetchTenants.mockResolvedValue([tenant('t-1', 'Default')]);++ await reconcileServerWorkspaces('srv-1');+ await reconcileServerWorkspaces('srv-1');++ const found = await listWorkspacesForServer('srv-1');+ expect(found).toHaveLength(1);+ expect(found[0]!.id).toBe(before.id);+ });++ describe('the boot sweep', () => {+ // Asking costs a round trip that can only be refused, and the answer would+ // be thrown away.+ it('skips a server this install is not signed in to', async () => {+ await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });++ await reconcileAllWorkspaces();++ expect(fetchTenants).not.toHaveBeenCalled();+ });++ // One server being down must not stop the rest from being reconciled.+ it('carries on past a server that cannot be reached', async () => {+ await fixture.db.insert(switchServers).values({+ id: 'srv-2',+ name: 'Staging',+ gatewayUrl: 'https://srv-2.example.com',+ apiUrl: 'https://api-srv-2.example.com',+ });+ await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });+ await ensureServerWorkspace({ id: 'srv-2', name: 'Staging' });+ listServers.mockResolvedValue([{ id: 'srv-1' }, { id: 'srv-2' }]);+ getSessionCookie.mockResolvedValue('cookie');+ fetchTenants+ .mockRejectedValueOnce(new Error('no route to host'))+ .mockResolvedValue([tenant('t-2', 'Default')]);++ await reconcileAllWorkspaces();++ expect((await listWorkspacesForServer('srv-1'))[0]!.tenantId).toBeNull();+ expect((await listWorkspacesForServer('srv-2'))[0]!.tenantId).toBe('t-2');+ expect(warn).toHaveBeenCalled();+ });+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.tsnew file mode 100644index 000000000..4ac6e58de--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.ts@@ -0,0 +1,228 @@+import { isManagedServerRunning } from '@main/core/managed-switch-server/managed-server-status';+import {+ decodeJwtTenantId,+ fetchTenants,+ type RemoteTenant,+} from '@main/core/switch-servers/gateway-client';+import { requireServer } from '@main/core/switch-servers/require-server';+import { getSessionCookie, listServers } from '@main/core/switch-servers/servers-store';+import { events } from '@main/lib/events';+import { log } from '@main/lib/logger';+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';+import { workspacesChangedChannel } from '@shared/core/workspaces/workspaceEvents';+import type { Workspace } from '@shared/core/workspaces/workspaces';+import {+ clearWorkspaceRole,+ createTenantWorkspace,+ discardEmptyWorkspace,+ leaveUnavailableActiveWorkspace,+ listWorkspacesForServer,+ setWorkspaceTenant,+ workspaceHasAgents,+} from './workspaces-store';++/**+ * The tenant this server's session resolves to — the one whose data every call+ * made against it so far has actually reached.+ *+ * The gateway resolves a session to the tenant its cookie selects, or to the+ * sole membership when nothing is selected; with several memberships and no+ * selection it refuses the request instead of guessing. So a server that has+ * ever answered has exactly one answer here, and when there is none nothing has+ * been attached to a workspace yet and there is nothing to get wrong.+ */+async function resolvedTenant(+ server: SwitchServer,+ tenants: RemoteTenant[]+): Promise<RemoteTenant | null> {+ const cookie = await getSessionCookie(server.id);+ const selected = cookie ? decodeJwtTenantId(cookie) : null;+ // A claim naming a membership the account no longer holds answers nothing, so+ // it falls through rather than standing in the way of the sole-membership+ // answer below — which is what the gateway itself would resolve the next call+ // to.+ const claimed = selected ? tenants.find((tenant) => tenant.id === selected) : undefined;+ if (claimed) return claimed;+ return tenants.length === 1 ? tenants[0]! : null;+}++/**+ * The membership to give the tenant-less row a server is registered with, or+ * null when it cannot be told and must not be guessed.+ *+ * Every server starts with one such row, and until it is matched it belongs to+ * nothing: a call scoped to it selects no tenant, so the gateway answers under+ * whatever the session last selected — another workspace's rooms and agents,+ * under this one's name, with no error anywhere. Leaving one behind while+ * creating a row per membership is how that used to happen on every+ * multi-membership sign-in.+ */+async function tenantToAdopt(+ server: SwitchServer,+ unclaimed: Workspace,+ tenants: RemoteTenant[],+ unmatched: RemoteTenant[]+): Promise<RemoteTenant | null> {+ // The one this row's calls have been reaching all along, when no other row+ // holds it already.+ const resolved = await resolvedTenant(server, tenants);+ if (resolved && unmatched.some((tenant) => tenant.id === resolved.id)) return resolved;+ // Only where there is nothing to choose between. Nothing was ever registered+ // through the row, so there is no data to put anywhere, and a membership the+ // user can see and switch away from beats a row belonging to none of them.+ // With several it would be a coin toss deciding which membership inherits the+ // id the saved navigation and the active selection point at; left unadopted,+ // every membership gets its own row and the empty placeholder is dropped+ // further down, which reaches the same list without the toss.+ if (unmatched.length === 1 && !(await workspaceHasAgents(unclaimed.id))) return unmatched[0]!;+ return null;+}++/**+ * Mark the workspaces still held locally for a membership that has gone.+ *+ * The row is kept — deleting it would silently detach its agents — so the mark+ * is what stops it reading as a workspace the user can still open. A log line+ * alone would leave the switcher listing it exactly like the others, and the+ * only sign would be the gateway refusing the call after the click.+ */+async function markWithdrawnMemberships(+ serverId: string,+ local: Workspace[],+ tenants: RemoteTenant[]+): Promise<void> {+ for (const workspace of local) {+ if (!workspace.tenantId) continue;+ if (tenants.some((tenant) => tenant.id === workspace.tenantId)) continue;+ log.warn(+ 'workspaces: this account is no longer a member of a workspace held locally; calls scoped to it will be refused',+ { server: serverId, workspace: workspace.id }+ );+ if (workspace.role !== null) await clearWorkspaceRole(workspace.id);+ }+}++/**+ * Match this install's workspaces for a server against the memberships the+ * gateway reports.+ *+ * A server registers before anyone asks which workspaces its account belongs+ * to, so its first row is created tenant-less and named after the server. This+ * is what later gives that row its tenant — claiming it rather than replacing+ * it, so the agents registered through it stay where they are — and adds a row+ * for every other membership.+ *+ * A row whose membership has been withdrawn is kept, not deleted. Deleting it+ * would silently detach that workspace's agents; leaving it means the next call+ * scoped to it fails and says why.+ */+export async function reconcileServerWorkspaces(serverId: string): Promise<void> {+ // The boot sweep is not awaited and a sign-in can land in the middle of it.+ // Two passes that both read the rows before either writes create the same+ // tenant twice, and the unique index turns the loser into an error that+ // abandons the rest of its pass — so they run one after the other instead.+ const queued = (inFlight.get(serverId) ?? Promise.resolve())+ .then(+ () => reconcileOneServer(serverId),+ () => reconcileOneServer(serverId)+ )+ .then(() => leaveUnavailableActiveWorkspace(serverId))+ // An open window read its list before this ran, and nothing else tells it+ // the list moved. Without this a membership added or withdrawn between+ // launches stays invisible for the session, and a placeholder dropped below+ // goes on being offered in the switcher after the row it names has gone.+ .then(() => {+ events.emit(workspacesChangedChannel, undefined);+ });+ inFlight.set(+ serverId,+ queued.then(+ () => {},+ () => {}+ )+ );+ return queued;+}++const inFlight = new Map<string, Promise<void>>();++async function reconcileOneServer(serverId: string): Promise<void> {+ const server = await requireServer(serverId);+ const tenants = await fetchTenants(server);+ const local = await listWorkspacesForServer(serverId);+ // Marked before the short-circuit below, not after it: an account that is in+ // nothing has had every membership withdrawn, and that is precisely the case+ // where a row still claiming one would go on being offered as somewhere to+ // work.+ await markWithdrawnMemberships(serverId, local, tenants);++ if (tenants.length === 0) {+ log.warn('workspaces: the gateway reports no workspace membership for this account', {+ server: serverId,+ });+ return;+ }++ const claimed = new Map(+ local+ .filter((workspace) => workspace.tenantId)+ .map((workspace) => [workspace.tenantId!, workspace])+ );+ for (const tenant of tenants) {+ const workspace = claimed.get(tenant.id);+ if (workspace) await setWorkspaceTenant(workspace.id, tenant);+ }++ const unmatched = tenants.filter((tenant) => !claimed.has(tenant.id));+ const unclaimed = local.find((workspace) => !workspace.tenantId) ?? null;+ const adopting = unclaimed ? await tenantToAdopt(server, unclaimed, tenants, unmatched) : null;+ if (unclaimed && adopting) await setWorkspaceTenant(unclaimed.id, adopting);++ for (const tenant of unmatched) {+ if (tenant.id === adopting?.id) continue;+ await createTenantWorkspace(serverId, tenant);+ }++ if (!unclaimed || adopting) return;++ // Reached when every membership is held by another row and this one is left+ // over. Empty, it is a placeholder the reconcile has overtaken and dropping+ // it is the whole repair; holding agents, it is the only record of where they+ // live and is kept, unmatched, so the next call scoped to it is refused and+ // says why rather than answering as some other workspace.+ if (await workspaceHasAgents(unclaimed.id)) {+ log.warn(+ 'workspaces: cannot tell which workspace this server’s existing agents belong to; leaving it unmatched, and calls scoped to it will be refused',+ { server: serverId, workspace: unclaimed.id, memberships: tenants.length }+ );+ return;+ }+ await discardEmptyWorkspace(unclaimed.id);+}++/**+ * Reconcile every server this install holds a session for.+ *+ * Run at boot and left unawaited: a workspace list that is one launch stale is+ * cosmetic, and a server that is slow or down must not hold up the window. A+ * managed server whose stack is not running is skipped rather than probed —+ * its gateway port is not listening, so the attempt only produces a network+ * error in the log (CHOO-1657).+ */+export async function reconcileAllWorkspaces(): Promise<void> {+ for (const server of await listServers()) {+ // The cookie read is inside the guard with everything else: it opens the+ // keychain, and a machine that refuses to unlock it would otherwise take+ // the whole sweep down on the first server and skip the rest in silence.+ try {+ if (server.managed && !isManagedServerRunning(server)) continue;+ if (!(await getSessionCookie(server.id))) continue;+ await reconcileServerWorkspaces(server.id);+ } catch (error: unknown) {+ log.warn('workspaces: could not reconcile a server’s workspaces', {+ server: server.id,+ error: String(error),+ });+ }+ }+}diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/workspace-session.test.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/workspace-session.test.tsnew file mode 100644index 000000000..d53d17ee5--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/workspace-session.test.ts@@ -0,0 +1,312 @@+/**+ * The seam every tenant-owned gateway call goes through.+ *+ * What it has to get right is not visible in any one call: a Switch session+ * selects one tenant at a time, so the guarantee is about what happens when+ * calls for two workspaces on the same server overlap. If a switch can land+ * between another call reading the cookie and sending it, that call quietly+ * answers with the wrong workspace's data and nothing anywhere reports an+ * error. These tests drive that overlap deliberately, since it is not a state+ * the app reaches on demand.+ */+import { beforeEach, describe, expect, it, vi } from 'vitest';++const decodeJwtTenantId = vi.hoisted(() => vi.fn<(jwt: string) => string | null>());+const switchTenant = vi.hoisted(() =>+ vi.fn<(server: unknown, tenantId: string) => Promise<void>>()+);+const getSessionCookie = vi.hoisted(() => vi.fn<(serverId: string) => Promise<string | null>>());+const requireWorkspace = vi.hoisted(() => vi.fn());+const listWorkspacesForServer = vi.hoisted(() => vi.fn());+const hostUnreachable = vi.hoisted(() => vi.fn((): unknown => null));++vi.mock('@main/core/switch-servers/gateway-client', () => ({ decodeJwtTenantId, switchTenant }));+vi.mock('@main/core/switch-servers/servers-store', () => ({ getSessionCookie }));+vi.mock('@main/core/switch-servers/require-server', () => ({+ hostUnreachable,+ requireServer: async (serverId: string) => ({ id: serverId, name: serverId }),+}));+vi.mock('./workspaces-store', () => ({ requireWorkspace, listWorkspacesForServer }));++import { assertedTenant } from './asserted-tenant';+import {+ forgetServerSession,+ withReachableWorkspaceSession,+ withWorkspaceSession,+} from './workspace-session';++const SERVER = 'srv-1';++/**+ * The tenant the server's session currently selects, as the cookie would carry+ * it.+ *+ * Modelled rather than stubbed away: the seam decides whether to switch by+ * reading the cookie back, so a `switchTenant` that left it unchanged would+ * make every call look like a switch and hide the very interleaving these tests+ * are about.+ */+let selected: string | null = null;++/** The rows the seam resolves, keyed by workspace id. */+const rows = new Map<+ string,+ { id: string; name: string; serverId: string; tenantId: string | null; role: string | null }+>();++function workspace(+ id: string,+ tenantId: string | null,+ role: string | null = tenantId === null ? null : 'member'+) {+ const row = { id, name: id, serverId: SERVER, tenantId, role };+ rows.set(id, row);+ return row;+}++/** A promise plus the handles to settle it, so a call can be held mid-flight. */+function deferred<T>() {+ let resolve!: (value: T) => void;+ let reject!: (cause: unknown) => void;+ const promise = new Promise<T>((res, rej) => {+ resolve = res;+ reject = rej;+ });+ return { promise, resolve, reject };+}++/**+ * Let everything that can proceed proceed, so "still pending" means blocked+ * rather than merely not got to yet. A macrotask boundary, since the admission+ * queue is several promise hops deep.+ */+async function settle(): Promise<void> {+ for (let i = 0; i < 4; i++) await new Promise((resolve) => setTimeout(resolve, 0));+}++beforeEach(() => {+ rows.clear();+ forgetServerSession(SERVER);+ // A session that has selected nothing, as it is straight after signing in.+ selected = null;+ switchTenant.mockReset().mockImplementation(async (_server: unknown, tenantId: string) => {+ selected = tenantId;+ });+ hostUnreachable.mockReset().mockReturnValue(null);+ getSessionCookie.mockReset().mockImplementation(async () => `cookie:${selected ?? 'none'}`);+ decodeJwtTenantId.mockReset().mockImplementation((jwt: string) => {+ const tenant = jwt.slice('cookie:'.length);+ return tenant === 'none' ? null : tenant;+ });+ requireWorkspace.mockReset().mockImplementation(async (id: string) => {+ const row = rows.get(id);+ if (!row) throw new Error(`no workspace ${id}`);+ return row;+ });+ listWorkspacesForServer.mockReset().mockImplementation(async () => [...rows.values()]);+});++describe('withWorkspaceSession', () => {+ it('selects the workspace’s tenant before the call goes out', async () => {+ workspace('ws-a', 'tenant-a');+ const order: string[] = [];+ switchTenant.mockImplementation(async () => void order.push('switch'));++ await withWorkspaceSession('ws-a', async (server) => {+ order.push(`call:${server.id}`);+ });++ expect(order).toEqual(['switch', `call:${SERVER}`]);+ expect(switchTenant).toHaveBeenCalledWith(expect.objectContaining({ id: SERVER }), 'tenant-a');+ });++ it('does not switch when the session already selects that tenant', async () => {+ workspace('ws-a', 'tenant-a');+ selected = 'tenant-a';++ await withWorkspaceSession('ws-a', async () => {});++ expect(switchTenant).not.toHaveBeenCalled();+ });++ /**+ * The row a server is registered with, before any gateway has been asked.+ * There is no id to select and nothing to confuse it with, so the call goes+ * out as it did before workspaces existed.+ */+ it('asks a tenant-less workspace’s server without selecting anything', async () => {+ workspace('ws-only', null);++ await withWorkspaceSession('ws-only', async () => {});++ expect(switchTenant).not.toHaveBeenCalled();+ });++ /**+ * The same row on a server that turns out to hold several. The call would+ * still succeed — the gateway answers for whatever the session last selected+ * — and would answer with another workspace's rooms and agents under this+ * one's name. There is no way to tell which is meant, so it is refused rather+ * than guessed.+ */+ it('refuses a tenant-less workspace on a server holding several', async () => {+ workspace('ws-stale', null);+ workspace('ws-b', 'tenant-b');+ const ran = vi.fn();++ await expect(withWorkspaceSession('ws-stale', ran)).rejects.toThrow(+ /has not been matched to one of the 2/+ );+ expect(ran).not.toHaveBeenCalled();+ expect(switchTenant).not.toHaveBeenCalled();+ });++ /**+ * A membership the account signed in here no longer holds. The gateway would+ * refuse the switch too, but only as "not a member of this tenant", and on+ * every poll of every view showing the workspace.+ */+ it('refuses a withdrawn workspace without asking the server', async () => {+ workspace('ws-gone', 'tenant-gone', null);+ const ran = vi.fn();++ await expect(withWorkspaceSession('ws-gone', ran)).rejects.toThrow(+ /is not a member of ws-gone/+ );+ expect(ran).not.toHaveBeenCalled();+ expect(switchTenant).not.toHaveBeenCalled();+ });++ it('runs calls on the same tenant at the same time', async () => {+ workspace('ws-a', 'tenant-a');+ const first = deferred<void>();+ const inFlight: string[] = [];++ const a = withWorkspaceSession('ws-a', async () => {+ inFlight.push('a');+ await first.promise;+ });+ const b = withWorkspaceSession('ws-a', async () => void inFlight.push('b'));+ await settle();++ // Serialising here would be a correctness-free cost: they name one tenant,+ // so there is no switch between them to be straddled.+ expect(inFlight).toEqual(['a', 'b']);+ expect(switchTenant).toHaveBeenCalledTimes(1);++ first.resolve();+ await Promise.all([a, b]);+ });++ /**+ * The whole point of the lease. `switchTenant` replaces the selection for+ * every call on that server at once, so letting it run while another+ * workspace's call is outstanding would answer that call from the new tenant+ * — the exact silent wrong answer the seam exists to make impossible.+ */+ it('holds a switch back until the calls it would disturb are done', async () => {+ workspace('ws-a', 'tenant-a');+ workspace('ws-b', 'tenant-b');+ const holding = deferred<void>();+ const ranB = vi.fn();++ const a = withWorkspaceSession('ws-a', async () => {+ await holding.promise;+ });+ await settle();+ const b = withWorkspaceSession('ws-b', ranB);+ await settle();++ expect(switchTenant).toHaveBeenCalledTimes(1);+ expect(ranB).not.toHaveBeenCalled();++ holding.resolve();+ await a;+ await b;++ expect(switchTenant).toHaveBeenNthCalledWith(2, expect.anything(), 'tenant-b');+ expect(ranB).toHaveBeenCalled();+ });++ it('gives the lease up when the call throws, so the next switch is not stuck', async () => {+ workspace('ws-a', 'tenant-a');+ workspace('ws-b', 'tenant-b');++ await expect(+ withWorkspaceSession('ws-a', async () => {+ throw new Error('the gateway said no');+ })+ ).rejects.toThrow('the gateway said no');++ await withWorkspaceSession('ws-b', async () => {});++ expect(switchTenant).toHaveBeenNthCalledWith(2, expect.anything(), 'tenant-b');+ });++ /**+ * Read by anything that replaces the cookie underneath a call in flight: a+ * cookie minted by a fresh login selects no tenant, and handing it back+ * unchanged would finish the lease against the account's default workspace.+ */+ it('publishes the tenant the calls in flight are relying on, and forgets it after', async () => {+ workspace('ws-a', 'tenant-a');+ const holding = deferred<void>();++ const call = withWorkspaceSession('ws-a', async () => {+ await holding.promise;+ });+ await settle();++ expect(assertedTenant(SERVER)).toBe('tenant-a');++ holding.resolve();+ await call;++ expect(assertedTenant(SERVER)).toBeNull();+ });++ it('wakes a switch queued behind a server that has been removed', async () => {+ workspace('ws-a', 'tenant-a');+ workspace('ws-b', 'tenant-b');+ const holding = deferred<void>();++ const a = withWorkspaceSession('ws-a', async () => {+ await holding.promise;+ });+ await settle();+ const b = withWorkspaceSession('ws-b', async () => {});+ await settle();++ // The lease is never given up: the call belongs to a server that is gone.+ forgetServerSession(SERVER);+ await expect(b).resolves.toBeUndefined();++ holding.resolve();+ await a;+ });+});++describe('withReachableWorkspaceSession', () => {+ it('refuses before touching the session when the managed host is down', async () => {+ workspace('ws-a', 'tenant-a');+ hostUnreachable.mockReturnValue(new Error('build-box is not reachable'));+ const ran = vi.fn();++ await expect(withReachableWorkspaceSession('ws-a', ran)).rejects.toThrow('not reachable');++ // No switch means no side effect to undo, and the next call to a reachable+ // server does not find the session selecting a tenant nobody asked for.+ expect(switchTenant).not.toHaveBeenCalled();+ expect(ran).not.toHaveBeenCalled();+ expect(assertedTenant(SERVER)).toBeNull();+ });++ it('selects the tenant and runs while the host is up', async () => {+ workspace('ws-a', 'tenant-a');++ await expect(withReachableWorkspaceSession('ws-a', async () => 'answered')).resolves.toBe(+ 'answered'+ );+ expect(switchTenant).toHaveBeenCalledWith(expect.anything(), 'tenant-a');+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/workspace-session.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/workspace-session.tsnew file mode 100644index 000000000..c31ea4d42--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/workspace-session.ts@@ -0,0 +1,208 @@+import { decodeJwtTenantId, switchTenant } from '@main/core/switch-servers/gateway-client';+import { hostUnreachable, requireServer } from '@main/core/switch-servers/require-server';+import { getSessionCookie } from '@main/core/switch-servers/servers-store';+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';+import {+ isUnmatchedWorkspace,+ isWithdrawnWorkspace,+ type Workspace,+} from '@shared/core/workspaces/workspaces';+import { clearAssertedTenant, setAssertedTenant } from './asserted-tenant';+import { listWorkspacesForServer, requireWorkspace } from './workspaces-store';++/**+ * Calls in flight on a server's current tenant selection, and the queue that+ * changes it.+ *+ * A server session selects one tenant at a time, so a workspace-scoped call is+ * only addressing the workspace it names while that selection matches. Calls+ * that share the selection run in parallel and hold a lease; changing the+ * selection waits for every lease to be given up, so a switch can never land+ * between another call reading the cookie and sending it.+ */+type ServerSession = {+ leases: number;+ /** Resolvers waiting for `leases` to reach zero. */+ idle: Array<() => void>;+};++const sessions = new Map<string, ServerSession>();++/** Serialises the decision to switch, per server — never the calls themselves. */+const admissions = new Map<string, Promise<unknown>>();++function sessionFor(serverId: string): ServerSession {+ let session = sessions.get(serverId);+ if (!session) {+ session = { leases: 0, idle: [] };+ sessions.set(serverId, session);+ }+ return session;+}++function release(serverId: string, session: ServerSession): void {+ session.leases -= 1;+ if (session.leases > 0) return;+ for (const resolve of session.idle.splice(0)) resolve();+ clearAssertedTenant(serverId);+}++/**+ * Drop everything held for a server that no longer exists.+ *+ * Nothing prunes these as calls finish — an entry is the server's, not a call's+ * — so a removal is the one moment they can go. Left behind, a lease that leaked+ * would be inherited by whatever next holds the id, and a switch waiting for it+ * to be given up would wait for a call that ended with the server.+ */+export function forgetServerSession(serverId: string): void {+ const session = sessions.get(serverId);+ // Waiters first: a switch queued behind a server that has just gone would+ // otherwise never be woken at all.+ if (session) for (const resolve of session.idle.splice(0)) resolve();+ sessions.delete(serverId);+ admissions.delete(serverId);+ clearAssertedTenant(serverId);+}++function whenIdle(session: ServerSession): Promise<void> {+ if (session.leases === 0) return Promise.resolve();+ return new Promise<void>((resolve) => session.idle.push(resolve));+}++function admit<T>(serverId: string, task: () => Promise<T>): Promise<T> {+ const queued = (admissions.get(serverId) ?? Promise.resolve()).then(task, task);+ admissions.set(+ serverId,+ queued.then(+ () => {},+ () => {}+ )+ );+ return queued;+}++/**+ * Take a lease on `server`'s session with `tenantId` selected, switching the+ * selection first if it is something else.+ *+ * The caller must release the lease. Never call this from inside a leased call+ * on the same server: a switch waits for outstanding leases, and a call waiting+ * on its own would wait forever.+ */+async function acquire(server: SwitchServer, tenantId: string | null): Promise<ServerSession> {+ const session = sessionFor(server.id);+ await admit(server.id, async () => {+ if (tenantId !== null) {+ const cookie = await getSessionCookie(server.id);+ if (!cookie || decodeJwtTenantId(cookie) !== tenantId) {+ await whenIdle(session);+ await switchTenant(server, tenantId);+ }+ setAssertedTenant(server.id, tenantId);+ }+ session.leases += 1;+ });+ return session;+}++/**+ * The workspace, refusing one that names no tenant on a server holding several.+ *+ * A row without a tenant asserts nothing, so the call goes out under whatever+ * the session last selected and the gateway answers for that — another+ * workspace's rooms and agents, under this one's name, with no error anywhere.+ * Refusing costs nothing where a server holds one workspace: there is nothing+ * to confuse it with, and the gateway resolves the account's sole membership to+ * exactly that row.+ */+async function requireAddressableWorkspace(workspaceId: string): Promise<Workspace> {+ const workspace = await requireWorkspace(workspaceId);+ if (isWithdrawnWorkspace(workspace)) {+ // Refused here rather than sent: the gateway would refuse the switch as+ // well, but only as "not a member of this tenant", and every view polling+ // the workspace would ask again.+ throw new Error(+ `The account signed in to this Switch server is not a member of ${workspace.name}, so nothing in it can be read or changed. Switch to another workspace, or sign in as an account that belongs to it.`+ );+ }+ if (workspace.tenantId) return workspace;+ const onServer = await listWorkspacesForServer(workspace.serverId);+ if (isUnmatchedWorkspace(workspace, onServer.length)) {+ throw new Error(+ // Not "sign in again": signing in re-runs the reconcile, which is what+ // left the row unmatched in the first place and would do so again. The+ // row only survives because it holds agents, so the way out is to open+ // one of the workspaces the account does belong to and add those agents+ // there.+ `This workspace has not been matched to one of the ${onServer.length} this account belongs to on its Switch server, so there is no way to tell which one to ask. Switch to one of the others on this server; the agents left here have to be added again in the workspace they belong to.`+ );+ }+ return workspace;+}++/**+ * The server hosting a workspace, with no session work done.+ *+ * For the callers that have to know which server they are about to address+ * before they address it — the ones that report their own outcome, and so must+ * be able to count a refusal the session seam would otherwise raise past them.+ */+export async function workspaceServer(workspaceId: string): Promise<SwitchServer> {+ const workspace = await requireWorkspace(workspaceId);+ return requireServer(workspace.serverId);+}++/**+ * Run `fn` against the server hosting `workspaceId`, with that workspace's+ * tenant selected on the session.+ *+ * This is the seam every call that reads or writes tenant-owned data goes+ * through — rooms, agents, bridges, identities. Without it the renderer showing+ * one workspace while the session still selects another is invisible: every+ * call succeeds and answers with the other workspace's data. Making the+ * selection part of resolving the workspace makes that impossible rather than+ * something a bug report eventually surfaces.+ *+ * A workspace that has not been matched to a tenant yet asserts nothing — there+ * is no id to select, and the call goes out against whatever the session+ * resolves. That is the right answer only while the server holds one workspace,+ * which is why the rest are refused; see `requireAddressableWorkspace`. It still+ * takes a lease, so it cannot straddle another workspace's switch.+ */+export async function withWorkspaceSession<T>(+ workspaceId: string,+ fn: (server: SwitchServer) => Promise<T>+): Promise<T> {+ const workspace = await requireAddressableWorkspace(workspaceId);+ const server = await requireServer(workspace.serverId);+ const session = await acquire(server, workspace.tenantId);+ try {+ return await fn(server);+ } finally {+ release(server.id, session);+ }+}++/**+ * {@link withWorkspaceSession}, refusing to touch the gateway while the host+ * the server is managed on is unreachable (CHOO-1780).+ *+ * Checked before the session is acquired, so an unreachable host costs no+ * switch and starts no side effect it cannot finish.+ */+export async function withReachableWorkspaceSession<T>(+ workspaceId: string,+ fn: (server: SwitchServer) => Promise<T>+): Promise<T> {+ const workspace = await requireAddressableWorkspace(workspaceId);+ const server = await requireServer(workspace.serverId);+ const unreachable = hostUnreachable(server);+ if (unreachable) throw unreachable;+ const session = await acquire(server, workspace.tenantId);+ try {+ return await fn(server);+ } finally {+ release(server.id, session);+ }+}diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/workspaces-store.db.test.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/workspaces-store.db.test.tsnew file mode 100644index 000000000..0abc22d39--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/workspaces-store.db.test.ts@@ -0,0 +1,220 @@+import { openFixture } from '@tooling/utils/db';+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { AppDb } from '@main/db/client';+import { kv, switchServers, workspaces } from '@main/db/schema';++const mocks = vi.hoisted(() => ({+ db: undefined as AppDb | undefined,+}));++vi.mock('@main/db/client', () => ({+ get db() {+ if (!mocks.db) throw new Error('Test database not initialized');+ return mocks.db;+ },+}));++const {+ clearActiveWorkspaceOnServer,+ ensureServerWorkspace,+ getActiveWorkspaceId,+ listWorkspacesForServer,+ renameServerWorkspaces,+ requireWorkspaceForServer,+ requireWorkspace,+ serverIdForWorkspace,+ setActiveWorkspaceId,+} = await import('./workspaces-store');++describe('workspaces-store', () => {+ let fixture: Awaited<ReturnType<typeof openFixture>>;++ beforeEach(async () => {+ fixture = await openFixture('empty');+ mocks.db = fixture.db;+ fixture.sqlite.pragma('foreign_keys = ON');+ });++ afterEach(() => {+ fixture.close();+ mocks.db = undefined;+ });++ async function seedServer(id: string, name: string): Promise<void> {+ await fixture.db.insert(switchServers).values({+ id,+ name,+ gatewayUrl: `https://${id}.example.com`,+ apiUrl: `https://api-${id}.example.com`,+ });+ }++ describe('ensureServerWorkspace', () => {+ it('gives a newly registered server one workspace, named after it', async () => {+ await seedServer('srv-1', 'Local dev');++ const workspace = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });++ expect(workspace.serverId).toBe('srv-1');+ expect(workspace.name).toBe('Local dev');+ expect(workspace.tenantId).toBeNull();+ expect(workspace.slug).toBeNull();+ expect(workspace.role).toBeNull();+ });++ // The managed-server paths run again on every restart of a stack that+ // already exists, and a second workspace would silently split its agents.+ it('returns the existing workspace instead of adding a second', async () => {+ await seedServer('srv-1', 'Local dev');+ const first = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });++ const again = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });++ expect(again.id).toBe(first.id);+ expect(await listWorkspacesForServer('srv-1')).toHaveLength(1);+ });++ /**+ * The table's other unique index is on (server_id, tenant_id), and SQLite+ * treats NULLs as distinct, so it lets a second tenant-less row through.+ * Reconcile repairs the one unmatched row it finds; a second would be left+ * behind belonging to no membership, and every call scoped to it refused.+ */+ it('refuses a second tenant-less workspace on the same server', async () => {+ await seedServer('srv-1', 'Local dev');+ await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });++ await expect(+ fixture.db.insert(workspaces).values({ id: 'ws-2', serverId: 'srv-1', name: 'Local dev' })+ ).rejects.toThrow(/UNIQUE/);+ });+ });++ describe('requireWorkspaceForServer', () => {+ it('returns the one workspace a server has', async () => {+ await seedServer('srv-1', 'Local dev');+ const created = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });++ expect((await requireWorkspaceForServer('srv-1')).id).toBe(created.id);+ });++ it('raises for a server whose registration left it with none', async () => {+ await seedServer('srv-1', 'Local dev');++ await expect(requireWorkspaceForServer('srv-1')).rejects.toThrow('has no workspace');+ });++ // These callers run from screens showing the active workspace, so acting+ // anywhere else would act somewhere the user is not looking.+ it('takes the active one when a server has several', async () => {+ await seedServer('srv-1', 'Cloud');+ await fixture.db.insert(workspaces).values([+ { id: 'ws-a', serverId: 'srv-1', name: 'A', tenantId: 'tenant-a' },+ { id: 'ws-b', serverId: 'srv-1', name: 'B', tenantId: 'tenant-b' },+ ]);+ await setActiveWorkspaceId('ws-b');++ expect((await requireWorkspaceForServer('srv-1')).id).toBe('ws-b');+ });++ // Picking one would attach the agent to a workspace the user never chose,+ // and nothing would show them until it had already happened.+ it('raises when a server has several and the active one is elsewhere', async () => {+ await seedServer('srv-1', 'Cloud');+ await seedServer('srv-2', 'Local dev');+ await fixture.db.insert(workspaces).values([+ { id: 'ws-a', serverId: 'srv-1', name: 'A', tenantId: 'tenant-a' },+ { id: 'ws-b', serverId: 'srv-1', name: 'B', tenantId: 'tenant-b' },+ { id: 'ws-c', serverId: 'srv-2', name: 'C', tenantId: 'tenant-c' },+ ]);+ await setActiveWorkspaceId('ws-c');++ await expect(requireWorkspaceForServer('srv-1')).rejects.toThrow('must name one');+ });+ });++ describe('renameServerWorkspaces', () => {+ it('carries the new server name onto the workspace that took its name from it', async () => {+ await seedServer('srv-1', 'Old name');+ await ensureServerWorkspace({ id: 'srv-1', name: 'Old name' });++ await renameServerWorkspaces('srv-1', 'New name');++ expect((await listWorkspacesForServer('srv-1'))[0]!.name).toBe('New name');+ });++ // Once matched to a tenant the name is the gateway's, not the server's.+ it('leaves a tenant-bound workspace’s own name alone', async () => {+ await seedServer('srv-1', 'Old name');+ await fixture.db+ .insert(workspaces)+ .values({ id: 'ws-a', serverId: 'srv-1', name: 'Platform', tenantId: 'tenant-a' });++ await renameServerWorkspaces('srv-1', 'New name');++ expect((await listWorkspacesForServer('srv-1'))[0]!.name).toBe('Platform');+ });+ });++ describe('serverIdForWorkspace', () => {+ it('finds the server hosting a workspace', async () => {+ await seedServer('srv-1', 'Local dev');+ const created = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });++ expect(await serverIdForWorkspace(created.id)).toBe('srv-1');+ });++ it('answers null for an agent with no workspace', async () => {+ expect(await serverIdForWorkspace(null)).toBeNull();+ });+ });++ describe('the active selection', () => {+ it('round-trips a workspace id', async () => {+ await seedServer('srv-1', 'Local dev');+ const created = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });++ await setActiveWorkspaceId(created.id);++ expect(await getActiveWorkspaceId()).toBe(created.id);+ });++ it('refuses to select a workspace that does not exist', async () => {+ await expect(setActiveWorkspaceId('ws-missing')).rejects.toThrow('No workspace with id');+ });++ // The selection is a plain kv value; nothing cascades to it when the+ // server, and with it the workspace, is deleted.+ it('is cleared when the server holding the selected workspace goes', async () => {+ await seedServer('srv-1', 'Local dev');+ const created = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });+ await setActiveWorkspaceId(created.id);++ await clearActiveWorkspaceOnServer('srv-1');++ expect(await getActiveWorkspaceId()).toBeNull();+ expect(await fixture.db.select().from(kv).where(eq(kv.key, 'activeWorkspaceId'))).toEqual([]);+ });++ it('survives another server being removed', async () => {+ await seedServer('srv-1', 'Local dev');+ await seedServer('srv-2', 'Cloud');+ const created = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });+ await ensureServerWorkspace({ id: 'srv-2', name: 'Cloud' });+ await setActiveWorkspaceId(created.id);++ await clearActiveWorkspaceOnServer('srv-2');++ expect(await getActiveWorkspaceId()).toBe(created.id);+ });+ });++ describe('requireWorkspace', () => {+ it('names the id it could not find', async () => {+ await expect(requireWorkspace('ws-missing')).rejects.toThrow(+ 'No workspace with id ws-missing'+ );+ });+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/workspaces-store.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/workspaces-store.tsnew file mode 100644index 000000000..b8a1fc5fd--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/workspaces-store.ts@@ -0,0 +1,332 @@+import { randomUUID } from 'node:crypto';+import { and, asc, eq, isNull, sql } from 'drizzle-orm';+import { db, type DrizzleTx } from '@main/db/client';+import { agents, kv, type WorkspaceRow, workspaces } from '@main/db/schema';+import {+ type Workspace,+ type WorkspaceRole,+ workspaceUnavailability,+} from '@shared/core/workspaces/workspaces';++const ACTIVE_WORKSPACE_KV_KEY = 'activeWorkspaceId';++function mapRow(row: WorkspaceRow): Workspace {+ return {+ id: row.id,+ serverId: row.serverId,+ name: row.name,+ tenantId: row.tenantId ?? null,+ slug: row.slug ?? null,+ role: row.role ?? null,+ createdAt: row.createdAt,+ updatedAt: row.updatedAt,+ };+}++// `createdAt` is a one-second-granularity timestamp and a reconcile writes a+// server's rows in one loop, so ties are the norm rather than the exception. The+// id breaks them, because callers that take the first row — the one the window+// falls back to — must land on the same one every launch.+const workspaceOrder = [asc(workspaces.createdAt), asc(workspaces.id)];++export async function listWorkspaces(): Promise<Workspace[]> {+ const rows = await db+ .select()+ .from(workspaces)+ .orderBy(...workspaceOrder);+ return rows.map(mapRow);+}++export async function listWorkspacesForServer(serverId: string): Promise<Workspace[]> {+ const rows = await db+ .select()+ .from(workspaces)+ .where(eq(workspaces.serverId, serverId))+ .orderBy(...workspaceOrder);+ return rows.map(mapRow);+}++export async function getWorkspace(id: string): Promise<Workspace | null> {+ const [row] = await db.select().from(workspaces).where(eq(workspaces.id, id)).limit(1);+ return row ? mapRow(row) : null;+}++export async function requireWorkspace(id: string): Promise<Workspace> {+ const workspace = await getWorkspace(id);+ if (!workspace) throw new Error(`No workspace with id ${id}`);+ return workspace;+}++/**+ * The workspace to act in on a server, for a caller that knows only the server+ * — onboarding an agent, attaching one, discovering what a directory holds.+ *+ * Most servers carry exactly one workspace, and then there is nothing to+ * choose. Where there are several, the answer is the one the window is scoped+ * to: these callers are all driven from screens showing that workspace, so+ * anything else would act somewhere the user is not looking.+ *+ * Raises rather than picking when neither applies. A server with no workspace+ * is a registration that half-succeeded; a server with several, none of them+ * the active one, means the caller is the one that has to say which — and+ * attaching an agent to the wrong workspace is not something the user would see+ * until it had already happened.+ */+export async function requireWorkspaceForServer(serverId: string): Promise<Workspace> {+ const found = await listWorkspacesForServer(serverId);+ if (found.length === 1) return found[0]!;+ if (found.length === 0) throw new Error(`Switch server ${serverId} has no workspace`);++ const activeId = await getActiveWorkspaceId();+ const active = found.find((workspace) => workspace.id === activeId);+ if (active) return active;+ throw new Error(+ `Switch server ${serverId} has ${found.length} workspaces and none of them is the active one; the caller must name one`+ );+}++/**+ * Give a newly registered server its workspace, reusing the one it already has.+ *+ * Registering a server is what creates its first workspace — the gateway is+ * only asked which tenants the user belongs to afterwards, and the app has to+ * be usable before that answer arrives. The row starts tenant-less and named+ * after the server; a reconcile matches it to a tenant rather than replacing+ * it, so the agents pointing at it stay pointed at it.+ *+ * Idempotent, because the managed-server paths run again on every restart of a+ * stack that already exists. The read and the insert share one transaction, so+ * two of those restarts overlapping cannot each find no row and each create+ * one; the partial unique index on the table is the backstop for anything that+ * writes outside this function.+ */+export async function ensureServerWorkspace(server: {+ id: string;+ name: string;+}): Promise<Workspace> {+ return db.transaction((tx) => {+ const [existing] = tx+ .select()+ .from(workspaces)+ .where(eq(workspaces.serverId, server.id))+ .orderBy(...workspaceOrder)+ .limit(1)+ .all();+ return existing ? mapRow(existing) : insertServerWorkspace(tx, server);+ });+}++/**+ * The insert half of `ensureServerWorkspace`, so a caller registering a server+ * can create both rows in one transaction.+ *+ * A server row without a workspace cannot be used for anything — every path+ * that reaches a gateway resolves a workspace first — and nothing outside+ * registration creates one, so the two rows have to arrive together or not at+ * all.+ */+export function insertServerWorkspace(+ tx: DrizzleTx,+ server: { id: string; name: string }+): Workspace {+ const [row] = tx+ .insert(workspaces)+ .values({+ id: randomUUID(),+ serverId: server.id,+ name: server.name,+ updatedAt: sql`CURRENT_TIMESTAMP`,+ })+ .returning()+ .all();+ return mapRow(row!);+}++/**+ * Match a workspace row to the tenant it holds, and keep what the gateway owns+ * about that tenant up to date.+ *+ * An update rather than a replacement, because the row's id is what the agents,+ * the active selection and the saved navigation all point at — a new row for+ * the same workspace would detach every one of them.+ *+ * The name comes over with the rest. A matched workspace is a tenant, the+ * gateway is where it is named and renamed, and nothing in this app offers to+ * name one — so the alternative is a local label that can never be corrected+ * from either side. The row a server is registered with is named after the+ * server only for as long as it belongs to no tenant.+ */+export async function setWorkspaceTenant(+ workspaceId: string,+ tenant: { id: string; slug: string; name: string; role: WorkspaceRole }+): Promise<void> {+ await db+ .update(workspaces)+ .set({+ tenantId: tenant.id,+ slug: tenant.slug,+ name: tenant.name,+ role: tenant.role,+ updatedAt: sql`CURRENT_TIMESTAMP`,+ })+ .where(eq(workspaces.id, workspaceId));+}++/**+ * Record that the account is no longer a member of a workspace it still holds a+ * row for.+ *+ * The tenant id stays, because it is what the row's agents were registered+ * against and what a restored membership would match it back to; only the role+ * goes, since the gateway no longer reports one. A row naming a tenant with no+ * role is what the switcher reads as withdrawn.+ */+export async function clearWorkspaceRole(workspaceId: string): Promise<void> {+ await db+ .update(workspaces)+ .set({ role: null, updatedAt: sql`CURRENT_TIMESTAMP` })+ .where(eq(workspaces.id, workspaceId));+}++/**+ * Whether any agent still belongs to a workspace.+ *+ * Asked of the tenant-less row a server is registered with, to tell a+ * placeholder nothing was ever put in from the record of where a set of agents+ * lives. The first can be given a membership or dropped; the second cannot be+ * guessed at, because moving it would move those agents somewhere the user has+ * no way to see.+ */+export async function workspaceHasAgents(workspaceId: string): Promise<boolean> {+ const [row] = await db+ .select({ id: agents.id })+ .from(agents)+ .where(eq(agents.workspaceId, workspaceId))+ .limit(1);+ return row !== undefined;+}++/**+ * Drop a workspace nothing points at, moving the active selection off it first.+ *+ * Only ever the placeholder row a server is registered with, and only once a+ * reconcile has found that every membership the account holds is already held+ * by another row — leaving it would put a workspace in the switcher that+ * belongs to no membership at all. The caller checks it is empty first; the+ * selection is a plain `kv` value that no foreign key reaches, so it has to be+ * moved here rather than left pointing at a row that has gone.+ */+export async function discardEmptyWorkspace(workspaceId: string): Promise<void> {+ const workspace = await requireWorkspace(workspaceId);+ const sibling = (await listWorkspacesForServer(workspace.serverId)).find(+ (candidate) => candidate.id !== workspaceId+ );+ if (!sibling) throw new Error(`Workspace ${workspaceId} is the only one on its Switch server`);+ if ((await getActiveWorkspaceId()) === workspaceId) await setActiveWorkspaceId(sibling.id);+ await db.delete(workspaces).where(eq(workspaces.id, workspaceId));+}++/** Record a workspace the user belongs to that this install has no row for. */+export async function createTenantWorkspace(+ serverId: string,+ tenant: { id: string; slug: string; name: string; role: WorkspaceRole }+): Promise<Workspace> {+ const [row] = await db+ .insert(workspaces)+ .values({+ id: randomUUID(),+ serverId,+ name: tenant.name,+ tenantId: tenant.id,+ slug: tenant.slug,+ role: tenant.role,+ updatedAt: sql`CURRENT_TIMESTAMP`,+ })+ .returning();+ return mapRow(row!);+}++/**+ * Carry a server rename onto the workspaces that take their name from it.+ *+ * A tenant-less workspace has no name of its own — it was created named after+ * its server and nothing else has supplied one. Once matched to a tenant the+ * name is the gateway's, and a server rename must not overwrite it.+ */+export async function renameServerWorkspaces(serverId: string, name: string): Promise<void> {+ await db+ .update(workspaces)+ .set({ name, updatedAt: sql`CURRENT_TIMESTAMP` })+ .where(and(eq(workspaces.serverId, serverId), isNull(workspaces.tenantId)));+}++/**+ * The server hosting a workspace, or null when there is no workspace to ask+ * about — an agent that has not been attached to one.+ *+ * A workspace id that names no row is a different thing entirely, and raises:+ * the agents' foreign key means it cannot happen, so if it does the caller is+ * holding an id from somewhere the database does not know about, and answering+ * "no server" would send it on to fail somewhere further away.+ */+export async function serverIdForWorkspace(workspaceId: string | null): Promise<string | null> {+ if (!workspaceId) return null;+ const [row] = await db+ .select({ serverId: workspaces.serverId })+ .from(workspaces)+ .where(eq(workspaces.id, workspaceId))+ .limit(1);+ if (!row) throw new Error(`No workspace with id ${workspaceId}`);+ return row.serverId;+}++export async function getActiveWorkspaceId(): Promise<string | null> {+ const [row] = await db.select().from(kv).where(eq(kv.key, ACTIVE_WORKSPACE_KV_KEY)).limit(1);+ return row?.value ?? null;+}++export async function setActiveWorkspaceId(id: string): Promise<void> {+ await requireWorkspace(id);+ await db+ .insert(kv)+ .values({ key: ACTIVE_WORKSPACE_KV_KEY, value: id, updatedAt: sql`CURRENT_TIMESTAMP` })+ .onConflictDoUpdate({+ target: kv.key,+ set: { value: id, updatedAt: sql`CURRENT_TIMESTAMP` },+ });+}++/**+ * Move the selection off one of a server's workspaces that can no longer be+ * opened, onto one of its workspaces that can.+ *+ * A reconcile is how a withdrawn membership is found — signing in to a server+ * as a different account withdraws every workspace the previous one held — and+ * a window left on such a row is refused on every read it makes. Where the+ * server holds nothing openable the selection stays: there is nowhere better,+ * and the views say why.+ */+export async function leaveUnavailableActiveWorkspace(serverId: string): Promise<void> {+ const active = await getActiveWorkspaceId();+ const onServer = await listWorkspacesForServer(serverId);+ const current = onServer.find((workspace) => workspace.id === active);+ if (!current || workspaceUnavailability(current, onServer.length) === null) return;+ const openable = onServer.find(+ (workspace) => workspaceUnavailability(workspace, onServer.length) === null+ );+ if (openable) await setActiveWorkspaceId(openable.id);+}++/**+ * Drop the active selection if it names one of a server's workspaces.+ *+ * Removing a server takes its workspaces with it (the foreign key cascades),+ * and the selection is a plain `kv` value that nothing cascades to — so it has+ * to be cleared here, while the workspaces are still readable.+ */+export async function clearActiveWorkspaceOnServer(serverId: string): Promise<void> {+ const active = await getActiveWorkspaceId();+ if (!active) return;+ const onServer = (await listWorkspacesForServer(serverId)).some((w) => w.id === active);+ if (onServer) await db.delete(kv).where(eq(kv.key, ACTIVE_WORKSPACE_KV_KEY));+}diff --git a/console/apps/switch-console-desktop/src/main/db/schema.ts b/console/apps/switch-console-desktop/src/main/db/schema.tsindex 05e3586f2..d88ef167d 100644--- a/console/apps/switch-console-desktop/src/main/db/schema.ts+++ b/console/apps/switch-console-desktop/src/main/db/schema.ts@@ -4,14 +4,18 @@ import { versionedJsonColumn } from '@main/db/versioned-column';import { agentProviderConfig } from '@shared/core/agents/agent-provider-config';import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';import { sessionConfig } from '@shared/core/sessions/session-config';+import type { WorkspaceRole } from '@shared/core/workspaces/workspaces';// ---------------------------------------------------------------------------// Data model (Switch Console rework — diverges from upstream; see// agents/architecture/data-model.md for the full map)://+// switch_servers — a registered Switch gateway+// └─ workspaces — what the window is scoped to; one active at a time+//// locations — a working directory on a host (this machine or an SSH host)// └─ agents — a Switch agent identity (one provider each; many per-// │ location)+// │ location; belongs to one workspace)// └─ sessions — an instantiation/run of an agent (was "conversation";// │ one session == one terminal, folded in)// └─ messages@@ -82,10 +86,11 @@ export const appSettings = sqliteTable(/*** A Switch server: a gateway Switch Console can connect to. Switch Console is* multi-server — many gateways (a local dev one, a deployed pilot one) can be- * registered, and the UI works against one "active" server at a time (the- * active id is tracked in `kv` under `activeSwitchServerId`). The session JWT- * minted by the gateway is NOT stored here — it lives in the encrypted secrets- * store keyed by server id — so this table holds only non-secret connection+ * registered. What the window is scoped to is a workspace on one of them, not+ * the server itself, so the active selection names a workspace (`kv`,+ * `activeWorkspaceId`) and the server is read from it. The session JWT minted+ * by the gateway is NOT stored here — it lives in the encrypted secrets store+ * keyed by server id — so this table holds only non-secret connection* metadata.*/export const switchServers = sqliteTable(@@ -125,6 +130,66 @@ export const switchServers = sqliteTable(}));+/**+ * A workspace: the unit everything in the window is scoped to. A server hosts+ * one or more of them, and exactly one workspace is active at a time (tracked+ * in `kv` under `activeWorkspaceId`). Switching workspace swaps the whole+ * window — agents, rooms, sidebar — the way switching server used to.+ *+ * `tenantId` is the workspace's id on the gateway. It is null only until the+ * gateway has been asked: a workspace is created locally the moment a server is+ * registered, because the app has to be usable before the answer arrives, and+ * the upgrade to workspaces created one per already-registered server the same+ * way. Every deployed Switch server has tenancy — the backend migration that+ * introduced it puts every existing user in a tenant — so a tenant-less row is+ * a workspace that has not reconciled yet, not a server without tenants.+ *+ * Reconcile therefore has to *match* that row to a tenant rather than insert+ * the real workspace beside it: the row's id is what every agent points at, and+ * the (server, tenant) unique index cannot catch a duplicate here because+ * SQLite treats NULLs as distinct.+ *+ * `slug` is the gateway's handle for the workspace; null alongside a null+ * `tenantId`.+ */+export const workspaces = sqliteTable(+ 'workspaces',+ {+ id: text('id').primaryKey(),+ serverId: text('server_id')+ .notNull()+ .references(() => switchServers.id, { onDelete: 'cascade' }),+ name: text('name').notNull(),+ /** The workspace's id on the gateway; null when the server has no tenancy. */+ tenantId: text('tenant_id'),+ /** The gateway's slug for the workspace; null when it has no tenancy. */+ slug: text('slug'),+ /**+ * The caller's role in the workspace as the gateway last reported it+ * (`owner` / `admin` / `member`). Null for a tenant-less workspace, where+ * the notion does not apply.+ */+ role: text('role').$type<WorkspaceRole>(),+ createdAt: text('created_at')+ .notNull()+ .default(sql`CURRENT_TIMESTAMP`),+ updatedAt: text('updated_at')+ .notNull()+ .default(sql`CURRENT_TIMESTAMP`),+ },+ (table) => ({+ serverIdIdx: index('idx_workspaces_server_id').on(table.serverId),+ serverTenantIdx: uniqueIndex('idx_workspaces_server_tenant').on(table.serverId, table.tenantId),+ // A server has at most one unreconciled row. The index above cannot say so,+ // because SQLite treats NULLs as distinct, so two registrations racing on+ // the same server would each insert a placeholder and reconcile would only+ // ever repair the first one it found.+ serverPlaceholderIdx: uniqueIndex('idx_workspaces_server_placeholder')+ .on(table.serverId)+ .where(sql`tenant_id IS NULL`),+ })+);+/*** A Switch agent: an agent identity bound to a single provider, living at a* location. Many agents may share a location (e.g. a Claude Code and a Codex@@ -132,11 +197,10 @@ export const switchServers = sqliteTable(* the location dir is configured as a Switch agent (detected from* `.claude/settings.local.json`); they are null for a plain local agent.*- * `serverId` binds the agent to the one registered Switch server it belongs to.- * It is resolved by matching the detected `apiEndpoint` against the registered- * servers' origins. It is nullable: an agent whose server is not (or no longer)- * registered is shown as "unlinked" rather than guessed, and removing a server- * sets its agents' `serverId` to null instead of deleting them.+ * `workspaceId` binds the agent to the one workspace it belongs to, chosen and+ * verified at onboarding rather than inferred. It is nullable: an agent whose+ * workspace is gone is shown as "unlinked" rather than guessed, and removing a+ * server sets its workspaces' agents to null instead of deleting them.*/export const agents = sqliteTable('agents',@@ -153,7 +217,7 @@ export const agents = sqliteTable(providerId: text('provider_id').$type<AgentProviderId>().notNull(),switchAgentId: text('switch_agent_id'),apiEndpoint: text('api_endpoint'),- serverId: text('server_id').references(() => switchServers.id, { onDelete: 'set null' }),+ workspaceId: text('workspace_id').references(() => workspaces.id, { onDelete: 'set null' }),status: text('status'),// When set, Switch Console launches this agent's CLI with its auto-approve /// "bypass permissions" flag (e.g. `--dangerously-skip-permissions`).@@ -175,7 +239,7 @@ export const agents = sqliteTable(},(table) => ({locationIdIdx: index('idx_agents_location_id').on(table.locationId),- serverIdIdx: index('idx_agents_server_id').on(table.serverId),+ workspaceIdIdx: index('idx_agents_workspace_id').on(table.workspaceId),}));@@ -379,6 +443,8 @@ export type AppSecretRow = typeof appSecrets.$inferSelect;export type AppSecretInsert = typeof appSecrets.$inferInsert;export type SwitchServerRow = typeof switchServers.$inferSelect;export type SwitchServerInsert = typeof switchServers.$inferInsert;+export type WorkspaceRow = typeof workspaces.$inferSelect;+export type WorkspaceInsert = typeof workspaces.$inferInsert;export type RemoteHostRow = typeof remoteHosts.$inferSelect;export type RemoteHostInsert = typeof remoteHosts.$inferInsert;export type RemoteHostReachabilityRow = typeof remoteHostReachability.$inferSelect;diff --git a/console/apps/switch-console-desktop/src/main/db/tests/migrations/0051-workspaces.test.ts b/console/apps/switch-console-desktop/src/main/db/tests/migrations/0051-workspaces.test.tsnew file mode 100644index 000000000..34ca4f80d--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/db/tests/migrations/0051-workspaces.test.ts@@ -0,0 +1,356 @@+/**+ * Migration 0051 — introduces workspaces, the unit the window is scoped to, and+ * moves agents from being owned by a server to being owned by a workspace.+ *+ * The upgrade has to be invisible: everyone currently has servers and no+ * workspaces, so each server gets exactly one workspace reusing the server's id.+ * That reuse is the whole backward-compatibility story — agent rows, the active+ * selection in `kv`, and the opaque navigation snapshots all keep referring to+ * the same string — so these tests pin it rather than just checking the table+ * exists.+ *+ * The SQL is applied to a hand-built pre-0051 schema (the same approach as the+ * 0047 test) because the committed fixtures have already been migrated past it.+ */++import { readFileSync } from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import Database from 'better-sqlite3';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++const MIGRATION_SQL = readFileSync(+ path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ '../../../../../drizzle/0051_workspaces.sql'+ ),+ 'utf8'+);++type WorkspaceRow = {+ id: string;+ server_id: string;+ name: string;+ tenant_id: string | null;+ slug: string | null;+ role: string | null;+};++describe('migration 0051: workspaces', () => {+ let db: Database.Database;++ beforeEach(() => {+ db = new Database(':memory:');+ db.exec(`+ CREATE TABLE switch_servers (+ id TEXT PRIMARY KEY NOT NULL,+ name TEXT NOT NULL,+ gateway_url TEXT NOT NULL,+ api_url TEXT NOT NULL,+ managed INTEGER NOT NULL DEFAULT 0,+ management_kind TEXT,+ ssh_host TEXT,+ created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,+ updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP+ );+ CREATE TABLE locations (+ id TEXT PRIMARY KEY NOT NULL,+ name TEXT NOT NULL+ );+ INSERT INTO locations (id, name) VALUES ('loc-1', 'repo');+ -- Mirrors the real pre-0051 agents DDL, foreign keys included. The+ -- columns are not incidental: server_id carrying an FK is exactly why the+ -- migration has to recreate the table instead of dropping the column.+ CREATE TABLE agents (+ id TEXT PRIMARY KEY NOT NULL,+ location_id TEXT NOT NULL,+ name TEXT NOT NULL,+ provider_id TEXT NOT NULL,+ switch_agent_id TEXT,+ api_endpoint TEXT,+ server_id TEXT,+ status TEXT,+ auto_approve INTEGER DEFAULT false NOT NULL,+ owner_name TEXT,+ provider_config TEXT,+ created_at TEXT DEFAULT CURRENT_TIMESTAMP NOT NULL,+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP NOT NULL,+ FOREIGN KEY (location_id) REFERENCES locations(id),+ FOREIGN KEY (server_id) REFERENCES switch_servers(id) ON DELETE SET NULL+ );+ CREATE INDEX idx_agents_location_id ON agents (location_id);+ CREATE INDEX idx_agents_server_id ON agents (server_id);+ CREATE TABLE kv (+ key TEXT PRIMARY KEY NOT NULL,+ value TEXT NOT NULL,+ updated_at INTEGER NOT NULL DEFAULT 0+ );+ `);+ });++ afterEach(() => {+ db.close();+ });++ function seedServer(id: string, name: string): void {+ db.prepare(+ `INSERT INTO switch_servers (id, name, gateway_url, api_url) VALUES (?, ?, ?, ?)`+ ).run(id, name, `https://${id}.example`, `https://${id}.example:8000`);+ }++ function seedAgent(id: string, serverId: string | null): void {+ db.prepare(+ `INSERT INTO agents (id, location_id, name, provider_id, server_id) VALUES (?, 'loc-1', ?, 'claude', ?)`+ ).run(id, id, serverId);+ }++ function applyMigration(): void {+ for (const stmt of MIGRATION_SQL.split('--> statement-breakpoint')) {+ const trimmed = stmt.trim();+ if (trimmed) db.exec(trimmed);+ }+ }++ function workspaces(): WorkspaceRow[] {+ return db.prepare(`SELECT * FROM workspaces ORDER BY name`).all() as WorkspaceRow[];+ }++ it('gives every existing server exactly one workspace, named after it', () => {+ seedServer('srv-local', 'Local dev');+ seedServer('srv-cloud', 'Switch Cloud');++ applyMigration();++ expect(workspaces().map((w) => [w.server_id, w.name])).toEqual([+ ['srv-local', 'Local dev'],+ ['srv-cloud', 'Switch Cloud'],+ ]);+ });++ it('reuses the server id as the workspace id, so persisted ids stay valid', () => {+ seedServer('srv-local', 'Local dev');++ applyMigration();++ const [workspace] = workspaces();+ expect(workspace!.id).toBe('srv-local');+ });++ // No gateway is asked during the upgrade — it must not depend on one being+ // reachable — so the tenant is filled in by the first reconcile, not here.+ it('leaves the migrated workspaces tenant-less for the first reconcile to match', () => {+ seedServer('srv-local', 'Local dev');++ applyMigration();++ const [workspace] = workspaces();+ expect(workspace!.tenant_id).toBeNull();+ expect(workspace!.slug).toBeNull();+ expect(workspace!.role).toBeNull();+ });++ it("moves each agent onto its server's workspace", () => {+ seedServer('srv-local', 'Local dev');+ seedServer('srv-cloud', 'Switch Cloud');+ seedAgent('agent-a', 'srv-local');+ seedAgent('agent-b', 'srv-cloud');++ applyMigration();++ const rows = db.prepare(`SELECT id, workspace_id FROM agents ORDER BY id`).all() as {+ id: string;+ workspace_id: string | null;+ }[];+ expect(rows).toEqual([+ { id: 'agent-a', workspace_id: 'srv-local' },+ { id: 'agent-b', workspace_id: 'srv-cloud' },+ ]);+ });++ it('keeps an unlinked agent unlinked rather than guessing a workspace for it', () => {+ seedServer('srv-local', 'Local dev');+ seedAgent('agent-unlinked', null);++ applyMigration();++ const row = db+ .prepare(`SELECT workspace_id FROM agents WHERE id = ?`)+ .get('agent-unlinked') as {+ workspace_id: string | null;+ };+ expect(row.workspace_id).toBeNull();+ });++ // The old server_id was added by ALTER TABLE ADD COLUMN, which in SQLite+ // cannot carry ON DELETE, so its set-null was never enforced and a row can+ // point at a server that is gone. Carrying that value over would seed the new,+ // engine-enforced foreign key with a violation, and the migration runs with+ // foreign_keys=OFF, so nothing would catch it until much later.+ it('drops an agent’s link to a server that no longer exists', () => {+ seedServer('srv-local', 'Local dev');+ seedAgent('agent-a', 'srv-local');+ // The dangling value has to be written with the constraint off, which is+ // how it arises: the real column was added by ALTER TABLE, so the engine+ // never enforced the clause this fixture's DDL can only state up front.+ db.exec('PRAGMA foreign_keys = OFF');+ db.prepare(`UPDATE agents SET server_id = 'srv-gone' WHERE id = 'agent-a'`).run();++ applyMigration();+ db.exec('PRAGMA foreign_keys = ON');++ const row = db.prepare(`SELECT workspace_id FROM agents WHERE id = 'agent-a'`).get() as {+ workspace_id: string | null;+ };+ expect(row.workspace_id).toBeNull();+ expect(db.prepare(`PRAGMA foreign_key_check`).all()).toEqual([]);+ });++ it('carries every other agent column through the table rebuild', () => {+ seedServer('srv-local', 'Local dev');+ db.prepare(+ `INSERT INTO agents (id, location_id, name, provider_id, switch_agent_id, api_endpoint, server_id, status, auto_approve, owner_name, provider_config)+ VALUES ('agent-a', 'loc-1', 'Worker', 'codex', 'switch-123', 'https://api.example', 'srv-local', 'live', 1, 'owner-1', '{"v":1}')`+ ).run();++ applyMigration();++ const row = db.prepare(`SELECT * FROM agents WHERE id = 'agent-a'`).get() as Record<+ string,+ unknown+ >;+ expect(row).toMatchObject({+ location_id: 'loc-1',+ name: 'Worker',+ provider_id: 'codex',+ switch_agent_id: 'switch-123',+ api_endpoint: 'https://api.example',+ workspace_id: 'srv-local',+ status: 'live',+ auto_approve: 1,+ owner_name: 'owner-1',+ provider_config: '{"v":1}',+ });+ });++ it('keeps the location foreign key working after the rebuild', () => {+ seedServer('srv-local', 'Local dev');+ seedAgent('agent-a', 'srv-local');++ applyMigration();+ db.exec('PRAGMA foreign_keys = ON');++ expect(() =>+ db+ .prepare(`INSERT INTO agents (id, location_id, name, provider_id) VALUES (?, ?, ?, ?)`)+ .run('agent-b', 'loc-missing', 'B', 'claude')+ ).toThrow(/FOREIGN KEY/);+ });++ it('drops the old server column so nothing can keep reading it', () => {+ seedServer('srv-local', 'Local dev');++ applyMigration();++ const columns = (db.prepare(`PRAGMA table_info('agents')`).all() as { name: string }[]).map(+ (c) => c.name+ );+ expect(columns).toContain('workspace_id');+ expect(columns).not.toContain('server_id');+ });++ it('carries the active selection over, so the app opens where it was left', () => {+ seedServer('srv-local', 'Local dev');+ db.prepare(`INSERT INTO kv (key, value) VALUES ('activeSwitchServerId', 'srv-local')`).run();++ applyMigration();++ const active = db.prepare(`SELECT value FROM kv WHERE key = 'activeWorkspaceId'`).get() as+ | { value: string }+ | undefined;+ expect(active?.value).toBe('srv-local');++ const stale = db.prepare(`SELECT value FROM kv WHERE key = 'activeSwitchServerId'`).get();+ expect(stale).toBeUndefined();+ });++ it('survives an install that had no active selection recorded', () => {+ seedServer('srv-local', 'Local dev');++ applyMigration();++ const active = db.prepare(`SELECT value FROM kv WHERE key = 'activeWorkspaceId'`).get();+ expect(active).toBeUndefined();+ });++ it('survives a fresh install with no servers at all', () => {+ applyMigration();++ expect(workspaces()).toEqual([]);+ });++ it('removes a server’s workspaces with it', () => {+ seedServer('srv-local', 'Local dev');+ applyMigration();+ db.exec('PRAGMA foreign_keys = ON');++ db.prepare(`DELETE FROM switch_servers WHERE id = ?`).run('srv-local');++ expect(workspaces()).toEqual([]);+ });++ // Two foreign keys deep, and the one the old schema only claimed: the server's+ // workspaces cascade away, and their agents are unlinked rather than deleted.+ it('unlinks an agent when the server under its workspace is deleted', () => {+ seedServer('srv-local', 'Local dev');+ seedAgent('agent-a', 'srv-local');+ applyMigration();+ db.exec('PRAGMA foreign_keys = ON');++ db.prepare(`DELETE FROM switch_servers WHERE id = ?`).run('srv-local');++ const row = db.prepare(`SELECT workspace_id FROM agents WHERE id = 'agent-a'`).get() as {+ workspace_id: string | null;+ };+ expect(row.workspace_id).toBeNull();+ });++ it('lets two servers each keep a tenant-less workspace', () => {+ seedServer('srv-a', 'A');+ seedServer('srv-b', 'B');++ applyMigration();++ expect(workspaces()).toHaveLength(2);+ });++ it('refuses two workspaces with the same tenant on one server', () => {+ seedServer('srv-cloud', 'Switch Cloud');+ applyMigration();++ const insert = (id: string, tenantId: string) =>+ db+ .prepare(`INSERT INTO workspaces (id, server_id, name, tenant_id) VALUES (?, ?, ?, ?)`)+ .run(id, 'srv-cloud', id, tenantId);++ insert('ws-1', 'tenant-1');+ expect(() => insert('ws-2', 'tenant-1')).toThrow(/UNIQUE/);+ });++ it('allows the same tenant id on two different servers', () => {+ seedServer('srv-a', 'A');+ seedServer('srv-b', 'B');+ applyMigration();++ db.prepare(`INSERT INTO workspaces (id, server_id, name, tenant_id) VALUES (?, ?, ?, ?)`).run(+ 'ws-a',+ 'srv-a',+ 'Shared',+ 'tenant-1'+ );+ expect(() =>+ db+ .prepare(`INSERT INTO workspaces (id, server_id, name, tenant_id) VALUES (?, ?, ?, ?)`)+ .run('ws-b', 'srv-b', 'Shared', 'tenant-1')+ ).not.toThrow();+ });+});diff --git a/console/apps/switch-console-desktop/src/main/db/tests/migrations/journal-registration.test.ts b/console/apps/switch-console-desktop/src/main/db/tests/migrations/journal-registration.test.tsindex 75ea22dd6..ab2311463 100644--- a/console/apps/switch-console-desktop/src/main/db/tests/migrations/journal-registration.test.ts+++ b/console/apps/switch-console-desktop/src/main/db/tests/migrations/journal-registration.test.ts@@ -25,6 +25,10 @@ const journalTags = journal.entries.map((entry) => entry.tag);const sqlTags = readdirSync(drizzleDir).filter((name) => name.endsWith('.sql')).map((name) => name.replace(/\.sql$/, ''));+const snapshotIndices = readdirSync(`${drizzleDir}/meta`)+ .map((name) => /^(\d+)_snapshot\.json$/.exec(name))+ .filter((match) => match !== null)+ .map((match) => Number(match[1]));describe('migration journal registration', () => {it('finds the migration files at all, so the checks below are not vacuous', () => {@@ -42,6 +46,23 @@ describe('migration journal registration', () => {expect(missing).toEqual([]);});+ /**+ * A hand-written migration is easy to commit without one, and nothing at+ * runtime notices: the runner reads the journal and the `.sql`, never `meta/`.+ *+ * drizzle-kit does, and it takes the *highest-numbered snapshot file* as the+ * state to diff against rather than the last journal entry — a gap is not an+ * error it reports. So the next `db:generate` diffs the schema against the+ * last snapshot before the gap and re-emits everything since as one new+ * migration. On any machine that already ran the missing one, that lands as+ * `table workspaces already exists`, and it takes `db:fixtures` with it.+ */+ it('has a meta snapshot for every journal entry', () => {+ const missing = journal.entries.filter((entry) => !snapshotIndices.includes(entry.idx));++ expect(missing.map((entry) => entry.tag)).toEqual([]);+ });+it('numbers journal entries contiguously from zero', () => {// A gap means an entry was hand-edited out; a duplicate means two branches// claimed the same number and the merge kept both.diff --git a/console/apps/switch-console-desktop/src/main/index.ts b/console/apps/switch-console-desktop/src/main/index.tsindex caf6b57d3..e8dc118bf 100644--- a/console/apps/switch-console-desktop/src/main/index.ts+++ b/console/apps/switch-console-desktop/src/main/index.ts@@ -14,7 +14,6 @@ import { bridgeAgentEventsToRenderer } from './core/agents/agent-events-rendererimport { setAgentStorageMigrationReady } from './core/agents/agent-storage-migration-ready';import { migrateAgentStorage } from './core/agents/migrate-agent-storage';import { initializeRemoteDiscovery, initializeRemoteWatchers } from './core/agents/remote-watcher';-import { resolveAgentServers } from './core/agents/resolve-servers';import { appService } from './core/app/service';import { controlService } from './core/control-api/control-service';import { localDependencyManager } from './core/dependencies/dependency-managers';@@ -37,6 +36,7 @@ import { registerTelemetryListeners } from './core/telemetry/telemetry-listenersimport { trackEvent } from './core/telemetry/telemetry-service';import { updateService } from './core/updates/update-service';import { viewStateService } from './core/view-state/view-state-service';+import { reconcileAllWorkspaces } from './core/workspaces/reconcile-workspaces';import { initializeDatabase } from './db/initialize';import { logAppExit, logAppStart, registerAppDiagnostics } from './lib/app-diagnostics';import {@@ -145,12 +145,6 @@ void app.whenReady().then(async () => {registerTelemetryListeners();trackEvent('app_launched', {});- try {- await resolveAgentServers();- } catch (e) {- log.warn('switch-agents: failed to reconcile agent → server links at boot', { error: e });- }-// Kept off the boot path: this can open an SSH/SFTP connection per remote// agent, so awaiting it here delayed the window opening. Session relaunch below// waits on it (it needs each agent's definitionName); nothing else does.@@ -169,10 +163,23 @@ void app.whenReady().then(async () => {// Reflect a managed local Switch stack that survived the last quit, so the UI// shows it running without the user restarting it.- void localServerService.initialize();+ const localServerReady = localServerService.initialize();// Re-establish desktop-side forwards for remote-managed stacks that survived// the last quit, restoring their reachability from this machine.- void remoteServerService.initialize();+ const remoteServerReady = remoteServerService.initialize();++ // A server registered before its account's memberships were known carries one+ // tenant-less workspace; this is what gives it its tenant, and what notices a+ // membership added or withdrawn since the last launch. It runs after the two+ // services above because they are what make a stack that survived the last+ // quit report itself as running — before them every managed server still+ // looks stopped and would be passed over. Unawaited: it talks to every+ // signed-in server, and the window must not wait on any of them.+ void Promise.allSettled([localServerReady, remoteServerReady])+ .then(reconcileAllWorkspaces)+ .catch((error: unknown) => {+ log.error('Workspace reconcile could not run; every server was left as it was:', error);+ });const dependenciesReady = localDependencyManager.probeAll().catch((e: unknown) => {log.error('Failed to probe dependencies:', e);diff --git a/console/apps/switch-console-desktop/src/main/rpc.ts b/console/apps/switch-console-desktop/src/main/rpc.tsindex 4893c74dd..68a133597 100644--- a/console/apps/switch-console-desktop/src/main/rpc.ts+++ b/console/apps/switch-console-desktop/src/main/rpc.ts@@ -7,6 +7,7 @@ import { filesController } from './core/fs/controller';import { locationsController } from './core/locations/controller';import { localSwitchServerController } from './core/managed-switch-server/controller';import { remoteSwitchServerController } from './core/managed-switch-server/remote-controller';+import { onboardingController } from './core/onboarding/controller';import { providersController } from './core/providers/controller';import { remoteHostsController } from './core/remote-hosts/controller';import { resourceMonitorController } from './core/resource-monitor/controller';@@ -20,6 +21,7 @@ import { switchServersController } from './core/switch-servers/controller';import { telemetryController } from './core/telemetry/controller';import { updateController } from './core/updates/controller';import { viewStateController } from './core/view-state/controller';+import { workspacesController } from './core/workspaces/controller';export const rpcRouter = createRPCRouter({sdkHost: sdkHostController,@@ -37,6 +39,8 @@ export const rpcRouter = createRPCRouter({switchRooms: switchRoomsController,switchServers: switchServersController,agentTypes: agentTypesController,+ workspaces: workspacesController,+ onboarding: onboardingController,localSwitchServer: localSwitchServerController,remoteSwitchServer: remoteSwitchServerController,remoteHosts: remoteHostsController,diff --git a/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts b/console/apps/switch-console-desktop/src/renderer/app/modal-registry.tsindex b94ed44bb..3b572a63b 100644--- a/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts+++ b/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts@@ -20,6 +20,8 @@ import { DeleteServerModal } from '@renderer/features/switch-servers/DeleteServeimport { DisconnectMessagingAppModal } from '@renderer/features/switch-servers/DisconnectMessagingAppModal';import { RenameServerModal } from '@renderer/features/switch-servers/RenameServerModal';import { SaveTemplateModal } from '@renderer/features/templates/save-template-modal';+import { CreateWorkspaceModal } from '@renderer/features/workspaces/create-workspace-modal';+import { InvitePeopleModal } from '@renderer/features/workspaces/invite-people-modal';import { ConfirmActionDialog } from '@renderer/lib/components/confirm-action-dialog';import { ExternalLinkChoiceDialog } from '@renderer/lib/components/external-link-choice-dialog';import { UnsavedChangesDialog } from '@renderer/lib/components/unsaved-changes-dialog';@@ -65,6 +67,14 @@ export const modalRegistry = {}),deleteSessionModal: createModal(DeleteSessionModal, { size: 'sm' }),addServerModal: createModal(AddServerModal, { size: 'md', dismissOnOutsideClick: false }),+ createWorkspaceModal: createModal(CreateWorkspaceModal, {+ size: 'md',+ dismissOnOutsideClick: false,+ }),+ invitePeopleModal: createModal(InvitePeopleModal, {+ size: 'lg',+ dismissOnOutsideClick: false,+ }),addHostModal: createModal(AddHostModal, { size: 'md', dismissOnOutsideClick: false }),assignServerModal: createModal(AssignServerModal, { size: 'sm', dismissOnOutsideClick: false }),renameServerModal: createModal(RenameServerModal, {diff --git a/console/apps/switch-console-desktop/src/renderer/app/shell-shape.test.ts b/console/apps/switch-console-desktop/src/renderer/app/shell-shape.test.tsnew file mode 100644index 000000000..204e09326--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/app/shell-shape.test.ts@@ -0,0 +1,89 @@+import { describe, expect, it } from 'vitest';+import { shellShape } from './shell-shape';++/**+ * The window has two shapes and what the install holds picks between them. Both+ * wrong answers are bad in a way a layout bug is not: onboarding shown to+ * someone who has an install hides it behind a first-run page, and the+ * workspace shown on a fresh install is a sidebar listing nothing.+ */++/**+ * A loaded, empty, undisturbed install — the fresh-install case. Each test+ * below names only what it changes about it.+ */+function shape(differences: Partial<Parameters<typeof shellShape>[0]>) {+ return shellShape({+ loaded: true,+ listError: null,+ installIsEmpty: true,+ viewWorksWithoutServer: false,+ onboardingInProgress: false,+ ...differences,+ });+}++describe('what fills the window', () => {+ it('waits rather than guessing before anything has been read', () => {+ // The trap: an install with five servers looks exactly like a fresh one+ // until the read comes back, because neither has answered yet.+ expect(shape({ loaded: false, installIsEmpty: false })).toBe('loading');+ });++ it('onboards only once the install is known to be empty', () => {+ expect(shape({})).toBe('onboarding');+ });++ /**+ * "Something to show" is not "a server". Removing one says in as many words+ * that its agents are kept and can be re-linked elsewhere, so an install left+ * with agents and no server still has a window's worth of content — and the+ * sessions in those agents are still running behind it.+ */+ it('shows the workspace as soon as there is anything to show', () => {+ expect(shape({ installIsEmpty: false })).toBe('workspace');+ });++ it('lets a view that needs no server out of the onboarding page', () => {+ // Settings and the remote hosts are views, so only the workspace can draw+ // them, and the onboarding page carries no chrome of its own. Holding the+ // window on it would leave ⌘, and the Preferences menu item doing nothing.+ expect(shape({ viewWorksWithoutServer: true })).toBe('workspace');+ });++ /**+ * Settings is where the logs and the database are, so a failed first read is+ * precisely when it has to be reachable — and it needs nothing from the read+ * to draw. Ordering this after the load gate would leave ⌘, and Preferences+ * doing nothing in the one state that calls for them.+ */+ it('draws such a view even when nothing could be read', () => {+ expect(shape({ loaded: false, viewWorksWithoutServer: true })).toBe('workspace');+ expect(+ shape({ loaded: false, listError: 'Could not load', viewWorksWithoutServer: true })+ ).toBe('workspace');+ });++ it('stays on the first-run pages once the flow has added the server', () => {+ // The flow adds the server pages before it is done with it — signing in and+ // linking accounts both come after. Going by the contents alone would throw+ // the user out of the flow at the moment it half-succeeded.+ expect(shape({ installIsEmpty: false, onboardingInProgress: true })).toBe('onboarding');+ });++ it('still lets such a view out of a flow in progress', () => {+ expect(shape({ onboardingInProgress: true, viewWorksWithoutServer: true })).toBe('workspace');+ });++ it('says a first read failed instead of staying blank', () => {+ // Otherwise the failure is indistinguishable from the blank first frame and+ // the window just never fills.+ expect(shape({ loaded: false, listError: 'Could not load' })).toBe('failed');+ });++ it('keeps the workspace when a later read fails', () => {+ // The list in hand is still the list; a failed refresh is not a reason to+ // take the app away from someone using it.+ expect(shape({ listError: 'Could not load', installIsEmpty: false })).toBe('workspace');+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/app/shell-shape.ts b/console/apps/switch-console-desktop/src/renderer/app/shell-shape.tsnew file mode 100644index 000000000..5f9d0aec8--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/app/shell-shape.ts@@ -0,0 +1,70 @@+/** Which of the window's shapes what this install holds implies. */+export type ShellShape = 'loading' | 'failed' | 'onboarding' | 'workspace';++/**+ * Decide what fills the window from what is known about this install.+ *+ * Separated from the component because the wrong answer here is not a layout+ * bug — `onboarding` shown to someone who has an install hides the whole of it+ * behind a first-run page, and `workspace` shown on a fresh one is a sidebar+ * listing nothing. The inputs are easy to get the wrong way round, so they are+ * decided in one place that can be exercised directly.+ *+ * `loaded` is what separates an empty install from one that has not been asked+ * yet; both leave `installIsEmpty` false.+ */+export function shellShape({+ loaded,+ listError,+ installIsEmpty,+ viewWorksWithoutServer,+ onboardingInProgress,+}: {+ loaded: boolean;+ /**+ * The list read's own failure, not the store's shared error slot — every+ * action in that store writes the shared one, and a rename that went wrong+ * is not a reason to put the whole window into its failure shape.+ *+ * It must also outlive a retry rather than being cleared as one starts:+ * otherwise pressing "Try again" takes the failure page off screen, and the+ * button with it, for as long as the retry runs.+ */+ listError: string | null;+ /**+ * Whether this install holds nothing at all — no server, no location, no+ * agent.+ *+ * Not "has no server". Removing a server keeps its agents and says so in the+ * confirmation, and the sessions running in them carry on; reading that as a+ * fresh install would hide all of it behind a welcome page, permanently and+ * across relaunches.+ */+ installIsEmpty: boolean;+ /**+ * Whether what is on screen can be drawn with no server behind it.+ *+ * The way out of the onboarding page for the views that do not describe a+ * server. Without one, ⌘, and the Preferences menu item do nothing on a+ * fresh install. Each view says this about itself rather than being named+ * here, so the next one of the same kind is not missed.+ */+ viewWorksWithoutServer: boolean;+ /** Whether the first-run flow has been started and not yet finished. */+ onboardingInProgress: boolean;+}): ShellShape {+ // Checked before the read, not after. Such a view needs nothing from this+ // install to draw, and a first read that failed is exactly when Settings —+ // its logs, its database — is where the user has to be able to get to.+ if (viewWorksWithoutServer) return 'workspace';+ // A failed read that nevertheless loaded once keeps the workspace: the list+ // in hand is still the list, and a later refresh failing is not a reason to+ // take the app away.+ if (!loaded) return listError === null ? 'loading' : 'failed';+ // A flow in progress outranks what the install holds, because the flow is+ // what changes it: the server is added several pages before the user has+ // signed in to it, and going by the contents alone would throw them out of+ // the flow at the moment it half-succeeded.+ if (onboardingInProgress) return 'onboarding';+ return installIsEmpty ? 'onboarding' : 'workspace';+}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.tsindex fbd991036..e94190add 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@@ -58,12 +58,28 @@ export type ViewDefinition<TParams extends object = Record<never, never>> = {* by older builds, so each guard must validate the shape before using it.*/canActivate?: (params: unknown) => GuardResult;+ /**+ * Set on a view that has something to show with no Switch server registered+ * at all — Settings, the remote hosts. Everything else describes a server,+ * or a workspace on one, and has nothing to draw without one.+ *+ * The shell reads it to decide whether the first-run page may be stepped out+ * of. It lives on the view because only the view knows: a list of ids in the+ * shell is a list someone has to remember to add to.+ */+ worksWithoutServer?: boolean;};type Views = typeof views;export type ViewId = keyof Views;+/** Whether the view on screen can be drawn before any server is registered. */+export function viewWorksWithoutServer(viewId: ViewId): boolean {+ const view: Pick<ViewDefinition, 'MainPanel' | 'worksWithoutServer'> = views[viewId];+ return view.worksWithoutServer === true;+}+/*** The registry and the shared list of view ids say the same thing.*diff --git a/console/apps/switch-console-desktop/src/renderer/app/workspace.tsx b/console/apps/switch-console-desktop/src/renderer/app/workspace.tsxindex 648f23619..cb2f395c4 100644--- a/console/apps/switch-console-desktop/src/renderer/app/workspace.tsx+++ b/console/apps/switch-console-desktop/src/renderer/app/workspace.tsx@@ -1,36 +1,130 @@+import { observer } from 'mobx-react-lite';+import { useEffect, type ReactNode } from 'react';+import { OnboardingFlow } from '@renderer/features/onboarding/onboarding-flow';+import { onboardingStore } from '@renderer/features/onboarding/onboarding-store';import { LeftSidebar } from '@renderer/features/sidebar/left-sidebar';import { RoomEmbedLayer } from '@renderer/features/switch-rooms/room-embed-layer';+import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';import { CommandShortcutBinder } from '@renderer/lib/commands/command-shortcut-binder';import { AppKeyboardShortcuts } from '@renderer/lib/components/app-keyboard-shortcuts';import { MonacoKeyboardBridge } from '@renderer/lib/components/monaco-keyboard-bridge';import { useTheme } from '@renderer/lib/hooks/useTheme';-import { useWorkspaceWrapParams } from '@renderer/lib/layout/navigation-provider';+import { useCurrentViewId, useWorkspaceWrapParams } from '@renderer/lib/layout/navigation-provider';import { WorkspaceContentLayout, WorkspaceLayout } from '@renderer/lib/layout/workspace-layout';import { useWorkspaceSlots } from '@renderer/lib/layout/workspace-slots';+import { Button } from '@renderer/lib/ui/button';+import { Spinner } from '@renderer/lib/ui/spinner';import { Toaster } from '@renderer/lib/ui/toaster';+import { shellShape } from './shell-shape';+import { viewWorksWithoutServer } from './view-registry';-export function Workspace() {+/**+ * What fills the window.+ *+ * Two shapes, not one: the workspace — sidebar, views, the room layer — and the+ * onboarding flow that takes the whole window before there is any server to+ * show. The choice is made here rather than inside a view because it is the+ * chrome itself that differs; an onboarding page rendered into the workspace+ * would sit beside a sidebar listing nothing.+ *+ * The server list is read here for the same reason. It used to be loaded by the+ * sidebar, which is no longer always mounted, and the shell cannot ask a+ * component it may not render which shape to take.+ */+export const Workspace = observer(function Workspace() {useTheme();const { WrapView } = useWorkspaceSlots();const { wrapParams } = useWorkspaceWrapParams();+ useEffect(() => {+ void switchServersStore.init();+ }, []);+return (<><AppKeyboardShortcuts /><CommandShortcutBinder /><MonacoKeyboardBridge />- <WorkspaceLayout- leftSidebar={<LeftSidebar />}+ <ShellmainContent={<WrapView {...wrapParams}><WorkspaceViewContent /></WrapView>}- persistentLayer={<RoomEmbedLayer />}/><Toaster /></>);+});++const Shell = observer(function Shell({ mainContent }: { mainContent: ReactNode }) {+ const currentViewId = useCurrentViewId();+ const shape = shellShape({+ loaded: switchServersStore.loaded,+ listError: switchServersStore.listError,+ installIsEmpty: switchServersStore.installIsEmpty,+ viewWorksWithoutServer: viewWorksWithoutServer(currentViewId),+ onboardingInProgress: onboardingStore.inProgress,+ });++ switch (shape) {+ // Nothing on screen rather than a spinner: this is one or two local IPC+ // round-trips, and a spinner that flashes is worse than a beat of window.+ case 'loading':+ return null;+ case 'failed':+ return (+ <ShellFailure+ message={switchServersStore.listError ?? 'Could not load your Switch servers.'}+ detail={switchServersStore.listErrorDetail}+ retrying={switchServersStore.loadingServers}+ />+ );+ case 'onboarding':+ return <OnboardingFlow />;+ case 'workspace':+ return (+ <WorkspaceLayout+ leftSidebar={<LeftSidebar />}+ mainContent={mainContent}+ persistentLayer={<RoomEmbedLayer />}+ />+ );+ }+});++/**+ * The window when the first read of the server list failed.+ *+ * A retry runs on this page rather than replacing it. The read clears nothing+ * as it starts, so the message, the detail and the button all stay put and the+ * button says it is working — otherwise pressing it would unmount the only+ * thing on screen and leave a blank window for as long as the retry took.+ */+function ShellFailure({+ message,+ detail,+ retrying,+}: {+ message: string;+ detail: string | null;+ retrying: boolean;+}) {+ return (+ <div className="flex h-full flex-col items-center justify-center gap-3 bg-background p-8 text-center [-webkit-app-region:drag]">+ <p className="text-sm text-foreground">{message}</p>+ {detail && <p className="max-w-md text-xs text-foreground-muted">{detail}</p>}+ <Button+ className="[-webkit-app-region:no-drag]"+ variant="outline"+ disabled={retrying}+ onClick={() => void switchServersStore.init()}+ >+ {retrying && <Spinner size="sm" className="mr-2" />}+ {retrying ? 'Trying again…' : 'Try again'}+ </Button>+ </div>+ );}function WorkspaceViewContent() {diff --git a/console/apps/switch-console-desktop/src/renderer/features/command-palette/command-palette-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/command-palette/command-palette-modal.tsxindex 42ee93357..ee6c0ebdf 100644--- a/console/apps/switch-console-desktop/src/renderer/features/command-palette/command-palette-modal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/command-palette/command-palette-modal.tsx@@ -16,7 +16,7 @@ import { useDebounce } from '@renderer/lib/hooks/useDebounce';import { getEffectiveHotkey } from '@renderer/lib/hooks/useKeyboardShortcuts';import { rpc } from '@renderer/lib/ipc';import { useNavigate } from '@renderer/lib/layout/navigation-provider';-import { scopeToLocationServer } from '@renderer/lib/layout/scope-to-server';+import { scopeToLocationWorkspace } from '@renderer/lib/layout/scope-to-workspace';import { type BaseModalProps } from '@renderer/lib/modal/modal-provider';import { appState, sidebarStore } from '@renderer/lib/stores/app-state';import { report } from '@renderer/lib/telemetry/report';@@ -194,7 +194,7 @@ export function CommandPaletteModal({// Search spans every server, but the sidebar only loads the one it is showing// — so the others' rooms are pulled here, by the feature that needs them.useEffect(() => {- void switchRoomsStore.loadRoomsOnAllServers();+ void switchRoomsStore.loadRoomsInAllWorkspaces();}, []);// Prefetch recents immediately on mount so the empty-query view is instant.@@ -272,7 +272,7 @@ export function CommandPaletteModal({// span every server, not the active one: you search precisely because you do// not know where a thing is.const roomResults = useObserver(() =>- matchRooms(switchRoomsStore.listedRoomsOnAllServers, debouncedQuery)+ matchRooms(switchRoomsStore.listedRoomsInAllWorkspaces, debouncedQuery));const serverResults = useObserver(() => matchServers(switchServersStore.servers, debouncedQuery));@@ -325,7 +325,7 @@ export function CommandPaletteModal({if (!item.locationId) return;const locationId = item.locationId;handleClose();- void scopeToLocationServer(locationId).then(() =>+ void scopeToLocationWorkspace(locationId).then(() =>navigate('session', { locationId, sessionId: item.id }));};@@ -342,7 +342,7 @@ export function CommandPaletteModal({if (!item.locationId) return;const locationId = item.locationId;handleClose();- void scopeToLocationServer(locationId).then(() => {+ void scopeToLocationWorkspace(locationId).then(() => {sidebarStore.ensureGroupExpanded(agentExpandKey(item.id));navigate('location', { locationId, agentName: item.title });});diff --git a/console/apps/switch-console-desktop/src/renderer/features/command-palette/palette-agent-item.tsx b/console/apps/switch-console-desktop/src/renderer/features/command-palette/palette-agent-item.tsxindex a8e7ab034..c2ba81298 100644--- a/console/apps/switch-console-desktop/src/renderer/features/command-palette/palette-agent-item.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/command-palette/palette-agent-item.tsx@@ -5,7 +5,7 @@ import { agentsStore } from '@renderer/features/locations/stores/agents-store';import { AgentAvatar } from '@renderer/lib/components/agent-avatar';import { AgentIcon } from '@renderer/lib/components/agent-icon';import { sidebarStore } from '@renderer/lib/stores/app-state';-import { useAgentIconUrl } from '@renderer/lib/stores/use-remote-agents';+import { useAgentIconUrl } from '@renderer/lib/stores/use-workspace-agents';import type { SearchItem } from '@shared/core/search';import { PALETTE_ITEM_CLASS } from './palette-item-styles';@@ -14,7 +14,7 @@ import { PALETTE_ITEM_CLASS } from './palette-item-styles';* agent's own face leads, and what it runs on follows its name as a small mark.** A row of its own rather than a branch of `PaletteKindIcon`, because the- * chosen icon comes from a query keyed by server and a hook cannot be called+ * chosen icon comes from a query keyed by workspace and a hook cannot be called* from inside a switch. An agent this app does not hold — a hit whose local row* has gone — still gets the bot drawn from its name, which is the same face the* Switch bridges show.@@ -29,7 +29,7 @@ export const PaletteAgentItem = observer(function PaletteAgentItem({onSelect: () => void;}) {const agent = agentsStore.agentById(item.id);- const iconUrl = useAgentIconUrl(agent?.serverId ?? null, agent?.switchAgentId ?? null);+ const iconUrl = useAgentIconUrl(agent?.workspaceId ?? null, agent?.switchAgentId ?? null);return (<Command.Item value={value} onSelect={onSelect} className={PALETTE_ITEM_CLASS}>diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsxindex a2639a67b..8e267b83b 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx@@ -13,6 +13,7 @@ import {} from '@renderer/features/remote-hosts/host-readiness-notice';import { policyHasDeadRule } from '@renderer/features/switch-servers/addressing-policy-editor';import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { ProviderConnectionStatus } from '@renderer/lib/components/provider-connection-status';import { describeFailure } from '@renderer/lib/errors/describe-failure';import { toast } from '@renderer/lib/hooks/use-toast';@@ -23,7 +24,7 @@ import {useShowModal,type BaseModalProps,} from '@renderer/lib/modal/modal-provider';-import { useRemoteAgents } from '@renderer/lib/stores/use-remote-agents';+import { useWorkspaceAgents } from '@renderer/lib/stores/use-workspace-agents';import { Button } from '@renderer/lib/ui/button';import { ConfirmButton } from '@renderer/lib/ui/confirm-button';import {@@ -137,7 +138,7 @@ export const AddAgentModal = observer(function AddAgentModal({// Names already taken on the server, so a clash is refused before anything// is created rather than reported by the server afterwards.- const remoteAgents = useRemoteAgents(pickState.serverId);+ const remoteAgents = useWorkspaceAgents(workspacesStore.idOnServerInScope(pickState.serverId));const takenNames = useMemo(() => new Set((remoteAgents.data ?? []).map((a) => a.name)),[remoteAgents.data]@@ -385,9 +386,13 @@ export const AddAgentModal = observer(function AddAgentModal({setSubmitState('idle');return;}- if (form.addressingPolicy !== null && result.agent.switchAgentId) {- await rpc.switchServers.updateAddressingPolicy({- serverId: pickState.serverId,+ if (+ form.addressingPolicy !== null &&+ result.agent.switchAgentId &&+ result.agent.workspaceId+ ) {+ await rpc.workspaces.updateAddressingPolicy({+ workspaceId: result.agent.workspaceId,agentId: result.agent.switchAgentId,policy: form.addressingPolicy,});@@ -598,7 +603,7 @@ export const AddAgentModal = observer(function AddAgentModal({{canConfigureAgent && (<AgentSettingsSectionform={form}- serverId={pickState.serverId}+ workspaceId={workspacesStore.idOnServerInScope(pickState.serverId)}onAddServer={() => showAddServerModal({})}onOpenMessagingApps={() => {onClose();diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsxindex 7b179292a..b6574013a 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsx@@ -9,6 +9,7 @@ import { switchServersStore } from '@renderer/features/switch-servers/switch-serimport { useMyIdentities } from '@renderer/features/switch-servers/use-my-identities';import { AgentIconPicker } from '@renderer/lib/components/agent-icon-picker';import { rpc } from '@renderer/lib/ipc';+import { useWorkspaceAgents } from '@renderer/lib/stores/use-workspace-agents';import { Alert, AlertAction, AlertDescription } from '@renderer/lib/ui/alert';import { Button } from '@renderer/lib/ui/button';import { DisclosureRow } from '@renderer/lib/ui/disclosure-row';@@ -29,12 +30,12 @@ import type { ConfigureAgentFormState } from './modes';*/export const AgentSettingsSection = observer(function AgentSettingsSection({form,- serverId,+ workspaceId,onAddServer,onOpenMessagingApps,}: {form: ConfigureAgentFormState;- serverId: string | null;+ workspaceId: string | null;onAddServer: () => void;onOpenMessagingApps: () => void;}) {@@ -48,27 +49,24 @@ export const AgentSettingsSection = observer(function AgentSettingsSection({const servers = switchServersStore.servers;- // Selector data for the addressing-policy editor, scoped to the chosen server.+ // Selector data for the addressing-policy editor, scoped to the workspace the+ // chosen server is in scope for.const roomsQuery = useQuery({- queryKey: ['remote-rooms', serverId],- queryFn: () => rpc.switchServers.listRemoteRooms(serverId as string),- enabled: serverId !== null,+ queryKey: ['remote-rooms', workspaceId],+ queryFn: () => rpc.workspaces.listRooms(workspaceId as string),+ enabled: workspaceId !== null,});const groupsQuery = useQuery({- queryKey: ['remote-room-groups', serverId],- queryFn: () => rpc.switchServers.listRemoteRoomGroups(serverId as string),- enabled: serverId !== null,+ queryKey: ['remote-room-groups', workspaceId],+ queryFn: () => rpc.workspaces.listRoomGroups(workspaceId as string),+ enabled: workspaceId !== null,});const usersQuery = useQuery({- queryKey: ['remote-external-users', serverId],- queryFn: () => rpc.switchServers.listRemoteExternalUsers(serverId as string),- enabled: serverId !== null,- });- const agentsQuery = useQuery({- queryKey: ['remote-agents', serverId],- queryFn: () => rpc.switchServers.listRemoteAgents(serverId as string),- enabled: serverId !== null,+ queryKey: ['remote-external-users', workspaceId],+ queryFn: () => rpc.workspaces.listExternalUsers(workspaceId as string),+ enabled: workspaceId !== null,});+ const agentsQuery = useWorkspaceAgents(workspaceId);const roomOptions: OptionItem[] = (roomsQuery.data ?? []).map((r) => ({id: r.id,label: r.name,@@ -88,11 +86,11 @@ export const AgentSettingsSection = observer(function AgentSettingsSection({// Read here rather than inside the editor so the owner-only default can be// questioned before the agent exists, not after it has gone quiet.- const { identities } = useMyIdentities(serverId);+ const { identities } = useMyIdentities(workspaceId);const bridgesQuery = useQuery({- queryKey: ['remote-bridges', serverId],- queryFn: () => rpc.switchServers.listRemoteBridges(serverId as string),- enabled: serverId !== null,+ queryKey: ['remote-bridges', workspaceId],+ queryFn: () => rpc.workspaces.listBridges(workspaceId as string),+ enabled: workspaceId !== null,});const unlinkedApps =identities === null || bridgesQuery.data === undefineddiff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/location-titlebar.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/location-titlebar.tsxindex 4dc8dfbfe..1745fd09f 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/location-titlebar.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/location-titlebar.tsx@@ -19,7 +19,7 @@ import { useToast } from '@renderer/lib/hooks/use-toast';import { rpc } from '@renderer/lib/ipc';import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';import { useShowModal } from '@renderer/lib/modal/modal-provider';-import { useAgentIconUrl } from '@renderer/lib/stores/use-remote-agents';+import { useAgentIconUrl } from '@renderer/lib/stores/use-workspace-agents';import { Button } from '@renderer/lib/ui/button';import {DropdownMenu,@@ -38,7 +38,7 @@ import type { Agent } from '@shared/core/agents/agents';*/const AgentCrumb = observer(function AgentCrumb({ agent }: { agent: Agent | null }) {const label = agent?.name ?? 'Agent';- const iconUrl = useAgentIconUrl(agent?.serverId ?? null, agent?.switchAgentId ?? null);+ const iconUrl = useAgentIconUrl(agent?.workspaceId ?? null, agent?.switchAgentId ?? null);return (<TitlebarBreadcrumbcrumbs={[diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-page-header.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-page-header.tsxindex ee7380ce1..896aff096 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-page-header.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-page-header.tsx@@ -8,7 +8,10 @@ import { useToast } from '@renderer/lib/hooks/use-toast';import { rpc } from '@renderer/lib/ipc';import { useParams } from '@renderer/lib/layout/navigation-provider';import { useShowModal } from '@renderer/lib/modal/modal-provider';-import { remoteAgentsQueryKey, useRemoteAgents } from '@renderer/lib/stores/use-remote-agents';+import {+ workspaceAgentsQueryKey,+ useWorkspaceAgents,+} from '@renderer/lib/stores/use-workspace-agents';import { Badge } from '@renderer/lib/ui/badge';import { Button } from '@renderer/lib/ui/button';import { providerDisplayName } from '@shared/core/providers/agent-provider-registry';@@ -35,8 +38,8 @@ export const AgentPageHeader = observer(function AgentPageHeader() {const agentMachineName = agent?.name ?? agentName ?? 'Agent';const provider = agent?.providerId ? providerDisplayName(agent.providerId) : null;- const serverId = agent?.serverId ?? null;- const { data: remoteAgents } = useRemoteAgents(serverId);+ const workspaceId = agent?.workspaceId ?? null;+ const { data: remoteAgents } = useWorkspaceAgents(workspaceId);const remote = (remoteAgents ?? []).find((a) => a.id === agent?.switchAgentId) ?? null;const description = remote?.description ?? null;@@ -45,7 +48,7 @@ export const AgentPageHeader = observer(function AgentPageHeader() {// Show machine name as subtitle only if displayName exists and differs from nameconst showMachineName = remote?.displayName != null && remote.displayName !== agentMachineName;- const roomable = serverId !== null && agent?.switchAgentId != null;+ const roomable = workspaceId !== null && agent?.switchAgentId != null;const queryClient = useQueryClient();const { toast } = useToast();@@ -55,10 +58,10 @@ export const AgentPageHeader = observer(function AgentPageHeader() {* request that can fail. It is reported rather than swallowed: a picture* that silently reverts on the next refresh is worse than an error. */const changeIcon = async (iconUrl: string | null) => {- if (serverId === null || switchAgentId === null) return;+ if (workspaceId === null || switchAgentId === null) return;try {- await rpc.switchServers.updateAgentIcon({ serverId, agentId: switchAgentId, iconUrl });- await queryClient.invalidateQueries({ queryKey: remoteAgentsQueryKey(serverId) });+ await rpc.workspaces.updateAgentIcon({ workspaceId, agentId: switchAgentId, iconUrl });+ await queryClient.invalidateQueries({ queryKey: workspaceAgentsQueryKey(workspaceId) });} catch (cause) {const { headline, detail } = describeFailure(cause, "Could not change the agent's icon.");toast({@@ -69,7 +72,7 @@ export const AgentPageHeader = observer(function AgentPageHeader() {}};- const editableIcon = serverId !== null && switchAgentId !== null;+ const editableIcon = workspaceId !== null && switchAgentId !== null;return (<header className="flex shrink-0 items-start gap-5 pt-10">@@ -117,7 +120,7 @@ export const AgentPageHeader = observer(function AgentPageHeader() {variant="outline"onClick={() =>showAddToRoom({- serverId: serverId as string,+ workspaceId: workspaceId as string,switchAgentId: agent.switchAgentId as string,agentName: title,})diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section.tsxindex fc9f8de75..fb9c4a4c2 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section.tsx@@ -32,7 +32,7 @@ export function AddressingPolicySettingsSection({});const switchAgents = (agents ?? []).filter(- (a) => a.serverId && a.switchAgentId && (!agentId || a.id === agentId)+ (a) => a.workspaceId && a.switchAgentId && (!agentId || a.id === agentId));if (switchAgents.length === 0) return null;@@ -41,6 +41,7 @@ export function AddressingPolicySettingsSection({{switchAgents.map((agent) => (<AddressingPolicyRowkey={agent.id}+ workspaceId={agent.workspaceId as string}serverId={agent.serverId as string}agentId={agent.switchAgentId as string}agentName={agent.name}@@ -52,11 +53,15 @@ export function AddressingPolicySettingsSection({}function AddressingPolicyRow({+ workspaceId,serverId,agentId,agentName,showName,}: {+ workspaceId: string;+ /** Only for the link out to the server's messaging apps, which is a page+ * about the gateway rather than about this workspace's data. */serverId: string;agentId: string;agentName: string;@@ -64,37 +69,37 @@ function AddressingPolicyRow({}) {const queryClient = useQueryClient();const { navigate } = useNavigate();- const { identities } = useMyIdentities(serverId);+ const { identities } = useMyIdentities(workspaceId);const [draft, setDraft] = useState<AddressingPolicy | null>(null);const [dirty, setDirty] = useState(false);const [error, setError] = useState<string | null>(null);- const policyKey = ['agent-addressing-policy', serverId, agentId];+ const policyKey = ['agent-addressing-policy', workspaceId, agentId];const { data: saved } = useQuery({queryKey: policyKey,- queryFn: () => rpc.switchServers.getAddressingPolicy({ serverId, agentId }),+ queryFn: () => rpc.workspaces.getAddressingPolicy({ workspaceId, agentId }),});const rooms = useQuery({- queryKey: ['remote-rooms', serverId],- queryFn: () => rpc.switchServers.listRemoteRooms(serverId),+ queryKey: ['remote-rooms', workspaceId],+ queryFn: () => rpc.workspaces.listRooms(workspaceId),});const groups = useQuery({- queryKey: ['remote-room-groups', serverId],- queryFn: () => rpc.switchServers.listRemoteRoomGroups(serverId),+ queryKey: ['remote-room-groups', workspaceId],+ queryFn: () => rpc.workspaces.listRoomGroups(workspaceId),});const users = useQuery({- queryKey: ['remote-external-users', serverId],- queryFn: () => rpc.switchServers.listRemoteExternalUsers(serverId),+ queryKey: ['remote-external-users', workspaceId],+ queryFn: () => rpc.workspaces.listExternalUsers(workspaceId),});const remoteAgents = useQuery({- queryKey: ['remote-agents', serverId],- queryFn: () => rpc.switchServers.listRemoteAgents(serverId),+ queryKey: ['remote-agents', workspaceId],+ queryFn: () => rpc.workspaces.listAgents(workspaceId),});const bridges = useQuery({- queryKey: ['remote-bridges', serverId],- queryFn: () => rpc.switchServers.listRemoteBridges(serverId),+ queryKey: ['remote-bridges', workspaceId],+ queryFn: () => rpc.workspaces.listBridges(workspaceId),});- // The apps on this server the user has claimed no account on. Null until both+ // The apps in this workspace the user has claimed no account on. Null until both// halves have arrived: a bridge list without the identities would read as// every app unlinked.const unlinkedApps =@@ -109,7 +114,7 @@ function AddressingPolicyRow({const mutation = useMutation({mutationFn: (policy: AddressingPolicy | null) =>- rpc.switchServers.updateAddressingPolicy({ serverId, agentId, policy }),+ rpc.workspaces.updateAddressingPolicy({ workspaceId, agentId, policy }),onSuccess: (_result, policy) => {queryClient.setQueryData(policyKey, policy);setDirty(false);diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/stores/agents-store.test.ts b/console/apps/switch-console-desktop/src/renderer/features/locations/stores/agents-store.test.tsindex 1fb86772d..ea1004d6c 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/stores/agents-store.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/stores/agents-store.test.ts@@ -4,70 +4,75 @@ import { agentsStore } from './agents-store';vi.mock('@renderer/lib/ipc', () => ({ rpc: {} }));-function agent(locationId: string, serverId: string | null, name: string): Agent {- return { locationId, serverId, name } as Agent;+function agent(locationId: string, workspaceId: string | null, name: string): Agent {+ return { locationId, workspaceId, name } as Agent;}/*** The premise these cover: a directory can hold agents registered against- * several Switch servers at once, so "which server does this directory belong+ * several workspaces at once, so "which workspace does this directory belong* to" has no single answer and must not be asked (CHOO-2044).*/-describe('AgentsStore server scoping', () => {+describe('AgentsStore workspace scoping', () => {afterEach(() => {agentsStore.byLocation.clear();- agentsStore.optimisticServerByLocation.clear();+ agentsStore.optimisticWorkspaceByLocation.clear();});- it('returns only the agents belonging to the given server', () => {+ it('returns only the agents belonging to the given workspace', () => {agentsStore.byLocation.set('shared', [- agent('shared', 'server-1', 'a'),- agent('shared', 'server-2', 'b'),+ agent('shared', 'ws-1', 'a'),+ agent('shared', 'ws-2', 'b'),agent('shared', null, 'unlinked'),]);- expect(agentsStore.agentsOnServerAtLocation('shared', 'server-1').map((a) => a.name)).toEqual([+ expect(agentsStore.agentsInWorkspaceAtLocation('shared', 'ws-1').map((a) => a.name)).toEqual(['a',]);- expect(agentsStore.agentsOnServerAtLocation('shared', 'server-2').map((a) => a.name)).toEqual([+ expect(agentsStore.agentsInWorkspaceAtLocation('shared', 'ws-2').map((a) => a.name)).toEqual(['b',]);- expect(agentsStore.agentsOnServerAtLocation('shared', 'server-3')).toEqual([]);+ expect(agentsStore.agentsInWorkspaceAtLocation('shared', 'ws-3')).toEqual([]);});- it('reports a shared directory as present on every server it has agents on', () => {+ /**+ * Two workspaces on the same server are still two scopes: the sidebar shows+ * one of them at a time, so a directory present in both must answer for each+ * separately rather than for the server they share.+ */+ it('separates two workspaces that live on the same server', () => {agentsStore.byLocation.set('shared', [- agent('shared', 'server-1', 'a'),- agent('shared', 'server-2', 'b'),+ agent('shared', 'ws-1', 'a'),+ agent('shared', 'ws-2', 'b'),]);- expect(agentsStore.locationHasAgentsOnServer('shared', 'server-1')).toBe(true);- expect(agentsStore.locationHasAgentsOnServer('shared', 'server-2')).toBe(true);- expect(agentsStore.locationHasAgentsOnServer('shared', 'server-3')).toBe(false);- expect(agentsStore.serverIdsForLocation('shared').sort()).toEqual(['server-1', 'server-2']);+ expect(agentsStore.locationHasAgentsInWorkspace('shared', 'ws-1')).toBe(true);+ expect(agentsStore.locationHasAgentsInWorkspace('shared', 'ws-2')).toBe(true);+ expect(agentsStore.locationHasAgentsInWorkspace('shared', 'ws-3')).toBe(false);+ expect(agentsStore.workspaceIdsForLocation('shared').sort()).toEqual(['ws-1', 'ws-2']);});it('keeps a just-created location in scope before its agent row lands', () => {- agentsStore.noteLocationServer('fresh', 'server-1');+ agentsStore.noteLocationWorkspace('fresh', 'ws-1');- expect(agentsStore.locationHasAgentsOnServer('fresh', 'server-1')).toBe(true);- expect(agentsStore.locationHasAgentsOnServer('fresh', 'server-2')).toBe(false);- expect(agentsStore.serverIdsForLocation('fresh')).toEqual(['server-1']);+ expect(agentsStore.locationHasAgentsInWorkspace('fresh', 'ws-1')).toBe(true);+ expect(agentsStore.locationHasAgentsInWorkspace('fresh', 'ws-2')).toBe(false);+ expect(agentsStore.workspaceIdsForLocation('fresh')).toEqual(['ws-1']);});it('ignores the optimistic note once real agents exist', () => {- agentsStore.noteLocationServer('shared', 'server-9');- agentsStore.byLocation.set('shared', [agent('shared', 'server-1', 'a')]);+ agentsStore.noteLocationWorkspace('shared', 'ws-9');+ agentsStore.byLocation.set('shared', [agent('shared', 'ws-1', 'a')]);- expect(agentsStore.serverIdsForLocation('shared')).toEqual(['server-1']);- expect(agentsStore.locationHasAgentsOnServer('shared', 'server-9')).toBe(false);+ expect(agentsStore.workspaceIdsForLocation('shared')).toEqual(['ws-1']);+ expect(agentsStore.locationHasAgentsInWorkspace('shared', 'ws-9')).toBe(false);});- it('treats a location with only unlinked agents as on no server', () => {+ it('treats a location with only unlinked agents as in no workspace', () => {agentsStore.byLocation.set('orphan', [agent('orphan', null, 'a')]);- expect(agentsStore.serverIdsForLocation('orphan')).toEqual([]);- expect(agentsStore.locationHasAgentsOnServer('orphan', 'server-1')).toBe(false);+ expect(agentsStore.workspaceIdsForLocation('orphan')).toEqual([]);+ expect(agentsStore.locationHasAgentsInWorkspace('orphan', 'ws-1')).toBe(false);});});@@ -82,13 +87,13 @@ describe('AgentsStore server scoping', () => {describe('resolving the agent a location route is about', () => {afterEach(() => {agentsStore.byLocation.clear();- agentsStore.optimisticServerByLocation.clear();+ agentsStore.optimisticWorkspaceByLocation.clear();});it('picks the named agent out of a shared directory', () => {agentsStore.byLocation.set('dir', [- agent('dir', 'server-1', 'charlie'),- agent('dir', 'server-1', 'delta'),+ agent('dir', 'ws-1', 'charlie'),+ agent('dir', 'ws-1', 'delta'),]);expect(agentsStore.agentAtLocation('dir', 'charlie')?.name).toBe('charlie');@@ -97,22 +102,22 @@ describe('resolving the agent a location route is about', () => {it('resolves an unnamed route when the directory holds exactly one agent', () => {// Nothing to choose between, so there is nothing to get wrong.- agentsStore.byLocation.set('dir', [agent('dir', 'server-1', 'charlie')]);+ agentsStore.byLocation.set('dir', [agent('dir', 'ws-1', 'charlie')]);expect(agentsStore.agentAtLocation('dir', undefined)?.name).toBe('charlie');});it('refuses to guess between several agents', () => {agentsStore.byLocation.set('dir', [- agent('dir', 'server-1', 'charlie'),- agent('dir', 'server-1', 'delta'),+ agent('dir', 'ws-1', 'charlie'),+ agent('dir', 'ws-1', 'delta'),]);expect(agentsStore.agentAtLocation('dir', undefined)).toBeNull();});it('is null for a name that is not there, rather than the first agent', () => {- agentsStore.byLocation.set('dir', [agent('dir', 'server-1', 'charlie')]);+ agentsStore.byLocation.set('dir', [agent('dir', 'ws-1', 'charlie')]);expect(agentsStore.agentAtLocation('dir', 'nobody')).toBeNull();});diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/stores/agents-store.ts b/console/apps/switch-console-desktop/src/renderer/features/locations/stores/agents-store.tsindex 42a27c5bd..3d446c8f7 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/stores/agents-store.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/stores/agents-store.ts@@ -4,26 +4,27 @@ import type { Agent } from '@shared/core/agents/agents';/*** Renderer cache of every agent across all locations. The sidebar scopes its tree- * to the active server (see {@link switchServersStore.activeServerId}), so it needs- * a reactive lookup that does not depend on each row's own react-query.+ * to the active workspace (see {@link workspacesStore.activeId}), so it needs a+ * reactive lookup that does not depend on each row's own react-query.*- * **A server belongs to an agent, not to a directory.** A directory is a place on- * disk and can hold agents registered against several servers at once, so there is- * no such thing as "the location's server" to scope on — asking for one drags every- * agent in the directory under whichever answer came back first (CHOO-2044). Scope- * on {@link agentsOnServerAtLocation}; a location is in scope when it has any.+ * **A workspace belongs to an agent, not to a directory.** A directory is a place+ * on disk and can hold agents registered in several workspaces at once, so there+ * is no such thing as "the location's workspace" to scope on — asking for one+ * drags every agent in the directory under whichever answer came back first+ * (CHOO-2044). Scope on {@link agentsInWorkspaceAtLocation}; a location is in+ * scope when it has any.*/export class AgentsStore {/** All agents grouped by their location id. */readonly byLocation = new Map<string, Agent[]>();/**- * Server id a just-created location's agent will belong to, recorded by the+ * Workspace id a just-created location's agent will belong to, recorded by the* add-agent modal before {@link load} has re-fetched the new agent. Used as a- * fallback in {@link locationHasAgentsOnServer} so a freshly-created location does- * not flicker out of the sidebar's server-scoped view during the gap between the- * location mounting and the agent list refreshing.+ * fallback in {@link locationHasAgentsInWorkspace} so a freshly-created location+ * does not flicker out of the sidebar's workspace-scoped view during the gap+ * between the location mounting and the agent list refreshing.*/- readonly optimisticServerByLocation = new Map<string, string>();+ readonly optimisticWorkspaceByLocation = new Map<string, string>();loaded = false;constructor() {@@ -41,16 +42,16 @@ export class AgentsStore {}// Drop optimistic notes now superseded by a real agent record.for (const locationId of this.byLocation.keys()) {- this.optimisticServerByLocation.delete(locationId);+ this.optimisticWorkspaceByLocation.delete(locationId);}this.loaded = true;});}- /** Record the server a location's agent will bind to, ahead of {@link load}. */- noteLocationServer(locationId: string, serverId: string): void {+ /** Record the workspace a location's agent will bind to, ahead of {@link load}. */+ noteLocationWorkspace(locationId: string, workspaceId: string): void {runInAction(() => {- this.optimisticServerByLocation.set(locationId, serverId);+ this.optimisticWorkspaceByLocation.set(locationId, workspaceId);});}@@ -97,35 +98,60 @@ export class AgentsStore {return matching.sort((a, b) => a.name.localeCompare(b.name));}- /** A location's agents that belong to one server — what the sidebar renders- * under that server. Agents in the same directory registered elsewhere are not- * this server's to show. */- agentsOnServerAtLocation(locationId: string, serverId: string): Agent[] {- return (this.byLocation.get(locationId) ?? []).filter((a) => a.serverId === serverId);+ /**+ * This install's agents in a given workspace — the ones the room views may+ * list and offer.+ *+ * The workspace-addressed counterpart of {@link agentsOnServer}, and what a+ * view scoped to a workspace asks for: its rooms and their members are that+ * workspace's, and a server hosting several would otherwise offer agents from+ * all of them.+ */+ agentsInWorkspace(workspaceId: string): Agent[] {+ const matching: Agent[] = [];+ for (const agents of this.byLocation.values()) {+ for (const agent of agents) {+ if (agent.workspaceId === workspaceId && agent.switchAgentId) matching.push(agent);+ }+ }+ return matching.sort((a, b) => a.name.localeCompare(b.name));+ }++ /**+ * A location's agents that belong to one workspace — what the sidebar renders+ * under that workspace. Agents in the same directory registered elsewhere are+ * not this workspace's to show.+ *+ * Unlike {@link agentsInWorkspace} this keeps agents with no Switch identity:+ * an agent still being registered has a workspace and a row in the tree, and+ * dropping it would make it disappear from the sidebar mid-onboarding.+ */+ agentsInWorkspaceAtLocation(locationId: string, workspaceId: string): Agent[] {+ return (this.byLocation.get(locationId) ?? []).filter((a) => a.workspaceId === workspaceId);}- /** Whether a location has anything to show under `serverId`. */- locationHasAgentsOnServer(locationId: string, serverId: string): boolean {- return this.serverIdsForLocation(locationId).includes(serverId);+ /** Whether a location has anything to show under `workspaceId`. */+ locationHasAgentsInWorkspace(locationId: string, workspaceId: string): boolean {+ return this.workspaceIdsForLocation(locationId).includes(workspaceId);}/**- * The servers a location's agents belong to. A directory can span several, so- * this is a list rather than the one answer callers used to ask for.+ * The workspaces a location's agents belong to. A directory can span several,+ * so this is a list rather than the one answer callers used to ask for.** The optimistic note stands in only while the location has no agent rows at* all — that is the gap it exists to cover. Letting it also speak for a location- * that already has agents would have it claim a server the location is not on.+ * that already has agents would have it claim a workspace the location is not in.*/- serverIdsForLocation(locationId: string): string[] {+ workspaceIdsForLocation(locationId: string): string[] {const agents = this.byLocation.get(locationId);if (!agents || agents.length === 0) {- const optimistic = this.optimisticServerByLocation.get(locationId);+ const optimistic = this.optimisticWorkspaceByLocation.get(locationId);return optimistic ? [optimistic] : [];}const ids = new Set<string>();for (const agent of agents) {- if (agent.serverId !== null) ids.add(agent.serverId);+ if (agent.workspaceId !== null) ids.add(agent.workspaceId);}return [...ids];}diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/stores/location-manager.test.ts b/console/apps/switch-console-desktop/src/renderer/features/locations/stores/location-manager.test.tsindex 5954402f8..73e36e19b 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/stores/location-manager.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/stores/location-manager.test.ts@@ -74,6 +74,7 @@ function agent(overrides: Partial<Agent> = {}): Agent {providerId: 'claude',switchAgentId: 'sw-1',apiEndpoint: 'https://switch.example.com',+ workspaceId: 'workspace-1',serverId: 'server-1',status: null,autoApprove: false,diff --git a/console/apps/switch-console-desktop/src/renderer/features/onboarding/create-workspace-page.tsx b/console/apps/switch-console-desktop/src/renderer/features/onboarding/create-workspace-page.tsxnew file mode 100644index 000000000..af75cf12f--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/onboarding/create-workspace-page.tsx@@ -0,0 +1,137 @@+import { useState } from 'react';+import { createWorkspaceFailureText } from '@renderer/features/workspaces/describe-create-failure';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';+import { failureText } from '@renderer/lib/errors/describe-failure';+import { Button } from '@renderer/lib/ui/button';+import { ConfirmButton } from '@renderer/lib/ui/confirm-button';+import { Field, FieldGroup, FieldLabel } from '@renderer/lib/ui/field';+import { Input } from '@renderer/lib/ui/input';+import { WizardFrame } from '@renderer/lib/ui/wizard-frame';+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';+import type { Workspace } from '@shared/core/workspaces/workspaces';++/**+ * Make the workspace the account will work in.+ *+ * A name and nothing else. The design's address hint under the field describes+ * a workspace reachable at its own subdomain, which is not how a Switch+ * workspace is addressed — it lives on the server you signed in to, and showing+ * an address that resolves to nothing would be the app inventing an answer. The+ * "let my team join automatically" toggle is gone for the same reason: joining+ * by email domain is a thing no Switch server can do yet, so a switch for it+ * would silently do nothing.+ */+export function CreateWorkspacePage({+ server,+ onBack,+ onCreated,+}: {+ server: SwitchServer;+ /** Null where the account is in no workspace, so there is no list behind this. */+ onBack: (() => void) | null;+ onCreated: () => void;+}) {+ const [name, setName] = useState('');+ const [submitting, setSubmitting] = useState(false);+ const [error, setError] = useState<string | null>(null);+ /**+ * The workspace the server has already minted, when entering it is what+ * failed.+ *+ * Asking again would offer a name the server has just taken and come back+ * with a conflict that reads as the name being refused. On the page reached+ * with no memberships there is no Back either, so the only remaining move has+ * to be the one that can still work: entering what exists.+ */+ const [created, setCreated] = useState<Workspace | null>(null);++ const trimmed = name.trim();++ const submit = async () => {+ if (submitting || (created === null && trimmed === '')) return;+ setSubmitting(true);+ setError(null);+ try {+ const workspace = created ?? (await workspacesStore.create(server.id, trimmed));+ setCreated(workspace);+ await workspacesStore.setActive(workspace.id);+ onCreated();+ } catch (cause) {+ // Two different failures wear the same button. Before the workspace+ // exists the likeliest one is the name, and after it exists the name is+ // settled and what failed was the move into it — saying "could not+ // create" then would be describing the wrong step.+ setError(+ created === null+ ? createWorkspaceFailureText(+ cause,+ server.name,+ `${server.name} could not create the workspace.`+ )+ : failureText(cause, `This window could not be moved into ${created.name}.`)+ );+ setSubmitting(false);+ }+ };++ return (+ <WizardFrame+ title="Create your workspace"+ subtitle={+ onBack === null+ ? `You’re not in a workspace on ${server.name} yet, so you’re the first one here. A workspace is where your agents, rooms and teammates live.`+ : 'A workspace is where your agents, rooms and teammates live.'+ }+ pager={{+ pageName: 'Create your workspace',+ onBack: onBack && !submitting && created === null ? onBack : null,+ onNext: null,+ }}+ footer={+ <>+ {onBack && created === null && (+ <Button variant="outline" onClick={onBack} disabled={submitting}>+ Back+ </Button>+ )}+ <ConfirmButton+ onClick={() => void submit()}+ disabled={submitting || (created === null && trimmed === '')}+ >+ {created !== null+ ? submitting+ ? 'Opening…'+ : 'Open workspace'+ : submitting+ ? 'Creating…'+ : 'Create workspace'}+ </ConfirmButton>+ </>+ }+ >+ <FieldGroup>+ <Field>+ <FieldLabel>Name</FieldLabel>+ <Input+ value={name}+ onChange={(e) => setName(e.target.value)}+ placeholder="Acme Robotics"+ autoFocus+ disabled={created !== null}+ onKeyDown={(e) => {+ if (e.key === 'Enter') void submit();+ }}+ />+ {error && <p className="mt-1 text-xs text-destructive">{error}</p>}+ {created !== null && (+ <p className="mt-1 text-xs text-foreground-muted">+ {created.name} was created on {server.name}, but this window could not be moved into+ it. Try again — asking for it a second time would only be refused for the name it+ already has.+ </p>+ )}+ </Field>+ </FieldGroup>+ </WizardFrame>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/onboarding/invite-pages.tsx b/console/apps/switch-console-desktop/src/renderer/features/onboarding/invite-pages.tsxnew file mode 100644index 000000000..f4bfdc0e7--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/onboarding/invite-pages.tsx@@ -0,0 +1,182 @@+import { useCallback, useEffect, useRef, useState } from 'react';+import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';+import { failureText } from '@renderer/lib/errors/describe-failure';+import { Button } from '@renderer/lib/ui/button';+import { ConfirmButton } from '@renderer/lib/ui/confirm-button';+import { Field, FieldDescription, FieldGroup, FieldLabel } from '@renderer/lib/ui/field';+import { Input } from '@renderer/lib/ui/input';+import { Spinner } from '@renderer/lib/ui/spinner';+import { WizardFrame } from '@renderer/lib/ui/wizard-frame';+import type { InviteServer } from '@shared/core/switch-servers/switch-cloud';+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';+import { parseInviteLink, type InviteLink } from '@shared/core/workspaces/invite-link';++/**+ * Join a workspace from the invite link someone sent, instead of choosing where+ * Switch runs.+ *+ * The link names its server, so the page looks that up rather than asking: a+ * server this install already has, or Switch Cloud, goes straight to signing+ * in. Any other server still has to be connected to, because an invite link+ * carries the dashboard's address and the Console also needs the API's — that+ * form opens with the link's address filled in.+ */+export function InvitePage({+ onBack,+ onResolved,+}: {+ onBack: () => void;+ onResolved: (invite: InviteLink, server: InviteServer) => void;+}) {+ const [text, setText] = useState('');+ const [checking, setChecking] = useState(false);+ const [error, setError] = useState<string | null>(null);++ const submit = async () => {+ if (checking) return;+ let invite: InviteLink;+ try {+ invite = parseInviteLink(text);+ } catch (cause) {+ setError(failureText(cause, 'That invite link could not be read.'));+ return;+ }+ setChecking(true);+ setError(null);+ try {+ const server = await switchServersStore.serverForInvite(invite.origin);+ onResolved(invite, server);+ } catch (cause) {+ setError(failureText(cause, `Could not look up the server at ${invite.origin}.`));+ setChecking(false);+ }+ };++ return (+ <WizardFrame+ title="Join with an invite link"+ subtitle="Paste the link from your invitation. You'll sign in to the server it's for, then join the workspace."+ pager={{+ pageName: 'Join with an invite link',+ onBack: checking ? null : onBack,+ onNext: null,+ }}+ footer={+ <>+ <Button variant="outline" onClick={onBack} disabled={checking}>+ Back+ </Button>+ <ConfirmButton onClick={() => void submit()} disabled={checking || text.trim() === ''}>+ {checking ? 'Checking…' : 'Continue'}+ </ConfirmButton>+ </>+ }+ >+ <FieldGroup>+ <Field>+ <FieldLabel htmlFor="invite-link">Invite link</FieldLabel>+ <Input+ id="invite-link"+ value={text}+ onChange={(e) => setText(e.target.value)}+ placeholder="https://switch.example.com/invite#token=…"+ autoFocus+ disabled={checking}+ onKeyDown={(e) => {+ if (e.key === 'Enter') void submit();+ }}+ />+ <FieldDescription>+ It was in the invitation e-mail, or whoever invited you sent it.+ </FieldDescription>+ {error && (+ <p role="alert" className="mt-1 text-xs text-destructive">+ {error}+ </p>+ )}+ </Field>+ </FieldGroup>+ </WizardFrame>+ );+}++type Acceptance = { kind: 'accepting' } | { kind: 'failed'; message: string };++/**+ * Accept the held invitation now that there is an account to accept it with.+ *+ * Starts on arrival: the user already said what they wanted by pasting the+ * link, and a page with one button that does the obvious would be a question+ * with one answer. A refusal is shown as the server gave it — revoked, expired,+ * used up, addressed to someone else — because each of those needs a different+ * conversation with whoever sent it, and the user can still go on to the+ * workspaces the account is already in.+ */+export function AcceptInvitePage({+ server,+ invite,+ onAccepted,+ onSkip,+}: {+ server: SwitchServer;+ invite: InviteLink;+ onAccepted: () => void;+ onSkip: () => void;+}) {+ const [state, setState] = useState<Acceptance>({ kind: 'accepting' });+ const started = useRef(false);++ const accept = useCallback(async () => {+ setState({ kind: 'accepting' });+ try {+ const workspace = await workspacesStore.acceptInvitation(server.id, invite.token);+ await workspacesStore.setActive(workspace.id);+ onAccepted();+ } catch (cause) {+ setState({+ kind: 'failed',+ message: failureText(cause, `${server.name} could not accept the invitation.`),+ });+ }+ }, [server, invite, onAccepted]);++ useEffect(() => {+ if (started.current) return;+ started.current = true;+ void accept();+ }, [accept]);++ return (+ <WizardFrame+ title={state.kind === 'failed' ? 'The invitation was not accepted' : 'Joining the workspace'}+ subtitle={+ state.kind === 'failed'+ ? 'Ask whoever invited you for a new link, or go on to the workspaces you are already in.'+ : `Accepting your invitation on ${server.name}.`+ }+ pager={{ pageName: 'Accept invitation', onBack: null, onNext: null }}+ footer={+ state.kind === 'failed' ? (+ <>+ <Button variant="outline" onClick={onSkip}>+ Continue without it+ </Button>+ <ConfirmButton onClick={() => void accept()}>Try again</ConfirmButton>+ </>+ ) : null+ }+ >+ {state.kind === 'failed' ? (+ <p role="alert" className="text-sm text-destructive">+ {state.message}+ </p>+ ) : (+ <div className="flex items-center gap-2 text-sm text-foreground-muted">+ <Spinner className="size-3.5" />+ <span>Accepting…</span>+ </div>+ )}+ </WizardFrame>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/onboarding/onboarding-flow.tsx b/console/apps/switch-console-desktop/src/renderer/features/onboarding/onboarding-flow.tsxnew file mode 100644index 000000000..66e9e868c--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/onboarding/onboarding-flow.tsx@@ -0,0 +1,472 @@+import { Link2, Server, TriangleAlert, Wrench } from 'lucide-react';+import { observer } from 'mobx-react-lite';+import { useCallback, useEffect, useState } from 'react';+import {+ ChoiceCard,+ ExternalServerStep,+ LocalSetupStep,+ RemoteHostSetupStep,+ SignInStep,+} from '@renderer/features/switch-servers/AddServerModal';+import { LinkAccountsStep } from '@renderer/features/switch-servers/link-accounts-step';+import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';+import { useSwitchCloud } from '@renderer/features/switch-servers/use-switch-cloud';+import { describeFailure } from '@renderer/lib/errors/describe-failure';+import { rpc } from '@renderer/lib/ipc';+import { useNavigate } from '@renderer/lib/layout/navigation-provider';+import { report } from '@renderer/lib/telemetry/report';+import { Alert, AlertAction, AlertDescription, AlertTitle } from '@renderer/lib/ui/alert';+import { Button } from '@renderer/lib/ui/button';+import { Spinner } from '@renderer/lib/ui/spinner';+import { WizardChromeProvider, WizardFrame } from '@renderer/lib/ui/wizard-frame';+import type {+ AddServerChoiceName,+ AddServerStepName,+} from '@shared/core/switch-servers/add-server-steps';+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';+import { CreateWorkspacePage } from './create-workspace-page';+import { AcceptInvitePage, InvitePage } from './invite-pages';+import { onboardingStore, type OnboardingPage } from './onboarding-store';+import { PickWorkspacePage } from './pick-workspace-page';+import { WelcomePage, type WelcomeCloud } from './welcome-page';++/**+ * The first-run pages and the add-server wizard's steps, named against each+ * other so both funnels answer the same question.+ *+ * They are the same steps — the first-run pages are the wizard drawn full+ * window — so reporting them under new names would split "how far did people+ * get" in two. `firstRun` on the event is what keeps them apart where it+ * matters. The welcome page belongs to neither: nothing has been chosen on it+ * and there is no server being added yet.+ *+ * The workspace pages are unreported for the opposite reason: they are not+ * steps of the add-server wizard at all — the modal has nothing like them,+ * because by the time you open it you are already in a workspace — so counting+ * them here would put drop-offs from one funnel into the other's numbers.+ */+const STEP_FOR_PAGE: Record<OnboardingPage, AddServerStepName | null> = {+ welcome: null,+ invite: null,+ whoRuns: 'choose',+ local: 'local',+ remoteHost: 'remoteHost',+ connect: 'external',+ signIn: 'signIn',+ pickWorkspace: null,+ createWorkspace: null,+ acceptInvite: null,+ linkAccounts: 'linkAccounts',+};++/**+ * Which path each page belongs to.+ *+ * Unlike the modal's, these barely inherit: the only way to reach sign-in on a+ * fresh install is by connecting to a server someone else runs. Whether that+ * server was typed in or was Switch Cloud is the one thing the table cannot+ * know, so `choiceForPage` refines it.+ */+const CHOICE_FOR_PAGE: Record<OnboardingPage, AddServerChoiceName> = {+ welcome: 'none',+ invite: 'none',+ whoRuns: 'none',+ local: 'local',+ remoteHost: 'remoteHost',+ connect: 'external',+ signIn: 'external',+ pickWorkspace: 'external',+ createWorkspace: 'external',+ acceptInvite: 'external',+ linkAccounts: 'external',+};++/**+ * Everything the window shows before there is a server to show.+ *+ * The pages after the first are the add-server wizard's own steps, drawn full+ * window instead of in a dialog. Setting up a server is the same three+ * questions whether you have none or nine, and a first-run copy of them would+ * be a second place for the Docker check, the connection form and the sign-in+ * to drift from what the rest of the app does.+ *+ * Running a managed stack on a remote host is offered only when there is a host+ * to run it on. It needs one onboarded over SSH, which a fresh install has none+ * of — but onboarding a host needs no server, so someone who deleted their last+ * one may well arrive here with hosts already set up, and hiding the path from+ * them would leave it unreachable.+ */+export const OnboardingFlow = observer(function OnboardingFlow() {+ const { navigate } = useNavigate();++ const goTo = (page: OnboardingPage) => {+ onboardingStore.goTo(page);+ reportPage(page);+ };++ /**+ * Leave the first-run pages for the app they were setting up.+ *+ * Landing on the new server's page rather than wherever the window would+ * otherwise open: the flow was about that server, and dropping the user into+ * an empty home view would make the last ten minutes look like they did+ * nothing.+ */+ const finish = (serverId: string | null) => {+ onboardingStore.reset();+ if (serverId === null) return;+ void switchServersStore.setActive(serverId);+ navigate('server', { serverId });+ };++ // The server as the list has it, not as the flow remembers it. Once one+ // exists the window is the workspace again for any view that does not need a+ // server, so it can be deleted from under the flow — and a form aimed at a+ // row that is gone fails on submit with no way back to a working one.+ const server = switchServersStore.serverById(pageServerId());++ /**+ * Leave the flow for the app, with the server set up but the rest not done.+ *+ * Offered only once the page on screen has a server of its own, which is both+ * when there is something to come back to and when the flow stops being the+ * only thing the window can draw. Before that, stepping back off the welcome+ * page is the way out.+ */+ const exit = server === null ? null : { label: 'Finish later', onExit: () => finish(server.id) };++ const cloud = useSwitchCloud();+ const [cloudAttempt, setCloudAttempt] = useState<{ connecting: boolean; error: string | null }>({+ connecting: false,+ error: null,+ });++ /**+ * Register Switch Cloud and go straight to signing in to it.+ *+ * There is nothing to ask first: the address is the build's, and the name is+ * the Cloud's. The connect page's form would be a page of fields already+ * filled in.+ */+ const connectToCloud = () => {+ setCloudAttempt({ connecting: true, error: null });+ switchServersStore.connectToSwitchCloud().then(+ (added) => {+ setCloudAttempt({ connecting: false, error: null });+ onboardingStore.connected(added, 'cloud');+ reportPage('signIn');+ },+ (cause) => {+ const failure = describeFailure(cause, 'Could not connect to Switch Cloud.');+ setCloudAttempt({+ connecting: false,+ error: failure.detail ? `${failure.headline} ${failure.detail}` : failure.headline,+ });+ }+ );+ };++ const welcomeCloud: WelcomeCloud =+ cloud.kind === 'open' ? { ...cloud, ...cloudAttempt, onConnect: connectToCloud } : cloud;++ return (+ <WizardChromeProvider chrome="page" exit={exit}>+ {currentPage(server, welcomeCloud, goTo, finish)}+ </WizardChromeProvider>+ );+});++/**+ * The server the page on screen is the setup of, if it has one yet.+ *+ * Asked per page rather than kept as one field, because the paths reach a+ * server by different means and none of them owns another's: the connect page+ * hands one over and every page after it works on that same one, while each+ * managed page brings its own up. Reading a single field instead offered a way+ * out to a server the current page had nothing to do with — connect to one,+ * walk back, choose the local path, and the exit still pointed at the first.+ */+function pageServerId(): string | null {+ const page = onboardingStore.page;+ if (onboardingStore.registeredOn?.page === page) return onboardingStore.registeredOn.serverId;+ if (CHOICE_FOR_PAGE[page] !== 'external') return null;+ return onboardingStore.server?.id ?? null;+}++function choiceForPage(page: OnboardingPage): AddServerChoiceName {+ const choice = CHOICE_FOR_PAGE[page];+ if (choice === 'external' && page !== 'connect' && onboardingStore.via === 'cloud')+ return 'cloud';+ return choice;+}++function reportPage(page: OnboardingPage): void {+ const step = STEP_FOR_PAGE[page];+ if (step === null) return;+ report('add_server_step', { step, choice: choiceForPage(page), first_run: true });+}++function currentPage(+ server: SwitchServer | null,+ welcomeCloud: WelcomeCloud,+ goTo: (page: OnboardingPage) => void,+ finish: (serverId: string | null) => void+) {+ switch (onboardingStore.page) {+ case 'welcome':+ return (+ <WelcomePage+ cloud={welcomeCloud}+ onContinue={() => goTo('whoRuns')}+ onInvite={() => goTo('invite')}+ />+ );+ case 'invite':+ return (+ <InvitePage+ onBack={() => goTo('welcome')}+ onResolved={(invite, found) => {+ onboardingStore.holdInvite(invite);+ if (found.kind === 'known') {+ onboardingStore.connected(found.server, found.via);+ reportPage('signIn');+ } else {+ goTo('connect');+ }+ }}+ />+ );+ case 'whoRuns':+ return (+ <WhoRunsPage+ onBack={() => goTo('welcome')}+ onLocal={() => goTo('local')}+ onRemoteHost={() => goTo('remoteHost')}+ onExternal={() => goTo('connect')}+ />+ );+ case 'local':+ return (+ <LocalSetupStep+ onBack={() => goTo('whoRuns')}+ onDone={finish}+ onClose={null}+ onRegistered={(serverId) => onboardingStore.registered('local', serverId)}+ />+ );+ case 'remoteHost':+ return (+ <RemoteHostSetupStep+ onBack={() => goTo('whoRuns')}+ onDone={finish}+ onClose={() => goTo('whoRuns')}+ onRegistered={(serverId) => onboardingStore.registered('remoteHost', serverId)}+ />+ );+ case 'signIn':+ // Both of these need the server the connect page added. Without one there+ // is nothing to sign in to, so the flow goes back to the page that makes+ // it rather than drawing a form against nothing.+ if (server === null) break;+ return (+ <SignInStep+ server={server}+ // The Cloud was chosen on the welcome page, with no form in between+ // to go back to. An invite link names its server, so the page it was+ // pasted on is where a different one is chosen.+ onBack={() =>+ goTo(+ onboardingStore.invite !== null+ ? 'invite'+ : onboardingStore.via === 'cloud'+ ? 'welcome'+ : 'connect'+ )+ }+ onClose={null}+ onSignedIn={() =>+ goTo(onboardingStore.invite !== null ? 'acceptInvite' : 'pickWorkspace')+ }+ />+ );+ case 'pickWorkspace':+ if (server === null) break;+ return (+ <PickWorkspacePage+ server={server}+ onBack={() => goTo('signIn')}+ onPicked={() => goTo('linkAccounts')}+ onCreate={() => goTo('createWorkspace')}+ />+ );+ case 'createWorkspace':+ if (server === null) break;+ return (+ <CreateWorkspacePage+ server={server}+ // Nothing to go back to when the account is in no workspace and has+ // no invitation: the picker sent the user straight here, and+ // returning to it would be a door onto a list with nothing in it.+ onBack={onboardingStore.pickerHasChoices ? () => goTo('pickWorkspace') : null}+ onCreated={() => goTo('linkAccounts')}+ />+ );+ case 'acceptInvite': {+ const invite = onboardingStore.invite;+ if (server === null || invite === null) break;+ return (+ <AcceptInvitePage+ server={server}+ invite={invite}+ onAccepted={() => {+ onboardingStore.dropInvite();+ goTo('linkAccounts');+ }}+ onSkip={() => {+ onboardingStore.dropInvite();+ goTo('pickWorkspace');+ }}+ />+ );+ }+ case 'linkAccounts':+ if (server === null) break;+ return (+ <LinkAccountsStep+ serverId={server.id}+ serverName={server.name}+ onDone={() => finish(server.id)}+ />+ );+ case 'connect':+ break;+ }++ // An invite link for a server this install does not know gives its address,+ // which is the gateway's and usually the API's too. Both stay editable.+ const inviteOrigin = onboardingStore.invite?.origin ?? null;+ return (+ <ExternalServerStep+ initialGatewayUrl={inviteOrigin}+ initialApiUrl={inviteOrigin}+ initialName={null}+ serverId={null}+ isEdit={false}+ firstRun+ existing={server}+ onBack={() => goTo(inviteOrigin === null ? 'whoRuns' : 'invite')}+ onClose={() => goTo(inviteOrigin === null ? 'whoRuns' : 'invite')}+ onSuccess={() => finish(server?.id ?? null)}+ onConnected={(added) => {+ onboardingStore.connected(added, 'external');+ reportPage('signIn');+ }}+ />+ );+}++/**+ * Whether there are onboarded hosts to offer the managed path on.+ *+ * Three states, not two. A failed read is not an empty list — saying "no hosts"+ * because the question could not be asked hides a path the user has already set+ * up and leaves them no way to tell why.+ */+type HostsRead =+ | { kind: 'reading' }+ | { kind: 'read'; hosts: { sshHost: string }[] }+ | { kind: 'failed'; headline: string; detail: string | null };++function WhoRunsPage({+ onBack,+ onLocal,+ onRemoteHost,+ onExternal,+}: {+ onBack: () => void;+ onLocal: () => void;+ onRemoteHost: () => void;+ onExternal: () => void;+}) {+ const [hosts, setHosts] = useState<HostsRead>({ kind: 'reading' });++ const readHosts = useCallback(() => {+ setHosts({ kind: 'reading' });+ void rpc.remoteHosts.listHosts().then(+ (list) => setHosts({ kind: 'read', hosts: list }),+ (cause) =>+ setHosts({+ kind: 'failed',+ ...describeFailure(cause, 'Could not check for onboarded hosts.'),+ })+ );+ }, []);++ useEffect(readHosts, [readHosts]);++ return (+ <WizardFrame+ title="Who runs the server?"+ subtitle="Either Switch Console installs and looks after the stack for you, or you point it at one that already exists."+ /* The chevron below repeats this. It is unlabelled, so it cannot be the+ only way back from a page whose cards all lead forward. */+ footer={+ <Button variant="outline" onClick={onBack}>+ Back+ </Button>+ }+ pager={{ pageName: 'Who runs the server', onBack, onNext: null }}+ >+ {/* The whole set waits on the read, not just the card it decides. Painting+ two and inserting a third between them a round trip later moves the+ answer under a cursor already on its way to one. */}+ {hosts.kind === 'reading' ? (+ <div className="flex items-center gap-2 text-sm text-foreground-muted">+ <Spinner className="size-3.5" />+ <span>Looking for onboarded hosts…</span>+ </div>+ ) : (+ <div className="grid gap-3">+ {hosts.kind === 'failed' && (+ // The two certain paths are still offered: not knowing about hosts+ // is no reason to hold the whole question hostage. Retrying may add+ // a third card, but only because it was asked for.+ <Alert variant="destructive">+ <TriangleAlert className="size-4" />+ <AlertTitle>{hosts.headline}</AlertTitle>+ <AlertDescription>+ {hosts.detail ? `${hosts.detail} ` : ''}+ Running a server on one of your own hosts is not offered until this succeeds.+ </AlertDescription>+ <AlertAction>+ <Button variant="outline" size="sm" onClick={readHosts}>+ Try again+ </Button>+ </AlertAction>+ </Alert>+ )}+ <ChoiceCard+ icon={<Wrench className="size-5" />}+ title="Set it up for me"+ description="Switch Console installs the full stack on this computer with Docker and keeps it updated."+ onClick={onLocal}+ />+ {hosts.kind === 'read' && hosts.hosts.length > 0 && (+ <ChoiceCard+ icon={<Server className="size-5" />}+ title="Set it up on one of my hosts"+ description="Switch Console installs the stack over SSH on a host you've onboarded. Stays running when Switch Console is closed."+ onClick={onRemoteHost}+ />+ )}+ <ChoiceCard+ icon={<Link2 className="size-5" />}+ title="It's already running"+ description="Connect by URL to a Switch gateway your team or someone else operates. You'll need its gateway and API addresses."+ onClick={onExternal}+ />+ </div>+ )}+ </WizardFrame>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/onboarding/onboarding-store.ts b/console/apps/switch-console-desktop/src/renderer/features/onboarding/onboarding-store.tsnew file mode 100644index 000000000..c09dbdbd3--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/onboarding/onboarding-store.ts@@ -0,0 +1,156 @@+import { makeAutoObservable } from 'mobx';+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';+import type { InviteLink } from '@shared/core/workspaces/invite-link';+import type { Workspace } from '@shared/core/workspaces/workspaces';++/** Where a fresh install is in getting its first server. */+export type OnboardingPage =+ | 'welcome'+ | 'invite'+ | 'whoRuns'+ | 'local'+ | 'remoteHost'+ | 'connect'+ | 'signIn'+ | 'pickWorkspace'+ | 'createWorkspace'+ | 'acceptInvite'+ | 'linkAccounts';++/**+ * The first-run flow's place in itself.+ *+ * Held in a store rather than in the page that draws it, because the flow+ * outlives its own component. The shell takes the window away from it whenever+ * Settings is opened, and it decides between the first-run pages and the+ * workspace from the server list — which stops being empty halfway through the+ * flow, the moment the server is added but several pages before the user has+ * signed in to it. Without somewhere to say "still going", adding the server+ * would throw the user out of the flow that added it.+ *+ * Only the page and the server survive being unmounted. What is half typed into+ * a form does not: the fields belong to the page drawing them, so a stray ⌘,+ * on the connect page costs the two addresses.+ */+class OnboardingStore {+ page: OnboardingPage = 'welcome';+ /** The server the connect page added, and the subject of the pages after it. */+ server: SwitchServer | null = null;+ /**+ * How that server was reached: typed in on the connect page, or chosen as+ * Switch Cloud on the welcome page. Decides where Back from sign-in goes and+ * which path the pages after it are reported under.+ */+ via: 'external' | 'cloud' = 'external';+ /** The workspaces that server said the account is in, once it has been asked. */+ serverWorkspaces: Workspace[] | null = null;+ /**+ * How many other ways in that server listed alongside: invitations to the+ * account's address, and workspaces open to its domain.+ */+ joinOfferCount = 0;+ /**+ * The server a managed path brought up, and the page that brought it up.+ *+ * The page is kept with it because the two managed paths do not share one:+ * starting a stack on a host and then walking back to pick the local one+ * leaves a server that the page now on screen did not make, and an exit+ * offered to it would take the user somewhere they did not set up.+ */+ registeredOn: { page: OnboardingPage; serverId: string } | null = null;+ /**+ * The invite link the user pasted, until it has been accepted or given up on.+ *+ * Held across the connect and sign-in pages because accepting needs an+ * account on the server, and the link arrives before there is one.+ */+ invite: InviteLink | null = null;++ constructor() {+ makeAutoObservable(this);+ }++ /**+ * Whether the user has committed to setting a server up.+ *+ * The welcome page is not in progress: it asks a question and nothing has+ * been started, so a launch that finds servers should go straight past it.+ */+ get inProgress(): boolean {+ return this.page !== 'welcome';+ }++ goTo(page: OnboardingPage): void {+ // Walking back to the welcome page gives up on the attempt, including the+ // server it may already have registered and what that server answered.+ // Holding on to that reference would point the next attempt's save at a row+ // the user is free to delete in the meantime — the window is the workspace+ // again the moment one exists — and nothing short of a restart would clear+ // it.+ if (page === 'welcome') {+ this.server = null;+ this.via = 'external';+ this.serverWorkspaces = null;+ this.joinOfferCount = 0;+ this.registeredOn = null;+ this.invite = null;+ }+ this.page = page;+ }++ /**+ * A managed path has registered its server.+ *+ * Reported from an effect that fires on every render of a page whose stack is+ * up, so writing the same pair again has to be a no-op — a fresh object each+ * time would notify, re-render and report again without end.+ */+ registered(page: OnboardingPage, serverId: string): void {+ if (this.registeredOn?.page === page && this.registeredOn.serverId === serverId) return;+ this.registeredOn = { page, serverId };+ }++ connected(server: SwitchServer, via: 'external' | 'cloud'): void {+ this.server = server;+ this.via = via;+ this.page = 'signIn';+ }++ /**+ * What the server answered when asked which workspaces this account is in.+ *+ * Kept so the create page knows whether there was anything to come back to:+ * an account with no membership is sent straight to the form, and offering it+ * a Back to a list of nothing would be a door onto a blank wall.+ */+ resolved(workspaces: Workspace[], joinOfferCount: number): void {+ this.serverWorkspaces = workspaces;+ this.joinOfferCount = joinOfferCount;+ }++ /** Whether Pick a workspace had anything to offer: a membership, an invitation or an open workspace. */+ get pickerHasChoices(): boolean {+ return (this.serverWorkspaces?.length ?? 0) > 0 || this.joinOfferCount > 0;+ }++ holdInvite(invite: InviteLink): void {+ this.invite = invite;+ }++ /** The invitation was accepted, or the user went on without it. */+ dropInvite(): void {+ this.invite = null;+ }++ reset(): void {+ this.page = 'welcome';+ this.server = null;+ this.via = 'external';+ this.serverWorkspaces = null;+ this.joinOfferCount = 0;+ this.registeredOn = null;+ this.invite = null;+ }+}++export const onboardingStore = new OnboardingStore();diff --git a/console/apps/switch-console-desktop/src/renderer/features/onboarding/pick-workspace-page.tsx b/console/apps/switch-console-desktop/src/renderer/features/onboarding/pick-workspace-page.tsxnew file mode 100644index 000000000..0f3d1cc6e--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/onboarding/pick-workspace-page.tsx@@ -0,0 +1,389 @@+import { useQuery } from '@tanstack/react-query';+import { Plus } from 'lucide-react';+import { observer } from 'mobx-react-lite';+import { useCallback, useEffect, useRef, useState } from 'react';+import {+ invitationSummary,+ InvitedBadge,+ joinableSummary,+ listedInvitations,+ listedJoinable,+ useJoinableWorkspaces,+ usePendingInvitations,+} from '@renderer/features/workspaces/pending-invitations';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';+import { failureText } from '@renderer/lib/errors/describe-failure';+import { rpc } from '@renderer/lib/ipc';+import { Button } from '@renderer/lib/ui/button';+import { Spinner } from '@renderer/lib/ui/spinner';+import { WizardFrame } from '@renderer/lib/ui/wizard-frame';+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';+import type { JoinableWorkspace, PendingInvitation } from '@shared/core/workspaces/invitations';+import type { Workspace } from '@shared/core/workspaces/workspaces';+import { onboardingStore } from './onboarding-store';++/**+ * Which of the server's workspaces the window should be scoped to.+ *+ * The page asks the server rather than reading the list this app already holds:+ * signing in is the first moment the gateway will say what the account is a+ * member of, and an install that has been sitting on the sign-in form is+ * answering from before that.+ *+ * Memberships are offered, and so are invitations addressed to the account's+ * own address, which it accepts here without a link. A server older than the+ * route that lists those leaves the section out rather than showing it empty:+ * it cannot say whether anyone invited you, and an empty "nobody has" would be+ * a claim it never made. The third kind of row, workspaces open to the domain+ * of the account's address, is joined the same way and left out on the same+ * terms.+ */+export const PickWorkspacePage = observer(function PickWorkspacePage({+ server,+ onBack,+ onPicked,+ onCreate,+}: {+ server: SwitchServer;+ onBack: () => void;+ onPicked: () => void;+ onCreate: () => void;+}) {+ const [opening, setOpening] = useState<string | null>(null);+ const [openError, setOpenError] = useState<string | null>(null);++ const query = useQuery({+ queryKey: ['onboarding-workspaces', server.id],+ queryFn: () => rpc.switchServers.resolveWorkspaces(server.id),+ });+ const workspaces = query.data ?? null;+ const invitationsQuery = usePendingInvitations(server.id);+ const invitations = listedInvitations(invitationsQuery.data);+ const joinableQuery = useJoinableWorkspaces(server.id);+ const joinable = listedJoinable(joinableQuery.data);++ const open = useCallback(+ async (workspace: Workspace) => {+ setOpening(workspace.id);+ setOpenError(null);+ try {+ await workspacesStore.setActive(workspace.id);+ onPicked();+ } catch (cause) {+ setOpenError(failureText(cause, `Could not open ${workspace.name}.`));+ setOpening(null);+ }+ },+ [onPicked]+ );++ const accept = useCallback(+ async (invitation: PendingInvitation) => {+ setOpening(invitation.id);+ setOpenError(null);+ try {+ const workspace = await workspacesStore.acceptPendingInvitation(server.id, invitation);+ await workspacesStore.setActive(workspace.id);+ onPicked();+ } catch (cause) {+ setOpenError(failureText(cause, `Could not join ${invitation.workspaceName}.`));+ setOpening(null);+ }+ },+ [server.id, onPicked]+ );++ const join = useCallback(+ async (offer: JoinableWorkspace) => {+ setOpening(offer.tenantId);+ setOpenError(null);+ try {+ const workspace = await workspacesStore.joinByDomain(server.id, offer);+ await workspacesStore.setActive(workspace.id);+ onPicked();+ } catch (cause) {+ setOpenError(failureText(cause, `Could not join ${offer.workspaceName}.`));+ setOpening(null);+ }+ },+ [server.id, onPicked]+ );++ // Once per answer, not once per render: the callbacks are made fresh by the+ // page above, so without the latch a re-render would re-run the choice that+ // is already under way. Every question has to be answered first — an+ // invitation or an open workspace is a choice, so a lone membership beside+ // one is not the only way forward — and a failed check stops the page here,+ // where it is shown, rather than skipping past it on a guess.+ const settled = useRef(false);+ const offers = invitations.length + joinable.length;+ const offersPending = invitationsQuery.isPending || joinableQuery.isPending;+ const offersFailed = invitationsQuery.isError || joinableQuery.isError;+ useEffect(() => {+ if (workspaces === null || offersPending || settled.current) return;+ settled.current = true;+ onboardingStore.resolved(workspaces, offers);+ if (offersFailed || offers > 0) return;+ // A question with one answer is not a question, and with none there is+ // nothing here to answer it with.+ if (workspaces.length === 0) onCreate();+ else if (workspaces.length === 1) void open(workspaces[0]!);+ }, [workspaces, offers, offersPending, offersFailed, open, onCreate]);++ return (+ <WizardFrame+ title="Pick a workspace"+ subtitle={`${pickSubtitle(workspaces?.length ?? 0, offers)} A workspace is where your agents, rooms and teammates live.`}+ /* The chevron below repeats this. It is unlabelled, so it cannot be the+ only way back from a page whose rows all lead forward. Both are held+ shut while a workspace is being opened, since leaving now would land+ the user two pages on when it resolves. */+ footer={+ <Button variant="outline" onClick={onBack} disabled={opening !== null}>+ Back+ </Button>+ }+ pager={{+ pageName: 'Pick a workspace',+ onBack: opening === null ? onBack : null,+ onNext: null,+ }}+ >+ {query.isPending ? (+ <p className="flex items-center gap-2 text-sm text-foreground-muted">+ <Spinner className="size-3.5" />+ Checking which workspaces you’re in…+ </p>+ ) : query.isError ? (+ <div className="flex flex-col items-start gap-3">+ <p className="text-sm text-destructive">+ {failureText(query.error, `Could not ask ${server.name} which workspaces you’re in.`)}+ </p>+ <Button variant="outline" size="sm" onClick={() => void query.refetch()}>+ Retry+ </Button>+ </div>+ ) : (+ <div className="flex w-full flex-col gap-3">+ <ul className="flex flex-col gap-2">+ {(workspaces ?? []).map((workspace) => (+ <WorkspaceRow+ key={workspace.id}+ workspace={workspace}+ opening={opening === workspace.id}+ disabled={opening !== null}+ onOpen={() => void open(workspace)}+ />+ ))}+ {invitations.map((invitation) => (+ <InvitationRow+ key={invitation.id}+ invitation={invitation}+ accepting={opening === invitation.id}+ disabled={opening !== null}+ onAccept={() => void accept(invitation)}+ />+ ))}+ {joinable.map((offer) => (+ <JoinableRow+ key={offer.tenantId}+ offer={offer}+ joining={opening === offer.tenantId}+ disabled={opening !== null}+ onJoin={() => void join(offer)}+ />+ ))}+ </ul>++ {invitationsQuery.isPending && (+ <p className="flex items-center gap-2 text-xs text-foreground-muted">+ <Spinner className="size-3" />+ Checking for invitations to your address…+ </p>+ )}+ {invitationsQuery.isError && (+ <div className="flex items-center gap-3">+ <p className="min-w-0 flex-1 text-sm text-destructive">+ {failureText(+ invitationsQuery.error,+ `Could not ask ${server.name} for invitations to your address.`+ )}+ </p>+ <Button variant="outline" size="sm" onClick={() => void invitationsQuery.refetch()}>+ Retry+ </Button>+ </div>+ )}++ {joinableQuery.isError && (+ <div className="flex items-center gap-3">+ <p className="min-w-0 flex-1 text-sm text-destructive">+ {failureText(+ joinableQuery.error,+ `Could not ask ${server.name} which workspaces are open to your e-mail domain.`+ )}+ </p>+ <Button variant="outline" size="sm" onClick={() => void joinableQuery.refetch()}>+ Retry+ </Button>+ </div>+ )}++ {openError && <p className="text-sm text-destructive">{openError}</p>}++ <div className="flex items-center gap-3">+ <span className="h-px flex-1 bg-border" />+ <span className="text-xs text-foreground-muted">or start fresh</span>+ <span className="h-px flex-1 bg-border" />+ </div>++ <button+ type="button"+ onClick={onCreate}+ disabled={opening !== null}+ className="flex items-center justify-center gap-2 rounded-[10px] border border-dashed border-border px-3.5 py-3 text-sm font-medium text-foreground hover:bg-[var(--sel-soft)] disabled:opacity-50"+ >+ <Plus className="size-4" />+ Create a new workspace+ </button>+ </div>+ )}+ </WizardFrame>+ );+});++function pickSubtitle(memberships: number, offers: number): string {+ if (offers === 0) return 'You’re a member of these.';+ if (memberships === 0) return 'You can join these.';+ return 'You’re a member of these, or can join them.';+}++function JoinableRow({+ offer,+ joining,+ disabled,+ onJoin,+}: {+ offer: JoinableWorkspace;+ joining: boolean;+ disabled: boolean;+ onJoin: () => void;+}) {+ return (+ <li>+ <button+ type="button"+ onClick={onJoin}+ disabled={disabled}+ data-testid="joinable-workspace-row"+ className="flex w-full items-center gap-3 rounded-[10px] border border-border bg-[var(--surface-2)] px-3.5 py-3 text-left hover:bg-[var(--sel-soft)] disabled:opacity-60"+ >+ <span className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-background-tertiary text-sm font-semibold text-foreground">+ {initialOf(offer.workspaceName)}+ </span>+ <span className="min-w-0 flex-1">+ <span className="block truncate text-sm font-medium text-foreground">+ {offer.workspaceName}+ </span>+ <span className="block truncate text-xs text-foreground-muted">+ {joinableSummary(offer)}+ </span>+ </span>+ {joining ? (+ <Spinner className="size-3.5 shrink-0" />+ ) : (+ <span className="shrink-0 text-sm font-medium text-foreground">Join</span>+ )}+ </button>+ </li>+ );+}++function InvitationRow({+ invitation,+ accepting,+ disabled,+ onAccept,+}: {+ invitation: PendingInvitation;+ accepting: boolean;+ disabled: boolean;+ onAccept: () => void;+}) {+ return (+ <li>+ <button+ type="button"+ onClick={onAccept}+ disabled={disabled}+ data-testid="pending-invitation-row"+ className="flex w-full items-center gap-3 rounded-[10px] border border-border bg-[var(--surface-2)] px-3.5 py-3 text-left hover:bg-[var(--sel-soft)] disabled:opacity-60"+ >+ <span className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-background-tertiary text-sm font-semibold text-foreground">+ {initialOf(invitation.workspaceName)}+ </span>+ <span className="min-w-0 flex-1">+ <span className="block truncate text-sm font-medium text-foreground">+ {invitation.workspaceName}+ </span>+ <span className="block truncate text-xs text-foreground-muted">+ {invitationSummary(invitation)}+ </span>+ </span>+ <InvitedBadge />+ {accepting ? (+ <Spinner className="size-3.5 shrink-0" />+ ) : (+ <span className="shrink-0 text-sm font-medium text-foreground">Accept</span>+ )}+ </button>+ </li>+ );+}++function WorkspaceRow({+ workspace,+ opening,+ disabled,+ onOpen,+}: {+ workspace: Workspace;+ opening: boolean;+ disabled: boolean;+ onOpen: () => void;+}) {+ return (+ <li>+ <button+ type="button"+ onClick={onOpen}+ disabled={disabled}+ className="flex w-full items-center gap-3 rounded-[10px] border border-border bg-[var(--surface-2)] px-3.5 py-3 text-left hover:bg-[var(--sel-soft)] disabled:opacity-60"+ >+ <span className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-background-tertiary text-sm font-semibold text-foreground">+ {initialOf(workspace.name)}+ </span>+ <span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">+ {workspace.name}+ </span>+ {workspace.role && (+ <span className="shrink-0 rounded bg-background-tertiary px-1 py-px text-[10px] font-medium tracking-wide text-foreground-muted uppercase">+ {workspace.role}+ </span>+ )}+ {opening ? (+ <Spinner className="size-3.5 shrink-0" />+ ) : (+ <span className="shrink-0 text-sm text-foreground-muted">Open</span>+ )}+ </button>+ </li>+ );+}++const GRAPHEMES = new Intl.Segmenter();++/** By grapheme, so a name starting with an emoji is not cut in half. */+function initialOf(name: string): string {+ return ([...GRAPHEMES.segment(name)][0]?.segment ?? '?').toUpperCase();+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/onboarding/use-onboarding-checklist.ts b/console/apps/switch-console-desktop/src/renderer/features/onboarding/use-onboarding-checklist.tsindex 1b79489ee..b808d4669 100644--- a/console/apps/switch-console-desktop/src/renderer/features/onboarding/use-onboarding-checklist.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/onboarding/use-onboarding-checklist.ts@@ -33,7 +33,7 @@ export function useOnboardingProgress(): OnboardingProgress {addServer: switchServersStore.servers.length > 0,agentProviders: (agentTypes ?? []).some((type) => type.available),onboardAgents: appState.locations.locations.size > 0,- createRoom: switchRoomsStore.listedRoomsOnAllServers.length > 0,+ createRoom: switchRoomsStore.listedRoomsInAllWorkspaces.length > 0,};}diff --git a/console/apps/switch-console-desktop/src/renderer/features/onboarding/welcome-page.tsx b/console/apps/switch-console-desktop/src/renderer/features/onboarding/welcome-page.tsxnew file mode 100644index 000000000..4a265dd07--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/onboarding/welcome-page.tsx@@ -0,0 +1,201 @@+import { Cloud, Server } from 'lucide-react';+import type { ReactNode } from 'react';+import { SwitchConsoleAppIcon } from '@renderer/lib/switch-console-app-icon';+import { Button } from '@renderer/lib/ui/button';+import { Spinner } from '@renderer/lib/ui/spinner';+import { StepPager } from '@renderer/lib/ui/step-pager';+import { cn } from '@renderer/utils/utils';++const TAGLINE = 'Agents that work alongside your team, in the chat apps you already use.';++/**+ * What the welcome page can say about Switch Cloud, and what choosing it does.+ *+ * `connecting` and `error` belong to the attempt, not to the configuration: the+ * page stays up while the server is registered, and a failure is shown on the+ * card that was chosen rather than somewhere the eye has already left.+ */+export type WelcomeCloud =+ | { kind: 'reading' }+ | { kind: 'closed' }+ | { kind: 'failed'; headline: string; detail: string | null }+ | {+ kind: 'open';+ url: string;+ connecting: boolean;+ error: string | null;+ onConnect: () => void;+ };++/**+ * The first page of a fresh install: what Switch is, and where it should run.+ *+ * It takes the whole window. There is no sidebar behind it because there is+ * nothing for a sidebar to list — no servers, so no rooms, agents or sessions —+ * and a first impression made of empty containers says less about the app than+ * one question does.+ *+ * Switch Cloud is on the page only when this build has been told where it is;+ * otherwise your own server is the one place listed. A build whose Cloud+ * configuration could not be read still shows the card, marked unavailable in+ * words as well as in grey, since that is a broken build to fix. A radio group+ * would announce itself as something to pick between and then answer neither+ * arrow key nor click.+ *+ * Either way the controls are buttons that say which place they take, and the+ * emphasis on a card is a repeat of that in colour, not the only place it is+ * written. With two places open the pager has no Next: which one is next is the+ * question the page is asking.+ */+export function WelcomePage({+ cloud,+ onContinue,+ onInvite,+}: {+ cloud: WelcomeCloud;+ onContinue: () => void;+ /** Join a workspace someone else set up, from the link they sent. */+ onInvite: () => void;+}) {+ const cloudOpen = cloud.kind === 'open';+ return (+ <div className="flex h-full flex-col bg-background text-foreground [-webkit-app-region:drag]">+ <div className="flex min-h-0 flex-1 flex-col overflow-auto">+ {/* Everything the page shows opts out of the drag region: a scroll+ inside one is swallowed by the window move. What stays draggable is+ the margin around it. */}+ <div className="mx-auto flex w-full max-w-xl flex-1 flex-col justify-center gap-8 px-8 py-10 [-webkit-app-region:no-drag]">+ <div className="flex flex-col items-center gap-4">+ <SwitchConsoleAppIcon size={64} className="rounded-2xl" />+ <h1 className="text-3xl font-semibold">Welcome to Switch</h1>+ <p className="text-center text-sm text-foreground-muted">{TAGLINE}</p>+ </div>++ <div className="flex flex-col gap-3">+ <h2 className="text-sm font-medium">Where should it run?</h2>+ <ul className="grid gap-3">+ <CloudChoice cloud={cloud} />+ <HostingChoice+ icon={<Server className="size-5" />}+ title="Your own server"+ description="Run the Switch stack on hardware you control. Your data and your accounts stay there."+ emphasised={!cloudOpen}+ />+ </ul>+ <div className="mt-1 flex flex-wrap gap-2">+ {cloudOpen && (+ <Button onClick={cloud.onConnect} disabled={cloud.connecting}>+ {cloud.connecting && <Spinner className="size-3.5" />}+ Continue with Switch Cloud+ </Button>+ )}+ <Button+ variant={cloudOpen ? 'outline' : 'default'}+ onClick={onContinue}+ disabled={cloudOpen && cloud.connecting}+ >+ Continue with your own server+ </Button>+ </div>+ <p className="text-xs text-foreground-muted">+ Invited to a workspace?{' '}+ <button+ type="button"+ className="text-foreground underline underline-offset-2 disabled:opacity-50"+ onClick={onInvite}+ disabled={cloudOpen && cloud.connecting}+ >+ Paste your invite link+ </button>+ </p>+ </div>+ </div>+ </div>+ <div className="[-webkit-app-region:no-drag]">+ <StepPager pageName="Welcome" onBack={null} onNext={cloudOpen ? null : onContinue} />+ </div>+ </div>+ );+}++function CloudChoice({ cloud }: { cloud: WelcomeCloud }) {+ const icon = <Cloud className="size-5" />;+ switch (cloud.kind) {+ case 'open':+ return (+ <HostingChoice+ icon={icon}+ title="Switch Cloud"+ description={`We run it for you at ${new URL(cloud.url).host}. Sign in, or create an account there.`}+ emphasised+ error={cloud.error}+ />+ );+ case 'failed':+ return (+ <HostingChoice+ icon={icon}+ title="Switch Cloud"+ badge="Unavailable"+ description={`${cloud.headline}${cloud.detail ? ` ${cloud.detail}` : ''}`}+ unavailable+ />+ );+ // A build that cannot reach the Cloud does not mention it: stable ships+ // the code before the Cloud is open to it, and a card for somewhere you+ // cannot go is a promise the build has no way to keep.+ case 'reading':+ case 'closed':+ return null;+ }+}++function HostingChoice({+ icon,+ title,+ badge,+ description,+ unavailable = false,+ emphasised = false,+ error = null,+}: {+ icon: ReactNode;+ title: string;+ badge?: string;+ description: string;+ /** The place the primary button takes. */+ emphasised?: boolean;+ /** Why choosing this place just failed. */+ error?: string | null;+ /** Somewhere Switch cannot run yet. Said in the badge and the description+ * too, so it does not rest on the greyed-out card alone. */+ unavailable?: boolean;+}) {+ return (+ <li+ className={cn(+ 'flex list-none items-start gap-3 rounded-lg border p-4 text-left',+ unavailable && 'opacity-60',+ emphasised ? 'border-foreground' : 'border-border'+ )}+ >+ <span className="mt-0.5 text-foreground-muted">{icon}</span>+ <div className="space-y-1">+ <div className="flex items-center gap-2">+ <span className="text-sm font-medium text-foreground">{title}</span>+ {badge && (+ <span className="rounded-full bg-background-tertiary-2 px-2 py-0.5 text-[10px] text-foreground-muted">+ {badge}+ </span>+ )}+ </div>+ <p className="text-xs text-foreground-muted">{description}</p>+ {error && (+ <p role="alert" className="text-xs text-destructive">+ {error}+ </p>+ )}+ </div>+ </li>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/load-existing-agents-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/load-existing-agents-section.tsxindex 5b2890e03..b947f3e3e 100644--- a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/load-existing-agents-section.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/load-existing-agents-section.tsx@@ -64,10 +64,14 @@ export const LOAD_AGENTS_QUERY_KEY = 'load-existing-agents';export function LoadExistingAgentsSection({sshHost,serverId,+ workspaceId,initiallyOpen = false,}: {sshHost: string;serverId: string;+ /** The workspace whose agents are discovered. One server can host several,+ * and each answers `GET /agents` with its own list. */+ workspaceId: string;initiallyOpen?: boolean;}) {const [isOpen, setIsOpen] = useState(initiallyOpen);@@ -76,8 +80,8 @@ export function LoadExistingAgentsSection({const showRemoveConfig = useShowModal('removeAgentConfigModal');const discovery = useQuery({- queryKey: [LOAD_AGENTS_QUERY_KEY, sshHost, serverId],- queryFn: () => rpc.agents.discoverLoadableAgentsOnHost({ sshHost, serverId }),+ queryKey: [LOAD_AGENTS_QUERY_KEY, sshHost, workspaceId],+ queryFn: () => rpc.agents.discoverLoadableAgentsOnHost({ sshHost, workspaceId }),enabled: isOpen && scanRequested,});@@ -194,7 +198,7 @@ export function LoadExistingAgentsSection({// waiting for the SSH round trip that a full refetch requires.const loaded = new Set(names);queryClient.setQueryData(- [LOAD_AGENTS_QUERY_KEY, sshHost, serverId],+ [LOAD_AGENTS_QUERY_KEY, sshHost, workspaceId],(prev: { agents: LoadableAgentRow[]; serverApiUrl: string } | undefined) => {if (!prev) return prev;return {@@ -216,7 +220,9 @@ export function LoadExistingAgentsSection({));- void queryClient.invalidateQueries({ queryKey: [LOAD_AGENTS_QUERY_KEY, sshHost, serverId] });+ void queryClient.invalidateQueries({+ queryKey: [LOAD_AGENTS_QUERY_KEY, sshHost, workspaceId],+ });},onError: (error) => {toast({@@ -246,7 +252,9 @@ export function LoadExistingAgentsSection({next.delete(key);return next;});- void queryClient.invalidateQueries({ queryKey: [LOAD_AGENTS_QUERY_KEY, sshHost, serverId] });+ void queryClient.invalidateQueries({+ queryKey: [LOAD_AGENTS_QUERY_KEY, sshHost, workspaceId],+ });},onError: (error) => {toast({@@ -271,7 +279,8 @@ export function LoadExistingAgentsSection({const [manualDir, setManualDir] = useState('');const manualScan = useMutation({- mutationFn: (dir: string) => rpc.agents.discoverLoadableAgentsInDir({ sshHost, dir, serverId }),+ mutationFn: (dir: string) =>+ rpc.agents.discoverLoadableAgentsInDir({ sshHost, dir, workspaceId }),onSuccess: (found) => {setManualServerApiUrl(found.serverApiUrl);setManualAgents((prev) => {@@ -287,9 +296,9 @@ export function LoadExistingAgentsSection({const deepScan = useMutation({mutationFn: () =>- rpc.agents.discoverLoadableAgentsOnHost({ sshHost, serverId, includeHomeScan: true }),+ rpc.agents.discoverLoadableAgentsOnHost({ sshHost, workspaceId, includeHomeScan: true }),onSuccess: (result) => {- queryClient.setQueryData([LOAD_AGENTS_QUERY_KEY, sshHost, serverId], result);+ queryClient.setQueryData([LOAD_AGENTS_QUERY_KEY, sshHost, workspaceId], result);},});@@ -404,7 +413,7 @@ export function LoadExistingAgentsSection({disabled={discovery.isFetching}onClick={() =>void queryClient.invalidateQueries({- queryKey: [LOAD_AGENTS_QUERY_KEY, sshHost, serverId],+ queryKey: [LOAD_AGENTS_QUERY_KEY, sshHost, workspaceId],})}>diff --git a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-host-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-host-view.tsxindex eb5d0dc3e..271f4b5d3 100644--- a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-host-view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-host-view.tsx@@ -37,6 +37,7 @@ import {import { deriveHostStatus } from '@shared/core/remote-hosts/host-status';import { isHostBlocked } from '@shared/core/remote-hosts/reachability';import { switchServersStore } from '../../switch-servers/switch-servers-store';+import { workspacesStore } from '../../workspaces/workspaces-store';import { hostReachabilityStore } from '../host-reachability-store';import { hostSetupStore } from '../host-setup-store';import { HostUnreachablePanel } from '../host-unreachable-panel';@@ -131,6 +132,10 @@ export const RemoteHostMainPanel = observer(function RemoteHostMainPanel() {if (managed) return managed.id;return activeServer?.id ?? servers[0]?.id ?? null;}, [sshHost, servers, activeServer]);+ // Which of that server's workspaces the discovery below asks. `GET /agents`+ // answers for one tenant, so without it the list would be whichever workspace+ // the session last selected.+ const workspaceId = workspacesStore.idOnServerInScope(serverId);const status = deriveHostStatus(reachability, plan.data ?? null);const { prerequisites, agentTypes } = useMemo(@@ -311,10 +316,11 @@ export const RemoteHostMainPanel = observer(function RemoteHostMainPanel() {</section>)}- {serverId && (+ {serverId && workspaceId && (<LoadExistingAgentsSectionsshHost={sshHost}serverId={serverId}+ workspaceId={workspaceId}initiallyOpen={justAdded}/>)}@@ -349,6 +355,9 @@ export const remoteHostView = {// No titlebar slot: the page header already names the host and repeats the// alias underneath it, so a third copy in the title bar was only noise.MainPanel: RemoteHostMainPanel,+ // A host is somewhere agents run, not something a server owns: its page says+ // the same things with no server registered as with ten.+ worksWithoutServer: true,canActivate: (params: unknown): GuardResult => {// Params can come from a snapshot written by an older build, so validate// rather than trust: a view with no host to show has nothing to render.diff --git a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-hosts-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-hosts-view.tsxindex 95760bd76..d41c1cc8e 100644--- a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-hosts-view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-hosts-view.tsx@@ -342,6 +342,10 @@ function RemoveHostButton({*/export const remoteHostsView = {MainPanel: RemoteHostsSettingsPage,+ // A host is somewhere agents run, not something a server owns, so the page+ // stands up with no server registered — as does the Settings tab it forwards+ // to.+ worksWithoutServer: true,canActivate: (): GuardResult => ({ok: false,redirect: 'settings',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.tsxindex 88b0d245d..05d7ed228 100644--- 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@@ -20,11 +20,11 @@ import type {} from '@shared/core/switch-servers/switch-servers';/**- * Everything the server has that a template can point at, read once by the+ * Everything the workspace 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;+ workspaceId: string | null;agents: AgentPick[];agentsLoading: boolean;rooms: RoomPick[];@@ -32,10 +32,10 @@ export type EntityLists = {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. */+ /** Platform users Switch has already seen in this workspace. */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. */+ * template leaves it open and the workspace has no default. */bridgeId: string | null;};@@ -54,7 +54,7 @@ function agentTileFor(name: string, lists: EntityLists, onRemove: () => void) {<ChosenAgentTilekey={name}agent={found}- subtitle={agentProviderLabelFor(found.id, lists.serverId)}+ subtitle={agentProviderLabelFor(found.id, lists.workspaceId)}onRemove={onRemove}/>) : (@@ -84,7 +84,10 @@ function AgentCombobox({onPick={(agent) => onPick(agent.name)}searchText={(agent) => agent.name}renderItem={(agent) => (- <AgentPickerRow agent={agent} subtitle={agentProviderLabelFor(agent.id, lists.serverId)} />+ <AgentPickerRow+ agent={agent}+ subtitle={agentProviderLabelFor(agent.id, lists.workspaceId)}+ />)}disabled={lists.agentsLoading}placeholder={lists.agentsLoading ? 'Loading agents…' : 'Search agents…'}@@ -275,12 +278,13 @@ function UserCombobox({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 searchable =+ bridgeId !== null && lists.workspaceId !== null && debounced.length >= MIN_QUERY_LENGTH;const directory = useQuery({- queryKey: ['bridge-directory', lists.serverId, bridgeId, debounced],+ queryKey: ['bridge-directory', lists.workspaceId, bridgeId, debounced],queryFn: () =>- rpc.switchServers.searchBridgeDirectory({- serverId: lists.serverId,+ rpc.workspaces.searchBridgeDirectory({+ workspaceId: lists.workspaceId as string,bridgeId: bridgeId as string,query: debounced,}),diff --git a/console/apps/switch-console-desktop/src/renderer/features/room-templates/room-template-capture-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/room-templates/room-template-capture-view.tsxindex f6f3bddca..59eedad2c 100644--- a/console/apps/switch-console-desktop/src/renderer/features/room-templates/room-template-capture-view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/room-templates/room-template-capture-view.tsx@@ -8,6 +8,7 @@ import { ServerSectionTitlebar } from '@renderer/features/switch-servers/server-import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';import { prefillForSave } from '@renderer/features/templates/agent-template-data';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { failureText } from '@renderer/lib/errors/describe-failure';import { rpc } from '@renderer/lib/ipc';import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';@@ -238,7 +239,9 @@ const CapturePanel = observer(function CapturePanel() {let cancelled = false;void (async () => {try {- const yaml = await rpc.switchServers.exportRoomYaml({ serverId, roomId });+ const workspaceId = workspacesStore.idOnServerInScope(serverId);+ if (workspaceId === null) throw new Error('This server’s workspace is not known yet.');+ const yaml = await rpc.workspaces.exportRoomYaml({ workspaceId, roomId });if (cancelled) return;setOriginalYaml(yaml);setCandidates(extractCandidates(yaml));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.tsxindex ea7f4c836..dfb3128e8 100644--- 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@@ -12,6 +12,7 @@ import {type TemplateAccess,visibilityOf,} from '@renderer/features/templates/template-visibility';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { failureText } from '@renderer/lib/errors/describe-failure';import { toast } from '@renderer/lib/hooks/use-toast';import { rpc } from '@renderer/lib/ipc';@@ -23,6 +24,7 @@ import { Button } from '@renderer/lib/ui/button';import { Field, FieldGroup, FieldLabel } from '@renderer/lib/ui/field';import { Input } from '@renderer/lib/ui/input';import { SegmentedControl } from '@renderer/lib/ui/segmented-control';+import { StepPager } from '@renderer/lib/ui/step-pager';// ── Source step ─────────────────────────────────────────────────────────────@@ -39,6 +41,7 @@ function SourceStep({onYamlChange,parseError,onNext,+ canAdvance,onFileSelect,onSaveToServer,saving,@@ -48,6 +51,9 @@ function SourceStep({onYamlChange: (text: string) => void;parseError: string | null;onNext: () => void;+ /** Whether there is a document to go on with. Decided by the page, so the+ * Next button and the pager's arrow cannot come to different answers. */+ canAdvance: boolean;onFileSelect: (name: string) => void;onSaveToServer: () => void;saving: boolean;@@ -174,7 +180,7 @@ function SourceStep({<Save className="mr-1.5 size-3.5" />{saving ? 'Saving…' : 'Save to workspace'}</Button>- <Button disabled={!yamlText.trim() || saving} onClick={onNext}>+ <Button disabled={!canAdvance} onClick={onNext}>Next<ArrowRight className="ml-1.5 size-3.5" /></Button>@@ -288,8 +294,10 @@ const TemplateImportPanel = observer(function TemplateImportPanel() {const kind = yamlText !== initialYaml ? await rpc.agentTemplates.kind({ yamlText }) : null;// Each field is sent only when changed, so saving one cannot put back// another that someone else changed meanwhile.- const saved = await rpc.switchServers.updateTemplate({- serverId,+ const workspaceId = workspacesStore.idOnServerInScope(serverId);+ if (workspaceId === null) throw new Error('This server’s workspace is not known yet.');+ const saved = await rpc.workspaces.updateTemplate({+ workspaceId,templateId: editingTemplate.id,...(name.trim() !== editingTemplate.name.trim() ? { name: name.trim() } : {}),...(description.trim() !== editingTemplate.description.trim()@@ -327,6 +335,10 @@ const TemplateImportPanel = observer(function TemplateImportPanel() {}}, [initialTemplateId, initialYaml, editing, serverId, handleParseAndAdvance]);+ // The pager's arrow only repeats the Next button below, so both read this+ // rather than spelling the condition once each and drifting apart.+ const canAdvance = yamlText.trim().length > 0 && !saving;+if (editingTemplate) {const nothingChanged =yamlText === initialYaml &&@@ -376,6 +388,7 @@ const TemplateImportPanel = observer(function TemplateImportPanel() {onYamlChange={setYamlText}parseError={parseError}onNext={handleParseAndAdvance}+ canAdvance={canAdvance}onFileSelect={setSourceName}onSaveToServer={handleSaveToServer}saving={saving}@@ -398,12 +411,20 @@ const TemplateImportPanel = observer(function TemplateImportPanel() {<ServerPagetitle="Import a template"description="Paste an agent, room or group template, or pick a YAML file. The document says which it is."+ footer={+ <StepPager+ pageName="Pick a template"+ onBack={null}+ onNext={canAdvance ? () => void handleParseAndAdvance() : null}+ />+ }><SourceStepyamlText={yamlText}onYamlChange={setYamlText}parseError={parseError}onNext={handleParseAndAdvance}+ canAdvance={canAdvance}onFileSelect={setSourceName}onSaveToServer={handleSaveToServer}saving={saving}diff --git a/console/apps/switch-console-desktop/src/renderer/features/sessions/create-session-modal/create-session-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/sessions/create-session-modal/create-session-modal.tsxindex 6bd08e04f..161812877 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sessions/create-session-modal/create-session-modal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sessions/create-session-modal/create-session-modal.tsx@@ -83,28 +83,27 @@ function useDefaultLocationId(propLocationId?: string): string | undefined {*/function useRoomMemberAgents(roomId: string | undefined): {agents: Agent[];- serverId: string | null;+ workspaceId: string | null;loading: boolean;} {- const serverId = roomId ? switchRoomsStore.roomServerId(roomId) : null;+ const workspaceId = roomId ? switchRoomsStore.roomWorkspaceId(roomId) : null;useEffect(() => {if (roomId) void agentsStore.load();}, [roomId]);const membersQuery = useQuery({- queryKey: ['roomAgentIds', serverId, roomId],- queryFn: () => rpc.switchServers.listRoomAgentIds({ serverId: serverId!, roomId: roomId! }),- enabled: !!serverId && !!roomId,+ queryKey: ['roomAgentIds', workspaceId, roomId],+ queryFn: () => rpc.workspaces.listRoomAgentIds({ workspaceId: workspaceId!, roomId: roomId! }),+ enabled: !!workspaceId && !!roomId,});const memberIds = useMemo(() => new Set(membersQuery.data ?? []), [membersQuery.data]);- const agents = [...agentsStore.byLocation.values()]- .flat()- .filter((a) => a.serverId === serverId && a.switchAgentId && memberIds.has(a.switchAgentId))- .sort((a, b) => a.name.localeCompare(b.name));+ const agents = (workspaceId ? agentsStore.agentsInWorkspace(workspaceId) : []).filter(+ (a) => a.switchAgentId && memberIds.has(a.switchAgentId)+ );- return { agents, serverId, loading: membersQuery.isLoading || !agentsStore.loaded };+ return { agents, workspaceId, loading: membersQuery.isLoading || !agentsStore.loaded };}/**@@ -211,24 +210,30 @@ export const CreateSessionModal = observer(function CreateSessionModal({? (locationAgents.find((a) => a.name === effectiveAgentName) ?? null): null;- const serverId = effectiveAgentName ? (subagent?.serverId ?? null) : (agent?.serverId ?? null);+ const agentWorkspaceId = effectiveAgentName+ ? (subagent?.workspaceId ?? null)+ : (agent?.workspaceId ?? null);const switchAgentId = effectiveAgentName? (subagent?.switchAgentId ?? null): (agent?.switchAgentId ?? null);useEffect(() => {- if (!roomFirst && serverId && switchAgentId) {- void switchRoomsStore.fetchAgentRooms(serverId, switchAgentId);+ if (!roomFirst && agentWorkspaceId && switchAgentId) {+ void switchRoomsStore.fetchAgentRooms(agentWorkspaceId, switchAgentId);}- }, [roomFirst, serverId, switchAgentId]);+ }, [roomFirst, agentWorkspaceId, switchAgentId]);const rooms =- serverId && switchAgentId- ? (switchRoomsStore.roomsFor(serverId, switchAgentId) ?? []).filter((r) => !r.archived)+ agentWorkspaceId && switchAgentId+ ? (switchRoomsStore.roomsFor(agentWorkspaceId, switchAgentId) ?? []).filter(+ (r) => !r.archived+ ): [];const roomsLoading =- !!serverId && !!switchAgentId && switchRoomsStore.isLoading(serverId, switchAgentId);- const canConnectRoom = !roomFirst && !!serverId && !!switchAgentId;+ !!agentWorkspaceId &&+ !!switchAgentId &&+ switchRoomsStore.isLoading(agentWorkspaceId, switchAgentId);+ const canConnectRoom = !roomFirst && !!agentWorkspaceId && !!switchAgentId;// In room-first mode the room is given, not chosen; everything downstream// (roles, the connect prompt) keys off the same value either way.@@ -243,15 +248,15 @@ export const CreateSessionModal = observer(function CreateSessionModal({}: null: room;- const roleServerId = roomFirst ? roomMembers.serverId : serverId;+ const roleWorkspaceId = roomFirst ? roomMembers.workspaceId : agentWorkspaceId;// Roles are room-scoped, so only fetch once a room is chosen. The set is small// and changes rarely, so a plain per-room query (no shared cache) is enough.const rolesQuery = useQuery({- queryKey: ['roomRoles', roleServerId, activeRoom?.roomId],+ queryKey: ['roomRoles', roleWorkspaceId, activeRoom?.roomId],queryFn: () =>- rpc.switchServers.listRoomRoles({ serverId: roleServerId!, roomId: activeRoom!.roomId }),- enabled: !!roleServerId && !!activeRoom,+ rpc.workspaces.listRoomRoles({ workspaceId: roleWorkspaceId!, roomId: activeRoom!.roomId }),+ enabled: !!roleWorkspaceId && !!activeRoom,});const roles = rolesQuery.data ?? [];diff --git a/console/apps/switch-console-desktop/src/renderer/features/settings/settings-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/settings/settings-view.tsxindex ddba564ae..110e01933 100644--- a/console/apps/switch-console-desktop/src/renderer/features/settings/settings-view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/settings/settings-view.tsx@@ -67,4 +67,8 @@ export function SettingsMainPanel() {export const settingsView = {WrapView: SettingsViewWrapper,MainPanel: SettingsMainPanel,+ // Preferences, themes, remote hosts and connector installs all stand on their+ // own before any server is registered, and ⌘, has to lead somewhere on a+ // fresh install.+ worksWithoutServer: true,};diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-item.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-item.tsxindex 76a362dd8..db389534d 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-item.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-item.tsx@@ -23,7 +23,7 @@ import { useNavigate, useParams } from '@renderer/lib/layout/navigation-providerimport { useWorkspaceSlots } from '@renderer/lib/layout/workspace-slots';import { useShowModal } from '@renderer/lib/modal/modal-provider';import { sidebarStore } from '@renderer/lib/stores/app-state';-import { useAgentIconUrl } from '@renderer/lib/stores/use-remote-agents';+import { useAgentIconUrl } from '@renderer/lib/stores/use-workspace-agents';import {ContextMenu,ContextMenuContent,@@ -66,7 +66,7 @@ export const SidebarAgentItem = observer(function SidebarAgentItem({const agentName = agent.name;const location = getLocationStore(agent.locationId);- const iconUrl = useAgentIconUrl(agent.serverId, agent.switchAgentId);+ const iconUrl = useAgentIconUrl(agent.workspaceId, agent.switchAgentId);// The agent's name IS its Switch identity: Switch Console chose it, registered it// under that name, and keys its credentials and definition by it. Reading thediff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-agent-row.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-agent-row.tsxindex facbd1d44..f47062843 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-agent-row.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-agent-row.tsx@@ -14,7 +14,7 @@ import { rpc } from '@renderer/lib/ipc';import { useNavigate } from '@renderer/lib/layout/navigation-provider';import { useShowModal } from '@renderer/lib/modal/modal-provider';import { appState, sidebarStore } from '@renderer/lib/stores/app-state';-import { useAgentIconUrl } from '@renderer/lib/stores/use-remote-agents';+import { useAgentIconUrl } from '@renderer/lib/stores/use-workspace-agents';import {ContextMenu,ContextMenuContent,@@ -64,7 +64,7 @@ export const RoomAgentRow = observer(function RoomAgentRow({// This is a Switch room's member list, so the Switch identity is what matters// — and that is the stored name: it is what was registered on the server.const label = agent.name || 'Unnamed agent';- const iconUrl = useAgentIconUrl(agent.serverId, agent.switchAgentId);+ const iconUrl = useAgentIconUrl(agent.workspaceId, agent.switchAgentId);const expandKey = roomAgentGroupKey(roomId, agent.id);const expanded = sidebarStore.isGroupExpanded(expandKey);@@ -84,12 +84,12 @@ export const RoomAgentRow = observer(function RoomAgentRow({if (!location) return null;const removeFromRoom = () => {- const serverId = switchRoomsStore.roomServerId(roomId);- if (!serverId || !agent.switchAgentId) return;+ const workspaceId = switchRoomsStore.roomWorkspaceId(roomId);+ if (!workspaceId || !agent.switchAgentId) return;const roomLabel = switchRoomsStore.roomNameById(roomId) ?? 'the room';void toastPromise(- rpc.switchServers- .removeRoomAgent({ serverId, roomId, agentId: agent.switchAgentId })+ rpc.workspaces+ .removeRoomAgent({ workspaceId, roomId, agentId: agent.switchAgentId }).then(() => switchRoomsStore.refreshRoomState()),{loading: `Removing ${label} from ${roomLabel}…`,diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsxindex 94aac1b64..996bed691 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx@@ -132,8 +132,8 @@ export const SidebarGroupedList = observer(function SidebarGroupedList() {*/const RoomStateDisclosure = observer(function RoomStateDisclosure() {const { navigate } = useNavigate();- const signedOut = switchRoomsStore.serversNotSignedIn;- const failed = switchRoomsStore.serversThatFailedToLoad;+ const signedOut = switchRoomsStore.workspacesNotSignedIn;+ const failed = switchRoomsStore.workspacesThatFailedToLoad;// Being signed out is the whole explanation, so it is said on its own: the// memberships that "didn't load" are the same fact, and offering a retry fordiff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-icon-backfill-toast.test.ts b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-icon-backfill-toast.test.tsindex d1076cb30..d21018db3 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-icon-backfill-toast.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-icon-backfill-toast.test.ts@@ -1,8 +1,8 @@import { beforeEach, describe, expect, it, vi } from 'vitest';/**- * The agent-icon backfill notice must be said once per server per run, however- * many times the sidebar refreshes (CHOO-2344).+ * The agent-icon backfill notice must be said once per workspace per run,+ * however many times the sidebar refreshes (CHOO-2344).** `refreshSidebarRoomState` runs on first paint, window focus, sign-in, the* background reconcile, the retry button and every membership-changing@@ -20,19 +20,20 @@ const AGENT = {id: 'agent-1',name: 'agent one',serverId: 'server-1',+ workspaceId: 'workspace-1',switchAgentId: 'switch-agent-1',createdAt: '2026-01-01T00:00:00.000Z',};vi.mock('@renderer/lib/hooks/use-toast', () => ({ toast }));vi.mock('@renderer/lib/ipc', () => ({- rpc: { switchServers: { backfillAgentIcons } },+ rpc: { workspaces: { backfillAgentIcons } },}));vi.mock('@renderer/features/locations/stores/agents-store', () => ({agentsStore: {load: vi.fn().mockResolvedValue(undefined),byLocation: new Map([[LOCATION.id, [AGENT]]]),- agentsOnServerAtLocation: () => [AGENT],+ agentsInWorkspaceAtLocation: () => [AGENT],},}));vi.mock('@renderer/features/switch-servers/switch-rooms-store', () => ({@@ -41,8 +42,8 @@ vi.mock('@renderer/features/switch-servers/switch-rooms-store', () => ({loadRoomNames: vi.fn().mockResolvedValue(undefined),},}));-vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({- switchServersStore: { activeServerId: 'server-1' },+vi.mock('@renderer/features/workspaces/workspaces-store', () => ({+ workspacesStore: { activeId: 'workspace-1' },}));vi.mock('@renderer/lib/stores/app-state', () => ({sidebarStore: {@@ -68,7 +69,7 @@ describe('agent icon backfill reporting', () => {backfillAgentIcons.mockReset();});- it('reports a server without the icon endpoint once, not on every refresh', async () => {+ it('reports a workspace without the icon endpoint once, not on every refresh', async () => {backfillAgentIcons.mockResolvedValue({ kind: 'unsupported' });const { refreshSidebarRoomState } = await loadSubject();diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsxindex 697081c75..afb66e379 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsx@@ -54,14 +54,14 @@ export function isRoomNameKnown(roomKey: string): boolean {*/export function deleteRoomAction(roomKey: string,- showDeleteRoomModal: (args: { serverId: string; roomId: string; roomName: string }) => void+ showDeleteRoomModal: (args: { workspaceId: string; roomId: string; roomName: string }) => void): (() => void) | null {if (roomKey === UNASSIGNED_ROOM_KEY) return null;- const serverId = switchRoomsStore.roomServerId(roomKey);+ const workspaceId = switchRoomsStore.roomWorkspaceId(roomKey);const room = switchRoomsStore.roomSummaryById(roomKey);- if (!serverId || !room) return null;- if (!switchRoomsStore.canDeleteRoom(serverId, room)) return null;- return () => showDeleteRoomModal({ serverId, roomId: roomKey, roomName: room.name });+ if (!workspaceId || !room) return null;+ if (!switchRoomsStore.canDeleteRoom(workspaceId, room)) return null;+ return () => showDeleteRoomModal({ workspaceId, roomId: roomKey, roomName: room.name });}/** Show a room's conversation in the main panel (no-op for Unassigned, whichdiff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-store.test.ts b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-store.test.tsindex 1d1d1eef9..2bcfdb4e8 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-store.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-store.test.ts@@ -1,8 +1,9 @@import { afterEach, describe, expect, it, vi } from 'vitest';import { agentsStore } from '@renderer/features/locations/stores/agents-store';-import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import type { AgentConnectionKind } from '@shared/core/agents/agent-connection';import type { Agent } from '@shared/core/agents/agents';+import type { Workspace } from '@shared/core/workspaces/workspaces';import {agentExpandKey,agentRoomGroupKey,@@ -14,6 +15,19 @@ import {type SidebarLocationManager = ConstructorParameters<typeof SidebarStore>[0];+/**+ * Scope the window to a workspace, the way choosing one in the switcher does.+ * Both workspaces here sit on the same server, which is the case the scope has+ * to tell apart: scoping by server would show them as one tree.+ */+function scopeToWorkspace(workspaceId: string | null): void {+ workspacesStore.workspaces = [+ { id: 'ws-1', serverId: 'server-1' } as Workspace,+ { id: 'ws-2', serverId: 'server-1' } as Workspace,+ ];+ workspacesStore.activeId = workspaceId;+}+vi.mock('@renderer/lib/ipc', () => ({events: {on: vi.fn(),@@ -267,87 +281,88 @@ describe('SidebarStore grouping', () => {});});-describe('SidebarStore active-server scoping', () => {- function linkAgent(locationId: string, serverId: string | null) {- agentsStore.byLocation.set(locationId, [{ locationId, serverId } as Agent]);+describe('SidebarStore active-workspace scoping', () => {+ function linkAgent(locationId: string, workspaceId: string | null) {+ agentsStore.byLocation.set(locationId, [{ locationId, workspaceId } as Agent]);}afterEach(() => {- switchServersStore.activeServerId = null;+ scopeToWorkspace(null);agentsStore.byLocation.clear();});- it("shows only the active server's locations", () => {+ it("shows only the active workspace's locations", () => {const store = new SidebarStore(locationManager([{ id: 'a', createdAt: '2026-01-01T00:00:00.000Z' },{ id: 'b', createdAt: '2026-01-02T00:00:00.000Z' },]));- linkAgent('a', 'server-1');- linkAgent('b', 'server-2');- switchServersStore.activeServerId = 'server-1';+ linkAgent('a', 'ws-1');+ linkAgent('b', 'ws-2');+ scopeToWorkspace('ws-1');expect(store.orderedLocations.map((p) => p.id)).toEqual(['a']);expect(store.isEmpty).toBe(false);});- it('shows all locations when no server is active', () => {+ it('shows all locations when no workspace is active', () => {const store = new SidebarStore(locationManager([{ id: 'a', createdAt: '2026-01-01T00:00:00.000Z' },{ id: 'b', createdAt: '2026-01-02T00:00:00.000Z' },]));- linkAgent('a', 'server-1');- linkAgent('b', 'server-2');+ linkAgent('a', 'ws-1');+ linkAgent('b', 'ws-2');expect(store.orderedLocations.map((p) => p.id).sort()).toEqual(['a', 'b']);});- it('hides unlinked locations when a server is active', () => {+ it('hides unlinked locations when a workspace is active', () => {const store = new SidebarStore(locationManager([{ id: 'a', createdAt: '2026-01-01T00:00:00.000Z' }]));linkAgent('a', null);- switchServersStore.activeServerId = 'server-1';+ scopeToWorkspace('ws-1');expect(store.orderedLocations).toEqual([]);expect(store.isEmpty).toBe(true);});- it('shows a directory shared between servers under both (CHOO-2044)', () => {- // A directory is a place on disk, not one server's territory. Resolving it to- // a single server filed it under whichever agent came back first, and the- // other server's agents vanished from the tree.+ it('shows a directory shared between workspaces under both (CHOO-2044)', () => {+ // A directory is a place on disk, not one workspace's territory. Resolving it+ // to a single one filed it under whichever agent came back first, and the+ // other workspace's agents vanished from the tree. The two here share a+ // server, so a server-scoped tree would not tell them apart at all.const store = new SidebarStore(locationManager([{ id: 'shared', createdAt: '2026-01-01T00:00:00.000Z' }]));agentsStore.byLocation.set('shared', [- { locationId: 'shared', serverId: 'server-1' } as Agent,- { locationId: 'shared', serverId: 'server-2' } as Agent,+ { locationId: 'shared', workspaceId: 'ws-1' } as Agent,+ { locationId: 'shared', workspaceId: 'ws-2' } as Agent,]);- switchServersStore.activeServerId = 'server-1';+ scopeToWorkspace('ws-1');expect(store.orderedLocations.map((p) => p.id)).toEqual(['shared']);- switchServersStore.activeServerId = 'server-2';+ scopeToWorkspace('ws-2');expect(store.orderedLocations.map((p) => p.id)).toEqual(['shared']);- switchServersStore.activeServerId = 'server-3';+ scopeToWorkspace('ws-3');expect(store.orderedLocations).toEqual([]);});- it('describes a shared directory by an agent on the active server (CHOO-2044)', () => {+ it('describes a shared directory by an agent in the active workspace (CHOO-2044)', () => {const store = new SidebarStore(locationManager([{ id: 'shared', createdAt: '2026-01-01T00:00:00.000Z' }]));agentsStore.byLocation.set('shared', [- { locationId: 'shared', serverId: 'server-1', providerId: 'claude' } as Agent,- { locationId: 'shared', serverId: 'server-2', providerId: 'codex' } as Agent,+ { locationId: 'shared', workspaceId: 'ws-1', providerId: 'claude' } as Agent,+ { locationId: 'shared', workspaceId: 'ws-2', providerId: 'codex' } as Agent,]);- switchServersStore.activeServerId = 'server-2';+ scopeToWorkspace('ws-2');expect(store.locationProviderId('shared')).toBe('codex');});});@@ -408,12 +423,12 @@ describe('SidebarStore filters', () => {}function linkAgent(locationId: string, fields: { providerId?: Agent['providerId'] }) {- agentsStore.byLocation.set(locationId, [{ locationId, serverId: null, ...fields } as Agent]);+ agentsStore.byLocation.set(locationId, [{ locationId, workspaceId: null, ...fields } as Agent]);}afterEach(() => {agentsStore.byLocation.clear();- switchServersStore.activeServerId = null;+ scopeToWorkspace(null);});it('returns all locations unfiltered when no filter is active', () => {diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-store.ts b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-store.tsindex 8a5725397..5e2d0501a 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-store.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-store.ts@@ -8,7 +8,7 @@ import {unregisteredSessionData,type SessionStore,} from '@renderer/features/sessions/stores/session-store';-import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import type { Snapshottable } from '@renderer/lib/stores/snapshottable';import type { AgentConnectionKind } from '@shared/core/agents/agent-connection';import {@@ -237,27 +237,27 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {}/**- * Whether a location has anything to show under the active server. The whole- * sidebar tree is scoped to one server at a time: a location shows when it holds- * at least one agent linked to {@link switchServersStore.activeServerId}.- * Unregistered locations (mid-onboarding, no agent row yet) always show so the- * user sees progress. When no server is active, nothing is hidden.+ * Whether a location has anything to show under the active workspace. The whole+ * sidebar tree is scoped to one workspace at a time: a location shows when it+ * holds at least one agent in {@link workspacesStore.activeId}. Unregistered+ * locations (mid-onboarding, no agent row yet) always show so the user sees+ * progress. When no workspace is active, nothing is hidden.*- * A directory can hold agents for several servers, so this is "has any here",+ * A directory can hold agents for several workspaces, so this is "has any here",* not "belongs to". Which of its agents are then drawn is* {@link scopedAgents}' business — a location being in scope does not put every- * agent in it on this server's tree (CHOO-2044).+ * agent in it on this workspace's tree (CHOO-2044).*/isLocationInActiveScope(locationId: string): boolean {- const activeServerId = switchServersStore.activeServerId;- if (!activeServerId) return true;+ const activeWorkspaceId = workspacesStore.activeId;+ if (!activeWorkspaceId) return true;const location = this.locationManager.locations.get(locationId);if (location && location.state === 'unregistered') return true;- return agentsStore.locationHasAgentsOnServer(locationId, activeServerId);+ return agentsStore.locationHasAgentsInWorkspace(locationId, activeWorkspaceId);}/**- * Server-scoped locations, newest first. Locations are no longer a level of+ * Workspace-scoped locations, newest first. Locations are no longer a level of* the sidebar tree — the manual order the user drags lives on agents and* rooms — so this is the plain default order the agent list is built from.*/@@ -271,12 +271,12 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {/** The representative agent of a location (the agent shown on its sidebar row):* the first real (non-definition) agent, not a former subagent's row. Restricted- * to the active server, so a directory shared with another server does not- * describe itself by an agent this tree is not showing. */+ * to the active workspace, so a directory shared with another does not describe+ * itself by an agent this tree is not showing. */private parentAgent(locationId: string) {- const activeServerId = switchServersStore.activeServerId;- const agents = activeServerId- ? agentsStore.agentsOnServerAtLocation(locationId, activeServerId)+ const activeWorkspaceId = workspacesStore.activeId;+ const agents = activeWorkspaceId+ ? agentsStore.agentsInWorkspaceAtLocation(locationId, activeWorkspaceId): (agentsStore.byLocation.get(locationId) ?? []);return agents[0] ?? (agentsStore.byLocation.get(locationId) ?? [])[0];}diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-tree-data.ts b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-tree-data.tsindex f9e406607..a5e875889 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-tree-data.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-tree-data.ts@@ -2,7 +2,7 @@ import { agentsStore } from '@renderer/features/locations/stores/agents-store';import type { LocationStore } from '@renderer/features/locations/stores/location';import type { SessionStore } from '@renderer/features/sessions/stores/session-store';import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';-import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { toast } from '@renderer/lib/hooks/use-toast';import { rpc } from '@renderer/lib/ipc';import { sidebarStore } from '@renderer/lib/stores/app-state';@@ -20,22 +20,26 @@ import type { AgentIconBackfill } from '@shared/core/switch-servers/switch-serveexport type AgentEntry = { agent: Agent; location: LocationStore };/**- * A location's agents that the active server's tree should draw.+ * A location's agents that the active workspace's tree should draw.*- * A location is in scope when *some* of its agents are on the active server, but a- * directory can hold agents for several servers at once — so scope has to be+ * A location is in scope when *some* of its agents are in the active workspace,+ * but a directory can hold agents for several at once — so scope has to be* re-applied per agent here. Taking the location's whole list instead drew agents- * belonging to another server under this one, which read as "onboarding brought+ * belonging to another workspace under this one, which read as "onboarding brought* them across" when nothing had been onboarded at all (CHOO-2044).+ *+ * The workspace and not its server: two workspaces on one server are two separate+ * trees, and scoping on the server would draw both of them under whichever name+ * the sidebar is showing.*/function agentsAtLocationInScope(location: LocationStore): Agent[] {- const activeServerId = switchServersStore.activeServerId;- if (!activeServerId) return agentsStore.byLocation.get(location.id) ?? [];- return agentsStore.agentsOnServerAtLocation(location.id, activeServerId);+ const activeWorkspaceId = workspacesStore.activeId;+ if (!activeWorkspaceId) return agentsStore.byLocation.get(location.id) ?? [];+ return agentsStore.agentsInWorkspaceAtLocation(location.id, activeWorkspaceId);}/**- * The flat list of agents in the active-server scope. Switch Console shows agents+ * The flat list of agents in the active-workspace scope. Switch Console shows agents* as a flat list — not grouped by directory (CHOO-1440).** Newest first, then overlaid with the user's manual drag order: an agent they@@ -57,7 +61,7 @@ export function scopedAgents(): AgentEntry[] {}/**- * Every agent on the active server, ignoring the agent filters.+ * Every agent in the active workspace, ignoring the agent filters.** Room membership is a fact about a room, so the agents a room lists — and the* agents whose membership is fetched at all — must not depend on which filters@@ -88,14 +92,14 @@ export function agentSessions(entry: AgentEntry): SessionStore[] {);}-/** Every agent on the active server that has a Switch identity, as+/** Every agent in the active scope that has a Switch identity, as* membership-lookup keys. Unfiltered on purpose — see* {@link agentsInActiveScope}. */-export function switchIdentities(): { serverId: string; switchAgentId: string }[] {- const identities: { serverId: string; switchAgentId: string }[] = [];+export function switchIdentities(): { workspaceId: string; switchAgentId: string }[] {+ const identities: { workspaceId: string; switchAgentId: string }[] = [];for (const { agent } of agentsInActiveScope()) {- if (agent.serverId && agent.switchAgentId) {- identities.push({ serverId: agent.serverId, switchAgentId: agent.switchAgentId });+ if (agent.workspaceId && agent.switchAgentId) {+ identities.push({ workspaceId: agent.workspaceId, switchAgentId: agent.switchAgentId });}}return identities;@@ -151,7 +155,7 @@ export async function refreshSidebarRoomStateAfterOnboarding(): Promise<void> {/*** Fill in the avatar of any of this user's agents registered before icons- * existed (CHOO-2171). The main process does it once per server per run, so+ * existed (CHOO-2171). The main process does it once per workspace per run, so* calling it on every refresh costs nothing after the first.** Not awaited by the caller and never allowed to throw: the sidebar must paint@@ -164,13 +168,13 @@ export async function refreshSidebarRoomStateAfterOnboarding(): Promise<void> {* lettered picture with nothing explaining why.*/async function giveExistingAgentsAnIcon(): Promise<void> {- const serverIds = new Set(switchIdentities().map((identity) => identity.serverId));- for (const serverId of serverIds) {+ const workspaceIds = new Set(switchIdentities().map((identity) => identity.workspaceId));+ for (const workspaceId of workspaceIds) {try {- reportBackfill(serverId, await rpc.switchServers.backfillAgentIcons(serverId));+ reportBackfill(workspaceId, await rpc.workspaces.backfillAgentIcons(workspaceId));} catch (cause) {- log.warn('could not give existing agents their icons', { serverId, cause });- reportOnce(serverId, 'failed', {+ log.warn('could not give existing agents their icons', { workspaceId, cause });+ reportOnce(workspaceId, 'failed', {title: 'Agent icons could not be saved',description:'Your agents show a generated icon here, but the Switch server has not stored it — so they keep their old picture in Slack and the other chat apps.',@@ -181,13 +185,14 @@ async function giveExistingAgentsAnIcon(): Promise<void> {}/**- * What each server was last told to the user about, so an unresolved condition- * is not re-announced on every refresh.+ * What each workspace was last told to the user about, so an unresolved+ * condition is not re-announced on every refresh.** The caller runs on first paint, window focus, sign-in, the background- * reconcile, the retry button and every membership-changing mutation. A server- * that is signed out or too old to store icons fails all of them, which turned- * one standing problem into a toast every few seconds (CHOO-2344).+ * reconcile, the retry button and every membership-changing mutation. A+ * workspace whose server is signed out or too old to store icons fails all of+ * them, which turned one standing problem into a toast every few seconds+ * (CHOO-2344).** Keyed by outcome, not a bare "said something already": if the situation* changes — a signed-out server starts answering and turns out to be too old —@@ -196,15 +201,15 @@ async function giveExistingAgentsAnIcon(): Promise<void> {*/const reportedBackfill = new Map<string, string>();-function reportOnce(serverId: string, outcome: string, notice: Parameters<typeof toast>[0]) {- if (reportedBackfill.get(serverId) === outcome) return;- reportedBackfill.set(serverId, outcome);+function reportOnce(workspaceId: string, outcome: string, notice: Parameters<typeof toast>[0]) {+ if (reportedBackfill.get(workspaceId) === outcome) return;+ reportedBackfill.set(workspaceId, outcome);toast(notice);}-function reportBackfill(serverId: string, outcome: AgentIconBackfill): void {+function reportBackfill(workspaceId: string, outcome: AgentIconBackfill): void {if (outcome.kind === 'unsupported') {- reportOnce(serverId, 'unsupported', {+ reportOnce(workspaceId, 'unsupported', {title: 'This Switch server does not support agent icons yet',description:'Your agents show a generated icon here, but it cannot be saved, so they keep their old picture in Slack and the other chat apps. Updating the server fixes it.',@@ -213,7 +218,7 @@ function reportBackfill(serverId: string, outcome: AgentIconBackfill): void {return;}if (outcome.kind === 'partial') {- reportOnce(serverId, `partial:${outcome.failed}`, {+ reportOnce(workspaceId, `partial:${outcome.failed}`, {title: `${outcome.failed} agent${outcome.failed === 1 ? '' : 's'} kept the old icon`,description:'Their icon could not be saved to the Switch server, so it will not show in Slack or the other chat apps.',@@ -221,5 +226,5 @@ function reportBackfill(serverId: string, outcome: AgentIconBackfill): void {});return;}- reportedBackfill.delete(serverId);+ reportedBackfill.delete(workspaceId);}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.tsxindex e4a435895..e1e09335c 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@@ -17,12 +17,12 @@ import {import { Field, FieldLabel } from '@renderer/lib/ui/field';type Props = BaseModalProps<void> & {- serverId: string;+ workspaceId: string;switchAgentId: string;agentName: string;};-/** A room the agent can be put in: one on its own server it is not already in. */+/** A room the agent can be put in: one in its own workspace it is not already in. */type Candidate = { id: string; name: string; bridgeType: string | null };/**@@ -31,10 +31,11 @@ type Candidate = { id: string; name: string; bridgeType: string | null };** Both write the same membership through `addRoomAgents`; which one you reach* for is only a matter of what you were looking at. An agent can only join rooms- * on the server it is registered with, so the choice is scoped to that server.+ * in the workspace it is registered in, so the choice is scoped to that+ * workspace.*/export const AddAgentToRoomsModal = observer(function AddAgentToRoomsModal({- serverId,+ workspaceId,switchAgentId,agentName,onSuccess,@@ -50,7 +51,7 @@ export const AddAgentToRoomsModal = observer(function AddAgentToRoomsModal({// so the rooms offered here and the rooms the agent is shown under cannot// disagree. Undefined means it was never fetched — offering every room then// would invite a join that is already in place, so say so instead.- const memberships = switchRoomsStore.roomsFor(serverId, switchAgentId);+ const memberships = switchRoomsStore.roomsFor(workspaceId, switchAgentId);const membershipUnknown = memberships === undefined;const alreadyIn = new Set((memberships ?? []).map((m) => m.roomId));@@ -58,7 +59,7 @@ export const AddAgentToRoomsModal = observer(function AddAgentToRoomsModal({// agent's usefulness is mostly in rooms someone else set up, and a picker that// omitted them made those rooms unreachable from here entirely.const candidates: Candidate[] = switchRoomsStore- .readableRoomsOnServer(serverId)+ .readableRoomsInWorkspace(workspaceId).filter((room) => !alreadyIn.has(room.id) && !selected.some((s) => s.id === room.id)).map((room) => ({ id: room.id, name: room.name, bridgeType: room.bridgeType }));const nothingToAdd = candidates.length === 0 && selected.length === 0;@@ -70,8 +71,8 @@ export const AddAgentToRoomsModal = observer(function AddAgentToRoomsModal({setError(null);try {for (const room of selected) {- await rpc.switchServers.addRoomAgents({- serverId,+ await rpc.workspaces.addRoomAgents({+ workspaceId,roomId: room.id,agentIds: [switchAgentId],direction: 'room_to_agents',@@ -85,7 +86,7 @@ export const AddAgentToRoomsModal = observer(function AddAgentToRoomsModal({setIsSubmitting(false);setCloseGuard(false);}- }, [serverId, switchAgentId, selected, onSuccess, setCloseGuard]);+ }, [workspaceId, switchAgentId, selected, onSuccess, setCloseGuard]);return (<>@@ -130,13 +131,13 @@ export const AddAgentToRoomsModal = observer(function AddAgentToRoomsModal({/>{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- is listed. Adding it to one it already belongs to changes nothing.+ Which rooms {agentName} is already in could not be read, so every room in the+ workspace is listed. Adding it to one it already belongs to changes nothing.</p>)}{nothingToAdd && !membershipUnknown && (<p className="mt-1 text-xs text-foreground-muted">- {agentName} is already in every room you can see on this server.+ {agentName} is already in every room you can see in this workspace.</p>)}</Field>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.tsxindex 0398d3a8d..34cc9679f 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@@ -6,6 +6,7 @@ import { agentsStore } from '@renderer/features/locations/stores/agents-store';import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';import { bundledTemplates } from '@renderer/features/templates/bundled-templates';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';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';@@ -14,7 +15,7 @@ import { toast } from '@renderer/lib/hooks/use-toast';import { rpc } from '@renderer/lib/ipc';import { useNavigate } from '@renderer/lib/layout/navigation-provider';import { type BaseModalProps, useModalContext } from '@renderer/lib/modal/modal-provider';-import { useRemoteAgents } from '@renderer/lib/stores/use-remote-agents';+import { useWorkspaceAgents } from '@renderer/lib/stores/use-workspace-agents';import { Button } from '@renderer/lib/ui/button';import { ConfirmButton } from '@renderer/lib/ui/confirm-button';import {@@ -42,7 +43,10 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({}: Props) {const { setCloseGuard } = useModalContext();const { navigate } = useNavigate();- const serverId = switchRoomsStore.roomServerId(roomId);+ const workspaceId = switchRoomsStore.roomWorkspaceId(roomId);+ // The template pages are still routed by server, so the Use page is reached+ // through the workspace's host.+ const serverId = workspaceId === null ? null : workspacesStore.serverIdFor(workspaceId);const roomName = switchRoomsStore.roomNameById(roomId);// Templates can create an agent straight into this room. The bundled@@ -50,10 +54,10 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({// returns.const [serverTemplates, setServerTemplates] = useState<StoredTemplateSummary[]>([]);useEffect(() => {- if (!serverId) return;+ if (workspaceId === null) return;let cancelled = false;- rpc.switchServers- .listTemplates({ serverId, kind: 'agent' })+ rpc.workspaces+ .listTemplates({ workspaceId, kind: 'agent' }).then((list) => {if (!cancelled) setServerTemplates(list);})@@ -69,7 +73,7 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({return () => {cancelled = true;};- }, [serverId]);+ }, [workspaceId]);// A built-in template the signed-in user saved to the workspace is listed// once, as their copy. Names are unique only per owner, so someone else's// template of the same name is not a copy.@@ -116,14 +120,14 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({const members = new Set(switchRoomsStore.localMemberIds(roomId));// The agents' own icons live on the server, not in the local row, so the// list is joined against the server's summary to draw them.- const { data: remoteAgents } = useRemoteAgents(serverId);+ const { data: remoteAgents } = useWorkspaceAgents(workspaceId);const remoteById = new Map((remoteAgents ?? []).map((agent) => [agent.id, agent]));// Only this install's agents are offered. An agent registered on another// Switch Console could be added server-side but could never be shown or driven// from here, so it is not ours to offer.- const candidates: Candidate[] = serverId+ const candidates: Candidate[] = workspaceId? agentsStore- .agentsOnServer(serverId)+ .agentsInWorkspace(workspaceId).map((agent) => ({id: agent.switchAgentId as string,name: agent.name,@@ -135,13 +139,13 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({const nothingToAdd = candidates.length === 0 && selected.length === 0;const handleSubmit = useCallback(async () => {- if (!serverId || selected.length === 0) return;+ if (!workspaceId || selected.length === 0) return;setIsSubmitting(true);setCloseGuard(true);setError(null);try {- await rpc.switchServers.addRoomAgents({- serverId,+ await rpc.workspaces.addRoomAgents({+ workspaceId,roomId,agentIds: selected.map((a) => a.id),direction: 'agents_to_room',@@ -154,7 +158,7 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({setIsSubmitting(false);setCloseGuard(false);}- }, [serverId, roomId, selected, onSuccess, setCloseGuard]);+ }, [workspaceId, roomId, selected, onSuccess, setCloseGuard]);return (<>@@ -163,9 +167,9 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({</DialogHeader><DialogContentArea className="pt-0"><div className="flex w-full flex-col gap-4">- {!serverId && (+ {!workspaceId && (<p className="text-xs text-destructive">- This room's server is not known yet, so its members cannot be changed.+ This room's workspace is not known yet, so its members cannot be changed.</p>)}@@ -247,7 +251,7 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({</Button><ConfirmButtononClick={() => void handleSubmit()}- disabled={!serverId || selected.length === 0 || isSubmitting}+ disabled={!workspaceId || selected.length === 0 || isSubmitting}>{isSubmitting ? 'Adding…' : 'Add to room'}</ConfirmButton>diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/DeleteRoomModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/DeleteRoomModal.tsxindex 11a65e610..889d29585 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/DeleteRoomModal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/DeleteRoomModal.tsx@@ -15,7 +15,7 @@ import {} from '@renderer/lib/ui/dialog';type Props = BaseModalProps<void> & {- serverId: string;+ workspaceId: string;roomId: string;roomName: string;};@@ -28,7 +28,7 @@ type Props = BaseModalProps<void> & {* trying, so they are said before rather than reported after.*/export const DeleteRoomModal = observer(function DeleteRoomModal({- serverId,+ workspaceId,roomId,roomName,onSuccess,@@ -47,7 +47,7 @@ export const DeleteRoomModal = observer(function DeleteRoomModal({setCloseGuard(true);setError(null);try {- await switchRoomsStore.deleteRoom(serverId, roomId);+ await switchRoomsStore.deleteRoom(workspaceId, roomId);onSuccess();} catch (cause) {setError(failureText(cause, 'Could not delete the room.'));@@ -55,7 +55,7 @@ export const DeleteRoomModal = observer(function DeleteRoomModal({} finally {setCloseGuard(false);}- }, [serverId, roomId, onSuccess, setCloseGuard]);+ }, [workspaceId, roomId, onSuccess, setCloseGuard]);return (<>diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/open-room.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/open-room.tsindex 05981eb11..7c59190c3 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/open-room.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/open-room.ts@@ -1,4 +1,4 @@-import { scopeToRoomServer } from '@renderer/lib/layout/scope-to-server';+import { scopeToRoomWorkspace } from '@renderer/lib/layout/scope-to-workspace';import { appState, sidebarStore } from '@renderer/lib/stores/app-state';/**@@ -12,7 +12,7 @@ import { appState, sidebarStore } from '@renderer/lib/stores/app-state';* findable in the tree it belongs to.*/export async function openRoom(roomId: string): Promise<void> {- await scopeToRoomServer(roomId);+ await scopeToRoomWorkspace(roomId);sidebarStore.setGrouping('room');sidebarStore.ensureRoomExpanded(roomId);appState.navigation.navigate('room', { roomId });diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsxindex 0e827fc81..19d924287 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx@@ -10,7 +10,7 @@ import { describeFailure, failureText } from '@renderer/lib/errors/describe-failimport { rpc } from '@renderer/lib/ipc';import { useNavigate } from '@renderer/lib/layout/navigation-provider';import { useShowModal } from '@renderer/lib/modal/modal-provider';-import { useRemoteAgents } from '@renderer/lib/stores/use-remote-agents';+import { useWorkspaceAgents } from '@renderer/lib/stores/use-workspace-agents';import { Button } from '@renderer/lib/ui/button';import { Input } from '@renderer/lib/ui/input';import {@@ -31,8 +31,8 @@ import { openRoomChannel } from './room-links';/** Query key for one room's own settings — shared so a save can write the* server's answer straight back into what the page is reading. */-function roomDetailKey(serverId: string, roomId: string) {- return ['remote-room-detail', serverId, roomId] as const;+function roomDetailKey(workspaceId: string, roomId: string) {+ return ['remote-room-detail', workspaceId, roomId] as const;}/**@@ -48,15 +48,15 @@ export const RoomConfigurationPanel = observer(function RoomConfigurationPanel({}: {roomId: string;}) {- const serverId = switchRoomsStore.roomServerId(roomId);+ const workspaceId = switchRoomsStore.roomWorkspaceId(roomId);const query = useQuery({- queryKey: roomDetailKey(serverId ?? '', roomId),- queryFn: () => rpc.switchServers.getRoomDetail({ serverId: serverId as string, roomId }),- enabled: serverId !== null,+ queryKey: roomDetailKey(workspaceId ?? '', roomId),+ queryFn: () => rpc.workspaces.getRoomDetail({ workspaceId: workspaceId as string, roomId }),+ enabled: workspaceId !== null,});- if (serverId === null) {- return <PanelNotice title="This room’s server is still loading." />;+ if (workspaceId === null) {+ return <PanelNotice title="This room’s workspace is still loading." />;}if (query.isPending) {@@ -91,13 +91,13 @@ export const RoomConfigurationPanel = observer(function RoomConfigurationPanel({return (<div className="h-full overflow-y-auto"><div className="mx-auto flex w-full max-w-4xl flex-col gap-8 px-10 py-8">- <RoomHeading serverId={serverId} room={room} />+ <RoomHeading serverId={switchRoomsStore.roomServerId(roomId)} room={room} />{/* Keyed on the room so the drafts below belong to the room on screen:switching rooms starts a fresh form rather than carrying half-typedtext across. */}- <GeneralSection key={room.id} serverId={serverId} room={room} />- <ParticipantsSection serverId={serverId} room={room} />- <DeleteRoomSection serverId={serverId} room={room} />+ <GeneralSection key={room.id} workspaceId={workspaceId} room={room} />+ <ParticipantsSection workspaceId={workspaceId} room={room} />+ <DeleteRoomSection workspaceId={workspaceId} room={room} /></div></div>);@@ -111,16 +111,16 @@ export const RoomConfigurationPanel = observer(function RoomConfigurationPanel({* none to find — the room is someone else's.*/const DeleteRoomSection = observer(function DeleteRoomSection({- serverId,+ workspaceId,room,}: {- serverId: string;+ workspaceId: string;room: RemoteRoomDetail;}) {const showDeleteRoomModal = useShowModal('deleteRoomModal');const { navigate } = useNavigate();- if (!switchRoomsStore.canDeleteRoom(serverId, room)) return null;+ if (!switchRoomsStore.canDeleteRoom(workspaceId, room)) return null;return (<section className="border-t border-border pt-6">@@ -138,7 +138,7 @@ const DeleteRoomSection = observer(function DeleteRoomSection({className="shrink-0 border-red-500/40 text-red-500 hover:bg-red-500/10 hover:text-red-500"onClick={() =>showDeleteRoomModal({- serverId,+ workspaceId,roomId: room.id,roomName: roomTitle(room),// The page this is on is the deleted room's own, so staying would@@ -154,7 +154,7 @@ const DeleteRoomSection = observer(function DeleteRoomSection({);});-function RoomHeading({ serverId, room }: { serverId: string; room: RemoteRoomDetail }) {+function RoomHeading({ serverId, room }: { serverId: string | null; room: RemoteRoomDetail }) {const platform = bridgePlatformLabel(room.bridgeType);const { navigate } = useNavigate();return (@@ -168,14 +168,16 @@ function RoomHeading({ serverId, room }: { serverId: string; room: RemoteRoomDet</p></div><div className="flex shrink-0 items-center gap-2">- <Button- variant="outline"- size="sm"- onClick={() => navigate('templateCapture', { serverId, roomId: room.id })}- >- <FileText className="size-3.5" />- Capture as template- </Button>+ {serverId !== null && (+ <Button+ variant="outline"+ size="sm"+ onClick={() => navigate('templateCapture', { serverId, roomId: room.id })}+ >+ <FileText className="size-3.5" />+ Capture as template+ </Button>+ )}{room.externalChannelUrl && (<>{room.bridgeDisplayName && (@@ -208,7 +210,7 @@ type SaveState = { phase: 'idle' | 'saving' | 'saved' } | { phase: 'failed'; mes** One request carries both fields, so the pair is stored together or not at all.*/-function GeneralSection({ serverId, room }: { serverId: string; room: RemoteRoomDetail }) {+function GeneralSection({ workspaceId, room }: { workspaceId: string; room: RemoteRoomDetail }) {const queryClient = useQueryClient();const savedDescription = room.description;const savedInstructions = room.instructions ?? '';@@ -221,13 +223,13 @@ function GeneralSection({ serverId, room }: { serverId: string; room: RemoteRoomasync function save() {setState({ phase: 'saving' });try {- const updated = await rpc.switchServers.updateRoom({- serverId,+ const updated = await rpc.workspaces.updateRoom({+ workspaceId,roomId: room.id,description,instructions,});- queryClient.setQueryData(roomDetailKey(serverId, room.id), updated);+ queryClient.setQueryData(roomDetailKey(workspaceId, room.id), updated);setState({ phase: 'saved' });} catch (cause) {setState({ phase: 'failed', message: failureText(cause, 'Could not save the change.') });@@ -322,10 +324,10 @@ function Field({* hierarchy the room does not have.*/const ParticipantsSection = observer(function ParticipantsSection({- serverId,+ workspaceId,room,}: {- serverId: string;+ workspaceId: string;room: RemoteRoomDetail;}) {const queryClient = useQueryClient();@@ -335,11 +337,11 @@ const ParticipantsSection = observer(function ParticipantsSection({// Names for agents belonging to other installs, which this computer has no// local record of. Shares its key with the rest of the app, so it is usually// already in hand.- const remoteAgents = useRemoteAgents(serverId);+ const remoteAgents = useWorkspaceAgents(workspaceId);const remoteById = new Map((remoteAgents.data ?? []).map((a) => [a.id, a]));async function refresh() {- await queryClient.invalidateQueries({ queryKey: roomDetailKey(serverId, room.id) });+ await queryClient.invalidateQueries({ queryKey: roomDetailKey(workspaceId, room.id) });await switchRoomsStore.refreshRoomState();}@@ -380,9 +382,11 @@ const ParticipantsSection = observer(function ParticipantsSection({{room.agentIds.map((agentId) => (<ParticipantCardkey={agentId}- mark={<AgentMark agentId={agentId} serverId={serverId} remoteById={remoteById} />}- name={agentNameFor(agentId, serverId, remoteById)}- detail={agentKindFor(agentId, serverId, remoteById)}+ mark={+ <AgentMark agentId={agentId} workspaceId={workspaceId} remoteById={remoteById} />+ }+ name={agentNameFor(agentId, workspaceId, remoteById)}+ detail={agentKindFor(agentId, workspaceId, remoteById)}/>))}{room.connectedUserNames.map((name) => (@@ -400,7 +404,7 @@ const ParticipantsSection = observer(function ParticipantsSection({</div>)}- {adding && <AddAgentPanel serverId={serverId} room={room} onAdded={refresh} />}+ {adding && <AddAgentPanel workspaceId={workspaceId} room={room} onAdded={refresh} />}</section>);});@@ -433,11 +437,11 @@ function ParticipantCard({* whose owner never agreed to it.*/const AddAgentPanel = observer(function AddAgentPanel({- serverId,+ workspaceId,room,onAdded,}: {- serverId: string;+ workspaceId: string;room: RemoteRoomDetail;onAdded: () => Promise<void>;}) {@@ -446,11 +450,11 @@ const AddAgentPanel = observer(function AddAgentPanel({const [error, setError] = useState<string | null>(null);const members = new Set(room.agentIds);- const { data: remoteAgents } = useRemoteAgents(serverId);+ const { data: remoteAgents } = useWorkspaceAgents(workspaceId);const remoteById = new Map((remoteAgents ?? []).map((agent) => [agent.id, agent]));const query = filter.trim().toLowerCase();const candidates = agentsStore- .agentsOnServer(serverId)+ .agentsInWorkspace(workspaceId).filter((agent) => agent.switchAgentId !== null && !members.has(agent.switchAgentId)).filter((agent) => query === '' || agent.name.toLowerCase().includes(query));@@ -458,8 +462,8 @@ const AddAgentPanel = observer(function AddAgentPanel({setBusyId(switchAgentId);setError(null);try {- await rpc.switchServers.addRoomAgents({- serverId,+ await rpc.workspaces.addRoomAgents({+ workspaceId,roomId: room.id,agentIds: [switchAgentId],direction: 'agents_to_room',@@ -569,18 +573,18 @@ function PanelNotice({/** An agent's own picture, beside the human participants' initials discs. */function AgentMark({agentId,- serverId,+ workspaceId,remoteById,}: {agentId: string;- serverId: string;+ workspaceId: string;remoteById: Map<string, RemoteAgentSummary>;}) {const remote = remoteById.get(agentId) ?? null;return (<span className="flex size-7 shrink-0 items-center justify-center"><AgentAvatar- name={agentNameFor(agentId, serverId, remoteById)}+ name={agentNameFor(agentId, workspaceId, remoteById)}iconUrl={remote?.iconUrl ?? null}size={26}/>@@ -590,19 +594,22 @@ function AgentMark({/** This install's record of a Switch agent, which is where its provider is* known — the server says what type an agent is, not what runs it here. */-function localAgentFor(switchAgentId: string, serverId: string) {+function localAgentFor(switchAgentId: string, workspaceId: string) {return (- agentsStore.agentsOnServer(serverId).find((a) => a.switchAgentId === switchAgentId) ?? null+ agentsStore.agentsInWorkspace(workspaceId).find((a) => a.switchAgentId === switchAgentId) ??+ null);}function agentNameFor(switchAgentId: string,- serverId: string,+ workspaceId: string,remoteById: Map<string, RemoteAgentSummary>): string {return (- localAgentFor(switchAgentId, serverId)?.name ?? remoteById.get(switchAgentId)?.name ?? 'Agent'+ localAgentFor(switchAgentId, workspaceId)?.name ??+ remoteById.get(switchAgentId)?.name ??+ 'Agent');}@@ -610,10 +617,10 @@ function agentNameFor(* otherwise the type the server knows it by. */function agentKindFor(switchAgentId: string,- serverId: string,+ workspaceId: string,remoteById: Map<string, RemoteAgentSummary>): string {- const providerId = localAgentFor(switchAgentId, serverId)?.providerId ?? null;+ const providerId = localAgentFor(switchAgentId, workspaceId)?.providerId ?? null;const knownType = remoteById.get(switchAgentId)?.knownAgentType ?? null;return providerDisplayName(providerId) ?? providerDisplayName(knownType) ?? 'agent';}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/session-deeplink-listener.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/session-deeplink-listener.tsxindex d699ea9c9..211cc0891 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/session-deeplink-listener.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/session-deeplink-listener.tsx@@ -4,7 +4,7 @@ import { agentsStore } from '@renderer/features/locations/stores/agents-store';import { getLocationManagerStore } from '@renderer/features/locations/stores/location-selectors';import { getSessionManagerStore } from '@renderer/features/sessions/stores/session-selectors';import { events } from '@renderer/lib/ipc';-import { scopeToLocationServer } from '@renderer/lib/layout/scope-to-server';+import { scopeToLocationWorkspace } from '@renderer/lib/layout/scope-to-workspace';import { appState } from '@renderer/lib/stores/app-state';import { report } from '@renderer/lib/telemetry/report';import { sessionDeeplinkChannel } from '@shared/core/switch-rooms/switchRoomEvents';@@ -95,7 +95,7 @@ export function SessionDeeplinkListener(): null {// is filtered out of the server-scoped tree and there is no row to// reveal. Navigating is all the sidebar needs — it expands and scrolls// to whatever the open view selects, from any origin.- await scopeToLocationServer(match.locationId);+ await scopeToLocationWorkspace(match.locationId);appState.navigation.navigate('session', match);})();}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/AddServerModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/AddServerModal.tsxindex bbd3db87a..24a70533f 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/AddServerModal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/AddServerModal.tsx@@ -1,7 +1,8 @@-import { CircleCheck, Globe, Info, Laptop, Server, TriangleAlert } from 'lucide-react';+import { CircleCheck, Cloud, Globe, Info, Laptop, Server, TriangleAlert } from 'lucide-react';import { observer } from 'mobx-react-lite';import { useCallback, useEffect, useRef, useState } from 'react';import { HostReachabilityNotice } from '@renderer/features/remote-hosts/host-reachability-notice';+import { describeFailure } from '@renderer/lib/errors/describe-failure';import { toast } from '@renderer/lib/hooks/use-toast';import { rpc } from '@renderer/lib/ipc';import { useNavigate } from '@renderer/lib/layout/navigation-provider';@@ -10,16 +11,10 @@ import { report } from '@renderer/lib/telemetry/report';import { Alert, AlertDescription, AlertTitle } from '@renderer/lib/ui/alert';import { Button } from '@renderer/lib/ui/button';import { ConfirmButton } from '@renderer/lib/ui/confirm-button';-import {- DialogContentArea,- DialogFooter,- DialogHeader,- DialogTitle,-} from '@renderer/lib/ui/dialog';import { Field, FieldGroup, FieldLabel } from '@renderer/lib/ui/field';import { Input } from '@renderer/lib/ui/input';import { Spinner } from '@renderer/lib/ui/spinner';-import { WizardStepHeader } from '@renderer/lib/ui/wizard-step-header';+import { WizardFrame } from '@renderer/lib/ui/wizard-frame';import {lockHolderSentence,othersRecentlySeen,@@ -40,6 +35,7 @@ import { type RemoteSetupAction, remoteSetupAction } from './remote-setup-actionimport { ServerSignInFields, useServerSignIn } from './server-sign-in';import { affectedSentence } from './shared-consoles';import { switchServersStore } from './switch-servers-store';+import { useSwitchCloud } from './use-switch-cloud';/*** Turn a server-API-URL cascade into a user-facing toast: confirm how many@@ -97,16 +93,6 @@ const _stepsAreComplete: Step extends AddServerStepName ? true : never = true;void _stepsAreExhaustive;void _stepsAreComplete;-/**- * How many steps connecting to a server someone else runs takes: choose that- * path, point at the server, sign in, then say which messaging account is you.- *- * The chooser is step 1 but carries no counter — the other two paths it leads- * to are not four steps, and a count shown before the choice would promise a- * length that depends on what is clicked next.- */-const CONNECT_STEPS = 4;-/*** Add a Switch server: run one here, run one on a host you have onboarded, or* connect to one someone else runs.@@ -164,7 +150,7 @@ export const AddServerModal = observer(function AddServerModal(props: Props) {useEffect(() => {if (isEdit || reportedOpening.current) return;reportedOpening.current = true;- report('add_server_step', { step: openedAt, choice: openedWith });+ report('add_server_step', { step: openedAt, choice: openedWith, first_run: false });}, [isEdit, openedAt, openedWith]);/**@@ -179,7 +165,7 @@ export const AddServerModal = observer(function AddServerModal(props: Props) {const nextChoice = CHOICE_FOR_STEP[next] ?? choice;setChoice(nextChoice);setStep(next);- report('add_server_step', { step: next, choice: nextChoice });+ report('add_server_step', { step: next, choice: nextChoice, first_run: false });};// The server the wizard just created, and the subject of every step after// it. Null in edit mode and on the two managed paths, which is what@@ -194,6 +180,18 @@ export const AddServerModal = observer(function AddServerModal(props: Props) {* whatever was behind it left no sign anything had happened. A path that* cannot name the server it made lands nowhere rather than guessing.*/+ /**+ * Switch Cloud has no form: its address is the build's. So it goes straight+ * from the chooser to signing in, and that step's Back returns to the+ * chooser rather than to a connect-by-URL form it never passed through.+ */+ const enterCloud = (server: SwitchServer) => {+ setConnected(server);+ setChoice('cloud');+ setStep('signIn');+ report('add_server_step', { step: 'signIn', choice: 'cloud', first_run: false });+ };+const finish = (serverId: string | null) => {if (serverId) {void switchServersStore.setActive(serverId);@@ -208,6 +206,7 @@ export const AddServerModal = observer(function AddServerModal(props: Props) {onLocal={() => goToStep('local')}onRemoteHost={() => goToStep('remoteHost')}onExternal={() => goToStep('external')}+ onCloud={enterCloud}onClose={props.onClose}/>);@@ -218,6 +217,9 @@ export const AddServerModal = observer(function AddServerModal(props: Props) {onBack={isEdit ? undefined : () => goToStep('choose')}onDone={finish}onClose={props.onClose}+ // The dialog is closed, not left part-way: Cancel is the way out and it+ // has no server to name.+ onRegistered={null}/>);}@@ -227,6 +229,7 @@ export const AddServerModal = observer(function AddServerModal(props: Props) {onBack={() => goToStep('choose')}onDone={finish}onClose={props.onClose}+ onRegistered={null}/>);}@@ -234,7 +237,7 @@ export const AddServerModal = observer(function AddServerModal(props: Props) {return (<SignInStepserver={connected}- onBack={() => goToStep('external')}+ onBack={() => goToStep(choice === 'cloud' ? 'choose' : 'external')}onClose={props.onClose}onSignedIn={() => goToStep('linkAccounts')}/>@@ -245,18 +248,22 @@ export const AddServerModal = observer(function AddServerModal(props: Props) {<LinkAccountsStepserverId={connected.id}serverName={connected.name}- step={CONNECT_STEPS}- of={CONNECT_STEPS}onDone={() => finish(connected.id)}/>);}return (<ExternalServerStep- {...props}+ onSuccess={props.onSuccess}+ onClose={props.onClose}+ initialGatewayUrl={props.initialGatewayUrl ?? null}+ initialApiUrl={props.initialApiUrl ?? null}+ initialName={props.initialName ?? null}+ serverId={props.serverId ?? null}isEdit={isEdit}+ firstRun={false}existing={connected}- onBack={isEdit ? undefined : () => goToStep('choose')}+ onBack={isEdit ? null : () => goToStep('choose')}onConnected={(server) => {setConnected(server);goToStep('signIn');@@ -273,65 +280,117 @@ function ChooseStep({onLocal,onRemoteHost,onExternal,+ onCloud,onClose,}: {onLocal: () => void;onRemoteHost: () => void;onExternal: () => void;+ onCloud: (server: SwitchServer) => void;onClose: () => void;}) {+ const cloud = useSwitchCloud();+ const [cloudAttempt, setCloudAttempt] = useState<{ connecting: boolean; error: string | null }>({+ connecting: false,+ error: null,+ });+ const connectToCloud = () => {+ setCloudAttempt({ connecting: true, error: null });+ switchServersStore.connectToSwitchCloud().then(onCloud, (cause) => {+ const failure = describeFailure(cause, 'Could not connect to Switch Cloud.');+ setCloudAttempt({+ connecting: false,+ error: failure.detail ? `${failure.headline} ${failure.detail}` : failure.headline,+ });+ });+ };+return (- <>- <DialogHeader showCloseButton={false}>- <DialogTitle>Add a Switch server</DialogTitle>- </DialogHeader>- <DialogContentArea className="pt-0">- <div className="grid gap-3">- <ChoiceCard- icon={<Laptop className="size-5" />}- title="Run a server on this computer"- description="Switch Console sets up and runs the full Switch stack here with Docker. Best for trying Switch out."- onClick={onLocal}- />- <ChoiceCard- icon={<Server className="size-5" />}- title="Run or join a server on a remote host"- description="Switch Console sets one up over SSH on a host you've onboarded, or joins the one already running there. Stays running when Switch Console is closed."- onClick={onRemoteHost}- />- <ChoiceCard- icon={<Globe className="size-5" />}- title="Connect to an existing server"- description="Point Switch Console at a Switch gateway someone else runs, by URL."- onClick={onExternal}- />- </div>- </DialogContentArea>- <DialogFooter>+ <WizardFrame+ title="Add a Switch server"+ subtitle={null}+ pager={{ pageName: 'Add a server', onBack: null, onNext: null }}+ footer={<Button variant="outline" onClick={onClose}>Cancel</Button>- </DialogFooter>- </>+ }+ >+ <div className="grid gap-3">+ {/* Offered only when this build knows where the Cloud is. A failed read+ is shown rather than dropped, since it means the build is broken. */}+ {cloud.kind === 'open' && (+ <ChoiceCard+ icon={+ cloudAttempt.connecting ? (+ <Spinner className="size-5" />+ ) : (+ <Cloud className="size-5" />+ )+ }+ title="Connect to Switch Cloud"+ description={`Sign in to the Switch we run for you at ${new URL(cloud.url).host}.`}+ onClick={connectToCloud}+ disabled={cloudAttempt.connecting}+ />+ )}+ {cloudAttempt.error && (+ <Alert variant="destructive">+ <TriangleAlert className="size-4" />+ <AlertTitle>Could not connect to Switch Cloud</AlertTitle>+ <AlertDescription>{cloudAttempt.error}</AlertDescription>+ </Alert>+ )}+ {cloud.kind === 'failed' && (+ <Alert variant="destructive">+ <TriangleAlert className="size-4" />+ <AlertTitle>{cloud.headline}</AlertTitle>+ {cloud.detail && <AlertDescription>{cloud.detail}</AlertDescription>}+ </Alert>+ )}+ <ChoiceCard+ icon={<Laptop className="size-5" />}+ title="Run a server on this computer"+ description="Switch Console sets up and runs the full Switch stack here with Docker. Best for trying Switch out."+ onClick={onLocal}+ />+ <ChoiceCard+ icon={<Server className="size-5" />}+ title="Run or join a server on a remote host"+ description="Switch Console sets one up over SSH on a host you've onboarded, or joins the one already running there. Stays running when Switch Console is closed."+ onClick={onRemoteHost}+ />+ <ChoiceCard+ icon={<Globe className="size-5" />}+ title="Connect to an existing server"+ description="Point Switch Console at a Switch gateway someone else runs, by URL."+ onClick={onExternal}+ />+ </div>+ </WizardFrame>);}-function ChoiceCard({+export function ChoiceCard({icon,title,description,onClick,+ disabled = false,}: {icon: React.ReactNode;title: string;description: string;onClick: () => void;+ /** While the choice is already being acted on. */+ disabled?: boolean;}) {return (<buttontype="button"onClick={onClick}- className="bg-card hover:border-border-hover flex items-start gap-3 rounded-lg border border-border p-4 text-left hover:bg-background-tertiary-2"+ disabled={disabled}+ className="bg-card hover:border-border-hover flex items-start gap-3 rounded-lg border border-border p-4 text-left hover:bg-background-tertiary-2 disabled:pointer-events-none disabled:opacity-60"><span className="mt-0.5 text-foreground-muted">{icon}</span><span className="space-y-1">@@ -355,15 +414,24 @@ function SetupStepItem({ children }: { children: React.ReactNode }) {// Step 2a — local server setup (preflight → progress → done)// ----------------------------------------------------------------------------const LocalSetupStep = observer(function LocalSetupStep({+export const LocalSetupStep = observer(function LocalSetupStep({onBack,onDone,onClose,+ onRegistered,}: {onBack?: () => void;/** Reports the server the stack registered, so the flow can end on it. */onDone: (serverId: string | null) => void;- onClose: () => void;+ /** Null where the flow has no way out but forwards — the first-run pages. */+ onClose: (() => void) | null;+ /**+ * Reports the server the moment it is registered rather than when Done is+ * pressed, so a flow that offers a way out can aim it at the right row.+ * Null for a chrome with no such offer — the dialog, which is closed instead+ * of left.+ */+ onRegistered: ((serverId: string) => void) | null;}) {const store = localServerStore;@@ -372,6 +440,11 @@ const LocalSetupStep = observer(function LocalSetupStep({void store.checkDocker();}, [store]);+ const registeredId = store.status?.serverId ?? null;+ useEffect(() => {+ if (registeredId !== null) onRegistered?.(registeredId);+ }, [registeredId, onRegistered]);+const running = store.isRunning;const starting = store.isTransitioning;const docker = store.docker;@@ -379,6 +452,14 @@ const LocalSetupStep = observer(function LocalSetupStep({const dockerUnavailable = docker && !docker.available ? docker : null;const idle = !running && !starting;+ // The pager's back arrow only ever repeats the footer's Back, so the two read+ // one const. Open during the install too: the store is a singleton the main+ // process streams into, so leaving loses only what is on screen, and holding+ // the page shut left the full-window flow with no live control at all through+ // a multi-gigabyte pull — while the same page in the dialog could still be+ // dismissed with Escape.+ const goBack = onBack ?? null;+const primaryLabel = running ? 'Done' : store.phase === 'error' ? 'Retry' : 'Start';const onPrimary = () => {if (running) onDone(store.status?.serverId ?? null);@@ -386,11 +467,25 @@ const LocalSetupStep = observer(function LocalSetupStep({};return (- <>- <DialogHeader showCloseButton={false}>- <DialogTitle>Set up a server on this computer</DialogTitle>- </DialogHeader>- <DialogContentArea className="space-y-4 pt-0">+ <WizardFrame+ title="Set up a server on this computer"+ subtitle="Switch Console installs the full stack with Docker and keeps it updated."+ pager={{ pageName: 'Set up a server', onBack: goBack, onNext: null }}+ footer={+ <>+ <BackOrClose+ onBack={goBack}+ onClose={onClose}+ closeDisabled={starting}+ closeLabel={running ? 'Close' : 'Cancel'}+ />+ <ConfirmButton onClick={onPrimary} disabled={starting || (!running && !dockerReady)}>+ {starting ? 'Starting…' : primaryLabel}+ </ConfirmButton>+ </>+ }+ >+ <div className="space-y-4"><div className="flex items-center gap-3"><div className="flex size-10 shrink-0 items-center justify-center rounded-lg bg-background-tertiary text-foreground-muted"><Laptop className="size-5" />@@ -442,9 +537,16 @@ const LocalSetupStep = observer(function LocalSetupStep({{(starting || store.logs.length > 0) && !running && (<div className="space-y-1.5">{store.message && starting && (- <div className="flex items-center gap-2 text-sm text-foreground">- <Spinner className="size-3.5" />- <span>{store.message}</span>+ <div className="space-y-1">+ <div className="flex items-center gap-2 text-sm text-foreground">+ <Spinner className="size-3.5" />+ <span>{store.message}</span>+ </div>+ {/* Said out loud, because Back being live during a download+ that takes minutes otherwise looks like it cancels one. */}+ <p className="text-xs text-foreground-muted">+ This keeps running if you leave the page — come back here to watch it.+ </p></div>)}<LogTail@@ -453,25 +555,51 @@ const LocalSetupStep = observer(function LocalSetupStep({/></div>)}- </DialogContentArea>- <DialogFooter>- {onBack && !starting ? (- <Button variant="outline" onClick={onBack}>- Back- </Button>- ) : (- <Button variant="outline" onClick={onClose} disabled={starting}>- {running ? 'Close' : 'Cancel'}- </Button>- )}- <ConfirmButton onClick={onPrimary} disabled={starting || (!running && !dockerReady)}>- {starting ? 'Starting…' : primaryLabel}- </ConfirmButton>- </DialogFooter>- </>+ </div>+ </WizardFrame>);});+/**+ * The button on the left of a wizard's footer.+ *+ * A page that can be left offers Cancel; one that can only be stepped back+ * through offers Back; the first-run pages can do neither while a stack is+ * installing, and get a Back that is visibly held rather than no button and a+ * footer that changes shape under the eye.+ */+function BackOrClose({+ onBack,+ onClose,+ closeDisabled,+ closeLabel,+}: {+ onBack: (() => void) | null;+ onClose: (() => void) | null;+ closeDisabled: boolean;+ closeLabel: string;+}) {+ if (onBack) {+ return (+ <Button variant="outline" onClick={onBack}>+ Back+ </Button>+ );+ }+ if (onClose) {+ return (+ <Button variant="outline" onClick={onClose} disabled={closeDisabled}>+ {closeLabel}+ </Button>+ );+ }+ return (+ <Button variant="outline" disabled>+ Back+ </Button>+ );+}+function DockerStatus({ready,unavailable,@@ -522,11 +650,14 @@ export const RemoteHostSetupStep = observer(function RemoteHostSetupStep({onBack,onDone,onClose,+ onRegistered,}: {onBack: () => void;/** Reports the server the stack registered, so the flow can end on it. */onDone: (serverId: string | null) => void;onClose: () => void;+ /** As on the local page: the registration, not the Done press. */+ onRegistered: ((serverId: string) => void) | null;}) {const store = remoteServerStore;const [hosts, setHosts] = useState<{ sshHost: string; name: string }[] | null>(null);@@ -567,6 +698,11 @@ export const RemoteHostSetupStep = observer(function RemoteHostSetupStep({const waiting = status?.waitingFor ?? null;const joining = action?.kind === 'connect';+ const registeredId = sshHost ? (status?.serverId ?? null) : null;+ useEffect(() => {+ if (registeredId !== null) onRegistered?.(registeredId);+ }, [registeredId, onRegistered]);+const canAct =!!sshHost &&name.trim().length > 0 &&@@ -583,13 +719,19 @@ export const RemoteHostSetupStep = observer(function RemoteHostSetupStep({sshHost && updating? affectedSentence(othersRecentlySeen(store.registerFor(sshHost), new Date()), new Date()): null;+ // One const for the footer's Back and the pager's back arrow, which only+ // repeats it. Open during the install, for the same reason as the local page:+ // the store outlives the page, so nothing is abandoned by leaving it.+ const goBack = onBack;const primaryLabel = running? 'Done'- : joining- ? updating- ? 'Update and connect'- : 'Connect'- : 'Start';+ : status?.phase === 'error'+ ? 'Retry'+ : joining+ ? updating+ ? 'Update and connect'+ : 'Connect'+ : 'Start';const onPrimary = () => {if (running) onDone(sshHost ? (store.statusFor(sshHost).serverId ?? null) : null);else if (sshHost && joining) void store.connect(sshHost, name.trim());@@ -597,11 +739,38 @@ export const RemoteHostSetupStep = observer(function RemoteHostSetupStep({};return (- <>- <DialogHeader showCloseButton={false}>- <DialogTitle>Run or join a server on a remote host</DialogTitle>- </DialogHeader>- <DialogContentArea className="space-y-4 pt-0">+ <WizardFrame+ title="Run or join a server on a remote host"+ subtitle={null}+ pager={{+ pageName: 'Set up on a remote host',+ onBack: goBack,+ onNext: null,+ }}+ footer={+ <>+ {sshHost && starting && waiting ? (+ // Only a wait for another Console can be cancelled: nothing has+ // been changed yet.+ <Button variant="outline" onClick={() => void store.cancelWait(sshHost)}>+ Stop waiting+ </Button>+ ) : (+ <BackOrClose onBack={goBack} onClose={onClose} closeDisabled closeLabel="Cancel" />+ )}+ <ConfirmButton onClick={onPrimary} disabled={!running && !canAct}>+ {starting+ ? updating+ ? 'Updating…'+ : joining+ ? 'Connecting…'+ : 'Starting…'+ : primaryLabel}+ </ConfirmButton>+ </>+ }+ >+ <div className="space-y-4">{hosts === null ? (<div className="flex items-center gap-2 text-sm text-foreground-muted"><Spinner className="size-3.5" />@@ -738,34 +907,8 @@ export const RemoteHostSetupStep = observer(function RemoteHostSetupStep({)}</>)}- </DialogContentArea>- <DialogFooter>- {!starting ? (- <Button variant="outline" onClick={onBack}>- Back- </Button>- ) : sshHost && waiting ? (- // Only a wait for another Console can be cancelled: nothing has- // been changed yet.- <Button variant="outline" onClick={() => void store.cancelWait(sshHost)}>- Stop waiting- </Button>- ) : (- <Button variant="outline" onClick={onClose} disabled>- Cancel- </Button>- )}- <ConfirmButton onClick={onPrimary} disabled={!running && !canAct}>- {starting- ? updating- ? 'Updating…'- : joining- ? 'Connecting…'- : 'Starting…'- : primaryLabel}- </ConfirmButton>- </DialogFooter>- </>+ </div>+ </WizardFrame>);});@@ -857,7 +1000,24 @@ function looksLikeUrl(value: string): boolean {}}-const ExternalServerStep = observer(function ExternalServerStep({+/**+ * A name for a server the user was never asked to name.+ *+ * The first-run form leaves the field out — someone connecting their only+ * server has nothing to tell it apart from, and a required text box between+ * them and a working app is a question asked for the list's benefit rather than+ * theirs. The hostname is what they would have typed anyway, and renaming is a+ * click away once there is a sidebar to see it in.+ */+function nameFromGatewayUrl(gatewayUrl: string): string {+ // The host rather than the hostname: two servers on one machine differ only+ // by port, and a sidebar with two rows both called `localhost` names neither+ // of them. An IPv6 address keeps its brackets, which is how an address with+ // a port beside it is written.+ return new URL(gatewayUrl).host;+}++export const ExternalServerStep = observer(function ExternalServerStep({onSuccess,onClose,onBack,@@ -866,11 +1026,21 @@ const ExternalServerStep = observer(function ExternalServerStep({initialName,serverId,isEdit,+ firstRun,existing,onConnected,-}: Props & {+}: {+ initialGatewayUrl: string | null;+ initialApiUrl: string | null;+ initialName: string | null;+ serverId: string | null;isEdit: boolean;- onBack?: () => void;+ /** The first-run wording of the same form: no name to ask for, and the+ * server's own accounts worth saying out loud before the sign-in step. */+ firstRun: boolean;+ onSuccess: () => void;+ onClose: () => void;+ onBack: (() => void) | null;/** Set when the wizard has already created the server and the user came back* to fix what they typed — the same form, saving instead of adding. */existing: SwitchServer | null;@@ -887,9 +1057,11 @@ const ExternalServerStep = observer(function ExternalServerStep({const trimmedApi = apiUrl.trim();const gatewayValid = looksLikeUrl(trimmedGateway);const apiValid = looksLikeUrl(trimmedApi);- // In edit mode the name is owned by the separate Rename action, so this form- // only edits the URLs — the name field isn't shown and isn't required.- const isValid = (isEdit || trimmedName.length > 0) && gatewayValid && apiValid;+ // In edit mode the name is owned by the separate Rename action, and on first+ // run it comes from the gateway, so neither shows the field or requires it.+ const asksForName = !isEdit && !firstRun;+ const isValid = (!asksForName || trimmedName.length > 0) && gatewayValid && apiValid;+ const submittedName = firstRun && gatewayValid ? nameFromGatewayUrl(trimmedGateway) : trimmedName;const gatewayMessage =trimmedGateway.length > 0 && !gatewayValid@@ -911,7 +1083,7 @@ const ExternalServerStep = observer(function ExternalServerStep({if (savedId) {const result = await switchServersStore.updateServer(savedId,- trimmedName,+ submittedName,trimmedGateway,trimmedApi);@@ -926,7 +1098,7 @@ const ExternalServerStep = observer(function ExternalServerStep({return;}} else {- const saved = await switchServersStore.addServer(trimmedName, trimmedGateway, trimmedApi);+ const saved = await switchServersStore.addServer(submittedName, trimmedGateway, trimmedApi);if (!saved) {setError(switchServersStore.errorText ?? 'Could not add the server.');setSubmitting(false);@@ -936,64 +1108,117 @@ const ExternalServerStep = observer(function ExternalServerStep({return;}onSuccess();- }, [isValid, isEdit, savedId, trimmedName, trimmedGateway, trimmedApi, onSuccess, onConnected]);+ }, [isValid, isEdit, savedId, submittedName, trimmedGateway, trimmedApi, onSuccess, onConnected]);++ // First run is asked before the saved row, because a page that goes on to the+ // sign-in must not offer "Save changes" — the user stepped back to fix an+ // address, and the button still takes them forward rather than closing.+ const submitLabel = submitting+ ? savedId+ ? 'Saving…'+ : 'Adding…'+ : firstRun+ ? 'Sign in to this server'+ : savedId+ ? 'Save changes'+ : 'Add server';++ // The footer's Back and the pager's back arrow are the same move, so they+ // read one const. Shut while the form is submitting: the write registers a+ // server, and stepping off it mid-way leaves one behind with no page on it.+ const goBack = onBack && !submitting ? onBack : null;return (- <>- {isEdit ? (- <DialogHeader showCloseButton={false}>- <DialogTitle>Edit connection</DialogTitle>- </DialogHeader>- ) : (- <WizardStepHeader title="Connect to an existing server" step={2} of={CONNECT_STEPS} />- )}- <DialogContentArea className="pt-0">- <FieldGroup>- {!isEdit && (- <Field>- <FieldLabel>Name</FieldLabel>- <Input- value={name}- onChange={(e) => setName(e.target.value)}- placeholder="Pilot"- autoFocus- />- </Field>- )}- <Field>- <FieldLabel>Gateway URL</FieldLabel>- <Input- value={gatewayUrl}- onChange={(e) => setGatewayUrl(e.target.value)}- placeholder="https://switch-gateway.example.com"- autoFocus={isEdit}- />- {gatewayMessage && <p className="mt-1 text-xs text-destructive">{gatewayMessage}</p>}- </Field>+ <WizardFrame+ title={+ isEdit+ ? 'Edit connection'+ : firstRun+ ? 'Connect to your server'+ : 'Connect to an existing server'+ }+ subtitle={firstRun ? 'Whoever set it up can give you these addresses.' : null}+ /* Editing a connection is one dialog rather than a flow, and a pager on+ it would invent pages either side that do not exist. */+ pager={+ isEdit+ ? null+ : {+ pageName: 'Connect to a server',+ onBack: goBack,+ onNext: null,+ }+ }+ footer={+ <>+ <Button+ variant="outline"+ onClick={goBack ?? onClose}+ disabled={!!onBack && goBack === null}+ >+ {onBack ? 'Back' : 'Cancel'}+ </Button>+ <ConfirmButton onClick={() => void handleSubmit()} disabled={!isValid || submitting}>+ {submitLabel}+ </ConfirmButton>+ </>+ }+ >+ <FieldGroup>+ {asksForName && (<Field>- <FieldLabel>API URL</FieldLabel>+ <FieldLabel>Name</FieldLabel><Input- value={apiUrl}- onChange={(e) => setApiUrl(e.target.value)}- placeholder="https://switch-api.example.com"- onKeyDown={(e) => {- if (e.key === 'Enter') void handleSubmit();- }}+ value={name}+ onChange={(e) => setName(e.target.value)}+ placeholder="Pilot"+ autoFocus/>- {apiMessage && <p className="mt-1 text-xs text-destructive">{apiMessage}</p>}- {error && <p className="mt-1 text-xs text-destructive">{error}</p>}</Field>- </FieldGroup>- </DialogContentArea>- <DialogFooter>- <Button variant="outline" onClick={onBack ?? onClose}>- {onBack ? 'Back' : 'Cancel'}- </Button>- <ConfirmButton onClick={() => void handleSubmit()} disabled={!isValid || submitting}>- {submitting ? (savedId ? 'Saving…' : 'Adding…') : savedId ? 'Save changes' : 'Add server'}- </ConfirmButton>- </DialogFooter>- </>+ )}+ <Field>+ <FieldLabel>Gateway URL</FieldLabel>+ <Input+ value={gatewayUrl}+ onChange={(e) => setGatewayUrl(e.target.value)}+ placeholder="https://switch-gateway.example.com"+ autoFocus={isEdit || firstRun}+ />+ {firstRun && (+ <p className="mt-1 text-xs text-foreground-muted">Where the app and its chat live.</p>+ )}+ {gatewayMessage && <p className="mt-1 text-xs text-destructive">{gatewayMessage}</p>}+ </Field>+ <Field>+ <FieldLabel>API URL</FieldLabel>+ <Input+ value={apiUrl}+ onChange={(e) => setApiUrl(e.target.value)}+ placeholder="https://switch-api.example.com"+ onKeyDown={(e) => {+ if (e.key === 'Enter') void handleSubmit();+ }}+ />+ {firstRun && (+ <p className="mt-1 text-xs text-foreground-muted">+ Where agents connect. Often the same host on a different port — whoever set the server+ up knows which.+ </p>+ )}+ {apiMessage && <p className="mt-1 text-xs text-destructive">{apiMessage}</p>}+ {error && <p className="mt-1 text-xs text-destructive">{error}</p>}+ </Field>+ {firstRun && (+ <Alert>+ <Info className="size-4" />+ <AlertDescription>+ This server keeps its own accounts. Signing in here signs you in to it, not to+ anything else.+ </AlertDescription>+ </Alert>+ )}+ </FieldGroup>+ </WizardFrame>);});@@ -1007,7 +1232,7 @@ const ExternalServerStep = observer(function ExternalServerStep({* signed-out server lists no rooms, no agents and no messaging apps, and looks* broken rather than unauthenticated.*/-const SignInStep = observer(function SignInStep({+export const SignInStep = observer(function SignInStep({server,onBack,onClose,@@ -1015,7 +1240,8 @@ const SignInStep = observer(function SignInStep({}: {server: SwitchServer;onBack: () => void;- onClose: () => void;+ /** Null where there is nothing to close onto — the first-run pages. */+ onClose: (() => void) | null;onSignedIn: () => void;}) {const signIn = useServerSignIn(server.id);@@ -1026,40 +1252,47 @@ const SignInStep = observer(function SignInStep({if (await signIn.signInWithPassword()) onSignedIn();};+ // One const for the footer's Back and the pager's back arrow that repeats it.+ const goBack = signIn.submitting ? null : onBack;+return (- <>- <WizardStepHeader title={`Sign in to ${server.name}`} step={3} of={CONNECT_STEPS} />- <DialogContentArea className="pt-0">- <ServerSignInFields- signIn={signIn}- idPrefix="connect-server-sign-in"- gatewayUrl={server.gatewayUrl}- onSignedIn={onSignedIn}- />- </DialogContentArea>- <DialogFooter>- <Button variant="outline" onClick={onBack} disabled={signIn.submitting}>- Back- </Button>- {canUsePassword ? (- <ConfirmButton- onClick={() => void submit()}- disabled={!signIn.canSubmitPassword || signIn.submitting}- >- {signIn.submitting ? 'Signing in…' : 'Sign in'}- </ConfirmButton>- ) : (- // Nothing for a primary button to do: either the only method is the- // provider button in the body, or the server offers none at all and- // the body says so. Leaving a dead "Sign in" there would imply the- // form was incomplete rather than absent.- !canUseOidc && (- <Button variant="outline" onClick={onClose}>- Close- </Button>- )- )}- </DialogFooter>- </>+ <WizardFrame+ title={`Sign in to ${server.name}`}+ subtitle={null}+ pager={{ pageName: 'Sign in', onBack: goBack, onNext: null }}+ footer={+ <>+ <Button variant="outline" onClick={onBack} disabled={goBack === null}>+ Back+ </Button>+ {canUsePassword ? (+ <ConfirmButton+ onClick={() => void submit()}+ disabled={!signIn.canSubmitPassword || signIn.submitting}+ >+ {signIn.submitting ? 'Signing in…' : 'Sign in'}+ </ConfirmButton>+ ) : (+ // Nothing for a primary button to do: either the only method is the+ // provider button in the body, or the server offers none at all and+ // the body says so. Leaving a dead "Sign in" there would imply the+ // form was incomplete rather than absent.+ !canUseOidc &&+ onClose && (+ <Button variant="outline" onClick={onClose}>+ Close+ </Button>+ )+ )}+ </>+ }+ >+ <ServerSignInFields+ signIn={signIn}+ idPrefix="connect-server-sign-in"+ gatewayUrl={server.gatewayUrl}+ onSignedIn={onSignedIn}+ />+ </WizardFrame>);});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ClaimIdentityModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ClaimIdentityModal.tsxindex 47be809ce..4d234aea1 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ClaimIdentityModal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ClaimIdentityModal.tsx@@ -13,15 +13,14 @@ import {} from '@renderer/lib/ui/dialog';import type { LinkedIdentity } from '@shared/core/switch-servers/switch-servers';import { BridgeIdentitySearch } from './bridge-identity-search';-import { switchServersStore } from './switch-servers-store';import { useMyIdentities } from './use-my-identities';type ClaimIdentityModalArgs = {- /** Claim on this server instead of the active one. */- serverId?: string;- /** The messaging app to claim an account in. Required: an account is claimed- * in one workspace, and every entry point knows which one it opened from —- * asking again would be a question the caller has already answered. */+ /** The workspace the account is claimed in. Required rather than defaulted to+ * the active one: every entry point knows which workspace it opened from, and+ * falling back would claim the account somewhere the user was not looking. */+ workspaceId: string;+ /** The messaging app to claim an account in. */bridgeId: string;};@@ -41,22 +40,20 @@ type Props = BaseModalProps<{ identity: LinkedIdentity }> & ClaimIdentityModalAr* never posted in.*/export const ClaimIdentityModal = observer(function ClaimIdentityModal({- serverId: overrideServerId,+ workspaceId,bridgeId,onSuccess,onClose,}: Props) {- const serverId = overrideServerId ?? switchServersStore.activeServerId ?? '';// The search raises the close guard while a claim or unlink is in flight, so// this is also the signal that leaving now would abandon one.const { hasActiveCloseGuard } = useModalContext();- const { identities } = useMyIdentities(serverId || null);+ const { identities } = useMyIdentities(workspaceId);const bridgesQuery = useQuery({- queryKey: ['remote-bridges', serverId],- queryFn: () => rpc.switchServers.listRemoteBridges(serverId),- enabled: !!serverId,+ queryKey: ['remote-bridges', workspaceId],+ queryFn: () => rpc.workspaces.listBridges(workspaceId),});const bridges = bridgesQuery.data ?? [];@@ -80,15 +77,9 @@ export const ClaimIdentityModal = observer(function ClaimIdentityModal({Tell Switch which account is you, so your own agents can tell it's you.</p>- {!serverId && (- <p className="text-xs text-destructive">- No Switch server is selected. Choose a server in the sidebar first.- </p>- )}-{bridgeIsGone && (<p className="text-xs text-destructive">- That messaging app is no longer connected to this server.+ That messaging app is no longer connected to this workspace.</p>)}@@ -105,7 +96,7 @@ export const ClaimIdentityModal = observer(function ClaimIdentityModal({)}<BridgeIdentitySearch- serverId={serverId}+ workspaceId={workspaceId}bridgeId={bridgeId}bridgeDisplayName={selectedBridge?.displayName ?? 'the workspace'}platform={bridgePlatformLabel(selectedBridge?.type ?? '')}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsxindex 28f13a321..507a77d81 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsx@@ -2,6 +2,7 @@ import { useQuery } from '@tanstack/react-query';import { ExternalLink } from 'lucide-react';import { observer } from 'mobx-react-lite';import { useCallback, useMemo, useState } from 'react';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';import { bridgePlatformLabel, bridgeSetupDocsUrl } from '@renderer/lib/components/bridge-platform';import { failureText } from '@renderer/lib/errors/describe-failure';@@ -28,7 +29,9 @@ import {} from '@renderer/lib/ui/select';import { cn } from '@renderer/utils/utils';import type { CreateBridgeResult } from '@shared/core/switch-servers/switch-servers';+import { InstallMessagingAppPanel } from './InstallMessagingAppPanel';import { switchServersStore } from './switch-servers-store';+import { administersWorkspaceInScope } from './workspace-admin';type ConnectMessagingAppModalArgs = {/** Attach to this server instead of the active one. */@@ -55,8 +58,9 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppModconst { setCloseGuard } = useModalContext();const serverId = overrideServerId ?? switchServersStore.activeServerId ?? '';+ const workspaceId = workspacesStore.idOnServerInScope(serverId || null);const server = switchServersStore.servers.find((s) => s.id === serverId) ?? null;- const isAdmin = switchServersStore.statusFor(serverId)?.user?.role === 'admin';+ const isAdmin = administersWorkspaceInScope(serverId);const [typeKey, setTypeKey] = useState<string | null>(null);const [displayName, setDisplayName] = useState('');@@ -73,11 +77,23 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppModconst [error, setError] = useState<string | null>(null);const typesQuery = useQuery({- queryKey: ['remote-bridge-types', serverId],- queryFn: () => rpc.switchServers.listRemoteBridgeTypes(serverId),- enabled: !!serverId,+ queryKey: ['remote-bridge-types', workspaceId],+ queryFn: () => rpc.workspaces.listBridgeTypes(workspaceId as string),+ enabled: workspaceId !== null,});+ // Asked only of someone who may install: the route refuses everyone else, and+ // for them the dialog already says why nothing here will work.+ const installableQuery = useQuery({+ queryKey: ['installable-messaging-apps', workspaceId],+ queryFn: () => rpc.workspaces.listInstallablePlatforms(workspaceId as string),+ enabled: workspaceId !== null && isAdmin,+ });+ const installable = installableQuery.data ?? [];+ const [useOwnApp, setUseOwnApp] = useState(false);+ const offerInstall = installable.length > 0 && !useOwnApp;+ const showForm = !offerInstall && !(isAdmin && installableQuery.isLoading);+const types = useMemo(() => typesQuery.data ?? [], [typesQuery.data]);const selectedType = types.find((t) => t.key === typeKey) ?? null;// Unknown until the type list has loaded; assume supported so the checkbox@@ -113,7 +129,13 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppModreturn !(value ?? '').trim();});const canSubmit =- !!serverId && isAdmin && !!selectedType && !!trimmedName && !missingRequired && !isSubmitting;+ showForm &&+ workspaceId !== null &&+ isAdmin &&+ !!selectedType &&+ !!trimmedName &&+ !missingRequired &&+ !isSubmitting;const handleSubmit = useCallback(async () => {if (!canSubmit || !selectedType) return;@@ -135,8 +157,8 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppModif (trimmed) connectionConfig[field.key] = trimmed;}- const result = await rpc.switchServers.createBridge({- serverId,+ const result = await rpc.workspaces.createBridge({+ workspaceId: workspaceId as string,bridgeType: selectedType.key,displayName: trimmedName,connectionConfig,@@ -165,7 +187,7 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppMod}, [canSubmit,selectedType,- serverId,+ workspaceId,trimmedName,config,setAsDefault,@@ -175,6 +197,20 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppModsetCloseGuard,]);+ const handleInstalled = useCallback(+ (platform: string, bridge: { bridgeId: string; displayName: string }) => {+ onSuccess({+ ...bridge,+ // Unknown only if the type list failed to load; offering the link step+ // then costs a search that finds nothing, where skipping it would hide+ // a step that works.+ directorySearchSupported:+ types.find((t) => t.key === platform)?.directorySearchSupported ?? true,+ });+ },+ [onSuccess, types]+ );+return (<><DialogHeader showCloseButton={false}>@@ -190,42 +226,79 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppMod{server && !isAdmin && (<p className="text-xs text-destructive">- Connecting a messaging app requires an admin account on this server. You are signed in- without admin rights, so the server would reject this.+ Connecting a messaging app requires an owner or admin of this workspace. You are a+ member without admin rights, so the server would reject this.</p>)}- <Field>- <FieldLabel>Messaging app</FieldLabel>- <Select- value={typeKey ?? ''}- onValueChange={(next) => handleTypeChange(next ?? null)}- disabled={typesQuery.isLoading || types.length === 0 || !isAdmin}- >- <SelectTrigger>- <SelectValue placeholder={typesQuery.isLoading ? 'Loading…' : 'Choose a platform'}>- {selectedType ? bridgePlatformLabel(selectedType.key) : undefined}- </SelectValue>- </SelectTrigger>- <SelectContent>- {types.map((type) => (- <SelectItem key={type.key} value={type.key}>- <span className="flex items-center gap-2">- {hasBridgeIcon(type.key) && <BridgeIcon bridgeType={type.key} size={16} />}- {bridgePlatformLabel(type.key)}- </span>- </SelectItem>- ))}- </SelectContent>- </Select>- {typesQuery.isError && (- <p className="mt-1 text-xs text-destructive">- {failureText(typesQuery.error, 'Could not load the available messaging apps.')}- </p>- )}- </Field>+ {installableQuery.isError && (+ <p className="text-xs text-destructive">+ {failureText(+ installableQuery.error,+ 'Could not check which messaging apps this server can add for you, so only connecting your own app is offered.'+ )}+ </p>+ )}++ {isAdmin && installableQuery.isLoading && (+ <p className="text-xs text-foreground-muted">Loading…</p>+ )}++ {offerInstall && workspaceId !== null && (+ <>+ {installable.map((platform) => (+ <InstallMessagingAppPanel+ key={platform}+ workspaceId={workspaceId}+ platform={platform}+ onInstalled={(bridge) => handleInstalled(platform, bridge)}+ />+ ))}+ <button+ type="button"+ className="w-fit text-xs text-foreground-muted underline underline-offset-2 hover:text-foreground"+ onClick={() => setUseOwnApp(true)}+ >+ Use your own app instead+ </button>+ </>+ )}++ {showForm && (+ <Field>+ <FieldLabel>Messaging app</FieldLabel>+ <Select+ value={typeKey ?? ''}+ onValueChange={(next) => handleTypeChange(next ?? null)}+ disabled={typesQuery.isLoading || types.length === 0 || !isAdmin}+ >+ <SelectTrigger>+ <SelectValue+ placeholder={typesQuery.isLoading ? 'Loading…' : 'Choose a platform'}+ >+ {selectedType ? bridgePlatformLabel(selectedType.key) : undefined}+ </SelectValue>+ </SelectTrigger>+ <SelectContent>+ {types.map((type) => (+ <SelectItem key={type.key} value={type.key}>+ <span className="flex items-center gap-2">+ {hasBridgeIcon(type.key) && <BridgeIcon bridgeType={type.key} size={16} />}+ {bridgePlatformLabel(type.key)}+ </span>+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ {typesQuery.isError && (+ <p className="mt-1 text-xs text-destructive">+ {failureText(typesQuery.error, 'Could not load the available messaging apps.')}+ </p>+ )}+ </Field>+ )}- {selectedType && (+ {showForm && selectedType && (<><Field><FieldLabel>Name</FieldLabel>@@ -357,9 +430,11 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppMod<Button variant="outline" onClick={onClose} disabled={isSubmitting}>Cancel</Button>- <ConfirmButton onClick={() => void handleSubmit()} disabled={!canSubmit}>- {isSubmitting ? 'Connecting…' : 'Connect'}- </ConfirmButton>+ {showForm && (+ <ConfirmButton onClick={() => void handleSubmit()} disabled={!canSubmit}>+ {isSubmitting ? 'Connecting…' : 'Connect'}+ </ConfirmButton>+ )}</DialogFooter></>);@@ -371,7 +446,7 @@ function messageFor(result: Exclude<CreateBridgeResult, { kind: 'created' }>): scase 'unauthenticated':return 'Your session for this server expired. Sign in again, then retry.';case 'forbidden':- return 'Connecting a messaging app requires an admin account on this server.';+ return 'Connecting a messaging app requires an owner or admin of this workspace.';case 'invalid':// The gateway validated the credentials against the platform's own config// model, so its wording is more specific than anything we could invent.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.tsxindex 759887001..c16adda19 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@@ -4,6 +4,7 @@ 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 { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import {AgentPickerRow,ChosenAgentTile,@@ -49,6 +50,7 @@ export const CreateRoomModal = observer(function CreateRoomModal({// asking again would let the user create a room somewhere they are not// looking, and then wonder where it went.const serverId = overrideServerId ?? switchServersStore.activeServerId ?? '';+ const workspaceId = workspacesStore.idOnServerInScope(serverId || null);const server = switchServersStore.servers.find((s) => s.id === serverId) ?? null;const [name, setName] = useState('');@@ -61,20 +63,20 @@ export const CreateRoomModal = observer(function CreateRoomModal({const [error, setError] = useState<string | null>(null);const bridgesQuery = useQuery({- queryKey: ['remote-bridges', serverId],- queryFn: () => rpc.switchServers.listRemoteBridges(serverId),- enabled: !!serverId,+ queryKey: ['remote-bridges', workspaceId],+ queryFn: () => rpc.workspaces.listBridges(workspaceId as string),+ enabled: workspaceId !== null,});const agentsQuery = useQuery({- queryKey: ['remote-agents', serverId],- queryFn: () => rpc.switchServers.listRemoteAgents(serverId),- enabled: !!serverId,+ queryKey: ['remote-agents', workspaceId],+ queryFn: () => rpc.workspaces.listAgents(workspaceId as string),+ enabled: workspaceId !== null,});// Which account on each app is the person creating the room. A room on an app// they have not claimed an account on works, but their own messages in it are// from a stranger as far as the agents are concerned — so it is said here,// while the app is being chosen, rather than discovered later.- const { identities } = useMyIdentities(serverId);+ const { identities } = useMyIdentities(workspaceId);/*** Only agents this install registered on the server.@@ -86,7 +88,11 @@ export const CreateRoomModal = observer(function CreateRoomModal({* follow.*/const invitableAgents = (agentsQuery.data ?? []).filter((remote) =>- agentsStore.agentsOnServer(serverId).some((local) => local.switchAgentId === remote.id)+ workspaceId === null+ ? false+ : agentsStore+ .agentsInWorkspace(workspaceId)+ .some((local) => local.switchAgentId === remote.id));// Only a running bridge can back a new room, and creating a room here means@@ -111,7 +117,11 @@ export const CreateRoomModal = observer(function CreateRoomModal({const trimmedName = name.trim();const trimmedDescription = description.trim();const canSubmit =- !!serverId && !!trimmedName && !!trimmedDescription && !!selectedBridge && !isSubmitting;+ workspaceId !== null &&+ !!trimmedName &&+ !!trimmedDescription &&+ !!selectedBridge &&+ !isSubmitting;const handleSubmit = useCallback(async () => {if (!canSubmit || !selectedBridge) return;@@ -120,8 +130,8 @@ export const CreateRoomModal = observer(function CreateRoomModal({setError(null);try {- const result = await rpc.switchServers.createRoom({- serverId,+ const result = await rpc.workspaces.createRoom({+ workspaceId: workspaceId as string,name: trimmedName,description: trimmedDescription,instructions: instructions.trim() || undefined,@@ -160,7 +170,7 @@ export const CreateRoomModal = observer(function CreateRoomModal({}, [canSubmit,selectedBridge,- serverId,+ workspaceId,trimmedName,trimmedDescription,instructions,@@ -286,7 +296,7 @@ export const CreateRoomModal = observer(function CreateRoomModal({<ChosenAgentTilekey={agent.id}agent={agent}- subtitle={agentProviderLabelFor(agent.id, serverId)}+ subtitle={agentProviderLabelFor(agent.id, workspaceId)}onRemove={() =>setAgents((current) => current.filter((a) => a.id !== agent.id))}@@ -300,7 +310,10 @@ export const CreateRoomModal = observer(function CreateRoomModal({onPick={(next) => setAgents((current) => [...current, next])}searchText={(item) => item.name}renderItem={(item) => (- <AgentPickerRow agent={item} subtitle={agentProviderLabelFor(item.id, serverId)} />+ <AgentPickerRow+ agent={item}+ subtitle={agentProviderLabelFor(item.id, workspaceId)}+ />)}disabled={agentsQuery.isLoading}placeholder={agentsQuery.isLoading ? 'Loading agents…' : 'Search agents to add...'}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/DisconnectMessagingAppModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/DisconnectMessagingAppModal.tsxindex dad51f0b5..aea92eeed 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/DisconnectMessagingAppModal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/DisconnectMessagingAppModal.tsx@@ -17,7 +17,7 @@ import { Input } from '@renderer/lib/ui/input';import type { DeleteBridgeResult } from '@shared/core/switch-servers/switch-servers';type DisconnectMessagingAppModalArgs = {- serverId: string;+ workspaceId: string;bridgeId: string;bridgeDisplayName: string;};@@ -25,7 +25,7 @@ type DisconnectMessagingAppModalArgs = {type Props = BaseModalProps<void> & DisconnectMessagingAppModalArgs;/**- * Confirm disconnecting a messaging app from a Switch server (CHOO-2137).+ * Confirm disconnecting a messaging app from a workspace (CHOO-2137).** "Disconnect" undersells it: the server deletes every Switch room on the* bridge before removing the bridge itself, so this is the most destructive@@ -40,7 +40,7 @@ type Props = BaseModalProps<void> & DisconnectMessagingAppModalArgs;export const DisconnectMessagingAppModal = observer(function DisconnectMessagingAppModal({bridgeDisplayName,bridgeId,- serverId,+ workspaceId,onSuccess,onClose,}: Props) {@@ -55,7 +55,7 @@ export const DisconnectMessagingAppModal = observer(function DisconnectMessagingsetIsDeleting(true);setError(null);try {- const result = await rpc.switchServers.deleteBridge({ serverId, bridgeId });+ const result = await rpc.workspaces.deleteBridge({ workspaceId, bridgeId });if (result.kind !== 'deleted') {setError(messageFor(result));setIsDeleting(false);@@ -66,7 +66,7 @@ export const DisconnectMessagingAppModal = observer(function DisconnectMessagingsetError(failureText(cause, 'Could not disconnect the messaging app.'));setIsDeleting(false);}- }, [typeConfirmed, serverId, bridgeId, onSuccess]);+ }, [typeConfirmed, workspaceId, bridgeId, onSuccess]);return (<>@@ -130,7 +130,7 @@ function messageFor(result: Exclude<DeleteBridgeResult, { kind: 'deleted' }>): scase 'unauthenticated':return 'Your session for this server expired. Sign in again, then retry.';case 'forbidden':- return 'Disconnecting a messaging app requires an admin account on this server.';+ return 'Disconnecting a messaging app requires an owner or admin of this workspace.';case 'not-found':return 'That messaging app is no longer connected to this server.';case 'error':diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/InstallMessagingAppPanel.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/InstallMessagingAppPanel.tsxnew file mode 100644index 000000000..ea4e45a21--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/InstallMessagingAppPanel.tsx@@ -0,0 +1,119 @@+import { useQuery } from '@tanstack/react-query';+import { Loader2 } from 'lucide-react';+import { useEffect, useState } from 'react';+import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';+import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';+import { failureText } from '@renderer/lib/errors/describe-failure';+import { rpc } from '@renderer/lib/ipc';+import { openExternalUrl } from '@renderer/lib/open-external';+import { Button } from '@renderer/lib/ui/button';++/** How often to look for the new connection while the user is in the browser. */+export const INSTALL_POLL_INTERVAL_MS = 3000;++type InstalledBridge = { bridgeId: string; displayName: string };++type Phase =+ | { kind: 'idle' }+ | { kind: 'starting' }+ | { kind: 'waiting'; knownBridgeIds: ReadonlySet<string>; authorizeUrl: string };++type Props = {+ workspaceId: string;+ platform: string;+ onInstalled: (bridge: InstalledBridge) => void;+};++/**+ * Install the deployment's own app for `platform` into the workspace.+ *+ * The platform's consent screen runs in the user's browser and the server+ * finishes the install on its public callback, so nothing is handed back to+ * Switch Console. The only sign it worked is a new bridge of that platform, so+ * the panel notes which bridges existed before and watches for one it has not+ * seen.+ */+export function InstallMessagingAppPanel({ workspaceId, platform, onInstalled }: Props) {+ const label = bridgePlatformLabel(platform);+ const [phase, setPhase] = useState<Phase>({ kind: 'idle' });+ const [error, setError] = useState<string | null>(null);++ const waiting = phase.kind === 'waiting';+ const bridgesQuery = useQuery({+ queryKey: ['messaging-app-install-wait', workspaceId, platform],+ queryFn: () => rpc.workspaces.listBridges(workspaceId),+ enabled: waiting,+ refetchInterval: waiting ? INSTALL_POLL_INTERVAL_MS : false,+ gcTime: 0,+ });++ useEffect(() => {+ if (phase.kind !== 'waiting' || !bridgesQuery.data) return;+ const installed = bridgesQuery.data.find(+ (b) => b.type === platform && !phase.knownBridgeIds.has(b.id)+ );+ if (installed) onInstalled({ bridgeId: installed.id, displayName: installed.displayName });+ }, [phase, bridgesQuery.data, platform, onInstalled]);++ const start = async () => {+ setPhase({ kind: 'starting' });+ setError(null);+ try {+ const before = await rpc.workspaces.listBridges(workspaceId);+ const authorizeUrl = await rpc.workspaces.beginMessagingAppInstall({ workspaceId, platform });+ const opened = await openExternalUrl(authorizeUrl, `Could not open ${label}`);+ if (!opened) {+ setPhase({ kind: 'idle' });+ return;+ }+ setPhase({ kind: 'waiting', knownBridgeIds: new Set(before.map((b) => b.id)), authorizeUrl });+ } catch (cause) {+ setPhase({ kind: 'idle' });+ setError(failureText(cause, `Could not start adding ${label}.`));+ }+ };++ if (phase.kind === 'waiting') {+ return (+ <div className="flex flex-col gap-2">+ <p className="flex items-center gap-2 text-sm">+ <Loader2 className="size-4 animate-spin" />+ Waiting for {label}…+ </p>+ <p className="text-xs text-foreground-muted">+ Approve the Switch app in the browser window that opened. This connection appears here as+ soon as {label} confirms it.+ </p>+ <button+ type="button"+ className="w-fit text-xs text-foreground-muted underline underline-offset-2 hover:text-foreground"+ onClick={() => void openExternalUrl(phase.authorizeUrl, `Could not open ${label}`)}+ >+ Open the {label} page again+ </button>+ {bridgesQuery.isError && (+ <p className="text-xs text-destructive">+ {failureText(+ bridgesQuery.error,+ `Could not check whether ${label} is connected yet; still trying`+ )}+ </p>+ )}+ </div>+ );+ }++ return (+ <div className="flex flex-col gap-2">+ <p className="text-xs text-foreground-muted">+ Adds this Switch server’s own {label} app to your {label} workspace. {label} asks you to+ approve it in your browser; there are no tokens to copy.+ </p>+ <Button className="w-fit" onClick={() => void start()} disabled={phase.kind === 'starting'}>+ {hasBridgeIcon(platform) && <BridgeIcon bridgeType={platform} size={16} />}+ {phase.kind === 'starting' ? `Opening ${label}…` : `Add to ${label}`}+ </Button>+ {error && <p className="text-xs text-destructive">{error}</p>}+ </div>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsxindex eb09a49d1..cfa219ecd 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx@@ -14,6 +14,7 @@ import {} from 'lucide-react';import { observer } from 'mobx-react-lite';import { useEffect, useMemo, useState } from 'react';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';import { failureText } from '@renderer/lib/errors/describe-failure';@@ -46,10 +47,11 @@ import {import { switchRoomsStore } from './switch-rooms-store';import { switchServersStore } from './switch-servers-store';import { useMyIdentities } from './use-my-identities';+import { administersWorkspaceInScope } from './workspace-admin';/*** The messaging apps bridged to a server, which account in each one is the- * signed-in user, and — for an admin — the way to connect another+ * signed-in user, and — for a workspace owner or admin — the way to connect another* (CHOO-1784, CHOO-2137).** One row per app: its name with the account you have claimed on it underneath,@@ -61,7 +63,7 @@ import { useMyIdentities } from './use-my-identities';* Listing is offered on every server type, not just managed ones: a bridge is* registered through the server's own admin API, so there is nothing* Switch Console has to own locally for this to work. Attaching is gated on the- * signed-in user being an admin, because the endpoint is; linking an account is+ * signed-in user administering the workspace, because the endpoint is; linking an account is* not, because claiming an identity is something every user does for themselves.*//** Why a server has messaging apps at all: the agents registered here become@@ -90,15 +92,16 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({const showConnectMessagingApp = useShowModal('connectMessagingAppModal');const showClaimIdentity = useShowModal('claimIdentityModal');const showDisconnectMessagingApp = useShowModal('disconnectMessagingAppModal');- const isAdmin = switchServersStore.statusFor(serverId)?.user?.role === 'admin';+ const workspaceId = workspacesStore.idOnServerInScope(serverId);+ const isAdmin = administersWorkspaceInScope(serverId);// Only a stack Switch Console runs has a chat whose credentials it generated and// can therefore show; anyone else's Mattermost is their own to hand out.const isManaged = !!switchServersStore.servers.find((s) => s.id === serverId)?.managed;const bridgesQuery = useQuery({- queryKey: ['remote-bridges', serverId],- queryFn: () => rpc.switchServers.listRemoteBridges(serverId),- enabled: !!serverId,+ queryKey: ['remote-bridges', workspaceId],+ queryFn: () => rpc.workspaces.listBridges(workspaceId as string),+ enabled: workspaceId !== null,});const bridges = useMemo(() => orderBridges(bridgesQuery.data ?? []), [bridgesQuery.data]);@@ -107,7 +110,7 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({identities,error: identitiesError,refresh: refreshIdentities,- } = useMyIdentities(serverId);+ } = useMyIdentities(workspaceId);// Whose claim to drop when unlinking. Every account here is one the signed-in// user claimed, and other people may hold the same one — so name the user// rather than let the server infer it. Null until the session is read back,@@ -122,9 +125,9 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({// agent's policy should stop the warning on the next look, not a minute later.const anyUnlinked = hasUnlinkedMessagingApp(bridges, identities);const ownerAgentsQuery = useQuery({- queryKey: ['owns-owner-addressed-agent', serverId],- queryFn: () => rpc.switchServers.ownsOwnerAddressedAgent(serverId),- enabled: !!serverId && anyUnlinked,+ queryKey: ['owns-owner-addressed-agent', workspaceId],+ queryFn: () => rpc.workspaces.ownsOwnerAddressedAgent(workspaceId as string),+ enabled: workspaceId !== null && anyUnlinked,});// The probe failing costs no data on screen, only the warning — so it is// logged rather than shown, and the card does not warn on a guess.@@ -132,11 +135,11 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({useEffect(() => {if (ownerAgentsError) {log.warn('Could not check for owner-addressed agents', {- serverId,+ workspaceId,error: ownerAgentsError,});}- }, [ownerAgentsError, serverId]);+ }, [ownerAgentsError, workspaceId]);const unrecognisedIn = unrecognisedMessagingApps({bridges,@@ -151,11 +154,12 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({const [toggleError, setToggleError] = useState<string | null>(null);const handleToggleChannelCreation = async (bridge: RemoteBridge, enabled: boolean) => {+ if (workspaceId === null) return;setSavingBridgeId(bridge.id);setToggleError(null);try {- const result = await rpc.switchServers.updateBridge({- serverId,+ const result = await rpc.workspaces.updateBridge({+ workspaceId,bridgeId: bridge.id,channelCreationEnabled: enabled,});@@ -163,7 +167,7 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({setToggleError(`Could not update ${bridge.displayName}: ${messageForUpdate(result)}`);return;}- await queryClient.invalidateQueries({ queryKey: ['remote-bridges', serverId] });+ await queryClient.invalidateQueries({ queryKey: ['remote-bridges', workspaceId] });} catch (cause) {setToggleError(failureText(cause, `Could not update ${bridge.displayName}.`));} finally {@@ -206,7 +210,7 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({onSuccess: ({ bridgeId, displayName, directorySearchSupported }) => {// Refresh the bridge list everywhere it is consumed — this// card and the room-creation picker share the query key.- void queryClient.invalidateQueries({ queryKey: ['remote-bridges', serverId] });+ void queryClient.invalidateQueries({ queryKey: ['remote-bridges', workspaceId] });void switchRoomsStore.refreshRoomState();// Step 2 of connecting a workspace: say which account in it// is yours (CHOO-2137). Offered here because this is the one@@ -222,8 +226,11 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({// has messaged the app and there is a name to pick. Say that,// rather than closing on nothing and leaving the step looking// forgotten.- if (shouldOfferIdentityLinkOnConnect({ directorySearchSupported })) {- showClaimIdentity({ serverId, bridgeId });+ if (+ workspaceId !== null &&+ shouldOfferIdentityLinkOnConnect({ directorySearchSupported })+ ) {+ showClaimIdentity({ workspaceId, bridgeId });return;}const note = identityLinkOrderingNote({ displayName, directorySearchSupported });@@ -273,13 +280,14 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({<p className="mt-3 text-xs text-foreground-muted">{isAdmin? 'No messaging app is connected, so rooms created here would be unreachable. Connect one to get started.'- : 'No messaging app is connected. An admin on this server can connect one.'}+ : 'No messaging app is connected. An owner or admin of this workspace can connect one.'}</p>) : (<div className="mt-2 flex flex-col">{bridges.map((bridge) => (<MessagingAppRowkey={bridge.id}+ workspaceId={workspaceId}serverId={serverId}bridge={bridge}/* Nothing is drawn in the identity column until the list@@ -295,22 +303,23 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({onToggleChannelCreation={(enabled) =>void handleToggleChannelCreation(bridge, enabled)}- onDisconnect={() =>+ onDisconnect={() => {+ if (workspaceId === null) return;showDisconnectMessagingApp({- serverId,+ workspaceId,bridgeId: bridge.id,bridgeDisplayName: bridge.displayName,onSuccess: () => {void queryClient.invalidateQueries({- queryKey: ['remote-bridges', serverId],+ queryKey: ['remote-bridges', workspaceId],});// The rooms on that bridge went with it, so the sidebar// is stale in a way the bridge list alone does not// repair.void switchRoomsStore.refreshRoomState();},- })- }+ });+ }}/>))}</div>@@ -331,6 +340,7 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({* disconnecting it — is in the menu.*/export function MessagingAppRow({+ workspaceId,serverId,bridge,identities,@@ -342,9 +352,13 @@ export function MessagingAppRow({onToggleChannelCreation,onDisconnect,}: {+ /** Null while this install has not resolved the server's workspace; the+ * identity actions are the only thing that needs it, and they wait. */+ workspaceId: string | null;+ /** Only for the bundled chat's sign-in, which is about the gateway. */serverId: string;bridge: RemoteBridge;- /** Accounts the user has claimed on this server, or null while unknown. */+ /** Accounts the user has claimed in this workspace, or null while unknown. */identities: LinkedIdentity[] | null;currentUserId: string | null;onReleased: () => void;@@ -361,14 +375,18 @@ export function MessagingAppRow({const identity = identities?.find((i) => i.bridgeId === bridge.id) ?? null;const platform = bridgePlatformLabel(bridge.type);- const claim = () => showClaimIdentity({ serverId, bridgeId: bridge.id });+ const claim = () => {+ if (workspaceId === null) return;+ showClaimIdentity({ workspaceId, bridgeId: bridge.id });+ };const release = async (identityId: string) => {+ if (workspaceId === null) return;setReleasing(true);setReleaseError(null);try {- await rpc.switchServers.releaseBridgeIdentity({- serverId,+ await rpc.workspaces.releaseBridgeIdentity({+ workspaceId,bridgeId: bridge.id,identityId,userId: currentUserId,@@ -397,7 +415,7 @@ export function MessagingAppRow({const channelsLockedReason = !bridge.channelCreationSupported? `${platform} cannot create channels from Switch. Make the chat in the app and add the bot to it.`: !isAdmin- ? 'Only an admin on this server can change this.'+ ? 'Only an owner or admin of this workspace can change this.': null;return (@@ -561,7 +579,7 @@ function messageForUpdate(result: { kind: string; message?: string }): string {case 'unauthenticated':return 'Your session for this server expired. Sign in again, then retry.';case 'forbidden':- return 'This requires an admin account on this server.';+ return 'This requires an owner or admin of this workspace.';default:return result.message ?? 'The server rejected the change.';}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/agent-server-picker.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/agent-server-picker.tsxindex c3437f11c..e28b9d554 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/agent-server-picker.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/agent-server-picker.tsx@@ -2,6 +2,7 @@ import { useQuery } from '@tanstack/react-query';import { CheckCircle2, CircleAlert, Loader2 } from 'lucide-react';import { observer } from 'mobx-react-lite';import { useEffect } from 'react';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { rpc } from '@renderer/lib/ipc';import {Select,@@ -15,7 +16,7 @@ import type { AgentVerifyResult } from '@shared/core/switch-servers/switch-serveimport { switchServersStore } from './switch-servers-store';/** Verification phase the picker reports up so a parent can gate submission. */-export type ServerVerifyState = 'idle' | 'checking' | AgentVerifyResult;+export type ServerVerifyState = 'idle' | 'checking' | 'no-workspace' | AgentVerifyResult;interface AgentServerPickerProps {/** The Switch agent id to verify against the chosen server. */@@ -50,17 +51,24 @@ export const AgentServerPicker = observer(function AgentServerPicker({const servers = switchServersStore.servers;+ const workspaceId = workspacesStore.idOnServerInScope(serverId);const verifyQuery = useQuery({- queryKey: ['verifyAgent', serverId, switchAgentId],- queryFn: () => rpc.switchServers.verifyAgent({ serverId: serverId!, agentId: switchAgentId }),- enabled: !!serverId && !!switchAgentId,+ queryKey: ['verifyAgent', workspaceId, switchAgentId],+ queryFn: () =>+ rpc.workspaces.verifyAgent({ workspaceId: workspaceId!, agentId: switchAgentId }),+ enabled: !!workspaceId && !!switchAgentId,});+ // A disabled query reports `isPending` forever, so a server with no workspace+ // to verify against has to be its own state: read as "checking" it would spin+ // for as long as the dialog is open and never say why submit stays shut.const state: ServerVerifyState = !serverId? 'idle'- : verifyQuery.isPending- ? 'checking'- : (verifyQuery.data ?? 'checking');+ : workspaceId === null+ ? 'no-workspace'+ : verifyQuery.isPending+ ? 'checking'+ : (verifyQuery.data ?? 'checking');useEffect(() => {onVerifyStateChange(state);@@ -117,6 +125,13 @@ function VerifyStatus({ state, serverName }: { state: ServerVerifyState; serverN</Row>);}+ if (state === 'no-workspace') {+ return (+ <Row icon={<CircleAlert className="size-3.5 text-amber-500" />}>+ {serverName} has no workspace to register this agent in yet.+ </Row>+ );+ }if (state === 'unauthenticated') {return (<Row icon={<CircleAlert className="size-3.5 text-amber-500" />}>diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/bridge-identity-search.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/bridge-identity-search.tsxindex 0439ea870..52e8c8a8d 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/bridge-identity-search.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/bridge-identity-search.tsx@@ -2,6 +2,7 @@ import { useQuery, useQueryClient } from '@tanstack/react-query';import { CircleAlert } from 'lucide-react';import { observer } from 'mobx-react-lite';import { useState } from 'react';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { failureText } from '@renderer/lib/errors/describe-failure';import { useDebounce } from '@renderer/lib/hooks/useDebounce';import { rpc } from '@renderer/lib/ipc';@@ -38,7 +39,7 @@ const MIN_QUERY_LENGTH = 2;* written first.*/export const BridgeIdentitySearch = observer(function BridgeIdentitySearch({- serverId,+ workspaceId,bridgeId,bridgeDisplayName,platform,@@ -46,9 +47,9 @@ export const BridgeIdentitySearch = observer(function BridgeIdentitySearch({autoFocus,onClaimed,}: {- serverId: string;+ workspaceId: string;bridgeId: string;- /** The workspace being searched — two connections on the same platform can+ /** The bridge being searched — two connections on the same platform can* exist, and only the name tells them apart. */bridgeDisplayName: string;/** The platform as a person names it, for prose about what is searchable. */@@ -59,21 +60,24 @@ export const BridgeIdentitySearch = observer(function BridgeIdentitySearch({}) {const { setCloseGuard } = useModalContext();const queryClient = useQueryClient();- const currentUserId = switchServersStore.statusFor(serverId)?.user?.id ?? null;+ const serverId = workspacesStore.serverIdFor(workspaceId);+ const currentUserId = serverId+ ? (switchServersStore.statusFor(serverId)?.user?.id ?? null)+ : null;const [search, setSearch] = useState('');const [claiming, setClaiming] = useState<string | null>(null);const [releasing, setReleasing] = useState<string | null>(null);const [error, setError] = useState<string | null>(null);- const { refresh: refreshIdentities } = useMyIdentities(serverId || null);+ const { refresh: refreshIdentities } = useMyIdentities(workspaceId || null);const debouncedQuery = useDebounce(search.trim(), SEARCH_DEBOUNCE_MS);- const searchable = !!serverId && debouncedQuery.length >= MIN_QUERY_LENGTH;+ const searchable = !!workspaceId && debouncedQuery.length >= MIN_QUERY_LENGTH;const directoryQuery = useQuery({- queryKey: ['bridge-directory', serverId, bridgeId, debouncedQuery],+ queryKey: ['bridge-directory', workspaceId, bridgeId, debouncedQuery],queryFn: () =>- rpc.switchServers.searchBridgeDirectory({ serverId, bridgeId, query: debouncedQuery }),+ rpc.workspaces.searchBridgeDirectory({ workspaceId, bridgeId, query: debouncedQuery }),enabled: searchable,});@@ -82,8 +86,8 @@ export const BridgeIdentitySearch = observer(function BridgeIdentitySearch({setCloseGuard(true);setError(null);try {- const result = await rpc.switchServers.claimBridgeIdentity({- serverId,+ const result = await rpc.workspaces.claimBridgeIdentity({+ workspaceId,bridgeId,externalUserId: person.externalUserId,username: person.username,@@ -111,14 +115,16 @@ export const BridgeIdentitySearch = observer(function BridgeIdentitySearch({setCloseGuard(true);setError(null);try {- await rpc.switchServers.releaseBridgeIdentity({- serverId,+ await rpc.workspaces.releaseBridgeIdentity({+ workspaceId,bridgeId,identityId: person.knownExternalUserId,userId: currentUserId,});refreshIdentities();- await queryClient.invalidateQueries({ queryKey: ['bridge-directory', serverId, bridgeId] });+ await queryClient.invalidateQueries({+ queryKey: ['bridge-directory', workspaceId, bridgeId],+ });} catch (cause) {setError(failureText(cause, 'Could not unlink this account.'));} finally {diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-accounts-step.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-accounts-step.tsxindex 05fa1b28b..495a98e58 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-accounts-step.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-accounts-step.tsx@@ -2,15 +2,15 @@ import { useQuery } from '@tanstack/react-query';import { Check, Link2, MessageSquare, TriangleAlert } from 'lucide-react';import { observer } from 'mobx-react-lite';import { useState } from 'react';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';import { failureText } from '@renderer/lib/errors/describe-failure';import { rpc } from '@renderer/lib/ipc';import { Button } from '@renderer/lib/ui/button';import { ConfirmButton } from '@renderer/lib/ui/confirm-button';-import { DialogContentArea, DialogFooter } from '@renderer/lib/ui/dialog';import { Spinner } from '@renderer/lib/ui/spinner';-import { WizardStepHeader } from '@renderer/lib/ui/wizard-step-header';+import { WizardFrame } from '@renderer/lib/ui/wizard-frame';import type { LinkedIdentity, RemoteBridge } from '@shared/core/switch-servers/switch-servers';import { BridgeIdentitySearch } from './bridge-identity-search';import { connectedAppsSummary, LINK_ACCOUNTS_LATER } from './link-accounts-prose';@@ -28,14 +28,10 @@ import { useMyIdentities } from './use-my-identities';export const LinkAccountsStep = observer(function LinkAccountsStep({serverId,serverName,- step,- of,onDone,}: {serverId: string;serverName: string;- step: number;- of: number;onDone: () => void;}) {// Which app's directory is open, or null while the list is. Linking happens@@ -43,63 +39,81 @@ export const LinkAccountsStep = observer(function LinkAccountsStep({// to and give the user two Backs meaning different things.const [linking, setLinking] = useState<RemoteBridge | null>(null);+ const workspaceId = workspacesStore.idOnServerInScope(serverId);const bridgesQuery = useQuery({- queryKey: ['remote-bridges', serverId],- queryFn: () => rpc.switchServers.listRemoteBridges(serverId),+ queryKey: ['remote-bridges', workspaceId],+ queryFn: () => rpc.workspaces.listBridges(workspaceId as string),+ enabled: workspaceId !== null,});- const { identities } = useMyIdentities(serverId);+ // A disabled query never leaves its pending state, so without this the page+ // would spin on "reading the apps" forever and never say that it is not+ // reading anything. Messaging apps hang off a workspace; with none in scope+ // there is nothing to list and nothing to link an account to.+ const noWorkspace =+ workspaceId === null+ ? new Error(`Your account has no workspace on ${serverName} to link accounts in.`)+ : null;+ const { identities } = useMyIdentities(workspaceId);- if (linking) {+ // The footer's Back and the pager's back arrow are the same move, so they+ // read one const.+ const goBack = () => setLinking(null);++ if (linking && workspaceId !== null) {return (- <>- <WizardStepHeader- title={`Link your ${bridgePlatformLabel(linking.type)} account`}- step={step}- of={of}- />- <DialogContentArea className="pt-0">- <div className="flex w-full flex-col gap-4">- <p className="text-sm text-foreground-muted">- Find yourself in {linking.displayName} and tell Switch that account is you.- </p>- <BridgeIdentitySearch- serverId={serverId}- bridgeId={linking.id}- bridgeDisplayName={linking.displayName}- platform={bridgePlatformLabel(linking.type)}- directorySearchSupported={linking.directorySearchSupported}- autoFocus- onClaimed={() => setLinking(null)}- />- </div>- </DialogContentArea>- <DialogFooter>- <Button variant="outline" onClick={() => setLinking(null)}>+ <WizardFrame+ title={`Link your ${bridgePlatformLabel(linking.type)} account`}+ subtitle={null}+ pager={{+ pageName: `Link ${bridgePlatformLabel(linking.type)}`,+ onBack: goBack,+ onNext: null,+ }}+ footer={+ <Button variant="outline" onClick={goBack}>Back</Button>- </DialogFooter>- </>+ }+ >+ <div className="flex w-full flex-col gap-4">+ <p className="text-sm text-foreground-muted">+ Find yourself in {linking.displayName} and tell Switch that account is you.+ </p>+ <BridgeIdentitySearch+ workspaceId={workspaceId}+ bridgeId={linking.id}+ bridgeDisplayName={linking.displayName}+ platform={bridgePlatformLabel(linking.type)}+ directorySearchSupported={linking.directorySearchSupported}+ autoFocus+ onClaimed={() => setLinking(null)}+ />+ </div>+ </WizardFrame>);}return (- <>- <WizardStepHeader title="Link your messaging accounts" step={step} of={of} />- <DialogContentArea className="pt-0">- <BridgeList- serverName={serverName}- bridges={bridgesQuery.isSuccess ? orderBridges(bridgesQuery.data) : null}- identities={identities}- isPending={bridgesQuery.isPending}- error={bridgesQuery.isError ? bridgesQuery.error : null}- onRetry={() => void bridgesQuery.refetch()}- onLink={setLinking}- />- </DialogContentArea>- <DialogFooter>- <ConfirmButton onClick={onDone}>Done</ConfirmButton>- </DialogFooter>- </>+ <WizardFrame+ title="Link your messaging accounts"+ subtitle={null}+ /* The last page of the flow, and signing in cannot be undone by walking+ backwards, so there is nowhere for either arrow to go. */+ pager={{ pageName: 'Link accounts', onBack: null, onNext: null }}+ footer={<ConfirmButton onClick={onDone}>Done</ConfirmButton>}+ >+ <BridgeList+ serverName={serverName}+ bridges={bridgesQuery.isSuccess ? orderBridges(bridgesQuery.data) : null}+ identities={identities}+ isPending={noWorkspace === null && bridgesQuery.isPending}+ error={noWorkspace ?? (bridgesQuery.isError ? bridgesQuery.error : null)}+ onRetry={() =>+ void (noWorkspace === null ? bridgesQuery.refetch() : workspacesStore.refresh())+ }+ onLink={setLinking}+ />+ </WizardFrame>);});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-agents-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-agents-view.tsxindex d8f0c0ede..12e97c28c 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-agents-view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-agents-view.tsx@@ -13,7 +13,7 @@ import { useToast } from '@renderer/lib/hooks/use-toast';import { rpc } from '@renderer/lib/ipc';import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';import { useShowModal } from '@renderer/lib/modal/modal-provider';-import { useAgentIconUrl } from '@renderer/lib/stores/use-remote-agents';+import { useAgentIconUrl } from '@renderer/lib/stores/use-workspace-agents';import { Button } from '@renderer/lib/ui/button';import {DropdownMenu,@@ -96,7 +96,7 @@ const AgentCard = observer(function AgentCard({const sshHost = location?.data?.sshHost ?? null;const label = agent.name || 'Unnamed agent';const provider = providerDisplayName(agent.providerId);- const iconUrl = useAgentIconUrl(serverId, agent.switchAgentId);+ const iconUrl = useAgentIconUrl(agent.workspaceId, agent.switchAgentId);const gatewayUrl =agent.switchAgentId && switchRoomsStore.gatewayAgentUrl(serverId, agent.switchAgentId);diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-page.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-page.tsxindex cd80e2b23..c1d76cb5f 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-page.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-page.tsx@@ -10,6 +10,7 @@ export function ServerPage({title,description,action,+ footer,children,}: {title: string;@@ -17,20 +18,26 @@ export function ServerPage({/** Header-level action, where the page has one. Agents has none: its add* affordance is the first tile of its grid. */action?: ReactNode;+ /** A bar pinned under the page, outside the scrolling content — a pager for+ * the pages that are one step of a flow. */+ footer?: ReactNode;children: ReactNode;}) {return (- <div className="relative z-10 flex min-h-0 flex-1 flex-col overflow-auto bg-background">- <div className="mx-auto w-full max-w-4xl space-y-6 p-6">- <header className="flex items-start justify-between gap-3">- <div className="min-w-0">- <h2 className="truncate text-2xl font-semibold text-foreground">{title}</h2>- <p className="mt-1 text-sm text-foreground-muted">{description}</p>- </div>- {action && <div className="flex shrink-0 items-center gap-2">{action}</div>}- </header>- {children}+ <div className="relative z-10 flex min-h-0 flex-1 flex-col bg-background">+ <div className="flex min-h-0 flex-1 flex-col overflow-auto">+ <div className="mx-auto w-full max-w-4xl space-y-6 p-6">+ <header className="flex items-start justify-between gap-3">+ <div className="min-w-0">+ <h2 className="truncate text-2xl font-semibold text-foreground">{title}</h2>+ <p className="mt-1 text-sm text-foreground-muted">{description}</p>+ </div>+ {action && <div className="flex shrink-0 items-center gap-2">{action}</div>}+ </header>+ {children}+ </div></div>+ {footer}</div>);}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-rooms-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-rooms-view.tsxindex 5ca6828d2..0dda4c543 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-rooms-view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-rooms-view.tsx@@ -6,12 +6,13 @@ import { agentsStore } from '@renderer/features/locations/stores/agents-store';import { refreshSidebarRoomState } from '@renderer/features/sidebar/sidebar-tree-data';import { openRoom } from '@renderer/features/switch-rooms/open-room';import { roomTitle } from '@renderer/features/switch-rooms/room-labels';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { AgentAvatar } from '@renderer/lib/components/agent-avatar';import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';import { useParams } from '@renderer/lib/layout/navigation-provider';import { useShowModal } from '@renderer/lib/modal/modal-provider';-import { useRemoteAgents } from '@renderer/lib/stores/use-remote-agents';+import { useWorkspaceAgents } from '@renderer/lib/stores/use-workspace-agents';import { Button } from '@renderer/lib/ui/button';import { SearchInput } from '@renderer/lib/ui/search-input';import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';@@ -43,9 +44,10 @@ const ServerRoomsPanel = observer(function ServerRoomsPanel() {void refreshSidebarRoomState(false);}, [serverId]);- const rooms = switchRoomsStore.readableRoomsOnServer(serverId);- const signedOut = switchRoomsStore.serversNotSignedIn.some((s) => s.id === serverId);- const failed = switchRoomsStore.serversThatFailedToLoad.some((s) => s.id === serverId);+ const workspaceId = workspacesStore.idOnServerInScope(serverId);+ const rooms = workspaceId === null ? [] : switchRoomsStore.readableRoomsInWorkspace(workspaceId);+ const signedOut = switchRoomsStore.workspacesNotSignedIn.some((w) => w.id === workspaceId);+ const failed = switchRoomsStore.workspacesThatFailedToLoad.some((w) => w.id === workspaceId);const query = filter.trim().toLowerCase();const matching = query === '' ? rooms : rooms.filter((r) => r.name.toLowerCase().includes(query));@@ -56,16 +58,24 @@ const ServerRoomsPanel = observer(function ServerRoomsPanel() {title="Your Rooms"description={`Rooms on ${server?.name ?? 'this server'}. Create one, see who is in it, and where it is bridged.`}action={- <Button size="sm" disabled={signedOut} onClick={() => showCreateRoomModal({ serverId })}>+ <Button+ size="sm"+ disabled={signedOut || workspaceId === null}+ onClick={() => showCreateRoomModal({ serverId })}+ ><Plus className="size-4" />Create room</Button>}>- {/* Three ways to have no rows, and only one of them means "there are no- rooms". Saying that in the other two would send someone off to create a+ {/* Four ways to have no rows, and only one of them means "there are no+ rooms". Saying that in the others would send someone off to create aroom they already have. */}- {signedOut ? (+ {workspaceId === null ? (+ <ServerTableEmpty>+ This server has no workspace yet, so its rooms cannot be read.+ </ServerTableEmpty>+ ) : signedOut ? (<ServerTableEmpty>Sign in to {server?.name ?? 'this server'} to see its rooms.</ServerTableEmpty>@@ -98,6 +108,7 @@ const ServerRoomsPanel = observer(function ServerRoomsPanel() {key={group.key}group={group}serverId={serverId}+ workspaceId={workspaceId}// Nothing folds while a filter is on. Typing a name and being// shown a "Show 3 more" where the match is hiding is the one// moment the fold would cost more than it saves.@@ -171,10 +182,12 @@ const ROOMS_BEFORE_FOLD = 5;const MessagingAppGroup = observer(function MessagingAppGroup({group,serverId,+ workspaceId,fold,}: {group: RoomGroup;serverId: string;+ workspaceId: string;/** Whether long groups are cut short. False while the list is filtered. */fold: boolean;}) {@@ -217,7 +230,7 @@ const MessagingAppGroup = observer(function MessagingAppGroup({{open && (<div className="divide-y divide-border overflow-hidden rounded-[10px] border border-border">{shown.map((room) => (- <RoomRow key={room.id} room={room} serverId={serverId} />+ <RoomRow key={room.id} room={room} serverId={serverId} workspaceId={workspaceId} />))}{fold && group.rooms.length > ROOMS_BEFORE_FOLD && (<button@@ -240,12 +253,14 @@ const MessagingAppGroup = observer(function MessagingAppGroup({const RoomRow = observer(function RoomRow({room,serverId,+ workspaceId,}: {room: RemoteRoomSummary;serverId: string;+ workspaceId: string;}) {const members = switchRoomsStore.localMemberIds(room.id);- const { data: remoteAgents } = useRemoteAgents(serverId);+ const { data: remoteAgents } = useWorkspaceAgents(workspaceId);const remoteById = new Map((remoteAgents ?? []).map((agent) => [agent.id, agent]));const localAgents = agentsStore.agentsOnServer(serverId)diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-stat-tiles.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-stat-tiles.tsxindex 185fca734..1f1c299f8 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-stat-tiles.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-stat-tiles.tsx@@ -2,6 +2,7 @@ import { useQuery } from '@tanstack/react-query';import { observer } from 'mobx-react-lite';import { useEffect } from 'react';import { agentsStore } from '@renderer/features/locations/stores/agents-store';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { rpc } from '@renderer/lib/ipc';import { switchRoomsStore } from './switch-rooms-store';@@ -18,12 +19,14 @@ export const ServerStatTiles = observer(function ServerStatTiles({}: {serverId: string;}) {+ const workspaceId = workspacesStore.idOnServerInScope(serverId);+// Shares the key every other bridge reader uses, so the list is already in// cache by the time this renders and the tile never fetches on its own.const bridgesQuery = useQuery({- queryKey: ['remote-bridges', serverId],- queryFn: () => rpc.switchServers.listRemoteBridges(serverId),- enabled: !!serverId,+ queryKey: ['remote-bridges', workspaceId],+ queryFn: () => rpc.workspaces.listBridges(workspaceId as string),+ enabled: workspaceId !== null,});// The sidebar loads this too, but the page must not depend on the sidebar@@ -40,7 +43,11 @@ export const ServerStatTiles = observer(function ServerStatTiles({/><StatTilelabel="Your Rooms"- value={switchRoomsStore.readableRoomsOnServer(serverId).length}+ value={+ workspaceId === null+ ? null+ : switchRoomsStore.readableRoomsInWorkspace(workspaceId).length+ }/><StatTile label="Messaging apps" value={bridgesQuery.data?.length ?? null} /></div>diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.test.tsindex eb2e1fcbb..e30d987d9 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.test.ts@@ -1,20 +1,32 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { RemoteRoomSummary } from '@shared/core/switch-servers/switch-servers';-const listRemoteRooms = vi.hoisted(() => vi.fn());+const listRooms = vi.hoisted(() => vi.fn());const listAgentRooms = vi.hoisted(() => vi.fn());const serversStore = vi.hoisted(() => ({servers: [] as { id: string; name?: string; managed?: boolean }[],- activeServerId: null as string | null,isConnected: (_serverId: string): boolean => true,// These servers answer; they are simply not signed in to.isUnreachable: (_serverId: string): boolean => false,statusFor: (serverId: string) => ({ user: { id: `user-of-${serverId}` } }),}));+const workspaces = vi.hoisted(() => ({+ workspaces: [] as { id: string; serverId: string; name: string }[],+ activeId: null as string | null,+ byId(workspaceId: string) {+ return this.workspaces.find((w) => w.id === workspaceId) ?? null;+ },+ serverIdFor(workspaceId: string) {+ return this.byId(workspaceId)?.serverId ?? null;+ },+}));vi.mock('@renderer/lib/ipc', () => ({events: { on: vi.fn() },- rpc: { switchServers: { listRemoteRooms, listAgentRooms } },+ rpc: { workspaces: { listRooms, listAgentRooms } },+}));+vi.mock('@renderer/features/workspaces/workspaces-store', () => ({+ workspacesStore: workspaces,}));vi.mock('./switch-servers-store', () => ({ switchServersStore: serversStore }));vi.mock('./local-server-store', () => ({ localServerStore: { isRunning: true } }));@@ -39,19 +51,28 @@ function room(id: string, ownerId: string | null, overrides: Partial<RemoteRoomS} satisfies RemoteRoomSummary;}+/** Two workspaces, one per server, which is what every install has today. */+function twoWorkspaces() {+ workspaces.workspaces = [+ { id: 'ws-a', serverId: 'srv-a', name: 'Alpha' },+ { id: 'ws-b', serverId: 'srv-b', name: 'Beta' },+ ];+}+describe('listed rooms', () => {beforeEach(() => {vi.clearAllMocks();serversStore.servers = [{ id: 'srv-a' }, { id: 'srv-b' }];- serversStore.activeServerId = null;+ twoWorkspaces();+ workspaces.activeId = null;});- it('lists every room on a server this install manages', async () => {+ it('lists every room in a workspace on a server this install manages', async () => {// You run that deployment. Nothing on it should need a second app to see.serversStore.servers = [{ id: 'srv-a', managed: true }, { id: 'srv-b' }];- serversStore.activeServerId = 'srv-a';- listRemoteRooms.mockImplementation(async (serverId: string) =>- serverId === 'srv-a'+ workspaces.activeId = 'ws-a';+ listRooms.mockImplementation(async (workspaceId: string) =>+ workspaceId === 'ws-a'? [room('mine', 'user-of-srv-a'),room('someone-elses', 'user-of-someone-else'),@@ -67,8 +88,8 @@ describe('listed rooms', () => {});it('lists only rooms owned by that server’s signed-in user, excluding archived ones', async () => {- listRemoteRooms.mockImplementation(async (serverId: string) =>- serverId === 'srv-a'+ listRooms.mockImplementation(async (workspaceId: string) =>+ workspaceId === 'ws-a'? [room('mine', 'user-of-srv-a'),room('someone-elses', 'user-of-someone-else'),@@ -84,138 +105,117 @@ describe('listed rooms', () => {expect(store.listedRoomsInActiveScope.map((r: { id: string }) => r.id)).toEqual(['mine']);});- it('shows only the active server’s rooms, not every connected server’s', async () => {- listRemoteRooms.mockImplementation(async (serverId: string) => [- room(`${serverId}-room`, `user-of-${serverId}`),+ it('shows only the active workspace’s rooms, not every connected one’s', async () => {+ listRooms.mockImplementation(async (workspaceId: string) => [+ room(`${workspaceId}-room`, `user-of-${workspaces.serverIdFor(workspaceId)}`),]);const store = new SwitchRoomsStore();await store.loadRoomNames();- serversStore.activeServerId = 'srv-b';+ workspaces.activeId = 'ws-b';- expect(store.listedRoomsInActiveScope.map((r: { id: string }) => r.id)).toEqual(['srv-b-room']);+ expect(store.listedRoomsInActiveScope.map((r: { id: string }) => r.id)).toEqual(['ws-b-room']);});- it('hides nothing when no server is active, matching how locations are scoped', async () => {- listRemoteRooms.mockImplementation(async (serverId: string) => [- room(`${serverId}-room`, `user-of-${serverId}`),+ it('hides nothing when no workspace is active, matching how locations are scoped', async () => {+ listRooms.mockImplementation(async (workspaceId: string) => [+ room(`${workspaceId}-room`, `user-of-${workspaces.serverIdFor(workspaceId)}`),]);const store = new SwitchRoomsStore();await store.loadRoomNames();expect(store.listedRoomsInActiveScope.map((r: { id: string }) => r.id)).toEqual([- 'srv-a-room',- 'srv-b-room',+ 'ws-a-room',+ 'ws-b-room',]);});- it('keeps a server that failed to respond from dropping the others', async () => {- listRemoteRooms.mockImplementation(async (serverId: string) => {- if (serverId === 'srv-a') throw new Error('unreachable');- return [room('srv-b-room', 'user-of-srv-b')];+ it('keeps a workspace that failed to respond from dropping the others', async () => {+ listRooms.mockImplementation(async (workspaceId: string) => {+ if (workspaceId === 'ws-a') throw new Error('unreachable');+ return [room('ws-b-room', 'user-of-srv-b')];});const store = new SwitchRoomsStore();await store.loadRoomNames();- expect(store.listedRoomsInActiveScope.map((r: { id: string }) => r.id)).toEqual(['srv-b-room']);+ expect(store.listedRoomsInActiveScope.map((r: { id: string }) => r.id)).toEqual(['ws-b-room']);});- it('says the room list is incomplete when a server could not be read', async () => {- serversStore.servers = [- { id: 'srv-a', name: 'Alpha' },- { id: 'srv-b', name: 'Beta' },- ];- listRemoteRooms.mockImplementation(async (serverId: string) => {- if (serverId === 'srv-a') throw new Error('unreachable');- return [room('srv-b-room', 'user-of-srv-b')];+ it('says the room list is incomplete when a workspace could not be read', async () => {+ listRooms.mockImplementation(async (workspaceId: string) => {+ if (workspaceId === 'ws-a') throw new Error('unreachable');+ return [room('ws-b-room', 'user-of-srv-b')];});const store = new SwitchRoomsStore();await store.loadRoomNames();- expect(store.serversThatFailedToLoad.map((s) => s.name)).toEqual(['Alpha']);+ expect(store.workspacesThatFailedToLoad.map((w) => w.name)).toEqual(['Alpha']);});- it('asks only the active server for its rooms', async () => {- serversStore.servers = [- { id: 'srv-a', name: 'Alpha' },- { id: 'srv-b', name: 'Beta' },- ];- serversStore.activeServerId = 'srv-b';- listRemoteRooms.mockImplementation(async () => []);+ it('asks only the active workspace for its rooms', async () => {+ workspaces.activeId = 'ws-b';+ listRooms.mockImplementation(async () => []);const store = new SwitchRoomsStore();await store.loadRoomNames();- expect(listRemoteRooms).toHaveBeenCalledExactlyOnceWith('srv-b');+ expect(listRooms).toHaveBeenCalledExactlyOnceWith('ws-b');});- it('does not report another server’s failure against the one you are viewing', async () => {- // Each server is its own world. A server you are not looking at being down- // says nothing about the one you are, and warning about it trains you to- // ignore the warning.- serversStore.servers = [- { id: 'srv-a', name: 'Alpha' },- { id: 'srv-b', name: 'Beta' },- ];- listRemoteRooms.mockImplementation(async (serverId: string) => {- if (serverId === 'srv-a') throw new Error('unreachable');- return [room('srv-b-room', 'user-of-srv-b')];+ it('does not report another workspace’s failure against the one you are viewing', async () => {+ // Each workspace is its own world. One you are not looking at being+ // unreadable says nothing about the one you are, and warning about it trains+ // you to ignore the warning.+ listRooms.mockImplementation(async (workspaceId: string) => {+ if (workspaceId === 'ws-a') throw new Error('unreachable');+ return [room('ws-b-room', 'user-of-srv-b')];});const store = new SwitchRoomsStore();- // Search loads every server, so Alpha's failure is on the record...- await store.loadRoomsOnAllServers();- expect(store.serversThatFailedToLoad.map((s) => s.name)).toEqual(['Alpha']);+ // Search loads every workspace, so Alpha's failure is on the record...+ await store.loadRoomsInAllWorkspaces();+ expect(store.workspacesThatFailedToLoad.map((w) => w.name)).toEqual(['Alpha']);- // ...but it must not surface while Beta is the server on screen.- serversStore.activeServerId = 'srv-b';- expect(store.serversThatFailedToLoad).toEqual([]);- expect(store.serversNotSignedIn).toEqual([]);+ // ...but it must not surface while Beta is the workspace on screen.+ workspaces.activeId = 'ws-b';+ expect(store.workspacesThatFailedToLoad).toEqual([]);+ expect(store.workspacesNotSignedIn).toEqual([]);});- it('does not report a disconnected server you are not viewing', async () => {- serversStore.servers = [- { id: 'srv-a', name: 'Alpha' },- { id: 'srv-b', name: 'Beta' },- ];- serversStore.activeServerId = 'srv-b';+ it('does not report a signed-out workspace you are not viewing', async () => {+ workspaces.activeId = 'ws-b';serversStore.isConnected = (serverId: string) => serverId !== 'srv-a';- listRemoteRooms.mockImplementation(async () => []);+ listRooms.mockImplementation(async () => []);const store = new SwitchRoomsStore();- await store.loadRoomsOnAllServers();+ await store.loadRoomsInAllWorkspaces();- expect(store.serversNotSignedIn).toEqual([]);+ expect(store.workspacesNotSignedIn).toEqual([]);serversStore.isConnected = () => true;});- it('reports a server it is not signed in to as needing sign-in, not as failed', async () => {+ it('reports a workspace it is not signed in to as needing sign-in, not as failed', async () => {// Signing in is an action the user takes; a retry button cannot fix it, and// calling it a failure sends them round in a circle.- serversStore.servers = [- { id: 'srv-a', name: 'Alpha' },- { id: 'srv-b', name: 'Beta' },- ];- serversStore.activeServerId = 'srv-b';+ workspaces.activeId = 'ws-b';serversStore.isConnected = (serverId: string) => serverId !== 'srv-b';- listRemoteRooms.mockImplementation(async () => []);+ listRooms.mockImplementation(async () => []);const store = new SwitchRoomsStore();await store.loadRoomNames();- expect(store.serversNotSignedIn.map((s) => s.name)).toEqual(['Beta']);- expect(store.serversThatFailedToLoad).toEqual([]);+ expect(store.workspacesNotSignedIn.map((w) => w.name)).toEqual(['Beta']);+ expect(store.workspacesThatFailedToLoad).toEqual([]);serversStore.isConnected = () => true;});it('marks a room’s name as blocked on sign-in when its server is signed out', async () => {- serversStore.servers = [{ id: 'srv-a', name: 'Alpha' }];- serversStore.activeServerId = 'srv-a';+ workspaces.activeId = 'ws-a';serversStore.isConnected = () => false;- listRemoteRooms.mockImplementation(async () => []);+ listRooms.mockImplementation(async () => []);const store = new SwitchRoomsStore();await store.loadRoomNames();@@ -225,25 +225,26 @@ describe('listed rooms', () => {expect(store.roomNameBlockedBySignIn('some-room')).toBe(false);});- it('clears a server’s failure once it can be read again', async () => {- serversStore.servers = [{ id: 'srv-a', name: 'Alpha' }];- listRemoteRooms.mockImplementation(async () => {+ it('clears a workspace’s failure once it can be read again', async () => {+ workspaces.activeId = 'ws-a';+ listRooms.mockImplementation(async () => {throw new Error('unreachable');});const store = new SwitchRoomsStore();await store.loadRoomNames();- expect(store.serversThatFailedToLoad.map((s) => s.name)).toEqual(['Alpha']);+ expect(store.workspacesThatFailedToLoad.map((w) => w.name)).toEqual(['Alpha']);- listRemoteRooms.mockImplementation(async () => [room('back', 'user-of-srv-a')]);+ listRooms.mockImplementation(async () => [room('back', 'user-of-srv-a')]);await store.loadRoomNames();- expect(store.serversThatFailedToLoad).toEqual([]);+ expect(store.workspacesThatFailedToLoad).toEqual([]);});});describe('agent memberships', () => {beforeEach(() => {vi.clearAllMocks();+ twoWorkspaces();listAgentRooms.mockImplementation(async ({ agentId }: { agentId: string }) => [{roomId: `room-of-${agentId}`,@@ -259,17 +260,17 @@ describe('agent memberships', () => {const store = new SwitchRoomsStore();await store.ensureMembershipsFor([- { serverId: 'srv-a', switchAgentId: 'agent-1' },- { serverId: 'srv-a', switchAgentId: 'agent-2' },+ { workspaceId: 'ws-a', switchAgentId: 'agent-1' },+ { workspaceId: 'ws-a', switchAgentId: 'agent-2' },]);- expect(store.roomsFor('srv-a', 'agent-1')?.[0].roomId).toBe('room-of-agent-1');- expect(store.roomsFor('srv-a', 'agent-2')?.[0].roomId).toBe('room-of-agent-2');+ expect(store.roomsFor('ws-a', 'agent-1')?.[0].roomId).toBe('room-of-agent-1');+ expect(store.roomsFor('ws-a', 'agent-2')?.[0].roomId).toBe('room-of-agent-2');});it('serves cached memberships without refetching, unless forced', async () => {const store = new SwitchRoomsStore();- const agents = [{ serverId: 'srv-a', switchAgentId: 'agent-1' }];+ const agents = [{ workspaceId: 'ws-a', switchAgentId: 'agent-1' }];await store.ensureMembershipsFor(agents);await store.ensureMembershipsFor(agents);@@ -293,8 +294,8 @@ describe('agent memberships', () => {const store = new SwitchRoomsStore();await store.ensureMembershipsFor([- { serverId: 'srv-a', switchAgentId: 'agent-1' },- { serverId: 'srv-a', switchAgentId: 'agent-2' },+ { workspaceId: 'ws-a', switchAgentId: 'agent-1' },+ { workspaceId: 'ws-a', switchAgentId: 'agent-2' },]);expect(store.localMemberIds('shared').sort()).toEqual(['agent-1', 'agent-2']);@@ -307,7 +308,7 @@ describe('agent memberships', () => {]);const store = new SwitchRoomsStore();- await store.ensureMembershipsFor([{ serverId: 'srv-a', switchAgentId: 'agent-1' }]);+ await store.ensureMembershipsFor([{ workspaceId: 'ws-a', switchAgentId: 'agent-1' }]);expect(store.localMemberIds('gone')).toEqual([]);});@@ -319,20 +320,20 @@ describe('agent memberships', () => {if (agentId === 'agent-late') throw new Error('not yet');return [{ roomId: 'room-a', roomName: 'r', archived: false, status: 'live', roomRole: null }];});- listRemoteRooms.mockImplementation(async () => []);+ listRooms.mockImplementation(async () => []);const store = new SwitchRoomsStore();await store.ensureMembershipsFor([- { serverId: 'srv-a', switchAgentId: 'agent-1' },- { serverId: 'srv-a', switchAgentId: 'agent-late' },+ { workspaceId: 'ws-a', switchAgentId: 'agent-1' },+ { workspaceId: 'ws-a', switchAgentId: 'agent-late' },]);- expect(store.roomsFor('srv-a', 'agent-late')).toBeUndefined();+ expect(store.roomsFor('ws-a', 'agent-late')).toBeUndefined();listAgentRooms.mockImplementation(async () => [{ roomId: 'room-b', roomName: 'r', archived: false, status: 'live', roomRole: null },]);await store.refreshRoomState();- expect(store.roomsFor('srv-a', 'agent-late')?.[0].roomId).toBe('room-b');+ expect(store.roomsFor('ws-a', 'agent-late')?.[0].roomId).toBe('room-b');});it('reports an agent whose membership failed as unknown, not as in no rooms', async () => {@@ -343,8 +344,8 @@ describe('agent memberships', () => {const store = new SwitchRoomsStore();await store.ensureMembershipsFor([- { serverId: 'srv-a', switchAgentId: 'agent-1' },- { serverId: 'srv-a', switchAgentId: 'agent-2' },+ { workspaceId: 'ws-a', switchAgentId: 'agent-1' },+ { workspaceId: 'ws-a', switchAgentId: 'agent-2' },]);expect(store.agentsWithUnknownMembership).toBe(1);@@ -354,8 +355,8 @@ describe('agent memberships', () => {const store = new SwitchRoomsStore();await store.ensureMembershipsFor([- { serverId: 'srv-a', switchAgentId: 'agent-1' },- { serverId: 'srv-a', switchAgentId: 'agent-2' },+ { workspaceId: 'ws-a', switchAgentId: 'agent-1' },+ { workspaceId: 'ws-a', switchAgentId: 'agent-2' },]);expect(store.agentsWithUnknownMembership).toBe(0);@@ -369,15 +370,38 @@ describe('agent memberships', () => {const store = new SwitchRoomsStore();await store.ensureMembershipsFor([- { serverId: 'srv-a', switchAgentId: 'agent-1' },- { serverId: 'srv-a', switchAgentId: 'agent-2' },+ { workspaceId: 'ws-a', switchAgentId: 'agent-1' },+ { workspaceId: 'ws-a', switchAgentId: 'agent-2' },]);- expect(store.roomsFor('srv-a', 'agent-1')).toBeUndefined();- expect(store.errorFor('srv-a', 'agent-1')).toBe(+ expect(store.roomsFor('ws-a', 'agent-1')).toBeUndefined();+ expect(store.errorFor('ws-a', 'agent-1')).toBe('Could not load the rooms this agent belongs to. (nope)');- expect(store.roomsFor('srv-a', 'agent-2')?.[0].roomId).toBe('room-b');+ expect(store.roomsFor('ws-a', 'agent-2')?.[0].roomId).toBe('room-b');+ });++ it('keeps the same agent’s membership in two workspaces apart', async () => {+ // One server can host several, and an agent id is the server's — so a cache+ // keyed on the agent alone would answer one workspace with the other's rooms.+ listAgentRooms.mockImplementation(async ({ workspaceId }: { workspaceId: string }) => [+ {+ roomId: `room-in-${workspaceId}`,+ roomName: 'r',+ archived: false,+ status: 'live',+ roomRole: null,+ },+ ]);+ const store = new SwitchRoomsStore();++ await store.ensureMembershipsFor([+ { workspaceId: 'ws-a', switchAgentId: 'agent-1' },+ { workspaceId: 'ws-b', switchAgentId: 'agent-1' },+ ]);++ expect(store.roomsFor('ws-a', 'agent-1')?.[0].roomId).toBe('room-in-ws-a');+ expect(store.roomsFor('ws-b', 'agent-1')?.[0].roomId).toBe('room-in-ws-b');});});@@ -385,14 +409,15 @@ describe('rooms offered to a picker', () => {beforeEach(() => {vi.clearAllMocks();serversStore.servers = [{ id: 'srv-a' }];- serversStore.activeServerId = 'srv-a';+ workspaces.workspaces = [{ id: 'ws-a', serverId: 'srv-a', name: 'Alpha' }];+ workspaces.activeId = 'ws-a';});- it('offers every room the server returned, not only the ones this user made', async () => {- // The sidebar deliberately lists a narrower set — see `listedRoomsOnServer`.+ it('offers every room the workspace returned, not only the ones this user made', async () => {+ // The sidebar deliberately lists a narrower set — see `listedRoomsInWorkspace`.// A picker is a list you went looking for, so it must not hide a room you// are entitled to join.- listRemoteRooms.mockResolvedValue([+ listRooms.mockResolvedValue([room('mine', 'user-of-srv-a'),room('someone-elses', 'user-of-someone-else'),room('ownerless', null),@@ -401,16 +426,16 @@ describe('rooms offered to a picker', () => {const store = new SwitchRoomsStore();await store.loadRoomNames();- expect(store.readableRoomsOnServer('srv-a').map((r) => r.id)).toEqual([+ expect(store.readableRoomsInWorkspace('ws-a').map((r) => r.id)).toEqual(['mine','someone-elses','ownerless',]);- expect(store.listedRoomsOnServer('srv-a').map((r) => r.id)).toEqual(['mine']);+ expect(store.listedRoomsInWorkspace('ws-a').map((r) => r.id)).toEqual(['mine']);});it('leaves out archived rooms, which are not joinable', async () => {- listRemoteRooms.mockResolvedValue([+ listRooms.mockResolvedValue([room('live', 'user-of-someone-else'),room('gone', 'user-of-someone-else', { archived: true }),]);@@ -418,11 +443,11 @@ describe('rooms offered to a picker', () => {const store = new SwitchRoomsStore();await store.loadRoomNames();- expect(store.readableRoomsOnServer('srv-a').map((r) => r.id)).toEqual(['live']);+ expect(store.readableRoomsInWorkspace('ws-a').map((r) => r.id)).toEqual(['live']);});- it('offers nothing for a server whose rooms were never read', () => {- expect(new SwitchRoomsStore().readableRoomsOnServer('srv-a')).toEqual([]);+ it('offers nothing for a workspace whose rooms were never read', () => {+ expect(new SwitchRoomsStore().readableRoomsInWorkspace('ws-a')).toEqual([]);});});@@ -435,6 +460,7 @@ describe('who may delete a room', () => {beforeEach(() => {vi.clearAllMocks();serversStore.servers = [{ id: 'srv-a' }];+ workspaces.workspaces = [{ id: 'ws-a', serverId: 'srv-a', name: 'Alpha' }];serversStore.statusFor = statusWithRole(undefined);});@@ -444,28 +470,36 @@ describe('who may delete a room', () => {it('lets the owner delete their own room', () => {const store = new SwitchRoomsStore();- expect(store.canDeleteRoom('srv-a', room('r', 'user-of-srv-a'))).toBe(true);+ expect(store.canDeleteRoom('ws-a', room('r', 'user-of-srv-a'))).toBe(true);});it('refuses someone else’s room', () => {const store = new SwitchRoomsStore();- expect(store.canDeleteRoom('srv-a', room('r', 'user-of-someone-else'))).toBe(false);+ expect(store.canDeleteRoom('ws-a', room('r', 'user-of-someone-else'))).toBe(false);});it('lets an admin delete a room they do not own, matching the gateway', () => {serversStore.statusFor = statusWithRole('admin');const store = new SwitchRoomsStore();- expect(store.canDeleteRoom('srv-a', room('r', 'user-of-someone-else'))).toBe(true);+ expect(store.canDeleteRoom('ws-a', room('r', 'user-of-someone-else'))).toBe(true);});it('refuses an ownerless room to a non-admin, rather than treating it as unclaimed', () => {const store = new SwitchRoomsStore();- expect(store.canDeleteRoom('srv-a', room('r', null))).toBe(false);+ expect(store.canDeleteRoom('ws-a', room('r', null))).toBe(false);});it('refuses while signed out, when there is no one to compare against', () => {serversStore.statusFor = () => ({ user: null }) as never;const store = new SwitchRoomsStore();- expect(store.canDeleteRoom('srv-a', room('r', 'user-of-srv-a'))).toBe(false);+ expect(store.canDeleteRoom('ws-a', room('r', 'user-of-srv-a'))).toBe(false);+ });++ it('refuses a workspace whose server is not known yet', () => {+ // The permission is the server's to answer, so an unresolved workspace is+ // not a licence to offer the action.+ workspaces.workspaces = [];+ const store = new SwitchRoomsStore();+ expect(store.canDeleteRoom('ws-a', room('r', 'user-of-srv-a'))).toBe(false);});});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.tsindex 345702c77..80995b7de 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts@@ -1,4 +1,5 @@import { makeAutoObservable, runInAction } from 'mobx';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { failureText } from '@renderer/lib/errors/describe-failure';import { rpc } from '@renderer/lib/ipc';import type {@@ -9,9 +10,9 @@ import { UNBRIDGED_FILTER_VALUE } from '@shared/view-state';import { serverAvailability } from './server-availability';import { switchServersStore } from './switch-servers-store';-/** Cache key for an agent's room membership: server + Switch agent id. */-function key(serverId: string, switchAgentId: string): string {- return `${serverId}:${switchAgentId}`;+/** Cache key for an agent's room membership: workspace + Switch agent id. */+function key(workspaceId: string, switchAgentId: string): string {+ return `${workspaceId}:${switchAgentId}`;}/**@@ -20,43 +21,50 @@ function key(serverId: string, switchAgentId: string): string {* Entries are cached in memory and re-fetched on demand or on window focus, so* the "connect to room" picker and the room-focused sidebar grouping render the* last-known set instantly while a refresh runs.+ *+ * Everything here is keyed by workspace, because that is what a room belongs+ * to: one server can host several, and the same server answers with a different+ * set of rooms in each. Where a fact is about the gateway rather than about the+ * rooms — whether it is reachable, who is signed in, what its web app's URL is+ * — the server is resolved from the workspace and asked for that alone.*/export class SwitchRoomsStore {- /** Membership per `${serverId}:${switchAgentId}`. */+ /** Membership per `${workspaceId}:${switchAgentId}`. */private readonly roomsByAgent = new Map<string, RemoteAgentRoom[]>();- /** Room id → display name, aggregated across connected servers (room ids are+ /** Room id → display name, aggregated across workspaces (room ids are* globally unique UUIDs, so a flat map is safe). Drives sidebar room headers. */private readonly roomNames = new Map<string, string>();- /** Room id → owning server id, so a room can be linked to its gateway web app. */- private readonly roomServerById = new Map<string, string>();+ /** Room id → owning workspace id, so a room can be addressed and linked. */+ private readonly roomWorkspaceById = new Map<string, string>();/** Room id → bridge type (`slack`, `mattermost`, …) when the room is bridged* to an external platform, so the sidebar can show that platform's icon. */private readonly bridgeTypeByRoom = new Map<string, string>();/** Room id → native deeplink that opens its channel in the messaging app's* desktop client, when the room is bridged and the link could be built. */private readonly channelUrlByRoom = new Map<string, string>();- /** Server id → the active rooms on that server owned by the signed-in user.+ /** Workspace id → the active rooms in it owned by the signed-in user.* The sidebar lists these even when no session is connected to them, so a* room you create in Switch Console is visible the moment it exists rather than* only once an agent joins it. */- private readonly ownedRoomsByServer = new Map<string, RemoteRoomSummary[]>();- /** Server id → every active room on it. Listed in full for a server this- * install manages; elsewhere it backs lookups rather than the room list. */- private readonly allRoomsByServer = new Map<string, RemoteRoomSummary[]>();+ private readonly ownedRoomsByWorkspace = new Map<string, RemoteRoomSummary[]>();+ /** Workspace id → every active room in it. Listed in full for a workspace on a+ * server this install manages; elsewhere it backs lookups rather than the+ * room list. */+ private readonly allRoomsByWorkspace = new Map<string, RemoteRoomSummary[]>();/** Keys with an in-flight fetch. */readonly loading = new Set<string>();/** Last error per key, if the most recent fetch failed. */readonly errors = new Map<string, string>();- /** Server id → why its room list could not be read, if the last try failed. */+ /** Workspace id → why its room list could not be read, if the last try failed. */private readonly roomListErrors = new Map<string, string>();- /** Servers that were not connected when the room list was last refreshed, so- * their rooms were never asked for at all. */- private unreachableServerIds: string[] = [];+ /** Workspaces whose server was not connected when the room list was last+ * refreshed, so their rooms were never asked for at all. */+ private unreachableWorkspaceIds: string[] = [];/** The agents whose membership this store is responsible for keeping current.* Recorded on {@link ensureMembershipsFor} so a refresh re-reads the current* set rather than only the keys that happen to be cached — an agent created* after the sidebar mounted is otherwise never fetched. */- private trackedIdentities: { serverId: string; switchAgentId: string }[] = [];+ private trackedIdentities: { workspaceId: string; switchAgentId: string }[] = [];constructor() {makeAutoObservable(this);@@ -79,18 +87,26 @@ export class SwitchRoomsStore {return this.channelUrlByRoom.get(roomId) ?? null;}- /** Id of the server a room belongs to, or null if not yet loaded. The room- * view needs it to resolve that server's Mattermost session. */+ /** Id of the workspace a room belongs to, or null if not yet loaded. This is+ * what a call about the room is addressed with. */+ roomWorkspaceId(roomId: string): string | null {+ return this.roomWorkspaceById.get(roomId) ?? null;+ }++ /** Id of the server hosting a room's workspace, for the things that are about+ * the gateway rather than the room — its web app, its Mattermost session. */roomServerId(roomId: string): string | null {- return this.roomServerById.get(roomId) ?? null;+ const workspaceId = this.roomWorkspaceById.get(roomId);+ if (!workspaceId) return null;+ return workspacesStore.serverIdFor(workspaceId);}/*** URL of a room's detail page in the gateway web app, or null if the room's- * owning server isn't known yet (names/servers are loaded by loadRoomNames).+ * owning server isn't known yet (names/workspaces are loaded by loadRoomNames).*/gatewayRoomUrl(roomId: string): string | null {- const serverId = this.roomServerById.get(roomId);+ const serverId = this.roomServerId(roomId);if (!serverId) return null;const server = switchServersStore.servers.find((s) => s.id === serverId);if (!server) return null;@@ -115,71 +131,69 @@ export class SwitchRoomsStore {* considered — the ones that are there because of what they are, not because* one of this install's agents is in them.*- * On a server this install manages, that is **every** room: you run the- * deployment, so there is nothing on it you should have to go elsewhere to- * see. On any other server it is the rooms you created, which would otherwise- * disappear the moment you made one and put no agent in it.+ * In a workspace on a server this install manages, that is **every** room: you+ * run the deployment, so there is nothing on it you should have to go+ * elsewhere to see. Anywhere else it is the rooms you created, which would+ * otherwise disappear the moment you made one and put no agent in it.*- * The sidebar tree shows one server at a time, so these follow the same scope- * rule as locations do — including that no active server hides nothing.+ * The sidebar tree shows one workspace at a time, so these follow the same+ * scope rule as locations do — including that no active workspace hides+ * nothing.*/get listedRoomsInActiveScope(): RemoteRoomSummary[] {- const activeServerId = switchServersStore.activeServerId;- const serverIds = activeServerId- ? [activeServerId]- : [...new Set([...this.allRoomsByServer.keys(), ...this.ownedRoomsByServer.keys()])];- const listed = serverIds.flatMap((serverId) => this.listedRoomsOnServer(serverId));+ const listed = this.workspaceIdsInScope.flatMap((id) => this.listedRoomsInWorkspace(id));return listed.sort((a, b) => a.name.localeCompare(b.name));}/**- * The rooms one server contributes to the lists above, under the same scope- * rule. Named separately so a page about a single server asks for that- * server rather than for whichever one happens to be active.+ * The rooms one workspace contributes to the lists above, under the same scope+ * rule. Named separately so a page about a single workspace asks for that+ * workspace rather than for whichever one happens to be active.*/- listedRoomsOnServer(serverId: string): RemoteRoomSummary[] {+ listedRoomsInWorkspace(workspaceId: string): RemoteRoomSummary[] {+ const serverId = workspacesStore.serverIdFor(workspaceId);const managed = switchServersStore.servers.find((s) => s.id === serverId)?.managed ?? false;return (- (managed ? this.allRoomsByServer.get(serverId) : this.ownedRoomsByServer.get(serverId)) ?? []+ (managed+ ? this.allRoomsByWorkspace.get(workspaceId)+ : this.ownedRoomsByWorkspace.get(workspaceId)) ?? []);}/**- * Every active room the signed-in user can see on a server — what the gateway- * returned, which is already scoped to rooms they may read.+ * Every active room the signed-in user can see in a workspace — what the+ * gateway returned, which is already scoped to rooms they may read.*- * Wider than {@link listedRoomsOnServer} on purpose. A standing list has to+ * Wider than {@link listedRoomsInWorkspace} on purpose. A standing list has to* earn its place on screen, so the sidebar shows only rooms with a claim on* you; a picker is a list you went looking for, and one that hides rooms you* have every right to join cannot be searched into showing them.*/- readableRoomsOnServer(serverId: string): RemoteRoomSummary[] {- return this.allRoomsByServer.get(serverId) ?? [];+ readableRoomsInWorkspace(workspaceId: string): RemoteRoomSummary[] {+ return this.allRoomsByWorkspace.get(workspaceId) ?? [];}/*** The same listed rooms as {@link listedRoomsInActiveScope}, but across every- * server rather than the active one.+ * workspace rather than the active one.*- * Search is deliberately not scoped to the active server: you search precisely- * because you do not know where a thing is, and a result set silently limited- * to the server you happen to be looking at cannot answer that. Navigating to- * one of these switches the active server (see `scopeToRoomServer`), so the- * sidebar follows you there rather than filtering the room back out.+ * Search is deliberately not scoped to the active workspace: you search+ * precisely because you do not know where a thing is, and a result set+ * silently limited to the one you happen to be looking at cannot answer that.+ * Navigating to one of these switches the active workspace (see+ * `scopeToRoomWorkspace`), so the sidebar follows you there rather than+ * filtering the room back out.*/- get listedRoomsOnAllServers(): RemoteRoomSummary[] {- const serverIds = [- ...new Set([...this.allRoomsByServer.keys(), ...this.ownedRoomsByServer.keys()]),- ];- const listed = serverIds.flatMap((serverId) => this.listedRoomsOnServer(serverId));+ get listedRoomsInAllWorkspaces(): RemoteRoomSummary[] {+ const listed = workspacesStore.workspaces.flatMap((w) => this.listedRoomsInWorkspace(w.id));return listed.sort((a, b) => a.name.localeCompare(b.name));}/**- * The messaging-app values worth offering as a room filter on the active- * server: the bridge types actually in use, plus the unbridged sentinel when- * some room has no messaging app. Offering a platform with no rooms behind it- * would be a filter that can only ever empty the list.+ * The messaging-app values worth offering as a room filter in the active+ * workspace: the bridge types actually in use, plus the unbridged sentinel+ * when some room has no messaging app. Offering a platform with no rooms+ * behind it would be a filter that can only ever empty the list.*/get bridgeFilterValuesInActiveScope(): string[] {const present = new Set<string>();@@ -194,102 +208,105 @@ export class SwitchRoomsStore {});}- /** Full detail for a room, when its server's room list has been loaded. */+ /** Full detail for a room, when its workspace's room list has been loaded. */roomSummaryById(roomId: string): RemoteRoomSummary | null {- const serverId = this.roomServerById.get(roomId);- if (!serverId) return null;- return this.allRoomsByServer.get(serverId)?.find((room) => room.id === roomId) ?? null;+ const workspaceId = this.roomWorkspaceById.get(roomId);+ if (!workspaceId) return null;+ return this.allRoomsByWorkspace.get(workspaceId)?.find((room) => room.id === roomId) ?? null;}/*** Whether the signed-in user may delete a room: they own it, or they are an- * admin on its server.+ * admin on the server hosting its workspace.** This mirrors the gateway's own rule so the action is not offered where it* would only be refused. It is not the check that protects anything — the* server's is — and where ownership is unknown the answer is no, since* showing a delete that fails is worse than not showing one.*/- canDeleteRoom(serverId: string, room: RemoteRoomSummary): boolean {+ canDeleteRoom(workspaceId: string, room: RemoteRoomSummary): boolean {+ const serverId = workspacesStore.serverIdFor(workspaceId);+ if (!serverId) return false;const user = switchServersStore.statusFor(serverId)?.user ?? null;if (!user) return false;return room.ownerId === user.id || user.role === 'admin';}/**- * Delete a room on its server, then re-read what is left.+ * Delete a room in its workspace, then re-read what is left.** Throws on refusal rather than reporting a boolean: the caller is a* confirmation dialog, and a delete that quietly did nothing would leave the* room on screen with no account of why.*/- async deleteRoom(serverId: string, roomId: string): Promise<void> {- await rpc.switchServers.deleteRoom({ serverId, roomId });+ async deleteRoom(workspaceId: string, roomId: string): Promise<void> {+ await rpc.workspaces.deleteRoom({ workspaceId, roomId });await this.refreshRoomState();}/**- * The servers whose state is on screen: the active one, or all of them when- * none is active (the same scope rule the room and location lists follow).+ * The workspaces whose state is on screen: the active one, or all of them+ * when none is active (the same scope rule the room and location lists+ * follow).*- * Each server is its own world — its own rooms, its own agents, its own- * connection. Reading or reporting on one you are not looking at is both- * wasted work and, worse, someone else's problem presented as yours.+ * Each workspace is its own world — its own rooms, its own agents. Reading or+ * reporting on one you are not looking at is both wasted work and, worse,+ * someone else's problem presented as yours.*/- private get serverIdsInScope(): string[] {- const activeServerId = switchServersStore.activeServerId;- if (activeServerId) return [activeServerId];- return switchServersStore.servers.map((s) => s.id);+ private get workspaceIdsInScope(): string[] {+ const activeId = workspacesStore.activeId;+ if (activeId) return [activeId];+ return workspacesStore.workspaces.map((w) => w.id);}/**- * Refresh the room catalogue for the servers on screen.+ * Refresh the room catalogue for the workspaces on screen.*- * A server that cannot be read keeps its last-known rooms rather than losing- * them, but the failure is recorded in {@link roomListErrors} instead of being- * swallowed: last-known data rendered as if it were current is the one outcome- * worse than showing nothing.+ * A workspace that cannot be read keeps its last-known rooms rather than+ * losing them, but the failure is recorded in {@link roomListErrors} instead+ * of being swallowed: last-known data rendered as if it were current is the+ * one outcome worse than showing nothing.*/async loadRoomNames(): Promise<void> {- await this.loadRoomsFrom(this.serverIdsInScope);+ await this.loadRoomsFrom(this.workspaceIdsInScope);}/**- * Refresh the room catalogue for **every** server.+ * Refresh the room catalogue for **every** workspace.*- * Only for cross-server search, which is deliberately not scoped — you search- * because you do not know where a thing is. Everything else loads the servers- * it is actually showing.+ * Only for cross-workspace search, which is deliberately not scoped — you+ * search because you do not know where a thing is. Everything else loads the+ * workspaces it is actually showing.*/- async loadRoomsOnAllServers(): Promise<void> {- await this.loadRoomsFrom(switchServersStore.servers.map((s) => s.id));+ async loadRoomsInAllWorkspaces(): Promise<void> {+ await this.loadRoomsFrom(workspacesStore.workspaces.map((w) => w.id));}- private async loadRoomsFrom(serverIds: string[]): Promise<void> {- const servers = switchServersStore.servers.filter((s) => serverIds.includes(s.id));- const connected = servers.filter((s) => switchServersStore.isConnected(s.id));+ private async loadRoomsFrom(workspaceIds: string[]): Promise<void> {+ const asked = workspacesStore.workspaces.filter((w) => workspaceIds.includes(w.id));+ const connected = asked.filter((w) => switchServersStore.isConnected(w.serverId));runInAction(() => {// Not being connected is not a failure — there is simply nothing to ask- // right now — but the rooms on that server are equally unknown, and the+ // right now — but the rooms in that workspace are equally unknown, and the// sidebar has to be able to say so.- const asked = new Set(serverIds);- this.unreachableServerIds = [- ...this.unreachableServerIds.filter((id) => !asked.has(id)),- ...servers.filter((s) => !switchServersStore.isConnected(s.id)).map((s) => s.id),+ const askedIds = new Set(workspaceIds);+ this.unreachableWorkspaceIds = [+ ...this.unreachableWorkspaceIds.filter((id) => !askedIds.has(id)),+ ...asked.filter((w) => !switchServersStore.isConnected(w.serverId)).map((w) => w.id),];});await Promise.all(- connected.map(async (server) => {+ connected.map(async (workspace) => {try {- const rooms = await rpc.switchServers.listRemoteRooms(server.id);+ const rooms = await rpc.workspaces.listRooms(workspace.id);// Ownership is per server: the same person is a different user row on// each gateway, so match against that server's signed-in identity.- const signedInUserId = switchServersStore.statusFor(server.id)?.user?.id ?? null;+ const signedInUserId = switchServersStore.statusFor(workspace.serverId)?.user?.id ?? null;runInAction(() => {- this.roomListErrors.delete(server.id);+ this.roomListErrors.delete(workspace.id);for (const room of rooms) {this.roomNames.set(room.id, room.name);- this.roomServerById.set(room.id, server.id);+ this.roomWorkspaceById.set(room.id, workspace.id);if (room.bridgeType) this.bridgeTypeByRoom.set(room.id, room.bridgeType);else this.bridgeTypeByRoom.delete(room.id);if (room.externalChannelUrl)@@ -297,17 +314,17 @@ export class SwitchRoomsStore {else this.channelUrlByRoom.delete(room.id);}const active = rooms.filter((r) => !r.archived);- this.allRoomsByServer.set(server.id, active);- this.ownedRoomsByServer.set(- server.id,+ this.allRoomsByWorkspace.set(workspace.id, active);+ this.ownedRoomsByWorkspace.set(+ workspace.id,signedInUserId ? active.filter((r) => r.ownerId === signedInUserId) : []);});} catch (cause) {runInAction(() => {this.roomListErrors.set(- server.id,- failureText(cause, `Could not load the rooms on ${server.name}.`)+ workspace.id,+ failureText(cause, `Could not load the rooms in ${workspace.name}.`));});}@@ -324,42 +341,44 @@ export class SwitchRoomsStore {* being asked to wait or to act.*/roomNameBlockedBySignIn(roomId: string): boolean {- const serverId = this.roomServerById.get(roomId) ?? switchServersStore.activeServerId;+ const workspaceId = this.roomWorkspaceById.get(roomId) ?? workspacesStore.activeId;+ if (!workspaceId) return false;+ const serverId = workspacesStore.serverIdFor(workspaceId);if (!serverId) return false;return serverAvailability(serverId) === 'signed-out';}/**- * Servers on screen whose room list was asked for and failed.+ * Workspaces on screen whose room list was asked for and failed.*- * Distinct from {@link serversNotSignedIn}: this is a fault, it may be+ * Distinct from {@link workspacesNotSignedIn}: this is a fault, it may be* transient, and retrying is a sensible thing to offer.*/- get serversThatFailedToLoad(): { id: string; name: string }[] {- return this.namedServersInScope([...this.roomListErrors.keys()]);+ get workspacesThatFailedToLoad(): { id: string; name: string }[] {+ return this.namedWorkspacesInScope([...this.roomListErrors.keys()]);}/**- * Servers on screen that were never asked because Switch Console is not signed in- * to them.+ * Workspaces on screen that were never asked because Switch Console is not+ * signed in to their server.** Not a fault and not retryable — the user has to sign in. Reporting it as a* failure with a retry button offers an action that cannot work.*/- get serversNotSignedIn(): { id: string; name: string }[] {- return this.namedServersInScope(- this.unreachableServerIds.filter((id) => serverAvailability(id) === 'signed-out')+ get workspacesNotSignedIn(): { id: string; name: string }[] {+ return this.namedWorkspacesInScope(+ this.unreachableWorkspaceIds.filter((id) => {+ const serverId = workspacesStore.serverIdFor(id);+ return serverId !== null && serverAvailability(serverId) === 'signed-out';+ }));}- private namedServersInScope(serverIds: string[]): { id: string; name: string }[] {- const inScope = new Set(this.serverIdsInScope);- return [...new Set(serverIds)]+ private namedWorkspacesInScope(workspaceIds: string[]): { id: string; name: string }[] {+ const inScope = new Set(this.workspaceIdsInScope);+ return [...new Set(workspaceIds)].filter((id) => inScope.has(id))- .map((id) => ({- id,- name: switchServersStore.servers.find((s) => s.id === id)?.name ?? id,- }))+ .map((id) => ({ id, name: workspacesStore.byId(id)?.name ?? id })).sort((a, b) => a.name.localeCompare(b.name));}@@ -371,15 +390,15 @@ export class SwitchRoomsStore {*/get agentsWithUnknownMembership(): number {return this.trackedIdentities.filter(- ({ serverId, switchAgentId }) =>- this.roomsByAgent.get(key(serverId, switchAgentId)) === undefined &&- !this.isLoading(serverId, switchAgentId)+ ({ workspaceId, switchAgentId }) =>+ this.roomsByAgent.get(key(workspaceId, switchAgentId)) === undefined &&+ !this.isLoading(workspaceId, switchAgentId)).length;}/** Cached membership, or undefined if never fetched. */- roomsFor(serverId: string, switchAgentId: string): RemoteAgentRoom[] | undefined {- return this.roomsByAgent.get(key(serverId, switchAgentId));+ roomsFor(workspaceId: string, switchAgentId: string): RemoteAgentRoom[] | undefined {+ return this.roomsByAgent.get(key(workspaceId, switchAgentId));}/**@@ -436,23 +455,23 @@ export class SwitchRoomsStore {* agent's at a time.*/async ensureMembershipsFor(- agents: { serverId: string; switchAgentId: string }[],+ agents: { workspaceId: string; switchAgentId: string }[],options: { force?: boolean } = {}): Promise<void> {runInAction(() => {this.trackedIdentities = agents;});await Promise.all(- agents.map((a) => this.fetchAgentRooms(a.serverId, a.switchAgentId, options))+ agents.map((a) => this.fetchAgentRooms(a.workspaceId, a.switchAgentId, options)));}- isLoading(serverId: string, switchAgentId: string): boolean {- return this.loading.has(key(serverId, switchAgentId));+ isLoading(workspaceId: string, switchAgentId: string): boolean {+ return this.loading.has(key(workspaceId, switchAgentId));}- errorFor(serverId: string, switchAgentId: string): string | null {- return this.errors.get(key(serverId, switchAgentId)) ?? null;+ errorFor(workspaceId: string, switchAgentId: string): string | null {+ return this.errors.get(key(workspaceId, switchAgentId)) ?? null;}/**@@ -460,11 +479,11 @@ export class SwitchRoomsStore {* cache. Returns the membership, or null if the fetch failed.*/async fetchAgentRooms(- serverId: string,+ workspaceId: string,switchAgentId: string,options: { force?: boolean } = {}): Promise<RemoteAgentRoom[] | null> {- const k = key(serverId, switchAgentId);+ const k = key(workspaceId, switchAgentId);const cached = this.roomsByAgent.get(k);if (cached && !options.force) return cached;@@ -473,7 +492,7 @@ export class SwitchRoomsStore {this.errors.delete(k);});try {- const rooms = await rpc.switchServers.listAgentRooms({ serverId, agentId: switchAgentId });+ const rooms = await rpc.workspaces.listAgentRooms({ workspaceId, agentId: switchAgentId });runInAction(() => {this.roomsByAgent.set(k, rooms);});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.test.tsindex 7a6539c7a..2d44d5a22 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.test.ts@@ -4,10 +4,13 @@ import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';const getAuthConfig = vi.hoisted(() => vi.fn());const getConnectionStatus = vi.hoisted(() => vi.fn());const listServers = vi.hoisted(() => vi.fn());-const getActiveServerId = vi.hoisted(() => vi.fn());+const installIsEmpty = vi.hoisted(() => vi.fn());const setActiveServer = vi.hoisted(() => vi.fn());+/** The workspace selection as the main process holds it, by the server it is on. */+const selection = vi.hoisted(() => ({ serverId: null as string | null }));const removeServer = vi.hoisted(() => vi.fn());const addServer = vi.hoisted(() => vi.fn());+const connectToSwitchCloud = vi.hoisted(() => vi.fn());/** SSH hosts the reachability manager currently considers down. */const blockedHosts = vi.hoisted(() => new Set<string>());@@ -18,10 +21,40 @@ vi.mock('@renderer/lib/ipc', () => ({getAuthConfig,getConnectionStatus,listServers,- getActiveServerId,setActiveServer,removeServer,addServer,+ connectToSwitchCloud,+ },+ onboarding: { installIsEmpty },+ },+}));+/**+ * Stands in for the workspace selection this store now reads its active server+ * off, faithfully enough that the selection logic is still being tested rather+ * than asserted against a constant.+ *+ * Each server gets one workspace, which is the state every install is in, so+ * `listServers` and {@link selectServer} stay the knobs a test turns. A+ * selection naming a server that is no longer listed resolves to no workspace —+ * which is exactly what happens for real once the removed server takes its+ * workspace row with it.+ */+vi.mock('@renderer/features/workspaces/workspaces-store', () => ({+ workspacesStore: {+ workspaces: [] as { id: string; serverId: string }[],+ activeId: null as string | null,+ get active(): { id: string; serverId: string } | null {+ return this.workspaces.find((w) => w.id === this.activeId) ?? null;+ },+ get activeServerId(): string | null {+ return this.active?.serverId ?? null;+ },+ async refresh(): Promise<void> {+ const servers: SwitchServer[] = await listServers();+ const activeServerId = selection.serverId;+ this.workspaces = servers.map((s) => ({ id: `ws-${s.id}`, serverId: s.id }));+ this.activeId = activeServerId === null ? null : `ws-${activeServerId}`;},},}));@@ -35,6 +68,11 @@ vi.mock('@renderer/lib/stores/app-state', () => ({const { SwitchServersStore } = await import('./switch-servers-store');+/** Scope the window to a server, the way choosing one of its workspaces does. */+function selectServer(serverId: string | null): void {+ selection.serverId = serverId;+}+const authConfig = { passwordLoginEnabled: true, oidcEnabled: false, oidcProviderLabel: null };function server(id: string, overrides: Partial<SwitchServer> = {}): SwitchServer {@@ -91,6 +129,10 @@ beforeEach(() => {user: null,}));getAuthConfig.mockResolvedValue(authConfig);+ listServers.mockResolvedValue([]);+ installIsEmpty.mockResolvedValue(true);+ selectServer(null);+ setActiveServer.mockImplementation(async (serverId: string) => selectServer(serverId));});describe('fetching sign-in options', () => {@@ -196,7 +238,7 @@ describe('recovering when connectivity returns', () => {getAuthConfig.mockRejectedValueOnce(new Error('offline'));await store.ensureAuthConfig('srv-a');listServers.mockResolvedValue([]);- getActiveServerId.mockResolvedValue(null);+ selectServer(null);removeServer.mockResolvedValue(undefined);await store.removeServer('srv-a');@@ -207,11 +249,167 @@ describe('recovering when connectivity returns', () => {});});+describe('reading the server list', () => {+ it('serves callers arriving together one read', async () => {+ // The shell asks on the first frame and so does the sidebar. Two reads of+ // the same list race each other into the same fields for no gain.+ listServers.mockResolvedValue([server('srv-a')]);+ selectServer('srv-a');+ const store = new SwitchServersStore();++ await Promise.all([store.init(), store.init(), store.init()]);++ expect(revalidate).toHaveBeenCalledTimes(1);+ });++ it('reads again for a caller arriving after the last read settled', async () => {+ // Sharing only the read in flight: the paths that change something and then+ // ask for the list back must not be handed the answer from before it.+ const store = new SwitchServersStore();+ await store.init();+ listServers.mockResolvedValue([server('srv-a')]);++ await store.init();++ expect(store.servers.map((s) => s.id)).toEqual(['srv-a']);+ });++ it('keeps the failure on screen for as long as the retry runs', async () => {+ // The window draws its failure page — message, detail and the button that+ // starts the retry — from `listError`. Clearing it as the retry begins+ // unmounts the page and the button with it, leaving a blank window until+ // the retry lands.+ listServers.mockRejectedValueOnce(new Error('gateway unreachable'));+ const store = new SwitchServersStore();+ await store.init();+ expect(store.listError).not.toBeNull();++ const retryRead = deferred<SwitchServer[]>();+ listServers.mockReturnValueOnce(retryRead.promise);+ const retrying = store.init();+ await flush();++ expect(store.listError).not.toBeNull();+ expect(store.loadingServers).toBe(true);++ retryRead.resolve([server('srv-a')]);+ await retrying;++ expect(store.listError).toBeNull();+ expect(store.listErrorDetail).toBeNull();+ });++ it('reads what the install holds rather than inferring it from the list', async () => {+ // An install whose server was removed keeps its agents — the confirmation+ // says so — and the sessions in them are still running. An empty list is+ // therefore not the fresh-install answer, and the shell needs that answer+ // to decide whether to replace the window with a first-run page.+ listServers.mockResolvedValue([]);+ installIsEmpty.mockResolvedValue(false);+ const store = new SwitchServersStore();++ await store.init();++ expect(store.servers).toEqual([]);+ expect(store.installIsEmpty).toBe(false);+ });++ it('says a read is not coming back rather than leaving the window blank', async () => {+ // Nothing is drawn until the first read lands, so a handler that never+ // settles is a blank, inert window with no message and no way to ask again.+ vi.useFakeTimers();+ try {+ listServers.mockReturnValueOnce(deferred<SwitchServer[]>().promise);+ const store = new SwitchServersStore();+ void store.init();++ // Well past any deadline worth having: what is asserted is that one+ // exists, not the exact number of seconds.+ await vi.advanceTimersByTimeAsync(60_000);++ expect(store.loaded).toBe(false);+ expect(store.listError).not.toBeNull();+ expect(store.loadingServers).toBe(false);+ } finally {+ vi.useRealTimers();+ }+ });++ it('ignores a given-up read that lands after the retry has answered', async () => {+ // The read cannot be cancelled, only abandoned — so the stale one is still+ // out there, and letting it write would replace a good list with the one+ // the user already gave up on.+ vi.useFakeTimers();+ try {+ const stuck = deferred<SwitchServer[]>();+ listServers.mockReturnValueOnce(stuck.promise);+ const store = new SwitchServersStore();+ void store.init();+ await vi.advanceTimersByTimeAsync(60_000);++ listServers.mockResolvedValue([server('srv-a')]);+ await store.init();+ stuck.resolve([server('srv-stale')]);+ await vi.advanceTimersByTimeAsync(1);++ expect(store.servers.map((s) => s.id)).toEqual(['srv-a']);+ expect(store.listError).toBeNull();+ } finally {+ vi.useRealTimers();+ }+ });++ it('keeps a failure from elsewhere out of the slot the window reads', async () => {+ // `error` is the banner, written by every action here — a rename, a sign-out,+ // adding a server. None of those is a reason to take the window away.+ const store = newStore([server('srv-a')]);+ removeServer.mockRejectedValue(new Error('still in use'));++ await store.removeServer('srv-a');++ expect(store.error).not.toBeNull();+ expect(store.listError).toBeNull();+ });+});++describe('adding the first server', () => {+ // The shell draws the first-run page while the install is empty, and the+ // flow hands the window back only by finishing. An answer read at startup+ // and never again would send a finished flow straight back to its welcome.+ it('stops calling the install empty once a server is added', async () => {+ listServers.mockResolvedValue([]);+ const store = new SwitchServersStore();+ await store.init();+ expect(store.installIsEmpty).toBe(true);++ addServer.mockResolvedValue(server('a'));+ listServers.mockResolvedValue([server('a')]);+ installIsEmpty.mockResolvedValue(false);+ await store.addServer('a', 'https://a.example.com', 'https://a.example.com');++ expect(store.installIsEmpty).toBe(false);+ });++ it('stops calling the install empty once Switch Cloud is registered', async () => {+ listServers.mockResolvedValue([]);+ const store = new SwitchServersStore();+ await store.init();+ expect(store.installIsEmpty).toBe(true);++ connectToSwitchCloud.mockResolvedValue(server('cloud'));+ listServers.mockResolvedValue([server('cloud')]);+ installIsEmpty.mockResolvedValue(false);+ await store.connectToSwitchCloud();++ expect(store.installIsEmpty).toBe(false);+ });+});+describe('a page left on a server that is gone', () => {it('is revalidated when the server is removed', async () => {const store = newStore([server('srv-a')]);listServers.mockResolvedValue([]);- getActiveServerId.mockResolvedValue(null);+ selectServer(null);removeServer.mockResolvedValue(undefined);await store.removeServer('srv-a');@@ -224,7 +422,7 @@ describe('a page left on a server that is gone', () => {expect(store.loaded).toBe(false);listServers.mockResolvedValue([server('srv-a')]);- getActiveServerId.mockResolvedValue('srv-a');+ selectServer('srv-a');await store.init();expect(store.loaded).toBe(true);@@ -443,14 +641,14 @@ describe('a server that cannot be reached', () => {});/**- * A server is a workspace: the switcher, the sidebar and the sessions under it- * all read the active one, so "servers exist but none is active" is a state the- * UI cannot render. Nothing on the main side picks one, so the store must.+ * The switcher, the sidebar and the sessions under it all read the active+ * workspace, so "servers exist but none is active" is a state the UI cannot+ * render. Nothing on the main side picks one, so the store must.*/describe('keeping a server active', () => {it('selects the first server when nothing was active', async () => {listServers.mockResolvedValue([server('srv-a'), server('srv-b')]);- getActiveServerId.mockResolvedValue(null);+ selectServer(null);const store = new SwitchServersStore();await store.init();@@ -460,7 +658,7 @@ describe('keeping a server active', () => {it('keeps the server the user last chose', async () => {listServers.mockResolvedValue([server('srv-a'), server('srv-b')]);- getActiveServerId.mockResolvedValue('srv-b');+ selectServer('srv-b');const store = new SwitchServersStore();await store.init();@@ -474,7 +672,7 @@ describe('keeping a server active', () => {// workspace at all — no switcher, no destinations, no sidebar tree — while// a perfectly good server sat in the list.listServers.mockResolvedValue([server('srv-b')]);- getActiveServerId.mockResolvedValue('srv-gone');+ selectServer('srv-gone');const store = new SwitchServersStore();await store.init();@@ -488,7 +686,7 @@ describe('keeping a server active', () => {// the very first one left the app with no workspace to show — the sidebar// stayed on "Add a server" until the next launch.listServers.mockResolvedValue([]);- getActiveServerId.mockResolvedValue(null);+ selectServer(null);const store = new SwitchServersStore();await store.init();@@ -503,7 +701,7 @@ describe('keeping a server active', () => {it('does not move the workspace when a second server is added', async () => {listServers.mockResolvedValue([server('srv-a')]);- getActiveServerId.mockResolvedValue('srv-a');+ selectServer('srv-a');const store = new SwitchServersStore();await store.init();@@ -518,7 +716,7 @@ describe('keeping a server active', () => {it('leaves nothing active when there are no servers at all', async () => {listServers.mockResolvedValue([]);- getActiveServerId.mockResolvedValue(null);+ selectServer(null);const store = new SwitchServersStore();await store.init();diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.tsindex d10d1e625..2d04f94a6 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.ts@@ -1,8 +1,10 @@import { makeAutoObservable, runInAction } from 'mobx';import { hostReachabilityStore } from '@renderer/features/remote-hosts/host-reachability-store';-import { describeFailure } from '@renderer/lib/errors/describe-failure';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';+import { describeFailure, type FailureDescription } from '@renderer/lib/errors/describe-failure';import { rpc } from '@renderer/lib/ipc';import { appState } from '@renderer/lib/stores/app-state';+import type { InviteServer } from '@shared/core/switch-servers/switch-cloud';import type {ServerConnectionStatus,SwitchAuthConfig,@@ -10,6 +12,13 @@ import type {UpdateServerResult,} from '@shared/core/switch-servers/switch-servers';+/**+ * How long the first read of the server list may take before the window says so+ * instead of staying blank. Generous: this is local IPC, so anything near it is+ * already a handler that is not coming back.+ */+const LIST_READ_DEADLINE_MS = 10_000;+/*** Renderer store for the Switch-server integration. Holds the registered* gateways, the per-server connection status (so the sidebar can show a dot per@@ -21,7 +30,6 @@ import type {*/export class SwitchServersStore {servers: SwitchServer[] = [];- activeServerId: string | null = null;/** Connection status per server id, refreshed on focus / select / manually. */readonly statuses = new Map<string, ServerConnectionStatus>();@@ -63,9 +71,41 @@ export class SwitchServersStore {error: string | null = null;/** Diagnostics for the same failure, rendered under `error` rather than in it. */errorDetail: string | null = null;+ /**+ * The list read's own failure, as opposed to {@link error}, which every+ * action in this store writes — adding a server, renaming one, signing out.+ *+ * The shell decides what fills the window from this. Reading `error` there+ * would put the whole window into its failure shape because a rename went+ * wrong. Set only when a read fails and cleared only when one succeeds:+ * clearing it as a retry starts would take the failure page off screen — and+ * the retry button with it — for as long as the retry ran.+ */+ listError: string | null = null;+ /** Diagnostics for the failure in {@link listError}. */+ listErrorDetail: string | null = null;+ /**+ * Whether this install holds nothing at all — no server, no location, no+ * agent. Read alongside the list, because the shell decides between the+ * first-run page and the workspace from it and an empty server list is not+ * the same question: removing a server keeps its agents and says so, and+ * those agents plus the sessions running in them are still something to show.+ *+ * False until the first read lands; `loaded` is what separates that from an+ * install that really is empty.+ */+ installIsEmpty = false;+ /** The read in flight, so callers arriving together share one. Nothing renders it. */+ initInFlight: Promise<void> | null = null;+ /**+ * Which read is allowed to write. Bumped by each new read and by the deadline+ * below, so a read that has been given up on cannot land later and overwrite+ * the answer of the one that replaced it. Nothing renders it.+ */+ private listReadGeneration = 0;constructor() {- makeAutoObservable(this);+ makeAutoObservable(this, { initInFlight: false });}/** Headline and detail as one string, for the modals that have a single slot. */@@ -82,8 +122,24 @@ export class SwitchServersStore {return hostReachabilityStore.isBlocked(server.sshHost);}+ /**+ * The server the window is scoped to.+ *+ * Read off the active workspace rather than held here, so the two cannot+ * disagree. What the user selects is a workspace; the server is whichever one+ * hosts it, and the main process resolves it the same way.+ */+ get activeServerId(): string | null {+ return workspacesStore.activeServerId;+ }+get activeServer(): SwitchServer | null {- return this.servers.find((s) => s.id === this.activeServerId) ?? null;+ return this.serverById(this.activeServerId);+ }++ serverById(serverId: string | null): SwitchServer | null {+ if (!serverId) return null;+ return this.servers.find((s) => s.id === serverId) ?? null;}statusFor(serverId: string): ServerConnectionStatus | null {@@ -130,21 +186,48 @@ export class SwitchServersStore {return this.authConfigInFlight.has(serverId);}- async init(): Promise<void> {+ /**+ * Read the server list, once however many callers ask for it.+ *+ * The shell and the sidebar both ask on the first frame, and so does every+ * panel that needs a server list to draw. They share the read in flight+ * rather than making the same round-trip several times over; a caller+ * arriving after it settles starts a fresh one, so this never hands back a+ * stale answer to someone refreshing after a change of their own.+ */+ init(): Promise<void> {+ if (this.initInFlight) return this.initInFlight;+ // Only if it is still ours: a read given up on below is unhooked while it+ // is still running, and its eventual settling must not unhook the read that+ // replaced it.+ const read = this.readServers().finally(() => {+ if (this.initInFlight === read) this.initInFlight = null;+ });+ this.initInFlight = read;+ return read;+ }++ private async readServers(): Promise<void> {+ const generation = ++this.listReadGeneration;runInAction(() => {this.loadingServers = true;this.error = null;this.errorDetail = null;});+ const deadline = setTimeout(() => this.giveUpOnListRead(generation), LIST_READ_DEADLINE_MS);try {- const [servers, activeServerId] = await Promise.all([+ const [servers, installIsEmpty] = await Promise.all([rpc.switchServers.listServers(),- rpc.switchServers.getActiveServerId(),+ rpc.onboarding.installIsEmpty(),+ workspacesStore.refresh(),]);+ if (generation !== this.listReadGeneration) return;runInAction(() => {this.servers = servers;- this.activeServerId = activeServerId;+ this.installIsEmpty = installIsEmpty;this.loaded = true;+ this.listError = null;+ this.listErrorDetail = null;});// A page restored onto a server that has since been deleted can only be// judged once the list is known, and startup restores navigation before@@ -153,27 +236,63 @@ export class SwitchServersStore {await this.ensureActiveServer();await this.refreshAllStatuses();} catch (cause) {- this.setError(cause, 'Could not load your Switch servers.');- } finally {+ if (generation !== this.listReadGeneration) return;+ const { headline, detail } = this.setError(cause, 'Could not load your Switch servers.');runInAction(() => {- this.loadingServers = false;+ this.listError = headline;+ this.listErrorDetail = detail;});+ } finally {+ clearTimeout(deadline);+ if (generation === this.listReadGeneration) {+ runInAction(() => {+ this.loadingServers = false;+ });+ }}}/**- * A server is a workspace: the switcher, the sidebar and the sessions under- * it all read the active one, so one must be selected whenever any server- * exists. Nothing on the main side picks it — adding the first server leaves- * the active id null — so every path that changes the list ends here.+ * Stop waiting on a read that has not answered.+ *+ * Before the first one lands the shell has nothing to draw, so a handler that+ * never settles leaves a blank, inert window with no way to say anything went+ * wrong and no way to ask again. Saying so is the whole point: the read is+ * abandoned rather than cancelled — it cannot be cancelled — and the+ * generation bump is what stops it landing later on top of the retry's+ * answer.+ *+ * Only before the first success. Once there is a list in hand, a slow refresh+ * is not a reason to take the app away from someone using it.+ */+ private giveUpOnListRead(generation: number): void {+ if (generation !== this.listReadGeneration || this.loaded) return;+ this.listReadGeneration += 1;+ this.initInFlight = null;+ runInAction(() => {+ this.loadingServers = false;+ this.listError = 'Could not load your Switch servers.';+ this.listErrorDetail = `Nothing came back after ${LIST_READ_DEADLINE_MS / 1000} seconds.`;+ });+ }++ /**+ * The switcher, the sidebar and the sessions under it all read the active+ * workspace, so one must be selected whenever any exists. Nothing on the main+ * side picks it — adding the first server leaves the selection empty — so+ * every path that changes the list ends here.+ *+ * A stored selection that no longer names a workspace counts as none. It is+ * not hypothetical: removing the active server and adding another leaves the+ * id pointing at the removed one, and treating that as a selection left the+ * app with no workspace at all — no switcher, no sidebar tree, no way back.*- * A stored id that no longer names a server counts as no selection. It is not- * hypothetical: removing the active server and adding another leaves the id- * pointing at the removed one, and treating that as a selection left the app- * with no workspace at all — no switcher, no sidebar tree, no way back.+ * Which one it lands on is expressed over servers rather than workspaces,+ * because a server is what the user just added or removed, and its own+ * workspaces are then the main process's to choose between.*/private async ensureActiveServer(): Promise<void> {- if (this.activeServerId && this.servers.some((s) => s.id === this.activeServerId)) return;+ if (workspacesStore.active) return;const first = this.servers[0];if (first) await this.setActive(first.id);}@@ -328,13 +447,14 @@ export class SwitchServersStore {this.clearError();try {const created = await rpc.switchServers.addServer({ name, gatewayUrl, apiUrl });- const [servers, activeServerId] = await Promise.all([+ const [servers, installIsEmpty] = await Promise.all([rpc.switchServers.listServers(),- rpc.switchServers.getActiveServerId(),+ rpc.onboarding.installIsEmpty(),+ workspacesStore.refresh(),]);runInAction(() => {this.servers = servers;- this.activeServerId = activeServerId;+ this.installIsEmpty = installIsEmpty;});await this.ensureActiveServer();await this.refreshStatus(created.id);@@ -345,6 +465,52 @@ export class SwitchServersStore {}}+ /**+ * Register Switch Cloud, or take the row already registered for it.+ *+ * Raises rather than recording a store error like `addServer`: the Cloud is+ * chosen from a card with no form under it, so the card is where the failure+ * has to be shown.+ */+ async connectToSwitchCloud(): Promise<SwitchServer> {+ const server = await rpc.switchServers.connectToSwitchCloud();+ const [servers, installIsEmpty] = await Promise.all([+ rpc.switchServers.listServers(),+ rpc.onboarding.installIsEmpty(),+ workspacesStore.refresh(),+ ]);+ runInAction(() => {+ this.servers = servers;+ this.installIsEmpty = installIsEmpty;+ });+ await this.ensureActiveServer();+ await this.refreshStatus(server.id);+ return server;+ }++ /**+ * The server an invite link names, registering Switch Cloud when that is it.+ *+ * Refreshes like {@link connectToSwitchCloud} when a row was added, so the+ * sign-in page that follows finds the server in the list it reads.+ */+ async serverForInvite(origin: string): Promise<InviteServer> {+ const found = await rpc.switchServers.serverForInvite(origin);+ if (found.kind === 'unknown') return found;+ const [servers, installIsEmpty] = await Promise.all([+ rpc.switchServers.listServers(),+ rpc.onboarding.installIsEmpty(),+ workspacesStore.refresh(),+ ]);+ runInAction(() => {+ this.servers = servers;+ this.installIsEmpty = installIsEmpty;+ });+ await this.ensureActiveServer();+ await this.refreshStatus(found.server.id);+ return found;+ }+async updateServer(id: string,name: string,@@ -424,13 +590,12 @@ export class SwitchServersStore {* remote store, which disconnects from a shared remote server itself.*/async forgetRemovedServer(serverId: string): Promise<void> {- const [servers, activeServerId] = await Promise.all([+ const [servers] = await Promise.all([rpc.switchServers.listServers(),- rpc.switchServers.getActiveServerId(),+ workspacesStore.refresh(),]);runInAction(() => {this.servers = servers;- this.activeServerId = activeServerId;this.statuses.delete(serverId);this.authConfigs.delete(serverId);this.authConfigWanted.delete(serverId);@@ -444,13 +609,20 @@ export class SwitchServersStore {await this.ensureActiveServer();}+ /**+ * Scope the window to a server, for the callers that know only one — adding+ * a server, and following a navigation onto another server's room or agent.+ *+ * Which of its workspaces that lands on is the main process's to decide: it+ * keeps the current selection if it is already on this server, and otherwise+ * picks one. Picking here instead would make this store the second place that+ * answers the same question.+ */async setActive(serverId: string): Promise<void> {this.clearError();try {await rpc.switchServers.setActiveServer(serverId);- runInAction(() => {- this.activeServerId = serverId;- });+ await workspacesStore.refresh();} catch (cause) {this.setError(cause, 'Could not switch to that server.');}@@ -466,7 +638,9 @@ export class SwitchServersStore {});return false;}- await this.refreshStatus(serverId);+ // Signing in is when the server first says which workspaces the account+ // belongs to, so the list this app holds is stale the moment it returns.+ await Promise.all([this.refreshStatus(serverId), workspacesStore.refresh()]);return true;}@@ -483,7 +657,7 @@ export class SwitchServersStore {}return false;}- await this.refreshStatus(serverId);+ await Promise.all([this.refreshStatus(serverId), workspacesStore.refresh()]);return true;}@@ -509,13 +683,17 @@ export class SwitchServersStore {* shared boundary rather than carrying whatever was thrown. The fallback is* per-action: the store knows which request failed, and the failure itself* usually does not.+ *+ * Returns what it wrote, for the one caller that also keeps the failure in a+ * slot of its own.*/- private setError(cause: unknown, fallback: string): void {+ private setError(cause: unknown, fallback: string): FailureDescription {const { headline, detail } = describeFailure(cause, fallback);runInAction(() => {this.error = headline;this.errorDetail = detail;});+ return { headline, detail };}}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/use-my-identities.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/use-my-identities.tsindex 6e8a1fa2d..bc13dd5d9 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/use-my-identities.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/use-my-identities.ts@@ -5,21 +5,21 @@ import type { LinkedIdentity } from '@shared/core/switch-servers/switch-servers'/** Shared so every surface that claims or releases an identity refreshes the* same cache entry the owner-only warning reads. */-export function myIdentitiesQueryKey(serverId: string | null): unknown[] {- return ['my-switch-identities', serverId];+export function myIdentitiesQueryKey(workspaceId: string | null): unknown[] {+ return ['my-switch-identities', workspaceId];}/**- * The messaging accounts the signed-in user has claimed on a server+ * The messaging accounts the signed-in user has claimed in a workspace* (CHOO-2137).*- * `identities` is null while the answer is unknown — not signed in, no server- * chosen, still loading, or the read failed. Callers must treat that as+ * `identities` is null while the answer is unknown — not signed in, no+ * workspace chosen, still loading, or the read failed. Callers must treat that as* "unknown" rather than "none": warning that an owner-only agent is* unreachable, on the strength of a list that has not arrived, is the same* false alarm every time the page opens.*/-export function useMyIdentities(serverId: string | null): {+export function useMyIdentities(workspaceId: string | null): {identities: LinkedIdentity[] | null;isLoading: boolean;error: unknown;@@ -27,14 +27,14 @@ export function useMyIdentities(serverId: string | null): {} {const queryClient = useQueryClient();const query = useQuery({- queryKey: myIdentitiesQueryKey(serverId),- queryFn: () => rpc.switchServers.listMyIdentities(serverId as string),- enabled: serverId !== null,+ queryKey: myIdentitiesQueryKey(workspaceId),+ queryFn: () => rpc.workspaces.listMyIdentities(workspaceId as string),+ enabled: workspaceId !== null,});const refresh = useCallback(() => {- void queryClient.invalidateQueries({ queryKey: myIdentitiesQueryKey(serverId) });- }, [queryClient, serverId]);+ void queryClient.invalidateQueries({ queryKey: myIdentitiesQueryKey(workspaceId) });+ }, [queryClient, workspaceId]);return {identities: query.isSuccess ? query.data : null,diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/use-switch-cloud.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/use-switch-cloud.tsnew file mode 100644index 000000000..03d30e63d--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/use-switch-cloud.ts@@ -0,0 +1,41 @@+import { useEffect, useState } from 'react';+import { describeFailure } from '@renderer/lib/errors/describe-failure';+import { rpc } from '@renderer/lib/ipc';++/**+ * Whether this build can connect to Switch Cloud.+ *+ * Four states, not two. Not configured is the ordinary answer for a build that+ * was never pointed at a deployment. A configuration that could not be read is+ * a broken build or launch, and reporting it as "not open yet" would hide the+ * one thing that needs fixing.+ */+export type SwitchCloudAvailability =+ | { kind: 'reading' }+ | { kind: 'closed' }+ | { kind: 'open'; url: string }+ | { kind: 'failed'; headline: string; detail: string | null };++export function useSwitchCloud(): SwitchCloudAvailability {+ const [cloud, setCloud] = useState<SwitchCloudAvailability>({ kind: 'reading' });+ useEffect(() => {+ let current = true;+ void rpc.switchServers.switchCloud().then(+ (endpoint) => {+ if (current) setCloud(endpoint ? { kind: 'open', url: endpoint.url } : { kind: 'closed' });+ },+ (cause) => {+ if (current) {+ setCloud({+ kind: 'failed',+ ...describeFailure(cause, 'Could not read the Switch Cloud configuration.'),+ });+ }+ }+ );+ return () => {+ current = false;+ };+ }, []);+ return cloud;+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/view.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/view.tsxindex 15bf30100..e1568387e 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/view.tsx@@ -16,6 +16,7 @@ import { agentsStore } from '@renderer/features/locations/stores/agents-store';import { hostReachabilityStore } from '@renderer/features/remote-hosts/host-reachability-store';import { HostUnreachablePanel } from '@renderer/features/remote-hosts/host-unreachable-panel';import { useAppSettingsKey } from '@renderer/features/settings/use-app-settings-key';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { rpc } from '@renderer/lib/ipc';import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';import { useShowModal } from '@renderer/lib/modal/modal-provider';@@ -124,12 +125,15 @@ const ServerMainPanel = observer(function ServerMainPanel() {*/const refreshEverything = async (): Promise<void> => {setRefreshingPage(true);+ // The three caches below are keyed by workspace, so a server id would+ // invalidate nothing and the button would spin over stale cards.+ const workspaceId = workspacesStore.idOnServerInScope(serverId);try {await Promise.all([store.refreshServer(serverId),- queryClient.invalidateQueries({ queryKey: ['remote-bridges', serverId] }),- queryClient.invalidateQueries({ queryKey: myIdentitiesQueryKey(serverId) }),- queryClient.invalidateQueries({ queryKey: ['owns-owner-addressed-agent', serverId] }),+ queryClient.invalidateQueries({ queryKey: ['remote-bridges', workspaceId] }),+ queryClient.invalidateQueries({ queryKey: myIdentitiesQueryKey(workspaceId) }),+ queryClient.invalidateQueries({ queryKey: ['owns-owner-addressed-agent', workspaceId] }),switchRoomsStore.refreshRoomState(),agentsStore.load(),new Promise((resolve) => setTimeout(resolve, MIN_REFRESH_FEEDBACK_MS)),diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-admin.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-admin.tsnew file mode 100644index 000000000..561715894--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-admin.ts@@ -0,0 +1,14 @@+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';+import { administersWorkspace } from '@shared/core/workspaces/workspaces';+import { switchServersStore } from './switch-servers-store';++/**+ * Whether the signed-in account may manage the workspace a view about+ * `serverId` acts in: an owner or admin of that workspace, or the operator+ * running the server, whom the gateway lets administer every workspace.+ */+export function administersWorkspaceInScope(serverId: string): boolean {+ if (switchServersStore.statusFor(serverId)?.user?.role === 'admin') return true;+ const workspace = workspacesStore.onServerInScope(serverId);+ return workspace !== null && administersWorkspace(workspace);+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-switcher.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-switcher.tsxindex aaa72a706..603c41e39 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-switcher.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-switcher.tsx@@ -1,6 +1,21 @@-import { ChevronsUpDown, Plus } from 'lucide-react';+import { useQueryClient } from '@tanstack/react-query';+import { ChevronsUpDown, Plus, Server, UserPlus } from 'lucide-react';import { observer } from 'mobx-react-lite';import { useEffect } from 'react';+import {+ InvitedBadge,+ invitationSummary,+ joinableSummary,+ joinableWorkspacesKey,+ listedInvitations,+ listedJoinable,+ pendingInvitationsKey,+ useJoinableWorkspaces,+ usePendingInvitations,+} from '@renderer/features/workspaces/pending-invitations';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';+import { failureText } from '@renderer/lib/errors/describe-failure';+import { useToast } from '@renderer/lib/hooks/use-toast';import { useNavigate } from '@renderer/lib/layout/navigation-provider';import { useShowModal } from '@renderer/lib/modal/modal-provider';import { SwitchConsoleMark } from '@renderer/lib/switch-console-mark';@@ -16,8 +31,16 @@ import {import { Spinner } from '@renderer/lib/ui/spinner';import { cn } from '@renderer/utils/utils';import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';+import type { JoinableWorkspace, PendingInvitation } from '@shared/core/workspaces/invitations';+import {+ administersWorkspace,+ type Workspace,+ type WorkspaceUnavailability,+ workspaceUnavailability,+} from '@shared/core/workspaces/workspaces';import { localServerStore } from './local-server-store';import { remoteServerStore } from './remote-server-store';+import { serverAvailability } from './server-availability';import { serverIcon } from './server-icon';import {ServerAvatar,@@ -29,22 +52,65 @@ import {serverSubtitleLabel,} from './server-presentation';import { switchServersStore } from './switch-servers-store';+import { type SwitchCloudAvailability, useSwitchCloud } from './use-switch-cloud';++/**+ * How the button names where you are.+ *+ * A server registered before its workspaces are known names its only workspace+ * after itself, and until the account has been asked the two names are the same+ * — saying both would read as a stutter. Where they differ the server is the+ * more important half of the answer, since the same workspace name can exist on+ * two of them.+ */+function switcherSubtitle(workspace: Workspace, server: SwitchServer): string {+ const status = serverSubtitleLabel(server);+ return workspace.name === server.name ? status : `${server.name} · ${status}`;+}/**- * The workspace switcher at the top of the sidebar.+ * Whether the sidebar shows servers rather than workspaces.*- * A server is a workspace: the sidebar, its sessions and everything under them- * are scoped to whichever one is active, so exactly one is on screen at a time- * and the rest live behind this control. Before it, all servers were listed- * side by side and the scoping was left to be inferred from a highlighted row.+ * Workspaces are a Switch Cloud idea, so a build that cannot reach the Cloud+ * keeps the server list it had before them. A server row opens one workspace+ * on that server; any others the account has there are not offered from the+ * sidebar on such a build. A build whose Cloud configuration could not be read+ * keeps the workspace menu, so the broken configuration stays visible.+ */+export function showsServers(cloud: SwitchCloudAvailability['kind']): boolean {+ return cloud === 'reading' || cloud === 'closed';+}++/**+ * The workspace a server row opens: the one the window is already in when it+ * is on that server, otherwise the first that can be opened. Null when there is+ * none to open, with the first workspace's reason when there is one to give.+ */+export function serverRowWorkspace(+ workspaces: Workspace[],+ activeId: string | null+): { workspace: Workspace | null; unavailable: WorkspaceUnavailability | null } {+ const active = workspaces.find((w) => w.id === activeId);+ if (active) return { workspace: active, unavailable: null };+ const open = workspaces.find((w) => workspaceUnavailability(w, workspaces.length) === null);+ if (open) return { workspace: open, unavailable: null };+ const first = workspaces[0];+ return {+ workspace: null,+ unavailable: first ? workspaceUnavailability(first, workspaces.length) : null,+ };+}++/**+ * The switcher at the top of the sidebar: the workspace, or on a build without+ * Switch Cloud the server, that the window is scoped to.*- * With no servers there is nothing to switch between, so it collapses to the- * one action that leads anywhere.+ * With nothing to switch between it collapses to the one action that leads+ * anywhere.*/export const WorkspaceSwitcher = observer(function WorkspaceSwitcher() {const store = switchServersStore;- const { navigate } = useNavigate();- const showAddServerModal = useShowModal('addServerModal');+ const cloud = useSwitchCloud();useEffect(() => {void store.init();@@ -59,28 +125,44 @@ export const WorkspaceSwitcher = observer(function WorkspaceSwitcher() {};}, [store]);- const active = store.activeServer;+ const active = workspacesStore.active;+ const activeServer = active ? store.serverById(active.serverId) : null;- if (!active) {- return (- <div className="px-2">- <LocalServerPendingButton />- {localServerStore.phase === 'stopped' && (- <button- type="button"- onClick={() => showAddServerModal({})}- className="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-sm text-foreground-tertiary hover:bg-[var(--sel-soft)]"- >- <Plus className="size-4 shrink-0 text-foreground-muted" />- Add a server- </button>- )}- </div>- );- }+ if (!active || !activeServer) return <NoServerYet />;- const ActiveIcon = serverIcon(active);- const drift = serverDrift(active);+ return showsServers(cloud.kind) ? (+ <ServerMenu activeServer={activeServer} />+ ) : (+ <WorkspaceMenu active={active} activeServer={activeServer} />+ );+});++const NoServerYet = observer(function NoServerYet() {+ const showAddServerModal = useShowModal('addServerModal');+ return (+ <div className="px-2">+ <LocalServerPendingButton />+ {localServerStore.phase === 'stopped' && (+ <button+ type="button"+ onClick={() => showAddServerModal({})}+ className="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-sm text-foreground-tertiary hover:bg-[var(--sel-soft)]"+ >+ <Plus className="size-4 shrink-0 text-foreground-muted" />+ Add a server+ </button>+ )}+ </div>+ );+});++/** One row per server, as the sidebar had before workspaces. */+const ServerMenu = observer(function ServerMenu({ activeServer }: { activeServer: SwitchServer }) {+ const store = switchServersStore;+ const { navigate } = useNavigate();+ const showAddServerModal = useShowModal('addServerModal');+ const ActiveIcon = serverIcon(activeServer);+ const drift = serverDrift(activeServer);return (<div className="px-2">@@ -92,15 +174,15 @@ export const WorkspaceSwitcher = observer(function WorkspaceSwitcher() {aria-label="Switch server"className="flex w-full items-center gap-[10px] rounded-lg px-2 py-1.5 text-left hover:bg-[var(--sel-soft)]">- <ServerAvatar server={active} size="md" />+ <ServerAvatar server={activeServer} size="md" /><span className="min-w-0 flex-1"><span className="block truncate text-sm font-medium text-foreground">- {active.name}+ {activeServer.name}</span><span className="flex items-center gap-1.5 text-xs text-foreground-muted"><ActiveIcon className="size-3 shrink-0" />- <span className="truncate">{serverSubtitleLabel(active)}</span>- <ServerStatusDot server={active} />+ <span className="truncate">{serverSubtitleLabel(activeServer)}</span>+ <ServerStatusDot server={activeServer} />{drift && <ServerDriftIndicator drift={drift} />}</span></span>@@ -114,7 +196,11 @@ export const WorkspaceSwitcher = observer(function WorkspaceSwitcher() {Servers</DropdownMenuLabel>{store.servers.map((server) => (- <ServerMenuItem key={server.id} server={server} />+ <ServerMenuItem+ key={server.id}+ server={server}+ active={server.id === activeServer.id}+ />))}</DropdownMenuGroup><DropdownMenuSeparator />@@ -135,6 +221,168 @@ export const WorkspaceSwitcher = observer(function WorkspaceSwitcher() {);});+/**+ * A server, opened by switching to its one workspace.+ *+ * A server with no workspace has not finished registering, and one whose only+ * workspace this account has lost cannot be opened; both stay listed, disabled+ * and saying why, for the same reasons the workspace menu keeps such rows.+ */+const ServerMenuItem = observer(function ServerMenuItem({+ server,+ active,+}: {+ server: SwitchServer;+ active: boolean;+}) {+ const { navigate } = useNavigate();+ const { toast } = useToast();+ const Icon = serverIcon(server);+ const placement = serverPlacementLabel(server);+ const drift = serverDrift(server);+ const { workspace, unavailable } = serverRowWorkspace(+ workspacesStore.onServer(server.id),+ workspacesStore.activeId+ );+ const reason = unavailable+ ? UNAVAILABLE_REASON[unavailable](server.name)+ : !workspace+ ? 'This server has not finished being set up.'+ : undefined;++ return (+ <DropdownMenuItem+ aria-current={active ? 'true' : undefined}+ className={cn(active && 'bg-[var(--sel)]')}+ disabled={reason !== undefined}+ title={reason}+ onClick={() => {+ if (!workspace) return;+ void workspacesStore+ .setActive(workspace.id)+ .then(() => navigate('server', { serverId: server.id }))+ .catch(() => {+ toast({+ title: 'Could not switch server',+ description: `${server.name} is still there; the app stayed where it was.`,+ variant: 'destructive',+ });+ });+ }}+ >+ <ServerAvatar server={server} size="md" />+ <span className="min-w-0 flex-1">+ <span className="block truncate text-sm font-medium text-foreground">{server.name}</span>+ <span className="flex min-w-0 items-center gap-1.5 text-xs text-foreground-muted">+ <Icon className="size-3 shrink-0" />+ <span className="truncate">{serverStatusLabel(server)}</span>+ <ServerStatusDot server={server} />+ {(placement || unavailable) && (+ <span className="shrink-0 rounded bg-background-tertiary px-1 py-px text-[10px] font-medium tracking-wide text-foreground-muted uppercase">+ {unavailable ? UNAVAILABLE_BADGE[unavailable] : placement}+ </span>+ )}+ </span>+ </span>+ {drift && <ServerDriftIndicator drift={drift} />}+ </DropdownMenuItem>+ );+});++/**+ * Workspaces listed under the server hosting them rather than in one flat+ * list. A workspace only means anything on its server — two servers can each+ * have a "Default" — and the server is also what carries reachability, so the+ * group heading is where it is said once instead of on every row.+ */+const WorkspaceMenu = observer(function WorkspaceMenu({+ active,+ activeServer,+}: {+ active: Workspace;+ activeServer: SwitchServer;+}) {+ const store = switchServersStore;+ const { navigate } = useNavigate();+ const showAddServerModal = useShowModal('addServerModal');+ const showCreateWorkspaceModal = useShowModal('createWorkspaceModal');+ const showInvitePeopleModal = useShowModal('invitePeopleModal');++ const ActiveIcon = serverIcon(activeServer);+ const drift = serverDrift(activeServer);++ return (+ <div className="px-2">+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <button+ type="button"+ aria-label="Switch workspace"+ className="flex w-full items-center gap-[10px] rounded-lg px-2 py-1.5 text-left hover:bg-[var(--sel-soft)]"+ >+ <ServerAvatar server={activeServer} size="md" />+ <span className="min-w-0 flex-1">+ <span className="block truncate text-sm font-medium text-foreground">+ {active.name}+ </span>+ <span className="flex items-center gap-1.5 text-xs text-foreground-muted">+ <ActiveIcon className="size-3 shrink-0" />+ <span className="truncate">{switcherSubtitle(active, activeServer)}</span>+ <ServerStatusDot server={activeServer} />+ {drift && <ServerDriftIndicator drift={drift} />}+ </span>+ </span>+ <PendingInvitationCount server={activeServer} />+ <ChevronsUpDown className="size-3.5 shrink-0 text-foreground-muted" />+ </button>+ }+ />+ <DropdownMenuContent align="start" className="min-w-72">+ {store.servers.map((server) => (+ <ServerWorkspaceGroup key={server.id} server={server} />+ ))}+ <DropdownMenuSeparator />+ {/* Offered only where the gateway would take it: it refuses members,+ and a menu item that always ends in a 403 is a trap. */}+ {administersWorkspace(active) && (+ <DropdownMenuItem onClick={() => showInvitePeopleModal({ workspaceId: active.id })}>+ <UserPlus className="size-4" />+ Invite people to {active.name}+ </DropdownMenuItem>+ )}+ {/* Above Add server because it is the commoner errand by far: you add+ a server once and make workspaces on it for as long as you use+ it. It opens on the server you are already in — the modal asks+ which only where there is more than one to ask about. */}+ <DropdownMenuItem+ onClick={() =>+ showCreateWorkspaceModal({+ serverId: activeServer.id,+ onSuccess: (workspace) => navigate('server', { serverId: workspace.serverId }),+ })+ }+ >+ <Plus className="size-4" />+ New workspace+ </DropdownMenuItem>+ <DropdownMenuItem onClick={() => showAddServerModal({})}>+ <Server className="size-4" />+ Add server+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ {/* The welcome screen is what the app opens with before any server+ exists; once one does, this is how it stays reachable. */}+ <DropdownMenuItem onClick={() => navigate('home')}>+ <SwitchConsoleMark size={16} />+ About Switch+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ );+});+/*** A managed local stack that is starting has no server record yet, so it would* otherwise be invisible until it is healthy — and a failed setup invisible@@ -164,44 +412,283 @@ const LocalServerPendingButton = observer(function LocalServerPendingButton() {);});-const ServerMenuItem = observer(function ServerMenuItem({ server }: { server: SwitchServer }) {- const store = switchServersStore;- const { navigate } = useNavigate();+/** One server, as a heading over the workspaces the account has on it. */+const ServerWorkspaceGroup = observer(function ServerWorkspaceGroup({+ server,+}: {+ server: SwitchServer;+}) {const Icon = serverIcon(server);const placement = serverPlacementLabel(server);const drift = serverDrift(server);- const isActive = store.activeServerId === server.id;+ const workspaces = workspacesStore.onServer(server.id);++ return (+ <DropdownMenuGroup>+ <DropdownMenuLabel className="flex items-center gap-2 py-1.5">+ <ServerAvatar server={server} size="sm" />+ <span className="min-w-0 flex-1">+ <span className="block truncate text-xs font-medium text-foreground">{server.name}</span>+ <span className="flex min-w-0 items-center gap-1.5 text-xs font-normal text-foreground-muted">+ <Icon className="size-3 shrink-0" />+ <span className="truncate">{serverStatusLabel(server)}</span>+ {/* Beside the words it qualifies rather than at the row's right edge,+ where it read as a property of the row instead of of the status. */}+ <ServerStatusDot server={server} />+ {placement && (+ <span className="shrink-0 rounded bg-background-tertiary px-1 py-px text-[10px] font-medium tracking-wide text-foreground-muted uppercase">+ {placement}+ </span>+ )}+ </span>+ </span>+ {drift && <ServerDriftIndicator drift={drift} />}+ </DropdownMenuLabel>+ {workspaces.length === 0 ? (+ // Registering a server is what creates its first workspace, so a server+ // with none did not finish being registered. Saying so beats an empty+ // heading, which reads as a rendering fault.+ <div className="px-2 py-1.5 pl-9 text-xs text-foreground-muted">+ No workspace yet — this server has not finished being set up.+ </div>+ ) : (+ workspaces.map((workspace) => (+ <WorkspaceMenuItem+ key={workspace.id}+ workspace={workspace}+ server={server}+ onServerCount={workspaces.length}+ />+ ))+ )}+ {serverAvailability(server.id) === 'available' && (+ <>+ <PendingInvitationItems server={server} />+ <JoinableWorkspaceItems server={server} />+ </>+ )}+ </DropdownMenuGroup>+ );+});++const UNAVAILABLE_BADGE: Record<WorkspaceUnavailability, string> = {+ withdrawn: 'No longer a member',+ unmatched: 'Not matched',+};++/**+ * What to do about a workspace that cannot be opened — said on the row rather+ * than after the click, since the app already knows.+ *+ * The unmatched case deliberately does not say "sign in again": signing in+ * re-runs the reconcile, which is what left the row unmatched, and would do so+ * again. The row only survives because it holds agents, so the way out is the+ * workspace beside it plus adding those agents there.+ */+const UNAVAILABLE_REASON: Record<WorkspaceUnavailability, (name: string) => string> = {+ withdrawn: (name) =>+ `This account is no longer a member of ${name}. Its agents are still here; ask an admin to add you back to open it.`,+ unmatched: (name) =>+ `${name} was never matched to a workspace on this server, so there is no way to tell which one to ask for. Open one of the others; the agents left here have to be added again in the workspace they belong to.`,+};++const WorkspaceMenuItem = observer(function WorkspaceMenuItem({+ workspace,+ server,+ onServerCount,+}: {+ workspace: Workspace;+ server: SwitchServer;+ onServerCount: number;+}) {+ const { navigate } = useNavigate();+ const { toast } = useToast();+ const isActive = workspacesStore.activeId === workspace.id;+ // Kept in the list rather than hidden: its agents are still here and the row+ // is the only thing that says where they went. Disabled, because the gateway+ // refuses every call scoped to it — offering it would turn a fact the app+ // already knows into an error after the click.+ const unavailable = workspaceUnavailability(workspace, onServerCount);return (<DropdownMenuItem- // The active server is shown by filling its row rather than by a tick in- // the right margin, so the row you are on reads at a glance instead of+ // The active workspace is shown by filling its row rather than by a tick+ // in the right margin, so the row you are on reads at a glance instead of// needing the eye to travel to the end of it. `aria-current` carries the// same fact for anything that cannot see the fill.aria-current={isActive ? 'true' : undefined}- className={cn(isActive && 'bg-[var(--sel)]')}+ className={cn('pl-9', isActive && 'bg-[var(--sel)]')}+ disabled={unavailable !== null}+ title={unavailable ? UNAVAILABLE_REASON[unavailable](workspace.name) : undefined}onClick={() => {- void store.setActive(server.id);- navigate('server', { serverId: server.id });+ void workspacesStore+ .setActive(workspace.id)+ .then(() => navigate('server', { serverId: server.id }))+ .catch(() => {+ // Said out loud rather than swallowed: the sidebar would otherwise+ // keep showing the workspace you left, under the name of the one+ // you picked.+ toast({+ title: 'Could not switch workspace',+ description: `${workspace.name} is still there; the app stayed where it was.`,+ variant: 'destructive',+ });+ });}}>- <ServerAvatar server={server} size="md" />- <span className="min-w-0 flex-1">- <span className="block truncate text-sm font-medium text-foreground">{server.name}</span>- <span className="flex min-w-0 items-center gap-1.5 text-xs text-foreground-muted">- <Icon className="size-3 shrink-0" />- <span className="truncate">{serverStatusLabel(server)}</span>- {/* Beside the words it qualifies rather than at the row's right edge,- where it read as a property of the row instead of of the status. */}- <ServerStatusDot server={server} />- {placement && (- <span className="shrink-0 rounded bg-background-tertiary px-1 py-px text-[10px] font-medium tracking-wide text-foreground-muted uppercase">- {placement}- </span>- )}+ <span className="min-w-0 flex-1 truncate text-sm text-foreground">{workspace.name}</span>+ {(unavailable || workspace.role) && (+ <span className="shrink-0 rounded bg-background-tertiary px-1 py-px text-[10px] font-medium tracking-wide text-foreground-muted uppercase">+ {unavailable ? UNAVAILABLE_BADGE[unavailable] : workspace.role}</span>- </span>- {drift && <ServerDriftIndicator drift={drift} />}+ )}</DropdownMenuItem>);});++/**+ * How many invitations are waiting on the server you are in, on the switcher+ * button itself — the rows are behind the menu, and nothing else would say+ * they are there.+ */+const PendingInvitationCount = observer(function PendingInvitationCount({+ server,+}: {+ server: SwitchServer;+}) {+ if (serverAvailability(server.id) !== 'available') return null;+ return <PendingInvitationCountBadge serverId={server.id} />;+});++function PendingInvitationCountBadge({ serverId }: { serverId: string }) {+ const count = listedInvitations(usePendingInvitations(serverId).data).length;+ if (count === 0) return null;+ return (+ <span+ aria-label={count === 1 ? '1 invitation waiting' : `${count} invitations waiting`}+ className="bg-primary text-primary-foreground flex h-4 min-w-4 shrink-0 items-center justify-center rounded-full px-1 text-[10px] font-semibold"+ >+ {count}+ </span>+ );+}++/**+ * Invitations addressed to you on one server, under its workspaces. Choosing+ * one accepts it and opens the workspace it joins.+ *+ * A server too old to list them shows nothing, since it cannot say whether+ * there are any; a server that failed to answer says so, since then there may+ * be.+ */+function PendingInvitationItems({ server }: { server: SwitchServer }) {+ const query = usePendingInvitations(server.id);+ if (query.isError) {+ return (+ <div className="px-2 py-1.5 pl-9 text-xs text-foreground-muted">+ Could not check for invitations to your address.+ </div>+ );+ }+ return listedInvitations(query.data).map((invitation) => (+ <PendingInvitationMenuItem key={invitation.id} invitation={invitation} server={server} />+ ));+}++function PendingInvitationMenuItem({+ invitation,+ server,+}: {+ invitation: PendingInvitation;+ server: SwitchServer;+}) {+ const { navigate } = useNavigate();+ const { toast } = useToast();+ const queryClient = useQueryClient();++ return (+ <DropdownMenuItem+ className="pl-9"+ title={invitationSummary(invitation)}+ data-testid="pending-invitation-item"+ onClick={() => {+ void workspacesStore+ .acceptPendingInvitation(server.id, invitation)+ .then((workspace) => workspacesStore.setActive(workspace.id))+ .then(() => navigate('server', { serverId: server.id }))+ .catch((cause: unknown) => {+ toast({+ title: `Could not join ${invitation.workspaceName}`,+ description: failureText(cause, 'The invitation is still waiting.'),+ variant: 'destructive',+ });+ })+ .finally(+ () => void queryClient.invalidateQueries({ queryKey: pendingInvitationsKey(server.id) })+ );+ }}+ >+ <span className="min-w-0 flex-1 truncate text-sm text-foreground">+ {invitation.workspaceName}+ </span>+ <InvitedBadge />+ </DropdownMenuItem>+ );+}++/**+ * Workspaces open to the domain of your address on one server, after its+ * invitations, on the same terms. Choosing one joins it as a member.+ */+function JoinableWorkspaceItems({ server }: { server: SwitchServer }) {+ const query = useJoinableWorkspaces(server.id);+ if (query.isError) {+ return (+ <div className="px-2 py-1.5 pl-9 text-xs text-foreground-muted">+ Could not check for workspaces open to your e-mail domain.+ </div>+ );+ }+ return listedJoinable(query.data).map((offer) => (+ <JoinableWorkspaceMenuItem key={offer.tenantId} offer={offer} server={server} />+ ));+}++function JoinableWorkspaceMenuItem({+ offer,+ server,+}: {+ offer: JoinableWorkspace;+ server: SwitchServer;+}) {+ const { navigate } = useNavigate();+ const { toast } = useToast();+ const queryClient = useQueryClient();++ return (+ <DropdownMenuItem+ className="pl-9"+ title={joinableSummary(offer)}+ data-testid="joinable-workspace-item"+ onClick={() => {+ void workspacesStore+ .joinByDomain(server.id, offer)+ .then((workspace) => workspacesStore.setActive(workspace.id))+ .then(() => navigate('server', { serverId: server.id }))+ .catch((cause: unknown) => {+ toast({+ title: `Could not join ${offer.workspaceName}`,+ description: failureText(cause, 'Joining failed.'),+ variant: 'destructive',+ });+ })+ .finally(+ () => void queryClient.invalidateQueries({ queryKey: joinableWorkspacesKey(server.id) })+ );+ }}+ >+ <span className="min-w-0 flex-1 truncate text-sm text-foreground">{offer.workspaceName}</span>+ <span className="shrink-0 text-xs font-medium text-foreground-muted">Join</span>+ </DropdownMenuItem>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/agent-template-data.ts b/console/apps/switch-console-desktop/src/renderer/features/templates/agent-template-data.tsindex 133d4e935..67af9d2e8 100644--- a/console/apps/switch-console-desktop/src/renderer/features/templates/agent-template-data.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/agent-template-data.ts@@ -4,6 +4,7 @@ import type { TemplateSummary } from '@main/core/agent-templates/template-summarimport type { AgentTemplateOrigin } from '@main/core/agents/agent-config-file';import type { ParsedTemplate } from '@main/core/room-templates/controller';import type { StoredTemplateSummary } from '@main/core/switch-servers/gateway-client';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { rpc } from '@renderer/lib/ipc';import { type BundledTemplate, bundledTemplates, findBundledTemplate } from './bundled-templates';@@ -73,18 +74,37 @@ export async function loadAgentTemplateByOrigin(if (!bundled) throw new Error(`This Console no longer bundles "${origin.name}".`);return agentTemplateFromContent(origin.name, bundled.yamlText, bundled.instructions, origin);}- if (!origin.serverId)- throw new Error(`"${origin.name}" came from a server this Console does not know.`);- const detail = await rpc.switchServers.getTemplateDetail({- serverId: origin.serverId,+ const detail = await rpc.workspaces.getTemplateDetail({+ workspaceId: templateWorkspaceId(origin),templateId: origin.id,});return agentTemplateFromContent(origin.name, detail.definition, null, origin);}+/**+ * The workspace to ask for a server template, from what the origin recorded.+ *+ * A registry belongs to a workspace, so an origin naming only a server is+ * answerable exactly while that server holds one. Where it holds several the+ * window's own workspace is not an answer: it would load a different template+ * of the same id, or none, and offer it as this agent's.+ */+function templateWorkspaceId(origin: AgentTemplateOrigin): string {+ if (origin.workspaceId) return origin.workspaceId;+ if (!origin.serverId)+ throw new Error(`"${origin.name}" came from a server this Console does not know.`);+ const onServer = workspacesStore.onServer(origin.serverId);+ if (onServer.length === 1) return onServer[0]!.id;+ if (onServer.length === 0)+ throw new Error(`The workspace "${origin.name}" came from is not known yet.`);+ throw new Error(+ `"${origin.name}" was recorded before this Console kept which workspace a template came from, and its Switch server now has ${onServer.length}. Open it from that workspace's template list instead.`+ );+}+/** Resolve a listing entry (bundled or from the server's registry) into the agent it describes. */export async function loadAgentTemplate(- serverId: string,+ workspaceId: string,template: StoredTemplateSummary): Promise<AgentTemplate> {const bundled = findBundledTemplate(template.id);@@ -95,12 +115,14 @@ export async function loadAgentTemplate(source: 'bundled',});}- const detail = await rpc.switchServers.getTemplateDetail({ serverId, templateId: template.id });+ const detail = await rpc.workspaces.getTemplateDetail({ workspaceId, templateId: template.id });+ const serverId = workspacesStore.serverIdFor(workspaceId);return agentTemplateFromContent(detail.name, detail.definition, null, {id: detail.id,name: detail.name,source: 'server',- serverId,+ workspaceId,+ ...(serverId ? { serverId } : {}),});}@@ -135,7 +157,7 @@ export type LoadedTemplate = {* owner, so someone else's template of the same name is not a copy.*/export async function loadTemplateById(- serverId: string,+ workspaceId: string,templateId: string,meId: string | null): Promise<LoadedTemplate> {@@ -148,7 +170,7 @@ export async function loadTemplateById(let savedCopy: StoredTemplateSummary | null = null;if (bundled) {savedCopy =- (await rpc.switchServers.listTemplates({ serverId }).catch(() => [])).find(+ (await rpc.workspaces.listTemplates({ workspaceId }).catch(() => [])).find((t) => t.name === bundled.name && meId !== null && t.ownerId === meId) ?? null;name = bundled.name;@@ -160,7 +182,7 @@ export async function loadTemplateById(}): bundled.yamlText;} else {- const detail = await rpc.switchServers.getTemplateDetail({ serverId, templateId });+ const detail = await rpc.workspaces.getTemplateDetail({ workspaceId, templateId });const { definition, ...summary } = detail;name = detail.name;description = detail.description;diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/save-template-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/templates/save-template-modal.tsxindex 0d1a433ad..285d7646a 100644--- a/console/apps/switch-console-desktop/src/renderer/features/templates/save-template-modal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/save-template-modal.tsx@@ -1,4 +1,5 @@import { useId, useState } from 'react';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { failureText } from '@renderer/lib/errors/describe-failure';import { toast } from '@renderer/lib/hooks/use-toast';import { rpc } from '@renderer/lib/ipc';@@ -53,12 +54,18 @@ export function SaveTemplateModal({const [saving, setSaving] = useState(false);const [error, setError] = useState<string | null>(null);+ const workspaceId = workspacesStore.idOnServerInScope(serverId);+const save = async () => {+ if (workspaceId === null) {+ setError('This server’s workspace is not known yet.');+ return;+ }setSaving(true);setError(null);try {- const saved = await rpc.switchServers.saveTemplate({- serverId,+ const saved = await rpc.workspaces.saveTemplate({+ workspaceId,name: name.trim(),description: description.trim(),kind,diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/template-detail-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/templates/template-detail-view.tsxindex a078cdabf..9df654e55 100644--- a/console/apps/switch-console-desktop/src/renderer/features/templates/template-detail-view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/template-detail-view.tsx@@ -15,6 +15,7 @@ import { useEffect, useState } from 'react';import type { GuardResult, ViewDefinition } from '@renderer/app/view-registry';import { ServerSectionTitlebar } from '@renderer/features/switch-servers/server-section-titlebar';import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { PageHeader } from '@renderer/lib/components/page-header';import { failureText } from '@renderer/lib/errors/describe-failure';import { toast } from '@renderer/lib/hooks/use-toast';@@ -155,6 +156,7 @@ const KIND_LABEL: Record<LoadedTemplate['kind'], string> = {const TemplateDetailPanel = observer(function TemplateDetailPanel() {const { serverId, templateId } = useViewParams();+ const workspaceId = workspacesStore.idOnServerInScope(serverId);const { navigate } = useNavigate();const server = switchServersStore.servers.find((s) => s.id === serverId);const me = switchServersStore.statusFor(serverId)?.user ?? null;@@ -167,10 +169,18 @@ const TemplateDetailPanel = observer(function TemplateDetailPanel() {const [showInstructions, setShowInstructions] = useState(false);useEffect(() => {+ // No workspace is an answer, not a wait. Returning with neither a template+ // nor an error leaves the spinner below up forever, claiming something is+ // on its way that nobody is fetching.+ if (workspaceId === null) {+ setLoaded(null);+ setError('This server has no workspace yet, so its templates cannot be read.');+ return;+ }let cancelled = false;setLoaded(null);setError(null);- loadTemplateById(serverId, templateId, me?.id ?? null)+ loadTemplateById(workspaceId, templateId, me?.id ?? null).then((t) => {if (cancelled) return;setLoaded(t);@@ -183,7 +193,7 @@ const TemplateDetailPanel = observer(function TemplateDetailPanel() {cancelled = true;setCurrentName(null);};- }, [serverId, templateId, me?.id]);+ }, [workspaceId, templateId, me?.id]);const back = (<Button@@ -232,11 +242,11 @@ const TemplateDetailPanel = observer(function TemplateDetailPanel() {const use = () => navigate('templateUse', { serverId, templateId });const saveToServer = async () => {- if (!loaded.bundled) return;+ if (!loaded.bundled || workspaceId === null) return;setBusy('save');try {- const saved = await rpc.switchServers.saveTemplate({- serverId,+ const saved = await rpc.workspaces.saveTemplate({+ workspaceId,name: loaded.bundled.name,description: loaded.bundled.description,kind: loaded.bundled.kind,@@ -256,10 +266,10 @@ const TemplateDetailPanel = observer(function TemplateDetailPanel() {};const remove = async () => {- if (!loaded.server) return;+ if (!loaded.server || workspaceId === null) return;setBusy('delete');try {- await rpc.switchServers.deleteTemplate({ serverId, templateId: loaded.server.id });+ await rpc.workspaces.deleteTemplate({ workspaceId, templateId: loaded.server.id });toast({ title: `"${loaded.name}" removed from ${server?.name ?? 'the workspace'}` });navigate('templates', { serverId });} catch (e) {diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/template-runs-list.tsx b/console/apps/switch-console-desktop/src/renderer/features/templates/template-runs-list.tsxindex edf72ff13..2c892784b 100644--- a/console/apps/switch-console-desktop/src/renderer/features/templates/template-runs-list.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/template-runs-list.tsx@@ -20,24 +20,25 @@ const LIVE_RUN_POLL_MS = 15_000;* Quiet on failure: an older server without runs answers 404 and the list* stays empty, and a failed refresh keeps what was already shown.*/-export function useTemplateRuns(serverId: string): {+export function useTemplateRuns(workspaceId: string | null): {runs: TemplateRun[];replace: (run: TemplateRun) => void;} {const [runs, setRuns] = useState<TemplateRun[]>([]);- // An answer that lands after the listing moved to another server belongs- // to the old one and is dropped.- const shownServer = useRef(serverId);- shownServer.current = serverId;+ // An answer that lands after the listing moved to another workspace+ // belongs to the old one and is dropped.+ const shownWorkspace = useRef(workspaceId);+ shownWorkspace.current = workspaceId;const load = useCallback(async () => {+ if (workspaceId === null) return;try {- const list = await rpc.switchServers.listTemplateRuns({ serverId });- if (shownServer.current === serverId) setRuns(list ?? []);+ const list = await rpc.workspaces.listTemplateRuns({ workspaceId });+ if (shownWorkspace.current === workspaceId) setRuns(list ?? []);} catch {// The runs are an addition to the recents; the section renders without them.}- }, [serverId]);+ }, [workspaceId]);useEffect(() => {setRuns([]);@@ -98,11 +99,11 @@ function RunState({ run }: { run: TemplateRun }) {* room the run started from.*/export function TemplateRunRow({- serverId,+ workspaceId,run,onChanged,}: {- serverId: string;+ workspaceId: string;run: TemplateRun;onChanged: (run: TemplateRun) => void;}) {@@ -116,11 +117,11 @@ export function TemplateRunRow({const change = async (action: 'stop' | 'continue') => {setBusy(action);try {- const params = { serverId, rootRoomId: run.rootRoomId };+ const params = { workspaceId, rootRoomId: run.rootRoomId };onChanged(action === 'stop'- ? await rpc.switchServers.stopTemplateRun(params)- : await rpc.switchServers.continueTemplateRun(params)+ ? await rpc.workspaces.stopTemplateRun(params)+ : await rpc.workspaces.continueTemplateRun(params));} catch (error) {toast({diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/template-use-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/templates/template-use-view.tsxindex 5d46d8ccc..0c51dd6b5 100644--- a/console/apps/switch-console-desktop/src/renderer/features/templates/template-use-view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/template-use-view.tsx@@ -28,13 +28,17 @@ import { refreshSidebarRoomState } from '@renderer/features/sidebar/sidebar-treeimport { ServerSectionTitlebar } from '@renderer/features/switch-servers/server-section-titlebar';import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';import { useMyIdentities } from '@renderer/features/switch-servers/use-my-identities';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { failureText } from '@renderer/lib/errors/describe-failure';import { toast } from '@renderer/lib/hooks/use-toast';import { rpc } from '@renderer/lib/ipc';import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';import { useModalContext } from '@renderer/lib/modal/modal-provider';import { useAgentTypeAvailability } from '@renderer/lib/stores/use-agent-type-availability';-import { remoteAgentsQueryKey, useRemoteAgents } from '@renderer/lib/stores/use-remote-agents';+import {+ useWorkspaceAgents,+ workspaceAgentsQueryKey,+} from '@renderer/lib/stores/use-workspace-agents';import { Alert, AlertDescription } from '@renderer/lib/ui/alert';import { Button } from '@renderer/lib/ui/button';import { Switch } from '@renderer/lib/ui/switch';@@ -119,7 +123,7 @@ type UsePageTemplate = {warnings: string[];};-async function loadUsePageTemplate(serverId: string, params: Params): Promise<UsePageTemplate> {+async function loadUsePageTemplate(workspaceId: string, params: Params): Promise<UsePageTemplate> {let name: string;let yamlText: string;let instructions: string | null = null;@@ -132,13 +136,20 @@ async function loadUsePageTemplate(serverId: string, params: Params): Promise<Usinstructions = bundled.instructions;origin = { id: bundled.id, name: bundled.name, source: 'bundled' };} else {- const detail = await rpc.switchServers.getTemplateDetail({- serverId,+ const detail = await rpc.workspaces.getTemplateDetail({+ workspaceId,templateId: params.templateId,});name = detail.name;yamlText = detail.definition;- origin = { id: detail.id, name: detail.name, source: 'server', serverId };+ const serverId = workspacesStore.serverIdFor(workspaceId);+ origin = {+ id: detail.id,+ name: detail.name,+ source: 'server',+ workspaceId,+ ...(serverId ? { serverId } : {}),+ };}} else if (params.yamlText) {name = params.sourceName?.replace(/(\.template)?\.ya?ml$/i, '') ?? 'Pasted template';@@ -158,7 +169,7 @@ async function loadUsePageTemplate(serverId: string, params: Params): Promise<Us// Without the schema the form is built from the Console's own parse and// the server validates on create, so an older server without the schema// endpoint still gets a working page.- const schema = await rpc.switchServers.fetchTemplateSchema(serverId).catch(() => null);+ const schema = await rpc.workspaces.fetchTemplateSchema(workspaceId).catch(() => null);const parsed = forForm? await rpc.roomTemplates.parse({ yamlText: forForm, schema: schema ?? undefined }): null;@@ -237,6 +248,7 @@ type SlotSetup = {const TemplateUsePanel = observer(function TemplateUsePanel() {const params = useViewParams();const { serverId, intoRoomId = null } = params;+ const workspaceId = workspacesStore.idOnServerInScope(serverId);const { navigate } = useNavigate();const { showModal } = useModalContext();const queryClient = useQueryClient();@@ -255,7 +267,7 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {// What the server returned for the room, kept so that a step failing after// it does not make Retry create the room a second time.const createdRoom = useRef<Awaited<- ReturnType<typeof rpc.switchServers.createRoomFromTemplate>+ ReturnType<typeof rpc.workspaces.createRoomFromTemplate>> | null>(null);const [roomStatus, setRoomStatus] = useState<SlotStatus>('idle');const [createError, setCreateError] = useState<string | null>(null);@@ -276,10 +288,18 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {// render would reset the form.const { templateId, yamlText: givenYaml, sourceName } = params;useEffect(() => {+ // No workspace is an answer, not a wait. Returning with neither a template+ // nor an error leaves the page spinning forever, and Deploy reading+ // "Loading…" for something nobody is fetching.+ if (workspaceId === null) {+ setLoaded(null);+ setLoadError('This server has no workspace yet, so this template cannot be read.');+ return;+ }let cancelled = false;setLoaded(null);setLoadError(null);- loadUsePageTemplate(serverId, { serverId, templateId, yamlText: givenYaml, sourceName })+ loadUsePageTemplate(workspaceId, { serverId, templateId, yamlText: givenYaml, sourceName }).then((result) => {if (cancelled) return;setLoaded(result);@@ -305,7 +325,7 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {return () => {cancelled = true;};- }, [serverId, templateId, givenYaml, sourceName]);+ }, [serverId, workspaceId, templateId, givenYaml, sourceName]);const parsed = loaded?.parsed ?? null;// In the singular `agent:` form the room refers to the agent as `{agent}`.@@ -364,20 +384,23 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {const directoryParam = unboundOfType('directory');// ── Server lists (pickers, identities, bridges) ─────────────────────────- const agents = useRemoteAgents(serverId);+ const agents = useWorkspaceAgents(workspaceId);const roomsQuery = useQuery({- queryKey: ['remote-rooms', serverId],- queryFn: () => rpc.switchServers.listRemoteRooms(serverId),+ queryKey: ['remote-rooms', workspaceId],+ queryFn: () => rpc.workspaces.listRooms(workspaceId as string),+ enabled: workspaceId !== null,});const bridgesQuery = useQuery({- queryKey: ['remote-bridges', serverId],- queryFn: () => rpc.switchServers.listRemoteBridges(serverId),+ queryKey: ['remote-bridges', workspaceId],+ queryFn: () => rpc.workspaces.listBridges(workspaceId as string),+ enabled: workspaceId !== null,});const knownUsersQuery = useQuery({- queryKey: ['remote-external-users', serverId],- queryFn: () => rpc.switchServers.listRemoteExternalUsers(serverId),+ queryKey: ['remote-external-users', workspaceId],+ queryFn: () => rpc.workspaces.listExternalUsers(workspaceId as string),+ enabled: workspaceId !== null,});- const { identities, refresh: refreshIdentities } = useMyIdentities(serverId);+ const { identities, refresh: refreshIdentities } = useMyIdentities(workspaceId);const bridges = useMemo(() => bridgesQuery.data ?? [], [bridgesQuery.data]);const allowedHosts = useAllowedHosts(serverId);const hostLabel = useCallback(@@ -408,19 +431,20 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {templateBridge !== null &&identities !== null &&creatorIdentity === null;- const linkAccount = templateBridge- ? () =>- showModal('claimIdentityModal', {- serverId,- bridgeId: templateBridge.id,- onSuccess: () => refreshIdentities(),- })- : null;+ const linkAccount =+ templateBridge && workspaceId !== null+ ? () =>+ showModal('claimIdentityModal', {+ workspaceId,+ bridgeId: templateBridge.id,+ onSuccess: () => refreshIdentities(),+ })+ : null;const noMessagingApp = parsed !== null && bridgesQuery.data !== undefined && bridges.length === 0;const lists = useMemo((): EntityLists => ({- serverId,+ workspaceId,agents: agents.data ?? [],agentsLoading: agents.isLoading,rooms: roomsQuery.data ?? [],@@ -431,7 +455,7 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {bridgeId: templateBridge?.id ?? null,}),[- serverId,+ workspaceId,agents.data,agents.isLoading,roomsQuery.data,@@ -674,7 +698,7 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {const blockedReason: string | null =phase !== 'form'? null- : loaded === null+ : loaded === null || workspaceId === null? 'Loading…': missing.length > 0? `Fill in ${missing.map(paramLabel).join(', ')}`@@ -719,6 +743,7 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {}, [parsed, editedAgents, templateParams, values, slots, agents.data]);const [allowingHandoffs, setAllowingHandoffs] = useState(false);const allowHandoffs = useCallback(async () => {+ if (workspaceId === null) return;const byName = new Map((agents.data ?? []).map((a) => [a.name, a]));setAllowingHandoffs(true);try {@@ -740,26 +765,26 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {}return next;});- await rpc.switchServers.updateAddressingPolicy({- serverId,+ await rpc.workspaces.updateAddressingPolicy({+ workspaceId,agentId: target.id,policy: { rules },});}- await queryClient.invalidateQueries({ queryKey: remoteAgentsQueryKey(serverId) });+ await queryClient.invalidateQueries({ queryKey: workspaceAgentsQueryKey(workspaceId) });} catch (e) {toast({ title: failureText(e, 'Could not update the agents.'), variant: 'destructive' });} finally {setAllowingHandoffs(false);}- }, [agents.data, handoffBlocked, serverId, queryClient]);+ }, [agents.data, handoffBlocked, workspaceId, queryClient]);// ── Create ──────────────────────────────────────────────────────────────const setSlot = (i: number, patch: Partial<AgentSlot>) =>setSlots((prev) => prev.map((s, j) => (j === i ? { ...s, ...patch } : s)));const createAll = async () => {- if (!loaded || blockedReason !== null) return;+ if (!loaded || workspaceId === null || blockedReason !== null) return;setPhase('creating');setCreateError(null);setFieldErrors({});@@ -830,8 +855,8 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {// must be written as the open policy; leaving the default would keep it closed.if (switchAgentId && slot.entry.addressing) {setSlot(i, { step: 'policy' });- await rpc.switchServers.updateAddressingPolicy({- serverId,+ await rpc.workspaces.updateAddressingPolicy({+ workspaceId,agentId: switchAgentId,policy:slot.entry.addressing === 'owner-agents'@@ -854,7 +879,7 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {// fails must not fail the run.await agentsStore.load().catch(() => {});await queryClient- .invalidateQueries({ queryKey: remoteAgentsQueryKey(serverId) })+ .invalidateQueries({ queryKey: workspaceAgentsQueryKey(workspaceId) }).catch(() => {});}// A recent is used again from its own text, so a bundled template whose@@ -910,8 +935,8 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {setRoomStatus('creating');try {for (const [roomId, ids] of joinsByRoom) {- await rpc.switchServers.addRoomAgents({- serverId,+ await rpc.workspaces.addRoomAgents({+ workspaceId,roomId,agentIds: [...new Set(ids)],direction: 'agents_to_room',@@ -994,7 +1019,7 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {}const result =createdRoom.current ??- (await rpc.switchServers.createRoomFromTemplate(serverId, coreYaml, inputs, loaded.name));+ (await rpc.workspaces.createRoomFromTemplate(workspaceId, coreYaml, inputs, loaded.name));createdRoom.current = result;setRoomStatus('created');// The room exists whether or not the sidebar refreshes.diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/templates-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/templates/templates-view.tsxindex 3cef4e4f3..6286a70e9 100644--- a/console/apps/switch-console-desktop/src/renderer/features/templates/templates-view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/templates-view.tsx@@ -21,6 +21,7 @@ import type { GuardResult, ViewDefinition } from '@renderer/app/view-registry';import { ServerPage } from '@renderer/features/switch-servers/server-page';import { ServerSectionTitlebar } from '@renderer/features/switch-servers/server-section-titlebar';import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { failureText } from '@renderer/lib/errors/describe-failure';import { toast } from '@renderer/lib/hooks/use-toast';import { rpc } from '@renderer/lib/ipc';@@ -117,18 +118,18 @@ function summaryLine(s: TemplateSummary): string {// template and keeps it for the session.const summaryCache = new Map<string, Promise<TemplateSummary>>();-function fetchSummary(serverId: string, item: TemplateListEntry): Promise<TemplateSummary> {+function fetchSummary(workspaceId: string, item: TemplateListEntry): Promise<TemplateSummary> {// The version is part of the key, so an edit made elsewhere refreshes the// card as soon as the listing reports it.- const key = `${serverId}:${item.id}:${item.server?.version ?? 0}`;+ const key = `${workspaceId}:${item.id}:${item.server?.version ?? 0}`;let pending = summaryCache.get(key);if (!pending) {pending = (async () => {const yamlText =item.content ??(- await rpc.switchServers.getTemplateDetail({- serverId,+ await rpc.workspaces.getTemplateDetail({+ workspaceId,templateId: item.id,})).definition;@@ -140,11 +141,15 @@ function fetchSummary(serverId: string, item: TemplateListEntry): Promise<Templareturn pending;}-function useTemplateSummary(serverId: string, item: TemplateListEntry): TemplateSummary | null {+function useTemplateSummary(+ workspaceId: string | null,+ item: TemplateListEntry+): TemplateSummary | null {const [summary, setSummary] = useState<TemplateSummary | null>(null);useEffect(() => {+ if (workspaceId === null) return;let cancelled = false;- fetchSummary(serverId, item)+ fetchSummary(workspaceId, item).then((s) => {if (!cancelled) setSummary(s);})@@ -154,7 +159,7 @@ function useTemplateSummary(serverId: string, item: TemplateListEntry): Templatereturn () => {cancelled = true;};- }, [serverId, item]);+ }, [workspaceId, item]);return summary;}@@ -174,14 +179,14 @@ function OwnerRow({ name, mine }: { name: string; mine: boolean }) {}function TemplateCard({- serverId,+ workspaceId,item,meId,busy,onOpen,onUse,}: {- serverId: string;+ workspaceId: string | null;item: TemplateListEntry;meId: string | null;busy: boolean;@@ -189,7 +194,7 @@ function TemplateCard({onUse: () => void;}) {const Icon = KIND_ICON[item.kind];- const summary = useTemplateSummary(serverId, item);+ const summary = useTemplateSummary(workspaceId, item);const mine = item.server !== null && meId !== null && item.server.ownerId === meId;return (<div className="group relative flex min-h-[168px] flex-col rounded-[11px] border border-border bg-background transition-colors hover:border-border-1">@@ -262,6 +267,7 @@ function Section({*/function RecentsSection({serverId,+ workspaceId,serverName,onWorkspace,kind,@@ -269,6 +275,7 @@ function RecentsSection({onSaved,}: {serverId: string;+ workspaceId: string | null;serverName: string | null;/** Names of templates saved on the workspace. A recent with one of these names gets no Save button. */onWorkspace: ReadonlySet<string>;@@ -282,7 +289,7 @@ function RecentsSection({// Each recent with its kind, classified by the same parser as the listing.const [recents, setRecents] = useState<(RecentTemplate & { kind: TemplateKind })[] | null>(null);const [saving, setSaving] = useState<string | null>(null);- const { runs, replace: replaceRun } = useTemplateRuns(serverId);+ const { runs, replace: replaceRun } = useTemplateRuns(workspaceId);useEffect(() => {let cancelled = false;@@ -360,14 +367,15 @@ function RecentsSection({<span>When</span><span /></div>- {shownRuns.map((run) => (- <TemplateRunRow- key={run.rootRoomId}- serverId={serverId}- run={run}- onChanged={replaceRun}- />- ))}+ {workspaceId !== null &&+ shownRuns.map((run) => (+ <TemplateRunRow+ key={run.rootRoomId}+ workspaceId={workspaceId}+ run={run}+ onChanged={replaceRun}+ />+ ))}{shown.map((r) => {const Icon = KIND_ICON[r.kind];const saved = onWorkspace.has(r.name);@@ -416,6 +424,7 @@ function RecentsSection({const TemplatesPanel = observer(function TemplatesPanel() {const serverId = useServerId();+ const workspaceId = workspacesStore.idOnServerInScope(serverId);const server = switchServersStore.servers.find((s) => s.id === serverId);const meId = switchServersStore.statusFor(serverId)?.user?.id ?? null;const { navigate } = useNavigate();@@ -439,14 +448,14 @@ const TemplatesPanel = observer(function TemplatesPanel() {const [searchHits, setSearchHits] = useState<StoredTemplateSummary[] | null>(null);useEffect(() => {const q = query.trim();- if (q.length === 0) {+ if (q.length === 0 || workspaceId === null) {setSearchHits(null);return;}let cancelled = false;const timer = window.setTimeout(() => {- rpc.switchServers- .listTemplates({ serverId, q })+ rpc.workspaces+ .listTemplates({ workspaceId, q }).then((hits) => {if (!cancelled) setSearchHits(hits);})@@ -459,7 +468,7 @@ const TemplatesPanel = observer(function TemplatesPanel() {cancelled = true;window.clearTimeout(timer);};- }, [serverId, query, reloadKey]);+ }, [workspaceId, query, reloadKey]);// An agent template needs a coding agent where its agents will run, and// this computer is the default run location. Say at the top of the listing@@ -469,11 +478,19 @@ const TemplatesPanel = observer(function TemplatesPanel() {const noProvider = availability !== undefined && !availability.some((a) => a.available);useEffect(() => {+ // No workspace is an answer, not a wait. The bundled templates below still+ // render; leaving the spinner up would claim a list is on its way.+ if (workspaceId === null) {+ setTemplates([]);+ setListError('This server has no workspace yet, so its templates cannot be read.');+ setLoading(false);+ return;+ }let cancelled = false;setLoading(true);setListError(null);- rpc.switchServers- .listTemplates({ serverId })+ rpc.workspaces+ .listTemplates({ workspaceId }).then((result) => {if (!cancelled) setTemplates(result);})@@ -491,7 +508,7 @@ const TemplatesPanel = observer(function TemplatesPanel() {return () => {cancelled = true;};- }, [serverId, reloadKey]);+ }, [workspaceId, reloadKey]);const { builtIn, onWorkspace } = useMemo(() => {// A bundled card is always the bundled document. Saving it creates a@@ -556,7 +573,7 @@ const TemplatesPanel = observer(function TemplatesPanel() {const card = (item: TemplateListEntry) => (<TemplateCardkey={item.id}- serverId={serverId}+ workspaceId={workspaceId}item={item}meId={meId}busy={false}@@ -712,6 +729,7 @@ const TemplatesPanel = observer(function TemplatesPanel() {<RecentsSectionserverId={serverId}+ workspaceId={workspaceId}serverName={server?.name ?? null}onWorkspace={new Set(templates.map((t) => t.name))}kind={kind}diff --git a/console/apps/switch-console-desktop/src/renderer/features/workspaces/create-workspace-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/workspaces/create-workspace-modal.tsxnew file mode 100644index 000000000..7a2ae23aa--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/workspaces/create-workspace-modal.tsx@@ -0,0 +1,245 @@+import { observer } from 'mobx-react-lite';+import { useEffect, useState } from 'react';+import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';+import { failureText } from '@renderer/lib/errors/describe-failure';+import { useModalContext, type BaseModalProps } from '@renderer/lib/modal/modal-provider';+import { Button } from '@renderer/lib/ui/button';+import { ConfirmButton } from '@renderer/lib/ui/confirm-button';+import {+ DialogContentArea,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@renderer/lib/ui/dialog';+import { Field, FieldGroup, FieldLabel } from '@renderer/lib/ui/field';+import { Input } from '@renderer/lib/ui/input';+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@renderer/lib/ui/select';+import type { Workspace } from '@shared/core/workspaces/workspaces';+import { createWorkspaceFailureText } from './describe-create-failure';++type CreateWorkspaceModalArgs = {+ /** The server to create it on — the one the window is currently scoped to. */+ serverId: string;+};++type Props = BaseModalProps<Workspace> & CreateWorkspaceModalArgs;++/**+ * Why a server cannot be asked to create a workspace, or null when it can.+ *+ * Three refusals rather than one, because the remedies are three different+ * things and only one of them is a password. Telling someone to sign in again+ * because the network is down misattributes an outage to their credentials,+ * which is the same mistake as blaming the name for an authentication failure —+ * the one this modal exists to avoid — with the arrow reversed.+ */+function whyNotReady(serverId: string): string | null {+ const server = switchServersStore.serverById(serverId);+ if (server === null) return 'That server is no longer registered on this computer.';+ if (!switchServersStore.statuses.has(serverId)) {+ return `Checking whether you’re signed in to ${server.name}…`;+ }+ if (switchServersStore.isUnreachable(serverId)) {+ return `${server.name} can’t be reached right now, so it can’t be asked to create anything.`;+ }+ if (!switchServersStore.isConnected(serverId)) {+ return `You are not signed in to ${server.name}, so it cannot be asked to create anything. Sign in on its page first.`;+ }+ return null;+}++/**+ * Make a workspace from the switcher.+ *+ * A workspace belongs to a server, so the first thing this has to be sure of is+ * which one. It opens on the server the window is already in and offers the+ * others only where there is a choice to make — on the ordinary single-server+ * install the question never appears.+ *+ * Only a server you are signed in to can be asked. Offering the rest and+ * letting Create come back with an authentication failure would blame the name+ * for something the name had nothing to do with, so the modal says which server+ * is not ready and keeps the button off.+ *+ * The design's address hint and "let my team join automatically" toggle are not+ * here: a Switch workspace has no subdomain of its own, and no server can yet+ * admit people by email domain. See the first-run create page, which leaves+ * them out for the same reasons.+ */+export const CreateWorkspaceModal = observer(function CreateWorkspaceModal({+ serverId,+ onSuccess,+ onClose,+}: Props) {+ const { transitionModal, setCloseGuard } = useModalContext();+ const [chosen, setChosen] = useState<string | null>(null);+ const [name, setName] = useState('');+ const [submitting, setSubmitting] = useState(false);+ const [error, setError] = useState<string | null>(null);+ /**+ * The workspace the gateway has already minted, when entering it is what+ * failed.+ *+ * Creating it again would ask for a name the server has just taken and come+ * back with a conflict that reads as the name being refused — so once this is+ * set the button stops offering to create and offers to open instead.+ */+ const [created, setCreated] = useState<Workspace | null>(null);++ const candidates = switchServersStore.servers.filter((server) =>+ switchServersStore.isConnected(server.id)+ );+ // The server the window is in, when it can be asked; otherwise the only one+ // that can. A default that is not a candidate would hide the picker on a+ // question the user still has to answer, and leave Create disabled with the+ // usable server offered nowhere.+ const fallback = candidates.some((server) => server.id === serverId)+ ? serverId+ : (candidates[0]?.id ?? serverId);+ const where = chosen ?? fallback;+ const target = switchServersStore.serverById(where);+ const notReady = whyNotReady(where);+ const trimmed = name.trim();++ // A status nobody has read yet leaves the modal saying "checking" forever,+ // since nothing else on screen is watching this server.+ useEffect(() => {+ if (!switchServersStore.statuses.has(where)) void switchServersStore.refreshStatus(where);+ }, [where]);++ const submit = async () => {+ if (submitting) return;+ if (created === null && (notReady !== null || trimmed === '')) return;+ setSubmitting(true);+ setCloseGuard(true);+ setError(null);+ try {+ const workspace = created ?? (await workspacesStore.create(where, trimmed));+ setCreated(workspace);+ // Made and then entered: you asked for a workspace to work in, and+ // leaving the window in the old one would look like nothing happened.+ await workspacesStore.setActive(workspace.id);+ onSuccess(workspace);+ } catch (cause) {+ // Two different failures wear the same button. Before the workspace+ // exists the likeliest one is the name, and after it exists the name is+ // settled and what failed was the move into it — saying "could not+ // create" then would be describing the wrong step.+ setError(+ created === null+ ? createWorkspaceFailureText(+ cause,+ target?.name ?? 'that server',+ `${target?.name ?? 'That server'} could not create it.`+ )+ : failureText(cause, `This window could not be moved into ${created.name}.`)+ );+ setSubmitting(false);+ } finally {+ setCloseGuard(false);+ }+ };++ return (+ <>+ <DialogHeader showCloseButton={false}>+ <DialogTitle>Create a workspace</DialogTitle>+ </DialogHeader>+ <DialogContentArea className="pt-0">+ <FieldGroup>+ <Field>+ <FieldLabel>Name</FieldLabel>+ <Input+ value={name}+ onChange={(e) => {+ setName(e.target.value);+ setError(null);+ }}+ onKeyDown={(e) => {+ if (e.key === 'Enter') void submit();+ }}+ placeholder="Weekend Robotics"+ autoFocus+ disabled={created !== null}+ />+ </Field>++ {candidates.length > 1 && (+ <Field>+ <FieldLabel>Server</FieldLabel>+ <Select+ value={where}+ onValueChange={(value) => value && setChosen(value)}+ disabled={submitting || created !== null}+ >+ <SelectTrigger>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {candidates.map((server) => (+ <SelectItem key={server.id} value={server.id}>+ {server.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Field>+ )}++ {created !== null ? (+ <p className="text-xs text-foreground-muted">+ {created.name} was created on {target?.name ?? 'the server'}, but this window could+ not be moved into it. Try again, or close this and pick it from the switcher.+ </p>+ ) : notReady !== null ? (+ <p className="text-xs text-destructive">{notReady}</p>+ ) : target !== null && candidates.length <= 1 ? (+ <p className="text-xs text-foreground-muted">+ It will live on {target.name}, along with its rooms and agents.+ </p>+ ) : null}++ {error && <p className="text-xs text-destructive">{error}</p>}++ <p className="text-xs text-foreground-muted">+ Rather put it somewhere else?{' '}+ <button+ type="button"+ className="underline underline-offset-2 hover:text-foreground disabled:opacity-50"+ disabled={submitting || created !== null}+ onClick={() => transitionModal('addServerModal', {})}+ >+ Add a server+ </button>+ </p>+ </FieldGroup>+ </DialogContentArea>+ <DialogFooter>+ <Button variant="outline" onClick={onClose} disabled={submitting}>+ {created === null ? 'Cancel' : 'Close'}+ </Button>+ <ConfirmButton+ onClick={() => void submit()}+ /* Entering a workspace that already exists is a local move, so once it+ has been created the server's readiness stops being the question. */+ disabled={submitting || (created === null && (notReady !== null || trimmed === ''))}+ >+ {created !== null+ ? submitting+ ? 'Opening…'+ : 'Open workspace'+ : submitting+ ? 'Creating…'+ : 'Create workspace'}+ </ConfirmButton>+ </DialogFooter>+ </>+ );+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/workspaces/describe-create-failure.test.ts b/console/apps/switch-console-desktop/src/renderer/features/workspaces/describe-create-failure.test.tsnew file mode 100644index 000000000..d7de0cc47--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/workspaces/describe-create-failure.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from 'vitest';+import { RpcError } from '@shared/lib/ipc/rpc-error';+import { createWorkspaceFailureText } from './describe-create-failure';++function gatewayError(status: number, detail: string): RpcError {+ return new RpcError({+ __switchConsoleRpcError: true,+ code: 'GatewayError',+ message: `Gateway returned ${status}: ${detail}`,+ data: { kind: 'http', status, detail },+ } as unknown as ConstructorParameters<typeof RpcError>[0]);+}++const FALLBACK = 'Local dev could not create it.';++describe('creating a workspace, when it fails', () => {+ /**+ * The gateway's own words are `Slug already taken: acme-robotics` — no+ * terminal punctuation, so the shared description does not read it as a+ * sentence and shows it as diagnostics instead. What reached the user was a+ * status code and a slug they never typed, for the one refusal that is+ * entirely about what they did type.+ */+ it('blames the name for a name conflict, and says nothing about slugs', () => {+ const text = createWorkspaceFailureText(+ gatewayError(409, 'Slug already taken: acme-robotics'),+ 'Local dev',+ FALLBACK+ );++ expect(text).toContain('already goes by that name');+ expect(text).toContain('Local dev');+ expect(text).not.toContain('acme-robotics');+ expect(text).not.toContain('409');+ });++ // The whole point of the rewrite is that the name is at fault. Saying so over+ // an expired session sends the user to rename a workspace when what they have+ // to do is sign in.+ it('leaves every other gateway refusal to the shared description', () => {+ const expired = new RpcError({+ __switchConsoleRpcError: true,+ code: 'GatewayError',+ message: 'Gateway returned 401',+ data: { kind: 'unauthorized', status: 401 },+ } as unknown as ConstructorParameters<typeof RpcError>[0]);++ expect(createWorkspaceFailureText(expired, 'Local dev', FALLBACK)).toContain('Sign in again');+ });++ it('keeps the caller’s sentence for a failure it cannot place', () => {+ const text = createWorkspaceFailureText(new Error('socket hang up'), 'Local dev', FALLBACK);++ expect(text).toContain(FALLBACK);+ expect(text).toContain('socket hang up');+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/workspaces/describe-create-failure.ts b/console/apps/switch-console-desktop/src/renderer/features/workspaces/describe-create-failure.tsnew file mode 100644index 000000000..37d626664--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/workspaces/describe-create-failure.ts@@ -0,0 +1,31 @@+import { failureText } from '@renderer/lib/errors/describe-failure';+import { RpcError } from '@shared/lib/ipc/rpc-error';++/**+ * What to put under the name field when creating a workspace fails.+ *+ * The name being taken is by far the likeliest way this form fails, and it is+ * the only failure the person at the keyboard can fix. The gateway derives a+ * slug from the name and refuses a duplicate with `Slug already taken:+ * acme-robotics` — no terminal punctuation, so the generic description does not+ * read it as a sentence and shows it as diagnostic text instead: a status code+ * and a slug the user never typed, for the one refusal that is about what they+ * did type.+ *+ * Only that route's conflict is rewritten. Everything else keeps the shared+ * description, because a name-specific sentence over an expired session or an+ * unreachable server would blame the name for something it had nothing to do+ * with.+ */+export function createWorkspaceFailureText(+ error: unknown,+ serverName: string,+ fallback: string+): string {+ const conflict =+ error instanceof RpcError &&+ error.code === 'GatewayError' &&+ error.numberField('status') === 409;+ if (!conflict) return failureText(error, fallback);+ return `A workspace on ${serverName} already goes by that name. Capitalisation and punctuation do not make it a different one, so pick a name that stands apart.`;+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/workspaces/invite-people-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/workspaces/invite-people-modal.tsxnew file mode 100644index 000000000..d91dda84f--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/workspaces/invite-people-modal.tsx@@ -0,0 +1,473 @@+import { useQuery, useQueryClient, type UseQueryResult } from '@tanstack/react-query';+import { Check, Copy, TriangleAlert } from 'lucide-react';+import { observer } from 'mobx-react-lite';+import { useEffect, useState } from 'react';+import { JoinDomainsSection } from '@renderer/features/workspaces/join-domains-section';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';+import { failureText } from '@renderer/lib/errors/describe-failure';+import { rpc } from '@renderer/lib/ipc';+import { useModalContext, type BaseModalProps } from '@renderer/lib/modal/modal-provider';+import { AbsoluteTime } from '@renderer/lib/ui/absolute-time';+import { Alert, AlertDescription } from '@renderer/lib/ui/alert';+import { Badge } from '@renderer/lib/ui/badge';+import { Button } from '@renderer/lib/ui/button';+import { ConfirmButton } from '@renderer/lib/ui/confirm-button';+import {+ DialogContentArea,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@renderer/lib/ui/dialog';+import { Field, FieldDescription, FieldGroup, FieldLabel } from '@renderer/lib/ui/field';+import { Input } from '@renderer/lib/ui/input';+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@renderer/lib/ui/select';+import { Spinner } from '@renderer/lib/ui/spinner';+import {+ invitationStatus,+ type CreatedInvitation,+ type Invitation,+ type InvitationEmailDelivery,+ type InvitationStatus,+ type WorkspaceInvitations,+} from '@shared/core/workspaces/invitations';+import type { WorkspaceRole } from '@shared/core/workspaces/workspaces';++type InvitePeopleModalArgs = {+ /** The workspace to invite to. Its admins and owners are the only ones offered this. */+ workspaceId: string;+};++type Props = BaseModalProps<void> & InvitePeopleModalArgs;++const EXPIRY_CHOICES = [+ { hours: 24, label: '1 day' },+ { hours: 168, label: '7 days' },+ { hours: 720, label: '30 days' },+] as const;++const ROLE_LABEL: Record<WorkspaceRole, string> = {+ member: 'Member',+ admin: 'Admin',+ owner: 'Owner',+};++const STATUS_LABEL: Record<InvitationStatus, string> = {+ active: 'Active',+ revoked: 'Revoked',+ expired: 'Expired',+ used: 'Used',+};++/**+ * What happened to the e-mail, said beside the link it may have failed to carry.+ *+ * Every case ends on the link, because every case still has one: the+ * invitation stands whether or not the mail went out, and this is the only time+ * it can be shown.+ */+function deliveryNotice(+ delivery: InvitationEmailDelivery,+ email: string | null+): { tone: 'default' | 'warning' | 'destructive'; text: string } {+ switch (delivery) {+ case 'sent':+ return {+ tone: 'default',+ text: `Invitation e-mailed to ${email}. The link below works too; it is shown only once.`,+ };+ case 'not_configured':+ return {+ tone: 'warning',+ text: `No e-mail was sent — this server has no mail set up. Send this link to ${email} yourself; it is shown only once.`,+ };+ case 'failed':+ return {+ tone: 'destructive',+ text: `Sending the e-mail to ${email} failed. The invitation was created: send this link yourself; it is shown only once.`,+ };+ case 'unsupported':+ return email === null+ ? {+ tone: 'default',+ text: 'Send this link to the person you are inviting. It is shown only once.',+ }+ : {+ tone: 'warning',+ text: `No e-mail was sent — this server does not e-mail invitations. Send this link to ${email} yourself; it is shown only once.`,+ };+ case 'not_requested':+ return {+ tone: 'default',+ text: 'Send this link to the person you are inviting. It is shown only once.',+ };+ }+}++/**+ * Invite people to a workspace, and see who has been invited.+ *+ * The same invitations the server's dashboard makes, so one made here can be+ * revoked there and the other way round. Naming an address e-mails the link+ * when the server has mail set up and restricts who can accept it; leaving it+ * empty makes a link for anyone who holds it. Either way the link is shown+ * once, on creation — the server keeps only a hash of it, so nothing can show+ * it again afterwards.+ */+export const InvitePeopleModal = observer(function InvitePeopleModal({+ workspaceId,+ onClose,+}: Props) {+ const { setCloseGuard } = useModalContext();+ const queryClient = useQueryClient();+ const workspace = workspacesStore.byId(workspaceId);+ const queryKey = ['workspace-invitations', workspaceId];++ const query = useQuery({+ queryKey,+ queryFn: () => rpc.workspaces.listInvitations(workspaceId),+ });+ const emailEnabled = query.data?.emailEnabled;++ const [email, setEmail] = useState('');+ const [role, setRole] = useState<WorkspaceRole>('member');+ const [expiresInHours, setExpiresInHours] = useState<number>(168);+ const [uses, setUses] = useState('1');+ const [submitting, setSubmitting] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [created, setCreated] = useState<CreatedInvitation | null>(null);+ const [copied, setCopied] = useState(false);+ const [revoking, setRevoking] = useState<string | null>(null);+ const [revokeError, setRevokeError] = useState<string | null>(null);++ // Re-read on a timer so an invitation that lapses while the modal is open+ // stops showing as active and stops offering Revoke.+ const [now, setNow] = useState(() => Date.now());+ useEffect(() => {+ const timer = window.setInterval(() => setNow(Date.now()), 30_000);+ return () => window.clearInterval(timer);+ }, []);++ if (workspace === null) {+ return (+ <>+ <DialogHeader showCloseButton={false}>+ <DialogTitle>Invite people</DialogTitle>+ </DialogHeader>+ <DialogContentArea className="pt-0">+ <p className="text-sm text-destructive">+ That workspace is no longer held on this computer.+ </p>+ </DialogContentArea>+ <DialogFooter>+ <Button variant="outline" onClick={onClose}>+ Close+ </Button>+ </DialogFooter>+ </>+ );+ }++ const roles: WorkspaceRole[] =+ workspace.role === 'owner' ? ['member', 'admin', 'owner'] : ['member', 'admin'];+ const trimmedEmail = email.trim();+ const usesNumber = Number(uses);+ const usesValid = Number.isInteger(usesNumber) && usesNumber > 0;+ const addressed = trimmedEmail !== '';++ const submit = async () => {+ if (submitting || !usesValid) return;+ setSubmitting(true);+ setCloseGuard(true);+ setError(null);+ try {+ const result = await rpc.workspaces.createInvitation({+ workspaceId,+ role,+ email: addressed ? trimmedEmail : null,+ expiresInHours,+ usesRemaining: usesNumber,+ });+ setCreated(result);+ setCopied(false);+ await queryClient.invalidateQueries({ queryKey });+ } catch (cause) {+ setError(failureText(cause, `${workspace.name} could not create the invitation.`));+ } finally {+ setSubmitting(false);+ setCloseGuard(false);+ }+ };++ const copy = async () => {+ if (created === null) return;+ await navigator.clipboard.writeText(created.link);+ setCopied(true);+ };++ const inviteAnother = () => {+ setCreated(null);+ setEmail('');+ setCopied(false);+ };++ const revoke = async (invitation: Invitation) => {+ setRevoking(invitation.id);+ setRevokeError(null);+ try {+ await rpc.workspaces.revokeInvitation({ workspaceId, invitationId: invitation.id });+ await queryClient.invalidateQueries({ queryKey });+ } catch (cause) {+ setRevokeError(failureText(cause, 'Could not revoke the invitation.'));+ } finally {+ setRevoking(null);+ }+ };++ const notice = created ? deliveryNotice(created.emailDelivery, created.invitation.email) : null;++ return (+ <>+ <DialogHeader showCloseButton={false}>+ <DialogTitle>Invite people to {workspace.name}</DialogTitle>+ </DialogHeader>+ <DialogContentArea className="flex flex-col gap-6 pt-0">+ {created !== null && notice !== null ? (+ <div className="flex flex-col gap-3">+ <Alert variant={notice.tone}>+ {notice.tone !== 'default' && <TriangleAlert />}+ <AlertDescription>{notice.text}</AlertDescription>+ </Alert>+ <Field>+ <FieldLabel htmlFor="invite-people-link">Invite link</FieldLabel>+ <div className="flex gap-2">+ <Input+ id="invite-people-link"+ value={created.link}+ readOnly+ onFocus={(e) => e.currentTarget.select()}+ />+ <Button variant="outline" onClick={() => void copy()}>+ {copied ? <Check className="size-4" /> : <Copy className="size-4" />}+ {copied ? 'Copied' : 'Copy'}+ </Button>+ </div>+ <FieldDescription>+ They open it in a browser, or paste it into Switch Console when it first starts.+ </FieldDescription>+ </Field>+ </div>+ ) : (+ <FieldGroup>+ <Field>+ <FieldLabel htmlFor="invite-people-email">E-mail (optional)</FieldLabel>+ <Input+ id="invite-people-email"+ type="email"+ value={email}+ onChange={(e) => setEmail(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === 'Enter') void submit();+ }}+ placeholder="[email protected]"+ autoFocus+ disabled={submitting}+ />+ <FieldDescription>+ {emailEnabled === false+ ? 'This server has no e-mail set up, so you’ll get a link to send yourself. '+ : emailEnabled === null+ ? 'This server does not e-mail invitations, so you’ll get a link to send yourself. '+ : emailEnabled === true+ ? 'We’ll e-mail them the link. '+ : ''}+ Only someone signed in with this address can accept. Leave it empty for a link+ anyone can use.+ </FieldDescription>+ </Field>+ <div className="grid grid-cols-3 gap-3">+ <Field>+ <FieldLabel>Role</FieldLabel>+ <Select+ value={role}+ onValueChange={(value) => value && setRole(value as WorkspaceRole)}+ disabled={submitting}+ >+ <SelectTrigger aria-label="Role">+ <SelectValue>{ROLE_LABEL[role]}</SelectValue>+ </SelectTrigger>+ <SelectContent>+ {roles.map((r) => (+ <SelectItem key={r} value={r}>+ {ROLE_LABEL[r]}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Field>+ <Field>+ <FieldLabel>Expires in</FieldLabel>+ <Select+ value={String(expiresInHours)}+ onValueChange={(value) => value && setExpiresInHours(Number(value))}+ disabled={submitting}+ >+ <SelectTrigger aria-label="Expires in">+ <SelectValue>+ {EXPIRY_CHOICES.find((c) => c.hours === expiresInHours)?.label}+ </SelectValue>+ </SelectTrigger>+ <SelectContent>+ {EXPIRY_CHOICES.map((c) => (+ <SelectItem key={c.hours} value={String(c.hours)}>+ {c.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Field>+ <Field>+ <FieldLabel htmlFor="invite-people-uses">Uses</FieldLabel>+ <Input+ id="invite-people-uses"+ type="number"+ min={1}+ value={uses}+ onChange={(e) => setUses(e.target.value)}+ disabled={submitting}+ />+ </Field>+ </div>+ {!usesValid && (+ <p className="text-xs text-destructive">Uses must be a whole number, 1 or more.</p>+ )}+ {error && (+ <p role="alert" className="text-xs text-destructive">+ {error}+ </p>+ )}+ </FieldGroup>+ )}++ <section className="flex flex-col gap-2">+ <h3 className="text-sm font-medium">Invitations</h3>+ <InvitationList+ query={query}+ now={now}+ revoking={revoking}+ onRevoke={(invitation) => void revoke(invitation)}+ />+ {revokeError && (+ <p role="alert" className="text-xs text-destructive">+ {revokeError}+ </p>+ )}+ </section>++ <JoinDomainsSection workspaceId={workspaceId} />+ </DialogContentArea>+ <DialogFooter>+ {created !== null ? (+ <>+ <Button variant="outline" onClick={inviteAnother}>+ Invite someone else+ </Button>+ <Button onClick={onClose}>Done</Button>+ </>+ ) : (+ <>+ <Button variant="outline" onClick={onClose} disabled={submitting}>+ Close+ </Button>+ <ConfirmButton onClick={() => void submit()} disabled={submitting || !usesValid}>+ {submitting && <Spinner className="size-3.5" />}+ {addressed && emailEnabled === true ? 'Send invitation' : 'Create link'}+ </ConfirmButton>+ </>+ )}+ </DialogFooter>+ </>+ );+});++function InvitationList({+ query,+ now,+ revoking,+ onRevoke,+}: {+ query: UseQueryResult<WorkspaceInvitations>;+ now: number;+ revoking: string | null;+ onRevoke: (invitation: Invitation) => void;+}) {+ if (query.isPending) {+ return (+ <div className="flex items-center gap-2 text-xs text-foreground-muted">+ <Spinner className="size-3" />+ Loading invitations…+ </div>+ );+ }+ if (query.isError) {+ return (+ <p role="alert" className="text-xs text-destructive">+ {failureText(query.error, 'Could not load the invitations.')}{' '}+ <button type="button" className="underline" onClick={() => void query.refetch()}>+ Try again+ </button>+ </p>+ );+ }+ const invitations = query.data.invitations;+ if (invitations.length === 0) {+ return <p className="text-xs text-foreground-muted">Nobody has been invited yet.</p>;+ }+ return (+ <ul className="flex max-h-56 flex-col divide-y divide-border overflow-auto rounded-lg border border-border">+ {invitations.map((invitation) => {+ const status = invitationStatus(invitation, now);+ return (+ <li+ key={invitation.id}+ data-testid="invitation-row"+ className="flex items-center gap-3 px-3 py-2 text-xs"+ >+ <span className="min-w-0 flex-1 truncate text-foreground">+ {invitation.email ?? 'Anyone with the link'}+ </span>+ <span className="text-foreground-muted">{ROLE_LABEL[invitation.role]}</span>+ <Badge variant={status === 'active' ? 'outline' : 'secondary'}>+ {STATUS_LABEL[status]}+ </Badge>+ <span className="w-24 text-foreground-muted">+ {status === 'active' ? (+ <>+ until <AbsoluteTime value={invitation.expiresAt} />+ </>+ ) : null}+ </span>+ <span className="w-16 text-right">+ {status === 'active' && (+ <Button+ variant="ghost"+ size="sm"+ className="text-destructive"+ disabled={revoking !== null}+ onClick={() => onRevoke(invitation)}+ >+ {revoking === invitation.id ? 'Revoking…' : 'Revoke'}+ </Button>+ )}+ </span>+ </li>+ );+ })}+ </ul>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/workspaces/join-domains-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/workspaces/join-domains-section.tsxnew file mode 100644index 000000000..0a89c4496--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/workspaces/join-domains-section.tsx@@ -0,0 +1,124 @@+import { useQuery, useQueryClient } from '@tanstack/react-query';+import { useState } from 'react';+import { failureText } from '@renderer/lib/errors/describe-failure';+import { rpc } from '@renderer/lib/ipc';+import { Button } from '@renderer/lib/ui/button';+import { Spinner } from '@renderer/lib/ui/spinner';++/**+ * The e-mail domains anyone may join a workspace from, as a member, without an+ * invitation.+ *+ * The one domain on offer is the admin's own: that is the domain their+ * signed-in address proves they belong to, and the server refuses any other.+ * It also refuses a public provider's domain, and the reason is shown in place+ * of the button. A server older than the route leaves the section out.+ */+export function JoinDomainsSection({ workspaceId }: { workspaceId: string }) {+ const queryClient = useQueryClient();+ const queryKey = ['workspace-join-domains', workspaceId];+ const query = useQuery({+ queryKey,+ queryFn: () => rpc.workspaces.listJoinDomains(workspaceId),+ });+ const [busy, setBusy] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);++ async function change(domain: string, action: 'add' | 'remove') {+ setBusy(domain);+ setError(null);+ try {+ if (action === 'add') await rpc.workspaces.addJoinDomain({ workspaceId, domain });+ else await rpc.workspaces.removeJoinDomain({ workspaceId, domain });+ await queryClient.invalidateQueries({ queryKey });+ } catch (cause) {+ setError(+ failureText(+ cause,+ action === 'add'+ ? `Could not open the workspace to ${domain}.`+ : `Could not close ${domain}.`+ )+ );+ } finally {+ setBusy(null);+ }+ }++ if (query.isPending) {+ return (+ <section className="flex items-center gap-2 text-xs text-foreground-muted">+ <Spinner className="size-3" />+ Loading e-mail domains…+ </section>+ );+ }+ if (query.isError) {+ return (+ <section>+ <p role="alert" className="text-xs text-destructive">+ {failureText(query.error, 'Could not load the e-mail domains.')}{' '}+ <button type="button" className="underline" onClick={() => void query.refetch()}>+ Try again+ </button>+ </p>+ </section>+ );+ }+ const data = query.data;+ if (data.kind === 'unsupported') return null;+ const ownOpen = data.domains.includes(data.ownDomain);++ return (+ <section className="flex flex-col gap-2" data-testid="join-domains-section">+ <h3 className="text-sm font-medium">Joining by e-mail domain</h3>+ {data.domains.length > 0 && (+ <ul className="flex flex-col divide-y divide-border rounded-lg border border-border">+ {data.domains.map((domain) => (+ <li+ key={domain}+ data-testid="join-domain-row"+ className="flex items-center gap-3 px-3 py-2 text-xs"+ >+ <span className="min-w-0 flex-1 truncate text-foreground">+ Anyone with an @{domain} address can join as a member+ </span>+ <Button+ variant="ghost"+ size="sm"+ className="text-destructive"+ disabled={busy !== null}+ onClick={() => void change(domain, 'remove')}+ >+ {busy === domain ? 'Removing…' : 'Remove'}+ </Button>+ </li>+ ))}+ </ul>+ )}+ {!ownOpen &&+ (data.ownDomainRefusal !== null ? (+ <p className="text-xs text-foreground-muted">{data.ownDomainRefusal}.</p>+ ) : (+ <div className="flex items-center gap-3">+ <p className="min-w-0 flex-1 text-xs text-foreground-muted">+ Let anyone with an @{data.ownDomain} address join as a member, without an invitation.+ </p>+ <Button+ variant="outline"+ size="sm"+ disabled={busy !== null}+ onClick={() => void change(data.ownDomain, 'add')}+ >+ {busy === data.ownDomain ? 'Allowing…' : 'Allow'}+ </Button>+ </div>+ ))}+ {error && (+ <p role="alert" className="text-xs text-destructive">+ {error}+ </p>+ )}+ </section>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/workspaces/pending-invitations.tsx b/console/apps/switch-console-desktop/src/renderer/features/workspaces/pending-invitations.tsxnew file mode 100644index 000000000..551579800--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/workspaces/pending-invitations.tsx@@ -0,0 +1,76 @@+import { useQuery, type UseQueryResult } from '@tanstack/react-query';+import { rpc } from '@renderer/lib/ipc';+import type {+ JoinableWorkspace,+ JoinableWorkspaces,+ PendingInvitation,+ PendingInvitations,+} from '@shared/core/workspaces/invitations';++export function pendingInvitationsKey(serverId: string): readonly unknown[] {+ return ['pending-invitations', serverId];+}++/**+ * The invitations waiting for the signed-in account on a server.+ *+ * One query per server, shared by every view that asks, so the switcher's badge+ * and its rows cannot disagree about how many there are.+ */+export function usePendingInvitations(serverId: string): UseQueryResult<PendingInvitations> {+ return useQuery({+ queryKey: pendingInvitationsKey(serverId),+ queryFn: () => rpc.switchServers.listPendingInvitations(serverId),+ staleTime: 60_000,+ });+}++const NONE: PendingInvitation[] = [];++/**+ * The invitations a server listed, or none where it listed nothing: still+ * asking, failed, or too old to be asked. The views say which of those it was+ * from the query itself; this is only the rows.+ */+export function listedInvitations(data: PendingInvitations | undefined): PendingInvitation[] {+ return data?.kind === 'listed' ? data.invitations : NONE;+}++export function invitationSummary(invitation: PendingInvitation): string {+ return `${invitation.invitedBy} invited you as ${invitation.role}`;+}++export function InvitedBadge() {+ return (+ <span className="shrink-0 rounded bg-[var(--sel-soft)] px-1 py-px text-[10px] font-medium tracking-wide text-foreground uppercase">+ Invited+ </span>+ );+}++export function joinableWorkspacesKey(serverId: string): readonly unknown[] {+ return ['joinable-workspaces', serverId];+}++/**+ * The workspaces open to the signed-in account's domain on a server, shared+ * the way {@link usePendingInvitations} is.+ */+export function useJoinableWorkspaces(serverId: string): UseQueryResult<JoinableWorkspaces> {+ return useQuery({+ queryKey: joinableWorkspacesKey(serverId),+ queryFn: () => rpc.switchServers.listJoinableWorkspaces(serverId),+ staleTime: 60_000,+ });+}++const NO_JOINABLE: JoinableWorkspace[] = [];++/** The joinable workspaces a server listed, or none, as {@link listedInvitations}. */+export function listedJoinable(data: JoinableWorkspaces | undefined): JoinableWorkspace[] {+ return data?.kind === 'listed' ? data.workspaces : NO_JOINABLE;+}++export function joinableSummary(joinable: JoinableWorkspace): string {+ return `Open to anyone at ${joinable.domain}`;+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspaces-store.test.ts b/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspaces-store.test.tsnew file mode 100644index 000000000..59f9e3163--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspaces-store.test.ts@@ -0,0 +1,184 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { Workspace } from '@shared/core/workspaces/workspaces';++const list = vi.hoisted(() => vi.fn());+const getActiveId = vi.hoisted(() => vi.fn());+const setActive = vi.hoisted(() => vi.fn());+const subscribers = vi.hoisted(() => new Map<string, (data: unknown) => void>());++vi.mock('@renderer/lib/ipc', () => ({+ events: {+ on: (event: { name: string }, cb: (data: unknown) => void) => {+ subscribers.set(event.name, cb);+ return () => subscribers.delete(event.name);+ },+ },+ rpc: { workspaces: { list, getActiveId, setActive } },+}));++const { WorkspacesStore } = await import('./workspaces-store');+const { workspacesChangedChannel } = await import('@shared/core/workspaces/workspaceEvents');++function workspace(id: string, serverId: string, name = id): Workspace {+ return {+ id,+ serverId,+ name,+ tenantId: `tenant-${id}`,+ slug: id,+ role: 'member',+ createdAt: '2026-01-01T00:00:00Z',+ updatedAt: '2026-01-01T00:00:00Z',+ };+}++/** A store holding the given workspaces, scoped to one of them. */+async function loaded(workspaces: Workspace[], activeId: string | null) {+ list.mockResolvedValue(workspaces);+ getActiveId.mockResolvedValue(activeId);+ const store = new WorkspacesStore();+ await store.refresh();+ return store;+}++beforeEach(() => {+ vi.clearAllMocks();+ subscribers.clear();+ setActive.mockResolvedValue(undefined);+});++/** Fire the main process's "the list moved" event at whoever subscribed. */+function announceChange(): void {+ const notify = subscribers.get(workspacesChangedChannel.name);+ expect(notify, 'nothing subscribed to the workspaces-changed event').toBeDefined();+ notify!(undefined);+}++describe('keeping up with the main process', () => {+ /**+ * The reconcile adds and matches rows without a window having asked — the+ * boot sweep, and every sign-in. Nothing else would tell an open window, so a+ * membership gained since the last launch would stay invisible for the whole+ * session.+ */+ it('re-reads the list when the main process says it changed', async () => {+ const store = await loaded([workspace('ws-a', 'srv-1')], 'ws-a');++ list.mockResolvedValue([workspace('ws-a', 'srv-1'), workspace('ws-b', 'srv-1')]);+ announceChange();++ await vi.waitFor(() => expect(store.workspaces).toHaveLength(2));+ });++ /**+ * The sweep drops the placeholder a server was registered with once every+ * membership has a row of its own. A window still listing it offers a+ * workspace that is not there, and the only thing it can report on the click+ * is that the switch failed — not that the row went.+ */+ it('drops a workspace the main process no longer has', async () => {+ const store = await loaded([workspace('ws-a', 'srv-1'), workspace('ws-b', 'srv-1')], 'ws-a');++ list.mockResolvedValue([workspace('ws-b', 'srv-1')]);+ getActiveId.mockResolvedValue('ws-b');+ announceChange();++ await vi.waitFor(() => expect(store.byId('ws-a')).toBeNull());+ expect(store.activeId).toBe('ws-b');+ });+});++describe('what the window is scoped to', () => {+ it('reads the server off the workspace rather than holding its own', async () => {+ const store = await loaded([workspace('ws-a', 'srv-1'), workspace('ws-b', 'srv-2')], 'ws-b');++ expect(store.active?.id).toBe('ws-b');+ expect(store.activeServerId).toBe('srv-2');+ });++ // Every install has this moment: the list arrives before anything has chosen.+ it('is scoped to nothing while no workspace is selected', async () => {+ const store = await loaded([workspace('ws-a', 'srv-1')], null);++ expect(store.active).toBeNull();+ expect(store.activeServerId).toBeNull();+ });++ /**+ * Removing a server takes its workspaces with it, leaving the stored+ * selection naming one that is gone. Reading that as a selection would scope+ * the window to a server that is no longer there.+ */+ it('is scoped to nothing when the selection names a workspace that has gone', async () => {+ const store = await loaded([workspace('ws-a', 'srv-1')], 'ws-removed');++ expect(store.active).toBeNull();+ expect(store.activeServerId).toBeNull();+ });++ it('moves the scope when a workspace is chosen', async () => {+ const store = await loaded([workspace('ws-a', 'srv-1'), workspace('ws-b', 'srv-1')], 'ws-a');++ await store.setActive('ws-b');++ expect(setActive).toHaveBeenCalledWith('ws-b');+ expect(store.activeId).toBe('ws-b');+ });++ /**+ * A switch that failed quietly would leave the sidebar listing one+ * workspace's rooms under another one's name — indistinguishable from the+ * rooms having disappeared.+ */+ it('raises and stays put when the selection cannot be saved', async () => {+ const store = await loaded([workspace('ws-a', 'srv-1'), workspace('ws-b', 'srv-1')], 'ws-a');+ setActive.mockRejectedValue(new Error('database is locked'));++ await expect(store.setActive('ws-b')).rejects.toThrow('database is locked');+ expect(store.activeId).toBe('ws-a');+ });+});++describe('the workspace a server-routed view acts in', () => {+ it('is the active one when the window is scoped to that server', async () => {+ const store = await loaded(+ [workspace('ws-a', 'srv-1'), workspace('ws-b', 'srv-1'), workspace('ws-c', 'srv-2')],+ 'ws-b'+ );++ expect(store.onServerInScope('srv-1')?.id).toBe('ws-b');+ });++ // A server with one workspace has nothing to choose between, so a page for it+ // works whether or not the window is scoped there.+ it('falls back to the only workspace on another server', async () => {+ const store = await loaded([workspace('ws-a', 'srv-1'), workspace('ws-c', 'srv-2')], 'ws-a');++ expect(store.onServerInScope('srv-2')?.id).toBe('ws-c');+ });++ // Addressing the wrong one answers with somebody else's rooms while looking+ // entirely correct, so the view has to render the absence instead.+ it('answers nothing for another server with several workspaces', async () => {+ const store = await loaded(+ [workspace('ws-a', 'srv-1'), workspace('ws-b', 'srv-2'), workspace('ws-c', 'srv-2')],+ 'ws-a'+ );++ expect(store.onServerInScope('srv-2')).toBeNull();+ expect(store.idOnServerInScope('srv-2')).toBeNull();+ });++ it('answers nothing for a server whose registration left it with none', async () => {+ const store = await loaded([workspace('ws-a', 'srv-1')], 'ws-a');++ expect(store.idOnServerInScope('srv-2')).toBeNull();+ });++ // Every page routed by server reads this before its server is known.+ it('answers nothing before a server has been chosen', async () => {+ const store = await loaded([workspace('ws-a', 'srv-1')], 'ws-a');++ expect(store.idOnServerInScope(null)).toBeNull();+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspaces-store.ts b/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspaces-store.tsnew file mode 100644index 000000000..ff6870192--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspaces-store.ts@@ -0,0 +1,195 @@+import { makeAutoObservable, runInAction } from 'mobx';+import { events, rpc } from '@renderer/lib/ipc';+import type { JoinableWorkspace, PendingInvitation } from '@shared/core/workspaces/invitations';+import { workspacesChangedChannel } from '@shared/core/workspaces/workspaceEvents';+import type { Workspace } from '@shared/core/workspaces/workspaces';++/**+ * Renderer view of the workspaces this install knows about, and which one the+ * window is scoped to.+ *+ * Everything that reads or writes what a workspace owns — rooms, agents,+ * bridges, identities — is addressed by workspace id, so this is where a view+ * holding a server or an agent gets the id to address it with. The server's own+ * identity stays in the servers store: reachability, sign-in and the gateway+ * URL are facts about a gateway, not about whose data it answers with.+ *+ * The selection is persisted by the main process, so this mirrors it rather+ * than owning it — but the window is scoped to a workspace, so this is where+ * the scope is read and changed, and the servers store derives its own notion+ * of "which server" from it.+ */+export class WorkspacesStore {+ workspaces: Workspace[] = [];+ activeId: string | null = null;+ /** Ordinal of the most recent {@link setActive}; nothing renders it. */+ lastSwitch = 0;++ constructor() {+ makeAutoObservable(this, { lastSwitch: false });++ // The reconcile adds, matches and drops rows without a window asking, so+ // the calls the servers store makes are not the only times this list moves.+ // A membership gained or lost since the last launch would otherwise stay+ // invisible until the next one, and a row the boot sweep deleted would go+ // on being offered here after it had gone.+ events.on(workspacesChangedChannel, () => {+ void this.refresh();+ });+ }++ get active(): Workspace | null {+ return this.workspaces.find((w) => w.id === this.activeId) ?? null;+ }++ /**+ * The server the window is scoped to, for the parts of the app still keyed by+ * one.+ *+ * Derived rather than stored alongside the workspace: the server is simply+ * the one hosting the selection, and the main process reads it back the same+ * way, so the two cannot come to disagree about which server the app is on.+ */+ get activeServerId(): string | null {+ return this.active?.serverId ?? null;+ }++ /**+ * Scope the window to a workspace.+ *+ * Raises if the selection does not take. The caller shows it: a switch that+ * failed quietly would leave the sidebar listing one workspace's rooms under+ * another one's name, which looks like data loss rather than a failed click.+ *+ * Only the last switch started may write the mirror. Two clicks in quick+ * succession are two round trips that can finish in either order, and the+ * slower one landing second would leave this pointing at a workspace the main+ * process has already moved off — every read after it addressed under a name+ * the window is no longer showing.+ */+ async setActive(workspaceId: string): Promise<void> {+ const request = ++this.lastSwitch;+ await rpc.workspaces.setActive(workspaceId);+ if (request !== this.lastSwitch) return;+ runInAction(() => {+ this.activeId = workspaceId;+ });+ }++ /**+ * Create a workspace on a server and return it.+ *+ * Refreshes before returning, so a caller that scopes the window to the new+ * workspace is not doing it against a list that does not contain it yet.+ * Failures propagate: the name may be refused for a slug already in use, and+ * the form has to say so rather than appear to have worked.+ */+ async create(serverId: string, name: string): Promise<Workspace> {+ const workspace = await rpc.switchServers.createWorkspace({ serverId, name });+ await this.refresh();+ return workspace;+ }++ /**+ * Accept an invitation on a server and return the workspace it admits to.+ *+ * Refreshes before returning, for the same reason as {@link create}.+ */+ async acceptInvitation(serverId: string, token: string): Promise<Workspace> {+ const workspace = await rpc.switchServers.acceptInvitation({ serverId, token });+ await this.refresh();+ return workspace;+ }++ /**+ * Accept an invitation addressed to the signed-in account on `serverId`, and+ * return the workspace it joined. Refreshes before returning, as+ * {@link acceptInvitation} does.+ */+ async acceptPendingInvitation(+ serverId: string,+ invitation: PendingInvitation+ ): Promise<Workspace> {+ const workspace = await rpc.switchServers.acceptPendingInvitation({+ serverId,+ tenantId: invitation.tenantId,+ invitationId: invitation.id,+ });+ await this.refresh();+ return workspace;+ }++ /**+ * Join a workspace open to the signed-in account's domain on `serverId`, and+ * return it. Refreshes before returning, as {@link acceptInvitation} does.+ */+ async joinByDomain(serverId: string, joinable: JoinableWorkspace): Promise<Workspace> {+ const workspace = await rpc.switchServers.joinWorkspaceByDomain({+ serverId,+ tenantId: joinable.tenantId,+ });+ await this.refresh();+ return workspace;+ }++ async refresh(): Promise<void> {+ const [workspaces, activeId] = await Promise.all([+ rpc.workspaces.list(),+ rpc.workspaces.getActiveId(),+ ]);+ runInAction(() => {+ this.workspaces = workspaces;+ this.activeId = activeId;+ });+ }++ byId(workspaceId: string): Workspace | null {+ return this.workspaces.find((w) => w.id === workspaceId) ?? null;+ }++ /** The server hosting a workspace, or null while the list is not loaded. */+ serverIdFor(workspaceId: string): string | null {+ return this.byId(workspaceId)?.serverId ?? null;+ }++ onServer(serverId: string): Workspace[] {+ return this.workspaces.filter((w) => w.serverId === serverId);+ }++ /**+ * The workspace a view about a server acts in — its page, its cards, its+ * pickers.+ *+ * The active one when the window is scoped to that server, which is the+ * ordinary case: choosing a workspace in the switcher is how you reach its+ * pages at all. A view about some other server falls back to its only+ * workspace, since then there is nothing to choose.+ *+ * Null rather than a guess where neither applies. A server with no workspace+ * has not finished registering; a server with several, none of them active,+ * means the view is the one that has to say which, and addressing the wrong+ * one answers with somebody else's rooms while looking entirely correct.+ * Callers render the absence; they must not substitute the server id, which+ * would reach the gateway and succeed.+ */+ onServerInScope(serverId: string | null): Workspace | null {+ if (serverId === null) return null;+ const active = this.active;+ if (active?.serverId === serverId) return active;+ const found = this.onServer(serverId);+ return found.length === 1 ? found[0]! : null;+ }++ /**+ * {@link onServerInScope} as an id, for a view still routed by server.+ *+ * Null means "no workspace to act in yet", and a view must hold its reads and+ * writes until it is not: the list arrives asynchronously, so this answers+ * null on the first render of every such page.+ */+ idOnServerInScope(serverId: string | null): string | null {+ return this.onServerInScope(serverId)?.id ?? null;+ }+}++export const workspacesStore = new WorkspacesStore();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.tsxindex 38e8388d1..e1570e126 100644--- 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@@ -15,9 +15,13 @@ export type AgentPick = {* 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 {+export function agentProviderLabelFor(switchAgentId: string, workspaceId: string | null): string {const local =- agentsStore.agentsOnServer(serverId).find((a) => a.switchAgentId === switchAgentId) ?? null;+ workspaceId === null+ ? null+ : (agentsStore+ .agentsInWorkspace(workspaceId)+ .find((a) => a.switchAgentId === switchAgentId) ?? null);return agentProviderLabel(local?.providerId);}diff --git a/console/apps/switch-console-desktop/src/renderer/lib/layout/scope-to-server.ts b/console/apps/switch-console-desktop/src/renderer/lib/layout/scope-to-server.tsdeleted file mode 100644index fe047b200..000000000--- a/console/apps/switch-console-desktop/src/renderer/lib/layout/scope-to-server.ts+++ /dev/null@@ -1,42 +0,0 @@-import { agentsStore } from '@renderer/features/locations/stores/agents-store';-import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';-import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';--/**- * Make a target's Switch server the active one before navigating to it.- *- * The active server scopes the whole sidebar — `sidebarStore.isLocationInActiveScope`- * and `switchRoomsStore.listedRoomsInActiveScope` both filter on it. Navigating- * to something on another server without this opens the view but leaves the- * sidebar showing a tree the target is not in, so the row you just opened is- * nowhere to be seen.- *- * A no-op when the target is already on the active server, when its server- * cannot be resolved (an unlinked location), or when no server is active.- */-async function activateServer(serverId: string | null): Promise<void> {- if (!serverId) return;- if (switchServersStore.activeServerId === serverId) return;- await switchServersStore.setActive(serverId);-}--/**- * Scope to a server that shows `locationId` — for agents and sessions.- *- * A directory can hold agents for several servers, so there may be more than one- * right answer. If the active server is already one of them there is nothing to do;- * switching away would hide the row the caller is navigating to (CHOO-2044).- */-export async function scopeToLocationServer(locationId: string): Promise<void> {- if (!agentsStore.loaded) await agentsStore.load();- const serverIds = agentsStore.serverIdsForLocation(locationId);- if (serverIds.length === 0) return;- const active = switchServersStore.activeServerId;- if (active && serverIds.includes(active)) return;- await activateServer(serverIds[0]);-}--/** Scope to the server owning `roomId`. */-export async function scopeToRoomServer(roomId: string): Promise<void> {- await activateServer(switchRoomsStore.roomServerId(roomId));-}diff --git a/console/apps/switch-console-desktop/src/renderer/lib/layout/scope-to-workspace.ts b/console/apps/switch-console-desktop/src/renderer/lib/layout/scope-to-workspace.tsnew file mode 100644index 000000000..219acde55--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/lib/layout/scope-to-workspace.ts@@ -0,0 +1,44 @@+import { agentsStore } from '@renderer/features/locations/stores/agents-store';+import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';++/**+ * Make a target's workspace the active one before navigating to it.+ *+ * The active workspace scopes the whole sidebar — `sidebarStore.isLocationInActiveScope`+ * and `switchRoomsStore.listedRoomsInActiveScope` both filter on it. Navigating+ * to something in another workspace without this opens the view but leaves the+ * sidebar showing a tree the target is not in, so the row you just opened is+ * nowhere to be seen. Scoping to the *server* is not enough: its other workspace+ * filters the target out just as surely as another server would.+ *+ * A no-op when the target is already in the active workspace, or when its+ * workspace cannot be resolved (an unlinked location).+ */+async function activateWorkspace(workspaceId: string | null): Promise<void> {+ if (!workspaceId) return;+ if (workspacesStore.activeId === workspaceId) return;+ await workspacesStore.setActive(workspaceId);+}++/**+ * Scope to a workspace that shows `locationId` — for agents and sessions.+ *+ * A directory can hold agents for several workspaces, so there may be more than+ * one right answer. If the active workspace is already one of them there is+ * nothing to do; switching away would hide the row the caller is navigating to+ * (CHOO-2044).+ */+export async function scopeToLocationWorkspace(locationId: string): Promise<void> {+ if (!agentsStore.loaded) await agentsStore.load();+ const workspaceIds = agentsStore.workspaceIdsForLocation(locationId);+ if (workspaceIds.length === 0) return;+ const active = workspacesStore.activeId;+ if (active && workspaceIds.includes(active)) return;+ await activateWorkspace(workspaceIds[0]!);+}++/** Scope to the workspace owning `roomId`. */+export async function scopeToRoomWorkspace(roomId: string): Promise<void> {+ await activateWorkspace(switchRoomsStore.roomWorkspaceId(roomId));+}diff --git a/console/apps/switch-console-desktop/src/renderer/lib/stores/use-remote-agents.ts b/console/apps/switch-console-desktop/src/renderer/lib/stores/use-workspace-agents.tssimilarity index 55%rename from console/apps/switch-console-desktop/src/renderer/lib/stores/use-remote-agents.tsrename to console/apps/switch-console-desktop/src/renderer/lib/stores/use-workspace-agents.tsindex 2b2b4798c..8a1859a96 100644--- a/console/apps/switch-console-desktop/src/renderer/lib/stores/use-remote-agents.ts+++ b/console/apps/switch-console-desktop/src/renderer/lib/stores/use-workspace-agents.ts@@ -2,39 +2,39 @@ import { useQuery } from '@tanstack/react-query';import { rpc } from '@renderer/lib/ipc';import type { RemoteAgentSummary } from '@shared/core/switch-servers/switch-servers';-/** The agent list a server holds, keyed so every surface shares one fetch.+/** The agent list a workspace holds, keyed so every surface shares one fetch.* Several unrelated views ask for this at once — the sidebar rows, the room* panels, the agent page — and they must agree, so the key is defined once* here rather than retyped at each call site. */-export function remoteAgentsQueryKey(serverId: string | null) {- return ['remote-agents', serverId] as const;+export function workspaceAgentsQueryKey(workspaceId: string | null) {+ return ['workspace-agents', workspaceId] as const;}/**- * Every agent registered on `serverId`, or an idle query when there is no- * server to ask.+ * Every agent registered in `workspaceId`, or an idle query when there is no+ * workspace to ask.*/-export function useRemoteAgents(serverId: string | null) {+export function useWorkspaceAgents(workspaceId: string | null) {return useQuery<RemoteAgentSummary[]>({- queryKey: remoteAgentsQueryKey(serverId),- queryFn: () => rpc.switchServers.listRemoteAgents(serverId as string),- enabled: serverId !== null,+ queryKey: workspaceAgentsQueryKey(workspaceId),+ queryFn: () => rpc.workspaces.listAgents(workspaceId as string),+ enabled: workspaceId !== null,});}/**- * An agent's chosen icon, or null when it has none, is not on this server, or- * the list has not arrived yet.+ * An agent's chosen icon, or null when it has none, is not in this workspace,+ * or the list has not arrived yet.** Null is not an error and callers must not treat it as one: `AgentAvatar`* draws a bot from the agent's name instead, so a row renders the right* picture on first paint and simply sharpens to a custom icon if there is one.*/export function useAgentIconUrl(- serverId: string | null,+ workspaceId: string | null,switchAgentId: string | null): string | null {- const agents = useRemoteAgents(serverId);+ const agents = useWorkspaceAgents(workspaceId);if (switchAgentId === null) return null;return agents.data?.find((agent) => agent.id === switchAgentId)?.iconUrl ?? null;}diff --git a/console/apps/switch-console-desktop/src/renderer/lib/ui/step-pager.tsx b/console/apps/switch-console-desktop/src/renderer/lib/ui/step-pager.tsxnew file mode 100644index 000000000..85e8c1e1a--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/lib/ui/step-pager.tsx@@ -0,0 +1,67 @@+import { ChevronLeft, ChevronRight } from 'lucide-react';+import { cn } from '@renderer/utils/utils';+import { Button } from './button';++/**+ * The bar at the foot of a paged flow: which page you are on, and the way back+ * or on from it.+ *+ * It names the page rather than counting it. A count is only honest once the+ * sequence has a fixed length, and these flows branch — how many pages are left+ * after "Add a server" depends on the answer given there — so a number would+ * have to renumber itself halfway through.+ *+ * An arrow only repeats a move the page already offers — its Back, its Next.+ * Where the way on is a button that installs a stack, signs you in or creates a+ * server, the page passes a null `onNext`: a chevron whose whole label is "next"+ * must not be the thing that commits you to any of those. The inert arrow stays+ * on screen rather than disappearing, so the bar keeps its shape from page to+ * page and the name does not shift under the eye.+ *+ * An inert arrow is `aria-disabled` rather than `disabled`, and says in its+ * label why it leads nowhere. A chevron is already a control that explains+ * nothing on sight; dropping it out of the tab order as well would leave the+ * one place the reason is written unreachable by the people who most need it.+ */+export function StepPager({+ pageName,+ onBack,+ onNext,+}: {+ pageName: string;+ onBack: (() => void) | null;+ onNext: (() => void) | null;+}) {+ return (+ <nav+ aria-label="Pages in this flow"+ className="flex shrink-0 items-center justify-center gap-4 border-t border-border bg-background-quaternary-1 px-3 py-1.5"+ >+ <Button+ variant="ghost"+ size="icon-xs"+ aria-label={onBack === null ? 'Previous page — this is the first page' : 'Previous page'}+ aria-disabled={onBack === null || undefined}+ className={cn(onBack === null && 'opacity-50')}+ onClick={onBack ?? undefined}+ >+ <ChevronLeft className="size-3.5" />+ </Button>+ <span aria-current="step" className="min-w-40 text-center text-xs text-foreground-muted">+ {pageName}+ </span>+ <Button+ variant="ghost"+ size="icon-xs"+ aria-label={+ onNext === null ? 'Next page — use the button on this page to go on' : 'Next page'+ }+ aria-disabled={onNext === null || undefined}+ className={cn(onNext === null && 'opacity-50')}+ onClick={onNext ?? undefined}+ >+ <ChevronRight className="size-3.5" />+ </Button>+ </nav>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/lib/ui/wizard-frame.tsx b/console/apps/switch-console-desktop/src/renderer/lib/ui/wizard-frame.tsxnew file mode 100644index 000000000..52cf103c5--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/lib/ui/wizard-frame.tsx@@ -0,0 +1,124 @@+import { createContext, useContext, type ReactNode } from 'react';+import { Button } from './button';+import { DialogContentArea, DialogFooter, DialogHeader, DialogTitle } from './dialog';+import { StepPager } from './step-pager';++/**+ * Where a wizard page is being drawn: inside a dialog, or filling the window.+ *+ * The same pages serve both. Setting up a server is a dialog once you already+ * have one and the whole window on a fresh install, where there is no app+ * behind the dialog for it to sit on top of — but it is the same three+ * questions either way, and a second copy of them would be a second place for+ * the Docker check, the log tail and the sign-in form to drift.+ */+export type WizardChrome = 'dialog' | 'page';++const WizardChromeContext = createContext<WizardChrome>('dialog');++/**+ * The way out of a wizard that fills the window.+ *+ * A dialog has its own — Escape, the backdrop, a Cancel button — and something+ * behind it to return to. A full-window wizard has neither, so a flow that can+ * be left part-way has to say so in words on every page rather than relying on+ * the user pressing Back until the window changes shape under them.+ */+export type WizardExit = { label: string; onExit: () => void };++const WizardExitContext = createContext<WizardExit | null>(null);++export function WizardChromeProvider({+ chrome,+ exit,+ children,+}: {+ chrome: WizardChrome;+ /** Null until there is something to leave behind — a flow that has registered+ * nothing yet is left by finishing it or by stepping back off its first page. */+ exit: WizardExit | null;+ children: ReactNode;+}) {+ return (+ <WizardChromeContext.Provider value={chrome}>+ <WizardExitContext.Provider value={exit}>{children}</WizardExitContext.Provider>+ </WizardChromeContext.Provider>+ );+}++/** The pager under a page, or null where the page is not part of a sequence. */+export type WizardPager = {+ pageName: string;+ onBack: (() => void) | null;+ onNext: (() => void) | null;+};++/**+ * One page of a wizard: its question, its body, what it offers at the foot.+ *+ * The page supplies no chrome of its own. A dialog's title bar and a full+ * window's centred heading are the same title, and which one gets rendered is+ * the frame's business rather than the page's.+ */+export function WizardFrame({+ title,+ subtitle,+ footer,+ pager,+ children,+}: {+ title: string;+ /** The line under the title, or null where the title says enough. */+ subtitle: string | null;+ /** Buttons for the foot of the page, in reading order, or null for a page+ * whose only way on is the choice made in its body. */+ footer: ReactNode | null;+ pager: WizardPager | null;+ children: ReactNode;+}) {+ const chrome = useContext(WizardChromeContext);+ const exit = useContext(WizardExitContext);++ if (chrome === 'dialog') {+ return (+ <>+ <DialogHeader showCloseButton={false}>+ <DialogTitle>{title}</DialogTitle>+ </DialogHeader>+ <DialogContentArea className="pt-0">+ {subtitle && <p className="pb-2 text-sm text-foreground-muted">{subtitle}</p>}+ {children}+ </DialogContentArea>+ {footer && <DialogFooter>{footer}</DialogFooter>}+ {pager && <StepPager {...pager} />}+ </>+ );+ }++ return (+ <div className="flex h-full flex-col bg-background text-foreground [-webkit-app-region:drag]">+ {exit && (+ <div className="flex justify-end px-3 pt-3 [-webkit-app-region:no-drag]">+ <Button variant="ghost" size="sm" onClick={exit.onExit}>+ {exit.label}+ </Button>+ </div>+ )}+ <div className="flex min-h-0 flex-1 flex-col overflow-auto">+ <div className="mx-auto flex w-full max-w-xl flex-1 flex-col justify-center gap-6 px-8 py-10 [-webkit-app-region:no-drag]">+ <div className="flex flex-col items-center gap-2 text-center">+ <h1 className="text-2xl font-semibold">{title}</h1>+ {subtitle && <p className="text-sm text-foreground-muted">{subtitle}</p>}+ </div>+ {children}+ {footer && <div className="flex gap-2">{footer}</div>}+ </div>+ </div>+ {pager && (+ <div className="[-webkit-app-region:no-drag]">+ <StepPager {...pager} />+ </div>+ )}+ </div>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/lib/ui/wizard-step-header.tsx b/console/apps/switch-console-desktop/src/renderer/lib/ui/wizard-step-header.tsxdeleted file mode 100644index 61c2c4a9c..000000000--- a/console/apps/switch-console-desktop/src/renderer/lib/ui/wizard-step-header.tsx+++ /dev/null@@ -1,19 +0,0 @@-import { DialogHeader, DialogTitle } from './dialog';--/**- * A dialog header that says where in a sequence you are.- *- * The count is only honest once the sequence has a fixed length, so a step that- * might or might not be reached must not be counted — a wizard that renumbers- * itself halfway through is worse than one that never numbered itself at all.- */-export function WizardStepHeader({ title, step, of }: { title: string; step: number; of: number }) {- return (- <DialogHeader className="flex-col items-start gap-1">- <DialogTitle>{title}</DialogTitle>- <p className="text-xs text-foreground-muted">- Step {step} of {of}- </p>- </DialogHeader>- );-}diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/add-agent-settings-disclosure.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/add-agent-settings-disclosure.test.tsxindex 8b46dc958..7d90e5d75 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/add-agent-settings-disclosure.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/add-agent-settings-disclosure.test.tsx@@ -31,12 +31,12 @@ vi.hoisted(() => {vi.mock('@renderer/lib/ipc', () => ({events: { on: vi.fn() },rpc: {- switchServers: {- listRemoteRooms: () => Promise.resolve([]),- listRemoteRoomGroups: () => Promise.resolve([]),- listRemoteExternalUsers: () => Promise.resolve([]),- listRemoteAgents: () => Promise.resolve([]),- listRemoteBridges: () => Promise.resolve(remote.bridges),+ workspaces: {+ listRooms: () => Promise.resolve([]),+ listRoomGroups: () => Promise.resolve([]),+ listExternalUsers: () => Promise.resolve([]),+ listAgents: () => Promise.resolve([]),+ listBridges: () => Promise.resolve(remote.bridges),listMyIdentities: () => Promise.resolve(remote.identities),},},@@ -72,7 +72,7 @@ function Panel() {return (<AgentSettingsSectionform={form}- serverId="srv-1"+ workspaceId="ws-1"onAddServer={() => {}}onOpenMessagingApps={() => {}}/>diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/connect-messaging-app-modal.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/connect-messaging-app-modal.test.tsxnew file mode 100644index 000000000..8f1be9d6e--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/connect-messaging-app-modal.test.tsx@@ -0,0 +1,220 @@+/**+ * Connecting a messaging app to a workspace.+ *+ * Where the server has its own app for a platform, the dialog leads with+ * installing it — the consent screen opens in the browser and the dialog+ * watches for the connection it creates — and keeps the paste-your-tokens+ * form one click away. Where it has none, the form is all there is.+ */+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const listBridgeTypes = vi.hoisted(() => vi.fn());+const listInstallablePlatforms = vi.hoisted(() => vi.fn());+const beginMessagingAppInstall = vi.hoisted(() => vi.fn());+const listBridges = vi.hoisted(() => vi.fn());+const createBridge = vi.hoisted(() => vi.fn());+const openExternalUrl = vi.hoisted(() => vi.fn());++vi.hoisted(() => {+ window.electronAPI ??= {+ invoke: () => Promise.resolve(undefined),+ eventOn: () => () => {},+ eventSend: () => {},+ } as unknown as typeof window.electronAPI;+});++vi.mock('@renderer/lib/ipc', () => ({+ rpc: {+ workspaces: {+ listBridgeTypes,+ listInstallablePlatforms,+ beginMessagingAppInstall,+ listBridges,+ createBridge,+ },+ },+ events: { on: () => () => {}, emit: () => {} },+}));+vi.mock('@renderer/lib/open-external', () => ({ openExternalUrl }));+vi.mock('@renderer/features/workspaces/workspaces-store', () => ({+ workspacesStore: { idOnServerInScope: () => 'ws-1' },+}));+vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({+ switchServersStore: { activeServerId: 'srv-1', servers: [{ id: 'srv-1', name: 'Dev' }] },+}));+vi.mock('@renderer/features/switch-servers/workspace-admin', () => ({+ administersWorkspaceInScope: () => true,+}));++import { ConnectMessagingAppModal } from '@renderer/features/switch-servers/ConnectMessagingAppModal';+import { Dialog } from '@renderer/lib/ui/dialog';++const onSuccess = vi.fn();+const onClose = vi.fn();++function bridge(id: string, type: string) {+ return {+ id,+ type,+ displayName: `${type} ${id}`,+ status: 'active',+ isDefault: false,+ homeUrl: null,+ channelCreationSupported: true,+ channelCreationEnabled: true,+ };+}++let container: HTMLDivElement | null = null;+let root: Root | null = null;++beforeEach(() => {+ listBridgeTypes+ .mockReset()+ .mockResolvedValue([+ { key: 'slack', fields: [], channelCreationSupported: true, directorySearchSupported: true },+ ]);+ listInstallablePlatforms.mockReset().mockResolvedValue(['slack']);+ beginMessagingAppInstall.mockReset().mockResolvedValue('https://slack.example/oauth?state=s');+ listBridges.mockReset().mockResolvedValue([bridge('b-old', 'slack')]);+ createBridge.mockReset();+ openExternalUrl.mockReset().mockResolvedValue(true);+ onSuccess.mockReset();+ onClose.mockReset();+});++afterEach(async () => {+ if (root) await act(async () => root!.unmount());+ container?.remove();+ container = null;+ root = null;+});++async function render(): Promise<HTMLElement> {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });+ await act(async () =>+ root!.render(+ <QueryClientProvider client={client}>+ <Dialog open onOpenChange={() => {}}>+ <ConnectMessagingAppModal onSuccess={onSuccess} onClose={onClose} />+ </Dialog>+ </QueryClientProvider>+ )+ );+ await settle();+ return document.body;+}++async function settle(): Promise<void> {+ for (let i = 0; i < 10; i++) await act(async () => await Promise.resolve());+}++function findButton(el: HTMLElement, label: string): HTMLButtonElement | undefined {+ return [...el.querySelectorAll<HTMLButtonElement>('button')].find((b) =>+ b.textContent?.includes(label)+ );+}++function button(el: HTMLElement, label: string): HTMLButtonElement {+ const found = findButton(el, label);+ expect(found, `no ${label} button`).toBeDefined();+ return found!;+}++describe('the connect-messaging-app dialog', () => {+ it('leads with installing the server’s own app, with no token form', async () => {+ const el = await render();++ expect(findButton(el, 'Add to Slack')).toBeDefined();+ expect(el.textContent).not.toContain('Choose a platform');+ expect(findButton(el, 'Connect')).toBeUndefined();+ });++ it('opens the consent page and hands back the connection it creates', async () => {+ const el = await render();+ listBridges+ .mockResolvedValueOnce([bridge('b-old', 'slack')])+ .mockResolvedValue([bridge('b-old', 'slack'), bridge('b-new', 'slack')]);++ await act(async () => button(el, 'Add to Slack').click());+ await settle();++ expect(beginMessagingAppInstall).toHaveBeenCalledWith({+ workspaceId: 'ws-1',+ platform: 'slack',+ });+ expect(openExternalUrl).toHaveBeenCalledWith(+ 'https://slack.example/oauth?state=s',+ 'Could not open Slack'+ );+ expect(onSuccess).toHaveBeenCalledWith({+ bridgeId: 'b-new',+ displayName: 'slack b-new',+ directorySearchSupported: true,+ });+ });++ it('keeps waiting while only connections that already existed are listed', async () => {+ const el = await render();++ await act(async () => button(el, 'Add to Slack').click());+ await settle();++ expect(el.textContent).toContain('Waiting for Slack');+ expect(onSuccess).not.toHaveBeenCalled();+ });++ it('stays put when the browser could not be opened', async () => {+ openExternalUrl.mockResolvedValue(false);+ const el = await render();++ await act(async () => button(el, 'Add to Slack').click());+ await settle();++ expect(el.textContent).not.toContain('Waiting for Slack');+ expect(findButton(el, 'Add to Slack')).toBeDefined();+ });++ it('says so when the install could not be started', async () => {+ beginMessagingAppInstall.mockRejectedValue(new Error('install refused'));+ const el = await render();++ await act(async () => button(el, 'Add to Slack').click());+ await settle();++ expect(el.textContent).toContain('Could not start adding Slack');+ expect(openExternalUrl).not.toHaveBeenCalled();+ });++ it('offers the token form behind "use your own app"', async () => {+ const el = await render();++ await act(async () => button(el, 'Use your own app instead').click());+ await settle();++ expect(el.textContent).toContain('Choose a platform');+ expect(findButton(el, 'Add to Slack')).toBeUndefined();+ });++ it('shows only the token form when the server has no app of its own', async () => {+ listInstallablePlatforms.mockResolvedValue([]);+ const el = await render();++ expect(el.textContent).toContain('Choose a platform');+ expect(findButton(el, 'Add to Slack')).toBeUndefined();+ });++ it('falls back to the token form, and says why, when the check fails', async () => {+ listInstallablePlatforms.mockRejectedValue(new Error('boom'));+ const el = await render();++ expect(el.textContent).toContain('Could not check which messaging apps');+ expect(el.textContent).toContain('Choose a platform');+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/create-workspace-modal.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/create-workspace-modal.test.tsxnew file mode 100644index 000000000..ba243866c--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/create-workspace-modal.test.tsx@@ -0,0 +1,369 @@+/**+ * Making a workspace from the switcher.+ *+ * A workspace belongs to a server, so what this has to get right is which one:+ * the question is only asked where there is a choice, and a server that cannot+ * be asked at all is said to be so rather than allowed to fail on Create.+ */+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const create = vi.hoisted(() => vi.fn());+const setActiveWorkspace = vi.hoisted(() => vi.fn());+const connected = vi.hoisted(() => new Set<string>());+/** Ids a status read has answered for. Not asked yet is its own state. */+const statuses = vi.hoisted(() => new Map<string, unknown>());+const unreachable = vi.hoisted(() => new Set<string>());+const refreshStatus = vi.hoisted(() => vi.fn());+const servers = vi.hoisted(() => [] as { id: string; name: string }[]);++vi.hoisted(() => {+ window.electronAPI ??= {+ invoke: () => Promise.resolve(undefined),+ eventOn: () => () => {},+ eventSend: () => {},+ } as unknown as typeof window.electronAPI;+});++vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({+ switchServersStore: {+ get servers() {+ return servers;+ },+ statuses,+ isConnected: (id: string) => connected.has(id),+ isUnreachable: (id: string) => unreachable.has(id),+ refreshStatus,+ serverById: (id: string) => servers.find((s) => s.id === id) ?? null,+ },+}));++vi.mock('@renderer/features/workspaces/workspaces-store', () => ({+ workspacesStore: { create, setActive: setActiveWorkspace },+}));++import { CreateWorkspaceModal } from '@renderer/features/workspaces/create-workspace-modal';+import { modalStore } from '@renderer/lib/modal/modal-store';+import { Dialog } from '@renderer/lib/ui/dialog';+import { RpcError } from '@shared/lib/ipc/rpc-error';++let container: HTMLDivElement | null = null;+let root: Root | null = null;++const onSuccess = vi.fn();+const onClose = vi.fn();++function workspace(id: string, serverId: string) {+ return {+ id,+ serverId,+ name: 'Weekend Robotics',+ tenantId: 't1',+ slug: 'weekend-robotics',+ role: 'owner' as const,+ createdAt: '',+ updatedAt: '',+ };+}++beforeEach(() => {+ create.mockReset();+ setActiveWorkspace.mockReset().mockResolvedValue(undefined);+ refreshStatus.mockReset();+ onSuccess.mockReset();+ onClose.mockReset();+ servers.length = 0;+ connected.clear();+ statuses.clear();+ unreachable.clear();+ modalStore.closeGuardActive = false;+});++/**+ * A server the app knows about, in one of the four states the modal tells+ * apart.+ *+ * `unknown` is the one that is not a failure: no status read has answered for+ * it yet, which is a different thing from having answered "not signed in".+ */+function addServer(+ id: string,+ name: string,+ state: 'signedIn' | 'signedOut' | 'unreachable' | 'unknown'+) {+ servers.push({ id, name });+ if (state === 'unknown') return;+ statuses.set(id, { serverId: id, connected: state === 'signedIn', user: null });+ if (state === 'signedIn') connected.add(id);+ if (state === 'unreachable') unreachable.add(id);+}++function deferred<T>() {+ let resolve!: (value: T) => void;+ let reject!: (cause: unknown) => void;+ const promise = new Promise<T>((res, rej) => {+ resolve = res;+ reject = rej;+ });+ return { promise, resolve, reject };+}++afterEach(async () => {+ if (root) await act(async () => root!.unmount());+ container?.remove();+ container = null;+ root = null;+});++async function render(serverId: string): Promise<HTMLDivElement> {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ // The modal renders the dialog's parts and not the dialog itself — the+ // registry supplies that in the app, and this supplies it here.+ await act(async () =>+ root!.render(+ <Dialog open onOpenChange={() => {}}>+ <CreateWorkspaceModal serverId={serverId} onSuccess={onSuccess} onClose={onClose} />+ </Dialog>+ )+ );+ return container;+}++async function settle(): Promise<void> {+ for (let i = 0; i < 8; i++) await act(async () => await Promise.resolve());+}++/** By substring: the confirm button carries its keyboard shortcut in its text. */+function button(el: HTMLElement, label: string): HTMLButtonElement {+ const found = [...el.querySelectorAll<HTMLButtonElement>('button')].find((b) =>+ b.textContent?.includes(label)+ );+ expect(found, `no ${label} button`).toBeDefined();+ return found!;+}++async function typeName(el: HTMLElement, value: string): Promise<void> {+ const input = el.querySelector('input')!;+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;+ await act(async () => {+ setter.call(input, value);+ input.dispatchEvent(new Event('input', { bubbles: true }));+ });+}++/** A label that is present in the dialog, ignoring the select's own portal. */+function hasLabel(el: HTMLElement, text: string): boolean {+ return [...el.querySelectorAll('label')].some((l) => l.textContent?.trim() === text);+}++describe('the create-workspace modal', () => {+ it('creates on the server the window is in, and goes there', async () => {+ addServer('srv-1', 'Acme prod', 'signedIn');+ const made = workspace('ws-9', 'srv-1');+ create.mockResolvedValue(made);++ const el = await render('srv-1');+ await typeName(el, ' Weekend Robotics ');+ await act(async () => button(el, 'Create workspace').click());+ await settle();++ expect(create).toHaveBeenCalledWith('srv-1', 'Weekend Robotics');+ expect(setActiveWorkspace).toHaveBeenCalledWith('ws-9');+ expect(onSuccess).toHaveBeenCalledWith(made);+ });++ it('does not ask which server when there is only one to ask about', async () => {+ addServer('srv-1', 'Acme prod', 'signedIn');++ const el = await render('srv-1');++ expect(hasLabel(el, 'Server')).toBe(false);+ expect(el.textContent).toContain('Acme prod');+ });++ it('asks which server once there are two you are signed in to', async () => {+ addServer('srv-1', 'Acme prod', 'signedIn');+ addServer('srv-2', 'Acme staging', 'signedIn');++ const el = await render('srv-1');++ expect(hasLabel(el, 'Server')).toBe(true);+ });++ // The failure would otherwise arrive as an authentication error on Create,+ // which reads as the name being refused.+ it('refuses to ask a server you are not signed in to', async () => {+ addServer('srv-1', 'Acme prod', 'signedOut');++ const el = await render('srv-1');+ await typeName(el, 'Weekend Robotics');++ expect(el.textContent).toContain('not signed in to Acme prod');+ expect(button(el, 'Create workspace').disabled).toBe(true);+ });++ it('will not create a workspace with no name', async () => {+ addServer('srv-1', 'Acme prod', 'signedIn');++ const el = await render('srv-1');+ await typeName(el, ' ');++ expect(button(el, 'Create workspace').disabled).toBe(true);+ });++ it('keeps the form and says why when the server refuses the name', async () => {+ addServer('srv-1', 'Acme prod', 'signedIn');+ create.mockRejectedValue(new Error('A workspace with that name already exists.'));++ const el = await render('srv-1');+ await typeName(el, 'Weekend Robotics');+ await act(async () => button(el, 'Create workspace').click());+ await settle();++ expect(el.textContent).toContain('already exists');+ expect(onSuccess).not.toHaveBeenCalled();+ expect(button(el, 'Create workspace').disabled).toBe(false);+ });++ /**+ * The refusal the gateway actually sends, rather than a plain Error. Its+ * words are `Slug already taken: weekend-robotics` — no terminal punctuation,+ * so the shared description does not read it as a sentence and demotes it to+ * diagnostics. What reached the user was a status code and a slug they never+ * typed, for the likeliest failure of this form and the only one they can fix.+ */+ it('blames the name for a name conflict, not the status code and the slug', async () => {+ addServer('srv-1', 'Acme prod', 'signedIn');+ create.mockRejectedValue(+ new RpcError({+ __switchConsoleRpcError: true,+ code: 'GatewayError',+ message: 'Gateway returned 409: Slug already taken: weekend-robotics',+ data: { kind: 'http', status: 409, detail: 'Slug already taken: weekend-robotics' },+ } as unknown as ConstructorParameters<typeof RpcError>[0])+ );++ const el = await render('srv-1');+ await typeName(el, 'Weekend Robotics');+ await act(async () => button(el, 'Create workspace').click());+ await settle();++ expect(el.textContent).toContain('already goes by that name');+ expect(el.textContent).not.toContain('weekend-robotics');+ expect(el.textContent).not.toContain('409');+ // Still typeable: a different name is the whole of the remedy.+ expect(el.querySelector('input')!.disabled).toBe(false);+ });++ /**+ * "Not signed in" and "cannot be reached" want different things from the+ * user, and only one of them is a password. Sending someone to re-authenticate+ * for a network outage is the same misattribution this modal exists to avoid,+ * pointing the other way.+ */+ it('says a server is unreachable rather than telling you to sign in again', async () => {+ addServer('srv-1', 'Acme prod', 'unreachable');++ const el = await render('srv-1');++ expect(el.textContent).toContain('can’t be reached');+ expect(el.textContent).not.toContain('not signed in');+ });++ it('does not claim you are signed out before it has looked', async () => {+ addServer('srv-1', 'Acme prod', 'unknown');++ const el = await render('srv-1');++ expect(el.textContent).toContain('Checking whether you’re signed in');+ expect(el.textContent).not.toContain('not signed in to');+ // Nothing else on screen is watching this server, so the modal has to ask+ // or the sentence above is what it says forever.+ expect(refreshStatus).toHaveBeenCalledWith('srv-1');+ });++ /**+ * The hidden default was the window's own server, which may be the one that+ * cannot be asked — leaving Create permanently off with the usable server+ * offered nowhere.+ */+ it('opens on a server it can ask when the window’s own cannot be', async () => {+ addServer('srv-1', 'Acme prod', 'signedOut');+ addServer('srv-2', 'Acme staging', 'signedIn');+ create.mockResolvedValue(workspace('ws-9', 'srv-2'));++ const el = await render('srv-1');+ await typeName(el, 'Weekend Robotics');+ await act(async () => button(el, 'Create workspace').click());+ await settle();++ expect(el.textContent).toContain('Acme staging');+ expect(create).toHaveBeenCalledWith('srv-2', 'Weekend Robotics');+ });++ /**+ * `dismissOnOutsideClick: false` stops the backdrop but not Escape, so+ * without the guard a keypress mid-create leaves the window re-scoped and+ * `onSuccess` firing on a modal the user believed they had cancelled.+ */+ it('holds itself shut while the create is in flight', async () => {+ addServer('srv-1', 'Acme prod', 'signedIn');+ const creating = deferred<ReturnType<typeof workspace>>();+ create.mockReturnValue(creating.promise);++ const el = await render('srv-1');+ await typeName(el, 'Weekend Robotics');+ await act(async () => button(el, 'Create workspace').click());++ expect(modalStore.closeGuardActive).toBe(true);++ creating.resolve(workspace('ws-9', 'srv-1'));+ await settle();++ expect(modalStore.closeGuardActive).toBe(false);+ });++ /**+ * The workspace exists on the server from the moment Create returns.+ * Offering Create again would send the same name back and earn a conflict+ * that reads as the name being refused — on the first-run page with no way+ * back, that is the end of the road.+ */+ it('offers to open the workspace it already made rather than creating it twice', async () => {+ addServer('srv-1', 'Acme prod', 'signedIn');+ create.mockResolvedValue(workspace('ws-9', 'srv-1'));+ setActiveWorkspace.mockRejectedValueOnce(new Error('could not switch'));++ const el = await render('srv-1');+ await typeName(el, 'Weekend Robotics');+ await act(async () => button(el, 'Create workspace').click());+ await settle();++ expect(el.textContent).toContain('could not be moved into it');++ await act(async () => button(el, 'Open workspace').click());+ await settle();++ expect(create).toHaveBeenCalledTimes(1);+ expect(onSuccess).toHaveBeenCalledWith(expect.objectContaining({ id: 'ws-9' }));+ });++ // Creating it and then leaving the window in the old workspace would look+ // like nothing happened, so a switch that fails is not reported as success.+ it('does not report success when the new workspace cannot be entered', async () => {+ addServer('srv-1', 'Acme prod', 'signedIn');+ create.mockResolvedValue(workspace('ws-9', 'srv-1'));+ setActiveWorkspace.mockRejectedValue(new Error('could not switch'));++ const el = await render('srv-1');+ await typeName(el, 'Weekend Robotics');+ await act(async () => button(el, 'Create workspace').click());+ await settle();++ expect(onSuccess).not.toHaveBeenCalled();+ expect(el.textContent).toContain('could not switch');+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/invite-people-modal.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/invite-people-modal.test.tsxnew file mode 100644index 000000000..a6edb660f--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/invite-people-modal.test.tsx@@ -0,0 +1,354 @@+/**+ * Inviting people to a workspace from the switcher.+ *+ * What matters is that the link is always handed over — whether or not the+ * e-mail went out, it is the one moment it can be shown — that the notice says+ * truthfully what happened to the e-mail, and that only live invitations offer+ * Revoke.+ */+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const listInvitations = vi.hoisted(() => vi.fn());+const createInvitation = vi.hoisted(() => vi.fn());+const revokeInvitation = vi.hoisted(() => vi.fn());+const byId = vi.hoisted(() => vi.fn());+const listJoinDomains = vi.hoisted(() => vi.fn());+const addJoinDomain = vi.hoisted(() => vi.fn());+const removeJoinDomain = vi.hoisted(() => vi.fn());++vi.hoisted(() => {+ window.electronAPI ??= {+ invoke: () => Promise.resolve(undefined),+ eventOn: () => () => {},+ eventSend: () => {},+ } as unknown as typeof window.electronAPI;+});++vi.mock('@renderer/lib/ipc', () => ({+ rpc: {+ workspaces: {+ listInvitations,+ createInvitation,+ revokeInvitation,+ listJoinDomains,+ addJoinDomain,+ removeJoinDomain,+ },+ },+ events: { on: () => () => {}, emit: () => {} },+}));++vi.mock('@renderer/features/workspaces/workspaces-store', () => ({+ workspacesStore: { byId },+}));++import { InvitePeopleModal } from '@renderer/features/workspaces/invite-people-modal';+import { modalStore } from '@renderer/lib/modal/modal-store';+import { Dialog } from '@renderer/lib/ui/dialog';+import { administersWorkspace } from '@shared/core/workspaces/workspaces';++const onClose = vi.fn();++function workspace(role: 'owner' | 'admin' | 'member') {+ return {+ id: 'ws-1',+ serverId: 'srv-1',+ name: 'Acme',+ tenantId: 't1',+ slug: 'acme',+ role,+ createdAt: '',+ updatedAt: '',+ };+}++function invitation(overrides: Record<string, unknown>) {+ return {+ id: 'inv-1',+ role: 'member',+ email: null,+ expiresAt: new Date(Date.now() + 86_400_000).toISOString(),+ usesRemaining: 1,+ revokedAt: null,+ createdAt: new Date().toISOString(),+ ...overrides,+ };+}++let container: HTMLDivElement | null = null;+let root: Root | null = null;++beforeEach(() => {+ listInvitations.mockReset();+ createInvitation.mockReset();+ revokeInvitation.mockReset();+ byId.mockReset().mockReturnValue(workspace('admin'));+ listJoinDomains.mockReset().mockResolvedValue({ kind: 'unsupported' });+ addJoinDomain.mockReset().mockResolvedValue(undefined);+ removeJoinDomain.mockReset().mockResolvedValue(undefined);+ onClose.mockReset();+ modalStore.closeGuardActive = false;+});++afterEach(async () => {+ if (root) await act(async () => root!.unmount());+ container?.remove();+ container = null;+ root = null;+});++async function render(): Promise<HTMLElement> {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });+ await act(async () =>+ root!.render(+ <QueryClientProvider client={client}>+ <Dialog open onOpenChange={() => {}}>+ <InvitePeopleModal workspaceId="ws-1" onSuccess={() => {}} onClose={onClose} />+ </Dialog>+ </QueryClientProvider>+ )+ );+ await settle();+ return document.body;+}++async function settle(): Promise<void> {+ for (let i = 0; i < 8; i++) await act(async () => await Promise.resolve());+}++function button(el: HTMLElement, label: string): HTMLButtonElement {+ const found = [...el.querySelectorAll<HTMLButtonElement>('button')].find((b) =>+ b.textContent?.includes(label)+ );+ expect(found, `no ${label} button`).toBeDefined();+ return found!;+}++async function type(input: HTMLInputElement, value: string): Promise<void> {+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;+ await act(async () => {+ setter.call(input, value);+ input.dispatchEvent(new Event('input', { bubbles: true }));+ });+}++describe('the invite-people modal', () => {+ it('is offered to admins and owners, not members', () => {+ expect(administersWorkspace(workspace('owner') as never)).toBe(true);+ expect(administersWorkspace(workspace('admin') as never)).toBe(true);+ expect(administersWorkspace(workspace('member') as never)).toBe(false);+ });++ it('e-mails an addressed invitation and still shows its link', async () => {+ listInvitations.mockResolvedValue({ invitations: [], emailEnabled: true });+ createInvitation.mockResolvedValue({+ invitation: invitation({ email: '[email protected]' }),+ link: 'https://switch.example.com/invite#token=tok-1',+ emailDelivery: 'sent',+ });+ const el = await render();++ await type(el.querySelector<HTMLInputElement>('#invite-people-email')!, ' [email protected] ');+ await act(async () => button(el, 'Send invitation').click());+ await settle();++ expect(createInvitation).toHaveBeenCalledWith({+ workspaceId: 'ws-1',+ role: 'member',+ email: '[email protected]',+ expiresInHours: 168,+ usesRemaining: 1,+ });+ expect(el.textContent).toContain('Invitation e-mailed to [email protected]');+ expect(el.querySelector<HTMLInputElement>('#invite-people-link')!.value).toBe(+ 'https://switch.example.com/invite#token=tok-1'+ );+ });++ it('says no e-mail went out when the server has no mail, and hands over the link', async () => {+ listInvitations.mockResolvedValue({ invitations: [], emailEnabled: false });+ createInvitation.mockResolvedValue({+ invitation: invitation({ email: '[email protected]' }),+ link: 'https://switch.example.com/invite#token=tok-1',+ emailDelivery: 'not_configured',+ });+ const el = await render();++ expect(el.textContent).toContain('This server has no e-mail set up');+ await type(el.querySelector<HTMLInputElement>('#invite-people-email')!, '[email protected]');+ await act(async () => button(el, 'Create link').click());+ await settle();++ expect(el.textContent).toContain('No e-mail was sent');+ expect(el.querySelector<HTMLInputElement>('#invite-people-link')!.value).toContain('tok-1');+ });++ it('works against a server older than e-mailed invitations', async () => {+ listInvitations.mockResolvedValue({ invitations: [], emailEnabled: null });+ createInvitation.mockResolvedValue({+ invitation: invitation({ email: '[email protected]' }),+ link: 'https://switch.example.com/invite#token=tok-1',+ emailDelivery: 'unsupported',+ });+ const el = await render();++ expect(el.textContent).toContain('This server does not e-mail invitations');+ await type(el.querySelector<HTMLInputElement>('#invite-people-email')!, '[email protected]');+ await act(async () => button(el, 'Create link').click());+ await settle();++ expect(el.textContent).toContain(+ 'No e-mail was sent — this server does not e-mail invitations'+ );+ expect(el.querySelector<HTMLInputElement>('#invite-people-link')!.value).toContain('tok-1');+ });++ it('makes a link for anyone when no address is given', async () => {+ listInvitations.mockResolvedValue({ invitations: [], emailEnabled: true });+ createInvitation.mockResolvedValue({+ invitation: invitation({}),+ link: 'https://switch.example.com/invite#token=tok-2',+ emailDelivery: 'not_requested',+ });+ const el = await render();++ await act(async () => button(el, 'Create link').click());+ await settle();++ expect(createInvitation).toHaveBeenCalledWith(expect.objectContaining({ email: null }));+ expect(el.textContent).toContain('Send this link to the person you are inviting');+ });++ it("shows the server's refusal and keeps the form", async () => {+ listInvitations.mockResolvedValue({ invitations: [], emailEnabled: true });+ createInvitation.mockRejectedValue(new Error('Not an e-mail address'));+ const el = await render();++ await type(el.querySelector<HTMLInputElement>('#invite-people-email')!, 'nope');+ await act(async () => button(el, 'Send invitation').click());+ await settle();++ expect(el.querySelector('[role="alert"]')?.textContent).toContain('Not an e-mail address');+ expect(el.querySelector('#invite-people-email')).not.toBeNull();+ });++ it('lists invitations and offers Revoke only on live ones', async () => {+ listInvitations.mockResolvedValue({+ emailEnabled: true,+ invitations: [+ invitation({ id: 'live', email: '[email protected]' }),+ invitation({ id: 'gone', revokedAt: new Date().toISOString() }),+ invitation({ id: 'lapsed', expiresAt: new Date(Date.now() - 1000).toISOString() }),+ invitation({ id: 'spent', usesRemaining: 0 }),+ ],+ });+ revokeInvitation.mockResolvedValue(invitation({ id: 'live' }));+ const el = await render();++ const rows = [...el.querySelectorAll<HTMLElement>('[data-testid="invitation-row"]')];+ expect(rows.map((r) => r.textContent)).toEqual([+ expect.stringContaining('Active'),+ expect.stringContaining('Revoked'),+ expect.stringContaining('Expired'),+ expect.stringContaining('Used'),+ ]);+ expect(+ rows.filter((r) => r.textContent?.includes('Revoke') && !r.textContent.includes('Revoked'))+ ).toHaveLength(1);++ await act(async () => button(rows[0]!, 'Revoke').click());+ await settle();++ expect(revokeInvitation).toHaveBeenCalledWith({ workspaceId: 'ws-1', invitationId: 'live' });+ expect(listInvitations).toHaveBeenCalledTimes(2);+ });++ it('does not let an admin hand out ownership', async () => {+ listInvitations.mockResolvedValue({ invitations: [], emailEnabled: true });+ byId.mockReturnValue(workspace('admin'));+ const el = await render();++ await act(async () => el.querySelector<HTMLElement>('[aria-label="Role"]')!.click());+ await settle();++ const options = [...document.querySelectorAll('[role="option"]')].map((o) => o.textContent);+ expect(options).toEqual(['Member', 'Admin']);+ });+});++describe('joining by e-mail domain', () => {+ function section(): HTMLElement | null {+ return document.querySelector<HTMLElement>('[data-testid="join-domains-section"]');+ }++ it("offers only the admin's own domain, and opens the workspace to it", async () => {+ listInvitations.mockResolvedValue({ invitations: [], emailEnabled: true });+ listJoinDomains+ .mockResolvedValueOnce({+ kind: 'listed',+ domains: [],+ ownDomain: 'acme.example',+ ownDomainRefusal: null,+ })+ .mockResolvedValue({+ kind: 'listed',+ domains: ['acme.example'],+ ownDomain: 'acme.example',+ ownDomainRefusal: null,+ });+ await render();++ expect(section()!.textContent).toContain('Let anyone with an @acme.example address join');+ await act(async () => button(section()!, 'Allow').click());+ await settle();++ expect(addJoinDomain).toHaveBeenCalledWith({ workspaceId: 'ws-1', domain: 'acme.example' });+ const rows = section()!.querySelectorAll('[data-testid="join-domain-row"]');+ expect(rows).toHaveLength(1);+ expect(section()!.textContent).not.toContain('Allow');+ });++ it('removes a domain', async () => {+ listInvitations.mockResolvedValue({ invitations: [], emailEnabled: true });+ listJoinDomains.mockResolvedValue({+ kind: 'listed',+ domains: ['acme.example'],+ ownDomain: 'acme.example',+ ownDomainRefusal: null,+ });+ await render();++ await act(async () => button(section()!, 'Remove').click());+ await settle();++ expect(removeJoinDomain).toHaveBeenCalledWith({ workspaceId: 'ws-1', domain: 'acme.example' });+ });++ it("shows why a public provider's domain cannot be added", async () => {+ listInvitations.mockResolvedValue({ invitations: [], emailEnabled: true });+ listJoinDomains.mockResolvedValue({+ kind: 'listed',+ domains: [],+ ownDomain: 'gmail.com',+ ownDomainRefusal:+ 'gmail.com is a public e-mail provider, so opening the workspace to it would let anyone with an address there join',+ });+ await render();++ expect(section()!.textContent).toContain('gmail.com is a public e-mail provider');+ expect(section()!.textContent).not.toContain('Allow');+ });++ it('is left out on a server too old to have it', async () => {+ listInvitations.mockResolvedValue({ invitations: [], emailEnabled: true });+ await render();++ expect(section()).toBeNull();+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/messaging-app-row.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/messaging-app-row.test.tsxindex b5acc042d..430ecf91b 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/messaging-app-row.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/messaging-app-row.test.tsx@@ -79,6 +79,7 @@ function row() {return (<MessagingAppRow+ workspaceId="ws-1"serverId="srv-1"bridge={overrides.bridge ?? bridge()}identities={overrides.identities === undefined ? [] : overrides.identities}diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/onboarding-flow.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/onboarding-flow.test.tsxnew file mode 100644index 000000000..892c24239--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/onboarding-flow.test.tsx@@ -0,0 +1,446 @@+/**+ * The path a fresh install takes to its first server.+ *+ * The flow is the add-server wizard drawn full window, so what is worth testing+ * is not the wizard again but the joins: that the welcome page leads into the+ * question rather than a dialog, that each page can be backed out of, and that+ * the one thing the first-run form does differently — not asking for a name —+ * still produces a server with a name on it.+ */+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const addServer = vi.hoisted(() => vi.fn());+const setActive = vi.hoisted(() => vi.fn());+const navigate = vi.hoisted(() => vi.fn());+const listHosts = vi.hoisted(() => vi.fn());+const switchCloud = vi.hoisted(() => vi.fn());+const connectToSwitchCloud = vi.hoisted(() => vi.fn());+const servers = vi.hoisted(() => [] as { id: string; name: string }[]);++vi.hoisted(() => {+ window.electronAPI ??= {+ invoke: () => Promise.resolve(undefined),+ eventOn: () => () => {},+ eventSend: () => {},+ } as unknown as typeof window.electronAPI;+});++vi.mock('@renderer/lib/ipc', () => ({+ events: { on: () => () => {} },+ rpc: { remoteHosts: { listHosts }, switchServers: { switchCloud } },+}));++vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({+ switchServersStore: {+ addServer,+ connectToSwitchCloud,+ setActive,+ serverById: (id: string | null) => servers.find((s) => s.id === id) ?? null,+ errorText: null,+ ensureAuthConfig: () => Promise.resolve(),+ authConfigFor: () => ({+ passwordLoginEnabled: true,+ oidcEnabled: false,+ oidcProviderLabel: null,+ }),+ authConfigCheckFailed: () => false,+ authConfigChecking: () => false,+ passwordLogin: () => Promise.resolve(true),+ oidcLogin: () => Promise.resolve(true),+ },+}));++vi.mock('@renderer/lib/layout/navigation-provider', () => ({+ useNavigate: () => ({ navigate }),+}));++/**+ * The local-server supervisor as the page sees it. Stands in for the real+ * singleton so a test can put the page in the middle of an install without a+ * Docker daemon anywhere near it.+ */+const localServer = vi.hoisted(() => ({+ status: null as { serverId: string | null; version: string } | null,+ docker: { available: true } as { available: boolean } | null,+ isRunning: false,+ isTransitioning: false,+ phase: 'stopped',+ message: null as string | null,+ error: null as string | null,+ errorDetail: null as string | null,+ logs: [] as string[],+ init: vi.fn(() => Promise.resolve()),+ checkDocker: vi.fn(() => Promise.resolve()),+ start: vi.fn(),+}));++vi.mock('@renderer/features/switch-servers/local-server-store', () => ({+ localServerStore: localServer,+}));++vi.mock('@renderer/lib/telemetry/report', () => ({ report: vi.fn() }));++import { OnboardingFlow } from '@renderer/features/onboarding/onboarding-flow';+import { onboardingStore } from '@renderer/features/onboarding/onboarding-store';++let container: HTMLDivElement | null = null;+let root: Root | null = null;++beforeEach(() => {+ addServer.mockReset();+ setActive.mockReset();+ navigate.mockReset();+ listHosts.mockReset();+ listHosts.mockResolvedValue([]);+ switchCloud.mockReset();+ switchCloud.mockResolvedValue(null);+ connectToSwitchCloud.mockReset();+ servers.length = 0;+ onboardingStore.reset();+ Object.assign(localServer, {+ status: null,+ docker: { available: true },+ isRunning: false,+ isTransitioning: false,+ phase: 'stopped',+ message: null,+ error: null,+ errorDetail: null,+ logs: [],+ });+});++/** Register a server the way the connect page does, list and all. */+function serverAdded(id: string) {+ const server = {+ id,+ name: 'switch.example.com',+ gatewayUrl: 'https://switch.example.com',+ apiUrl: 'https://switch.example.com:8000',+ };+ servers.push(server);+ addServer.mockResolvedValue(server);+ return server;+}++/** Walk the connect page to the point where the server exists. */+async function addFromConnectPage(el: HTMLElement) {+ await act(async () => button(el, 'Continue with your own server').click());+ await choose(el, "It's already running");+ await type(field(el, 'Gateway URL')!, 'https://switch.example.com');+ await type(field(el, 'API URL')!, 'https://switch.example.com:8000');+ await choose(el, 'Sign in to this server');+}++afterEach(async () => {+ if (root) await act(async () => root!.unmount());+ container?.remove();+ container = null;+ root = null;+});++async function renderFlow(): Promise<HTMLDivElement> {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ await act(async () => root!.render(<OnboardingFlow />));+ return container;+}++function button(el: HTMLElement, label: string): HTMLButtonElement {+ const found = [...el.querySelectorAll<HTMLButtonElement>('button')].find(+ (b) => b.textContent?.trim() === label+ );+ expect(found, `no ${label} button`).toBeDefined();+ return found!;+}++/** Every button's label, for asserting that one is not among them. */+function labels(el: HTMLElement): (string | null)[] {+ return [...el.querySelectorAll('button')].map((b) => b.textContent);+}++/** A card or button whose text contains this, wherever it sits in the page. */+async function choose(el: HTMLElement, text: string): Promise<void> {+ const found = [...el.querySelectorAll<HTMLButtonElement>('button')].find((b) =>+ b.textContent?.includes(text)+ );+ expect(found, `nothing to click named ${text}`).toBeDefined();+ await act(async () => found!.click());+}++function field(el: HTMLElement, label: string): HTMLInputElement | null {+ const labels = [...el.querySelectorAll<HTMLElement>('label')];+ const match = labels.find((l) => l.textContent?.trim() === label);+ if (!match) return null;+ const input = match.parentElement?.querySelector('input');+ expect(input, `no input under ${label}`).not.toBeNull();+ return input as HTMLInputElement;+}++async function type(input: HTMLInputElement, value: string): Promise<void> {+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;+ await act(async () => {+ setter.call(input, value);+ input.dispatchEvent(new Event('input', { bubbles: true }));+ });+}++describe('the first-run flow', () => {+ it('asks who runs the server once you continue past the welcome', async () => {+ const el = await renderFlow();++ await act(async () => button(el, 'Continue with your own server').click());++ expect(el.textContent).toContain('Who runs the server?');+ expect(el.textContent).toContain('Set it up for me');+ expect(el.textContent).toContain("It's already running");+ });++ it('leaves the managed host path out when there is no host to offer', async () => {+ // A fresh install has onboarded none, and the card would lead to an empty+ // list every time it was taken.+ const el = await renderFlow();++ await act(async () => button(el, 'Continue with your own server').click());++ expect(el.textContent).not.toContain('one of my hosts');+ });++ it('offers the managed host path once a host exists', async () => {+ // Onboarding a host needs no server, so someone who deleted their last+ // server arrives here with hosts already set up — and this is the only+ // place the managed path can be reached from.+ listHosts.mockResolvedValue([{ sshHost: 'build-box' }]);+ const el = await renderFlow();++ await act(async () => button(el, 'Continue with your own server').click());++ expect(el.textContent).toContain('one of my hosts');+ });++ it('paints no cards until it knows whether there are hosts to offer', async () => {+ // The set waits as a whole. Painting two and inserting a third between them+ // a round trip later moves the answer out from under a cursor already on+ // its way to one.+ let answer!: (list: { sshHost: string }[]) => void;+ listHosts.mockReturnValue(+ new Promise<{ sshHost: string }[]>((resolve) => {+ answer = resolve;+ })+ );+ const el = await renderFlow();++ await act(async () => button(el, 'Continue with your own server').click());++ expect(el.textContent).toContain('Looking for onboarded hosts');+ expect(el.textContent).not.toContain('Set it up for me');++ await act(async () => answer([{ sshHost: 'build-box' }]));++ expect(el.textContent).toContain('Set it up for me');+ expect(el.textContent).toContain('one of my hosts');+ });++ it('says the host check failed instead of reporting no hosts', async () => {+ // A read that never answered is not an empty list. Reading it as one hides+ // a path the user has already set up, and says nothing about why.+ listHosts.mockRejectedValue(new Error('could not read the ssh config'));+ const el = await renderFlow();++ await act(async () => button(el, 'Continue with your own server').click());++ expect(el.textContent).toContain('Could not check for onboarded hosts');+ expect(el.textContent).not.toContain('one of my hosts');+ // The two paths that need no such check are still offered: not knowing+ // about hosts is no reason to hold the whole question hostage.+ expect(el.textContent).toContain('Set it up for me');+ expect(el.textContent).toContain("It's already running");+ });++ it('offers the host path when a retry of the check answers', async () => {+ listHosts.mockRejectedValueOnce(new Error('could not read the ssh config'));+ const el = await renderFlow();+ await act(async () => button(el, 'Continue with your own server').click());++ listHosts.mockResolvedValue([{ sshHost: 'build-box' }]);+ await act(async () => button(el, 'Try again').click());++ expect(el.textContent).toContain('one of my hosts');+ });++ it('can be left while the local stack is installing, and says so', async () => {+ // A first run pulls a few gigabytes. Full window, with Back shut and the+ // primary disabled, that was minutes of a page with no live control at all+ // — while the same page in the dialog could still be dismissed.+ localServer.isTransitioning = true;+ localServer.phase = 'starting';+ localServer.message = 'Pulling images…';+ const el = await renderFlow();+ await act(async () => button(el, 'Continue with your own server').click());+ await choose(el, 'Set it up for me');++ expect(button(el, 'Back').disabled).toBe(false);+ expect(el.textContent).toContain('keeps running if you leave the page');++ await act(async () => button(el, 'Back').click());++ expect(el.textContent).toContain('Who runs the server?');+ });++ it('goes back from the question to the welcome, by a button and not only a chevron', async () => {+ // The chevron is unlabelled, so it may repeat the way back but never be the+ // only one.+ const el = await renderFlow();++ await act(async () => button(el, 'Continue with your own server').click());+ await act(async () => button(el, 'Back').click());++ expect(el.textContent).toContain('Welcome to Switch');+ });++ it('asks for the addresses, and not for a name, on the connect page', async () => {+ // Someone connecting their only server has nothing to tell it apart from,+ // so the field is a question asked for the list's benefit rather than+ // theirs.+ const el = await renderFlow();++ await act(async () => button(el, 'Continue with your own server').click());+ await choose(el, "It's already running");++ expect(el.textContent).toContain('Connect to your server');+ expect(field(el, 'Gateway URL')).not.toBeNull();+ expect(field(el, 'API URL')).not.toBeNull();+ expect(field(el, 'Name')).toBeNull();+ });++ it('names the server after its gateway, having never asked', async () => {+ // The page that skips the question still has to produce a name: an+ // unnamed row in the sidebar would be the cost of the shortcut.+ serverAdded('srv-1');+ const el = await renderFlow();++ await addFromConnectPage(el);++ expect(addServer).toHaveBeenCalledWith(+ 'switch.example.com',+ 'https://switch.example.com',+ 'https://switch.example.com:8000'+ );+ });++ it('keeps the flow on screen after the server is added, for the sign-in still to come', async () => {+ // The server exists from here on, which is exactly when the window would+ // otherwise decide onboarding is over and take the remaining pages away.+ serverAdded('srv-1');+ const el = await renderFlow();++ await addFromConnectPage(el);++ expect(onboardingStore.inProgress).toBe(true);+ expect(onboardingStore.page).toBe('signIn');+ });++ it('offers a way out by name once the server exists', async () => {+ // Sign-in can fail for good — a server that is down, a password that is+ // refused — and pressing Back until the window changes shape is not an+ // exit anyone finds.+ serverAdded('srv-1');+ const el = await renderFlow();++ await addFromConnectPage(el);+ await act(async () => button(el, 'Finish later').click());++ expect(onboardingStore.inProgress).toBe(false);+ expect(navigate).toHaveBeenCalledWith('server', { serverId: 'srv-1' });+ });++ it('offers nothing to finish later before a server has been registered', async () => {+ const el = await renderFlow();++ await act(async () => button(el, 'Continue with your own server').click());++ expect([...el.querySelectorAll('button')].map((b) => b.textContent)).not.toContain(+ 'Finish later'+ );+ });++ it('offers no way out to a server the page on screen did not set up', async () => {+ // Connect to one, walk back, take the local path instead: the exit read a+ // single remembered server, so it still pointed at the abandoned attempt —+ // and pressing it left for a server this page had nothing to do with.+ serverAdded('srv-1');+ const el = await renderFlow();+ await addFromConnectPage(el);+ expect(labels(el)).toContain('Finish later');++ await act(async () => button(el, 'Back').click());+ await act(async () => button(el, 'Back').click());+ await choose(el, 'Set it up for me');++ expect(el.textContent).toContain('Set up a server on this computer');+ expect(labels(el)).not.toContain('Finish later');+ });++ it('forgets a server it registered when the user walks back to the start', async () => {+ // Everything after the connect page edits that row, and the user is free to+ // delete it the moment it exists — the window is the workspace again for+ // anything that does not need a server. A remembered id would aim the next+ // attempt's save at a row that is gone.+ serverAdded('srv-1');+ const el = await renderFlow();++ await addFromConnectPage(el);+ onboardingStore.goTo('welcome');++ expect(onboardingStore.server).toBeNull();+ expect(el).toBeDefined();+ });+});++describe('the first-run flow with Switch Cloud named', () => {+ const CLOUD = {+ id: 'cloud-1',+ name: 'Switch Cloud',+ gatewayUrl: 'https://cloud.example.com',+ apiUrl: 'https://cloud.example.com',+ };++ beforeEach(() => {+ switchCloud.mockResolvedValue({ url: 'https://cloud.example.com' });+ servers.push(CLOUD);+ connectToSwitchCloud.mockResolvedValue(CLOUD);+ });++ it('goes straight to signing in, with no question about who runs it', async () => {+ const el = await renderFlow();++ await act(async () => button(el, 'Continue with Switch Cloud').click());++ expect(connectToSwitchCloud).toHaveBeenCalled();+ expect(onboardingStore.page).toBe('signIn');+ expect(onboardingStore.server?.id).toBe('cloud-1');+ expect(el.textContent).not.toContain('Who runs the server?');+ });++ it('goes back from signing in to the welcome, not to a connect page it never showed', async () => {+ const el = await renderFlow();+ await act(async () => button(el, 'Continue with Switch Cloud').click());++ await act(async () => button(el, 'Back').click());++ expect(onboardingStore.page).toBe('welcome');+ });++ it('stays on the welcome and says why when the Cloud cannot be registered', async () => {+ connectToSwitchCloud.mockRejectedValue(new Error('disk full'));+ const el = await renderFlow();++ await act(async () => button(el, 'Continue with Switch Cloud').click());++ expect(onboardingStore.page).toBe('welcome');+ expect(el.querySelector('[role="alert"]')?.textContent).toContain('disk full');+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/onboarding-invite.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/onboarding-invite.test.tsxnew file mode 100644index 000000000..53835d4af--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/onboarding-invite.test.tsx@@ -0,0 +1,239 @@+/**+ * Joining a workspace from an invite link on a fresh install.+ *+ * The link names its server and carries the token, so the flow skips choosing+ * where Switch runs: a server this install knows goes straight to signing in,+ * one it does not opens the connect form at the link's address, and the+ * invitation is accepted as soon as there is an account to accept it with. A+ * refusal is shown as the server gave it, with a way on that does not need the+ * invitation.+ */+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const serverForInvite = vi.hoisted(() => vi.fn());+const acceptInvitation = vi.hoisted(() => vi.fn());+const setActiveWorkspace = vi.hoisted(() => vi.fn());+const resolveWorkspaces = vi.hoisted(() => vi.fn());++vi.hoisted(() => {+ window.electronAPI ??= {+ invoke: () => Promise.resolve(undefined),+ eventOn: () => () => {},+ eventSend: () => {},+ } as unknown as typeof window.electronAPI;+});++vi.mock('@renderer/lib/ipc', () => ({+ rpc: {+ switchServers: {+ resolveWorkspaces,+ listPendingInvitations: () => Promise.resolve({ kind: 'listed', invitations: [] }),+ listJoinableWorkspaces: () => Promise.resolve({ kind: 'listed', workspaces: [] }),+ switchCloud: () => Promise.resolve(null),+ },+ remoteHosts: { listHosts: () => Promise.resolve([]) },+ },+ events: { on: () => () => {}, emit: () => {} },+}));++vi.mock('@renderer/features/workspaces/workspaces-store', () => ({+ workspacesStore: {+ setActive: setActiveWorkspace,+ acceptInvitation,+ idOnServerInScope: () => 'ws-1',+ },+}));++const SERVER = vi.hoisted(() => ({+ id: 'srv-1',+ name: 'switch.example.com',+ gatewayUrl: 'https://switch.example.com',+ apiUrl: 'https://switch.example.com',+}));++vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({+ switchServersStore: {+ serverForInvite,+ setActive: vi.fn(),+ errorText: null,+ serverById: (id: string | null) => (id === SERVER.id ? SERVER : null),+ ensureAuthConfig: () => Promise.resolve(),+ authConfigFor: () => ({+ passwordLoginEnabled: true,+ oidcEnabled: false,+ oidcProviderLabel: null,+ }),+ authConfigCheckFailed: () => false,+ authConfigChecking: () => false,+ passwordLogin: () => Promise.resolve(true),+ oidcLogin: () => Promise.resolve(true),+ },+}));++vi.mock('@renderer/features/switch-servers/link-accounts-step', () => ({+ LinkAccountsStep: () => <div>Link your messaging accounts</div>,+}));++vi.mock('@renderer/lib/layout/navigation-provider', () => ({+ useNavigate: () => ({ navigate: vi.fn() }),+}));++vi.mock('@renderer/lib/telemetry/report', () => ({ report: vi.fn() }));++import { OnboardingFlow } from '@renderer/features/onboarding/onboarding-flow';+import { onboardingStore } from '@renderer/features/onboarding/onboarding-store';++const LINK = 'https://switch.example.com/invite#token=tok-1';++const ACME = {+ id: 'ws-1',+ serverId: 'srv-1',+ name: 'Acme',+ tenantId: 'tenant-1',+ slug: 'acme',+ role: 'member' as const,+ createdAt: '2026-01-01T00:00:00Z',+ updatedAt: '2026-01-01T00:00:00Z',+};++let container: HTMLDivElement | null = null;+let root: Root | null = null;++beforeEach(() => {+ serverForInvite.mockReset();+ acceptInvitation.mockReset();+ resolveWorkspaces.mockReset().mockResolvedValue([ACME]);+ setActiveWorkspace.mockReset().mockResolvedValue(undefined);+ onboardingStore.reset();+});++afterEach(async () => {+ if (root) await act(async () => root!.unmount());+ container?.remove();+ container = null;+ root = null;+});++async function renderFlow(): Promise<HTMLDivElement> {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });+ await act(async () =>+ root!.render(+ <QueryClientProvider client={client}>+ <OnboardingFlow />+ </QueryClientProvider>+ )+ );+ await settle();+ return container;+}++async function settle(): Promise<void> {+ for (let i = 0; i < 8; i++) await act(async () => await Promise.resolve());+}++async function click(el: HTMLElement, text: string): Promise<void> {+ const found = [...el.querySelectorAll<HTMLButtonElement>('button')].find((b) =>+ b.textContent?.includes(text)+ );+ expect(found, `nothing to click named ${text}`).toBeDefined();+ await act(async () => found!.click());+ await settle();+}++async function type(input: HTMLInputElement, value: string): Promise<void> {+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;+ await act(async () => {+ setter.call(input, value);+ input.dispatchEvent(new Event('input', { bubbles: true }));+ });+}++async function pasteLink(el: HTMLElement, text: string): Promise<void> {+ await click(el, 'Paste your invite link');+ await type(el.querySelector<HTMLInputElement>('#invite-link')!, text);+ await click(el, 'Continue');+}++async function signIn(el: HTMLElement): Promise<void> {+ const [email, password] = [...el.querySelectorAll<HTMLInputElement>('input')];+ await type(email!, '[email protected]');+ await type(password!, 'secret');+ await click(el, 'Sign in');+}++describe('joining from an invite link', () => {+ it('says what is wrong with a paste that is not an invite link', async () => {+ const el = await renderFlow();++ await pasteLink(el, 'https://switch.example.com/rooms');++ expect(el.querySelector('[role="alert"]')?.textContent).toContain('not an invitation');+ expect(serverForInvite).not.toHaveBeenCalled();+ });++ it('signs in to the server the link names and accepts the invitation', async () => {+ serverForInvite.mockResolvedValue({ kind: 'known', server: SERVER, via: 'external' });+ acceptInvitation.mockResolvedValue(ACME);+ const el = await renderFlow();++ await pasteLink(el, LINK);+ expect(serverForInvite).toHaveBeenCalledWith('https://switch.example.com');+ expect(el.textContent).toContain('Sign in to switch.example.com');++ await signIn(el);++ expect(acceptInvitation).toHaveBeenCalledWith('srv-1', 'tok-1');+ expect(setActiveWorkspace).toHaveBeenCalledWith('ws-1');+ expect(el.textContent).toContain('Link your messaging accounts');+ expect(onboardingStore.invite).toBeNull();+ });++ it('opens the connect form at the link address for a server it does not know', async () => {+ serverForInvite.mockResolvedValue({ kind: 'unknown', origin: 'https://switch.example.com' });+ const el = await renderFlow();++ await pasteLink(el, LINK);++ const fields = [...el.querySelectorAll<HTMLInputElement>('input')].map((i) => i.value);+ expect(fields).toEqual(['https://switch.example.com', 'https://switch.example.com']);+ expect(onboardingStore.invite?.token).toBe('tok-1');+ });++ it('shows why the server refused, and goes on to the workspaces without it', async () => {+ serverForInvite.mockResolvedValue({ kind: 'known', server: SERVER, via: 'external' });+ acceptInvitation.mockRejectedValue(new Error('This invitation has expired'));+ resolveWorkspaces.mockResolvedValue([ACME, { ...ACME, id: 'ws-2', name: 'Skunkworks' }]);+ const el = await renderFlow();++ await pasteLink(el, LINK);+ await signIn(el);++ expect(el.querySelector('[role="alert"]')?.textContent).toContain(+ 'This invitation has expired'+ );++ await click(el, 'Continue without it');++ expect(resolveWorkspaces).toHaveBeenCalledWith('srv-1');+ expect(el.textContent).toContain('Skunkworks');+ expect(onboardingStore.invite).toBeNull();+ });++ it('forgets the invite link when the user walks back to the start', async () => {+ serverForInvite.mockResolvedValue({ kind: 'known', server: SERVER, via: 'external' });+ const el = await renderFlow();++ await pasteLink(el, LINK);+ await click(el, 'Back');+ await click(el, 'Back');++ expect(el.textContent).toContain('Welcome to Switch');+ expect(onboardingStore.invite).toBeNull();+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/onboarding-workspaces.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/onboarding-workspaces.test.tsxnew file mode 100644index 000000000..319c68fd5--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/onboarding-workspaces.test.tsx@@ -0,0 +1,450 @@+/**+ * Choosing a workspace on a server you have just signed in to.+ *+ * The interesting behaviour is not the list — it is what the pages do with the+ * three answers the server can give. None, one and several each lead somewhere+ * different, being asked and failing is not the same as being asked and told+ * "none", and the sections the server cannot answer for at all are absent+ * rather than drawn empty.+ */+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const resolveWorkspaces = vi.hoisted(() => vi.fn());+const createWorkspace = vi.hoisted(() => vi.fn());+const setActiveWorkspace = vi.hoisted(() => vi.fn());+const listPendingInvitations = vi.hoisted(() => vi.fn());+const acceptPendingInvitation = vi.hoisted(() => vi.fn());+const listJoinableWorkspaces = vi.hoisted(() => vi.fn());+const joinByDomain = vi.hoisted(() => vi.fn());++vi.hoisted(() => {+ window.electronAPI ??= {+ invoke: () => Promise.resolve(undefined),+ eventOn: () => () => {},+ eventSend: () => {},+ } as unknown as typeof window.electronAPI;+});++vi.mock('@renderer/lib/ipc', () => ({+ rpc: {+ switchServers: {+ resolveWorkspaces,+ listPendingInvitations,+ listJoinableWorkspaces,+ switchCloud: () => Promise.resolve(null),+ },+ },+ events: { on: () => () => {}, emit: () => {} },+}));++vi.mock('@renderer/features/workspaces/workspaces-store', () => ({+ workspacesStore: {+ setActive: setActiveWorkspace,+ create: createWorkspace,+ acceptPendingInvitation,+ joinByDomain,+ idOnServerInScope: () => 'ws-1',+ },+}));++const SERVER = vi.hoisted(() => ({+ id: 'srv-1',+ name: 'switch.example.com',+ gatewayUrl: 'https://switch.example.com',+ apiUrl: 'https://switch.example.com:8000',+}));++vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({+ switchServersStore: {+ setActive: vi.fn(),+ errorText: null,+ serverById: (id: string | null) => (id === SERVER.id ? SERVER : null),+ // Stepping back off the picker draws the sign-in page, which reads these.+ ensureAuthConfig: () => Promise.resolve(),+ authConfigFor: () => ({+ passwordLoginEnabled: true,+ oidcEnabled: false,+ oidcProviderLabel: null,+ }),+ authConfigCheckFailed: () => false,+ authConfigChecking: () => false,+ passwordLogin: () => Promise.resolve(true),+ oidcLogin: () => Promise.resolve(true),+ },+}));++// The last page of the flow, and not what these tests are about — stubbed so+// reaching it is a fact the test can assert without dragging in the bridge+// reads behind it.+vi.mock('@renderer/features/switch-servers/link-accounts-step', () => ({+ LinkAccountsStep: () => <div>Link your messaging accounts</div>,+}));++vi.mock('@renderer/lib/layout/navigation-provider', () => ({+ useNavigate: () => ({ navigate: vi.fn() }),+}));++vi.mock('@renderer/lib/telemetry/report', () => ({ report: vi.fn() }));++import { OnboardingFlow } from '@renderer/features/onboarding/onboarding-flow';+import { onboardingStore } from '@renderer/features/onboarding/onboarding-store';++function workspace(id: string, name: string) {+ return {+ id,+ serverId: 'srv-1',+ name,+ tenantId: `tenant-${id}`,+ slug: name.toLowerCase(),+ role: 'member' as const,+ createdAt: '2026-01-01T00:00:00Z',+ updatedAt: '2026-01-01T00:00:00Z',+ };+}++function invitation(id: string, workspaceName: string) {+ return {+ id,+ tenantId: `tenant-${id}`,+ workspaceName,+ role: 'member' as const,+ expiresAt: '2026-12-01T00:00:00Z',+ invitedBy: 'Ada Lovelace',+ };+}++let container: HTMLDivElement | null = null;+let root: Root | null = null;++beforeEach(() => {+ resolveWorkspaces.mockReset();+ createWorkspace.mockReset();+ setActiveWorkspace.mockReset().mockResolvedValue(undefined);+ listPendingInvitations.mockReset().mockResolvedValue({ kind: 'listed', invitations: [] });+ acceptPendingInvitation.mockReset();+ listJoinableWorkspaces.mockReset().mockResolvedValue({ kind: 'listed', workspaces: [] });+ joinByDomain.mockReset();+ onboardingStore.reset();+});++afterEach(async () => {+ if (root) await act(async () => root!.unmount());+ container?.remove();+ container = null;+ root = null;+});++/** The flow, opened at the page that follows a successful sign-in. */+async function renderAtPickWorkspace(): Promise<HTMLDivElement> {+ onboardingStore.connected(SERVER as never, 'external');+ onboardingStore.goTo('pickWorkspace');++ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });+ await act(async () =>+ root!.render(+ <QueryClientProvider client={client}>+ <OnboardingFlow />+ </QueryClientProvider>+ )+ );+ await settle();+ return container;+}++function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((res) => {+ resolve = res;+ });+ return { promise, resolve };+}++async function settle(): Promise<void> {+ for (let i = 0; i < 8; i++) await act(async () => await Promise.resolve());+}++async function click(el: HTMLElement, text: string): Promise<void> {+ const found = [...el.querySelectorAll<HTMLButtonElement>('button')].find((b) =>+ b.textContent?.includes(text)+ );+ expect(found, `nothing to click named ${text}`).toBeDefined();+ await act(async () => found!.click());+ await settle();+}++async function typeName(el: HTMLElement, value: string): Promise<void> {+ const input = el.querySelector('input');+ expect(input, 'no name field').not.toBeNull();+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;+ await act(async () => {+ setter.call(input, value);+ input!.dispatchEvent(new Event('input', { bubbles: true }));+ });+}++describe('picking a workspace after signing in', () => {+ it('lists the workspaces the account is a member of', async () => {+ resolveWorkspaces.mockResolvedValue([+ workspace('ws-1', 'Acme'),+ workspace('ws-2', 'Skunkworks'),+ ]);++ const el = await renderAtPickWorkspace();++ expect(resolveWorkspaces).toHaveBeenCalledWith('srv-1');+ expect(el.textContent).toContain('Pick a workspace');+ expect(el.textContent).toContain('Acme');+ expect(el.textContent).toContain('Skunkworks');+ expect(el.textContent).toContain('Create a new workspace');+ });++ it('leaves out the invite and join rows on a server too old to list them', async () => {+ // It cannot say whether anyone invited you or which workspaces are open to+ // your domain, so an empty section would be a claim it never made.+ resolveWorkspaces.mockResolvedValue([+ workspace('ws-1', 'Acme'),+ workspace('ws-2', 'Skunkworks'),+ ]);+ listPendingInvitations.mockResolvedValue({ kind: 'unsupported' });+ listJoinableWorkspaces.mockResolvedValue({ kind: 'unsupported' });++ const el = await renderAtPickWorkspace();++ expect(el.textContent).not.toContain('Join');+ expect(el.textContent).not.toContain('Accept');+ expect(el.textContent).not.toContain('invited you');+ expect(el.textContent).not.toContain('domain');+ });++ it('offers invitations to your address beside your memberships', async () => {+ resolveWorkspaces.mockResolvedValue([workspace('ws-1', 'Acme')]);+ listPendingInvitations.mockResolvedValue({+ kind: 'listed',+ invitations: [invitation('inv-1', 'Skunkworks')],+ });++ const el = await renderAtPickWorkspace();++ // One membership is no longer the only way forward, so nothing is chosen.+ expect(setActiveWorkspace).not.toHaveBeenCalled();+ expect(onboardingStore.page).toBe('pickWorkspace');+ const rows = el.querySelectorAll('[data-testid="pending-invitation-row"]');+ expect(rows).toHaveLength(1);+ expect(rows[0]!.textContent).toContain('Skunkworks');+ expect(rows[0]!.textContent).toContain('Ada Lovelace invited you as member');+ expect(rows[0]!.textContent).toContain('Invited');+ expect(el.textContent).toContain('You’re a member of these, or can join them.');+ });++ it('joins the workspace an invitation is for and opens it', async () => {+ resolveWorkspaces.mockResolvedValue([]);+ listPendingInvitations.mockResolvedValue({+ kind: 'listed',+ invitations: [invitation('inv-1', 'Skunkworks')],+ });+ acceptPendingInvitation.mockResolvedValue(workspace('ws-9', 'Skunkworks'));++ const el = await renderAtPickWorkspace();+ // With an invitation waiting, having no memberships is not a reason to+ // skip ahead to creating one.+ expect(onboardingStore.page).toBe('pickWorkspace');+ await click(el, 'Accept');++ expect(acceptPendingInvitation).toHaveBeenCalledWith(+ 'srv-1',+ expect.objectContaining({ id: 'inv-1' })+ );+ expect(setActiveWorkspace).toHaveBeenCalledWith('ws-9');+ expect(onboardingStore.page).toBe('linkAccounts');+ });++ it('stays on the picker with the error when accepting fails', async () => {+ resolveWorkspaces.mockResolvedValue([]);+ listPendingInvitations.mockResolvedValue({+ kind: 'listed',+ invitations: [invitation('inv-1', 'Skunkworks')],+ });+ acceptPendingInvitation.mockRejectedValue(new Error('This invitation has been revoked'));++ const el = await renderAtPickWorkspace();+ await click(el, 'Accept');++ expect(onboardingStore.page).toBe('pickWorkspace');+ expect(el.textContent).toContain('This invitation has been revoked');+ expect(setActiveWorkspace).not.toHaveBeenCalled();+ });++ it('does not choose for you when the invitation check failed', async () => {+ // Skipping ahead on one membership would hide an invitation the page could+ // not rule out.+ resolveWorkspaces.mockResolvedValue([workspace('ws-1', 'Acme')]);+ listPendingInvitations.mockRejectedValue(new Error('gateway unreachable'));++ const el = await renderAtPickWorkspace();++ expect(setActiveWorkspace).not.toHaveBeenCalled();+ expect(el.textContent).toContain('gateway unreachable');+ expect([...el.querySelectorAll('button')].map((b) => b.textContent)).toContain('Retry');+ });++ it('offers workspaces open to your e-mail domain, and joins one', async () => {+ resolveWorkspaces.mockResolvedValue([workspace('ws-1', 'Acme')]);+ listJoinableWorkspaces.mockResolvedValue({+ kind: 'listed',+ workspaces: [{ tenantId: 't-9', workspaceName: 'Skunkworks', domain: 'acme.example' }],+ });+ joinByDomain.mockResolvedValue(workspace('ws-9', 'Skunkworks'));++ const el = await renderAtPickWorkspace();++ expect(setActiveWorkspace).not.toHaveBeenCalled();+ const rows = el.querySelectorAll('[data-testid="joinable-workspace-row"]');+ expect(rows).toHaveLength(1);+ expect(rows[0]!.textContent).toContain('Open to anyone at acme.example');+ await click(el, 'Join');++ expect(joinByDomain).toHaveBeenCalledWith(+ 'srv-1',+ expect.objectContaining({ tenantId: 't-9' })+ );+ expect(setActiveWorkspace).toHaveBeenCalledWith('ws-9');+ expect(onboardingStore.page).toBe('linkAccounts');+ });++ it('does not choose for you when the domain check failed', async () => {+ resolveWorkspaces.mockResolvedValue([workspace('ws-1', 'Acme')]);+ listJoinableWorkspaces.mockRejectedValue(new Error('gateway unreachable'));++ const el = await renderAtPickWorkspace();++ expect(setActiveWorkspace).not.toHaveBeenCalled();+ expect(el.textContent).toContain('gateway unreachable');+ });++ it('does not ask a question with one answer', async () => {+ resolveWorkspaces.mockResolvedValue([workspace('ws-1', 'Acme')]);++ const el = await renderAtPickWorkspace();++ expect(setActiveWorkspace).toHaveBeenCalledWith('ws-1');+ expect(onboardingStore.page).toBe('linkAccounts');+ expect(el.textContent).toContain('Link your messaging accounts');+ });++ it('goes straight to creating one when the account is in none', async () => {+ resolveWorkspaces.mockResolvedValue([]);++ const el = await renderAtPickWorkspace();++ expect(onboardingStore.page).toBe('createWorkspace');+ expect(el.textContent).toContain('Create your workspace');+ // Nothing behind it: the picker had no list to return to. The arrow stays+ // in the tab order and says as much in its own label, so it is matched on+ // the start of one.+ const back = el.querySelector<HTMLButtonElement>('[aria-label^="Previous page"]')!;+ expect(back.getAttribute('aria-disabled')).toBe('true');+ expect([...el.querySelectorAll('button')].map((b) => b.textContent)).not.toContain('Back');+ });++ it('goes back by a button and not only by a chevron', async () => {+ // The chevron is unlabelled, so it may repeat the way back but never be the+ // only one — the same invariant the who-runs page keeps.+ resolveWorkspaces.mockResolvedValue([workspace('ws-1', 'Acme'), workspace('ws-2', 'Skunk')]);++ const el = await renderAtPickWorkspace();+ await click(el, 'Back');++ expect(onboardingStore.page).toBe('signIn');+ });++ /**+ * Leaving while a workspace is being entered lands the user two pages on when+ * it resolves — back on the sign-in, and then thrown forward out of it.+ */+ it('holds the way back shut while a workspace is being opened', async () => {+ resolveWorkspaces.mockResolvedValue([workspace('ws-1', 'Acme'), workspace('ws-2', 'Skunk')]);+ const opening = deferred<void>();+ setActiveWorkspace.mockReturnValue(opening.promise);++ const el = await renderAtPickWorkspace();+ await click(el, 'Acme');++ const back = [...el.querySelectorAll<HTMLButtonElement>('button')].find(+ (b) => b.textContent?.trim() === 'Back'+ )!;+ expect(back.disabled).toBe(true);+ const chevron = el.querySelector<HTMLButtonElement>('[aria-label^="Previous page"]')!;+ expect(chevron.getAttribute('aria-disabled')).toBe('true');++ opening.resolve();+ await settle();+ });++ it('says the server could not be asked, rather than treating it as no workspaces', async () => {+ // Conflating the two would offer to create a second workspace to someone+ // who already has one.+ resolveWorkspaces.mockRejectedValue(new Error('gateway unreachable'));++ const el = await renderAtPickWorkspace();++ expect(el.textContent).toContain('switch.example.com');+ expect(el.textContent).toContain('Retry');+ expect(onboardingStore.page).toBe('pickWorkspace');+ expect(el.textContent).not.toContain('Create your workspace');+ });++ it('creates a workspace and carries on into it', async () => {+ resolveWorkspaces.mockResolvedValue([]);+ createWorkspace.mockResolvedValue(workspace('ws-9', 'Acme'));++ const el = await renderAtPickWorkspace();+ await typeName(el, ' Acme ');+ await click(el, 'Create workspace');++ expect(createWorkspace).toHaveBeenCalledWith('srv-1', 'Acme');+ expect(setActiveWorkspace).toHaveBeenCalledWith('ws-9');+ expect(onboardingStore.page).toBe('linkAccounts');+ });++ /**+ * The workspace exists on the server from the moment Create returns. Asking+ * again would send back a name it has just taken and earn a conflict that+ * reads as the name being refused — and on this page, reached because the+ * account is in no workspace at all, there is no Back either.+ */+ it('offers to open the workspace it already made rather than creating it twice', async () => {+ resolveWorkspaces.mockResolvedValue([]);+ createWorkspace.mockResolvedValue(workspace('ws-9', 'Acme'));+ setActiveWorkspace.mockRejectedValueOnce(new Error('could not switch'));++ const el = await renderAtPickWorkspace();+ await typeName(el, 'Acme');+ await click(el, 'Create workspace');++ expect(el.textContent).toContain('could not be moved into it');++ setActiveWorkspace.mockResolvedValue(undefined);+ await click(el, 'Open workspace');++ expect(createWorkspace).toHaveBeenCalledTimes(1);+ expect(onboardingStore.page).toBe('linkAccounts');+ });++ it('keeps the form and says why when the name is refused', async () => {+ resolveWorkspaces.mockResolvedValue([]);+ createWorkspace.mockRejectedValue(new Error('That name is already taken.'));++ const el = await renderAtPickWorkspace();+ await typeName(el, 'Acme');+ await click(el, 'Create workspace');++ expect(el.textContent).toContain('already taken');+ expect(onboardingStore.page).toBe('createWorkspace');+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/palette-agent-icon.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/palette-agent-icon.test.tsxindex 59b5e5d75..44be7df70 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/palette-agent-icon.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/palette-agent-icon.test.tsx@@ -16,13 +16,14 @@ import { PaletteAgentItem } from '@renderer/features/command-palette/palette-ageimport { agentsStore } from '@renderer/features/locations/stores/agents-store';import { ThemeContext } from '@renderer/lib/providers/theme-provider';import { AGENTS_METADATA_QUERY_KEY } from '@renderer/lib/stores/use-agents';-import { remoteAgentsQueryKey } from '@renderer/lib/stores/use-remote-agents';+import { workspaceAgentsQueryKey } from '@renderer/lib/stores/use-workspace-agents';import type { Agent } from '@shared/core/agents/agents';import type { SearchItem } from '@shared/core/search';import type { RemoteAgentSummary } from '@shared/core/switch-servers/switch-servers';const LOCATION_ID = 'loc-1';const SERVER_ID = 'server-1';+const WORKSPACE_ID = 'workspace-1';const SWITCH_AGENT_ID = 'switch-agent-1';const AGENT_NAME = 'reviewer';@@ -33,6 +34,7 @@ const AGENT: Agent = {providerId: 'claude',switchAgentId: SWITCH_AGENT_ID,apiEndpoint: 'https://switch.example',+ workspaceId: WORKSPACE_ID,serverId: SERVER_ID,status: null,autoApprove: false,@@ -103,7 +105,7 @@ async function rowAvatarSrc(options: {// test has no main process to answer.defaultOptions: { queries: { retry: false, gcTime: 0, staleTime: Infinity } },});- client.setQueryData(remoteAgentsQueryKey(SERVER_ID), [remoteAgent(options.iconUrl)]);+ client.setQueryData(workspaceAgentsQueryKey(WORKSPACE_ID), [remoteAgent(options.iconUrl)]);// The provider mark beside the name reads its artwork from here. Seeded empty// so it resolves to nothing rather than reaching for a main process the test// does not have; the mark itself is the sidebar's, already covered there.diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/remote-host-setup-step.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/remote-host-setup-step.test.tsxindex e52e580fd..6509c4be1 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/remote-host-setup-step.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/remote-host-setup-step.test.tsx@@ -117,7 +117,12 @@ async function render() {root!.render(<Dialog open><DialogContent>- <RemoteHostSetupStep onBack={() => {}} onDone={() => {}} onClose={() => {}} />+ <RemoteHostSetupStep+ onBack={() => {}}+ onDone={() => {}}+ onClose={() => {}}+ onRegistered={null}+ /></DialogContent></Dialog>)@@ -266,13 +271,15 @@ describe('another Console changing the server', () => {expect(state.cancelWait).toHaveBeenCalledWith('vm-1');});- it('offers no way out of a start that is not waiting on anyone', async () => {+ it('offers Back, not Stop waiting, during a start that is not waiting on anyone', async () => {+ // The start belongs to the store, which outlives the page, so leaving it+ // abandons nothing; only a wait for another Console can be called off.state.transitioning = true;state.status = status({ phase: 'starting', message: 'Starting containers…' });await render();expect(() => button(/^Stop waiting$/)).toThrow();- expect(button(/^Cancel$/).disabled).toBe(true);+ expect(button(/^Back$/).disabled).toBe(false);});});@@ -311,7 +318,12 @@ describe('the rest of the step', () => {root!.render(<Dialog open><DialogContent>- <RemoteHostSetupStep onBack={() => {}} onDone={onDone} onClose={() => {}} />+ <RemoteHostSetupStep+ onBack={() => {}}+ onDone={onDone}+ onClose={() => {}}+ onRegistered={null}+ /></DialogContent></Dialog>)diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/room-configuration-save.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/room-configuration-save.test.tsxindex 4cbc59f23..395dfe9a7 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/room-configuration-save.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/room-configuration-save.test.tsx@@ -27,10 +27,10 @@ vi.hoisted(() => {vi.mock('@renderer/lib/ipc', () => ({events: { on: vi.fn() },rpc: {- switchServers: {+ workspaces: {updateRoom,getRoomDetail,- listRemoteAgents: vi.fn(() => Promise.resolve([])),+ listAgents: vi.fn(() => Promise.resolve([])),},agents: { getAgents: vi.fn(() => Promise.resolve([])) },},@@ -38,7 +38,8 @@ vi.mock('@renderer/lib/ipc', () => ({vi.mock('@renderer/features/switch-servers/switch-rooms-store', () => ({switchRoomsStore: {- roomServerId: () => 'srv-1',+ roomWorkspaceId: () => 'ws-1',+ roomServerId: () => 'server-1',canDeleteRoom: () => false,},}));@@ -156,7 +157,7 @@ describe('a room’s description and instructions', () => {expect(updateRoom).toHaveBeenCalledTimes(1);expect(updateRoom).toHaveBeenCalledWith({- serverId: 'srv-1',+ workspaceId: 'ws-1',roomId: 'room-1',description: 'The original description',instructions: 'Be brief',diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/step-pager.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/step-pager.test.tsxnew file mode 100644index 000000000..de75c58b0--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/step-pager.test.tsx@@ -0,0 +1,106 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { StepPager } from '@renderer/lib/ui/step-pager';++/**+ * The pager is the only thing on a wizard page that says where you are, and its+ * arrows are unlabelled. So what matters is that an arrow with nowhere to go+ * cannot be pressed: a page that is mid-install passes no way back, and a+ * chevron that fired anyway would abandon the install with nothing watching it.+ */++let container: HTMLDivElement | null = null;+let root: Root | null = null;++afterEach(async () => {+ if (root) await act(async () => root!.unmount());+ container?.remove();+ container = null;+ root = null;+});++async function render(node: React.ReactNode): Promise<HTMLDivElement> {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ await act(async () => root!.render(node));+ return container;+}++// Matched on the start of the label, because an arrow leading nowhere appends+// the reason to its own.+function arrow(el: HTMLElement, label: string): HTMLButtonElement {+ const found = el.querySelector<HTMLButtonElement>(`[aria-label^="${label}"]`);+ expect(found).not.toBeNull();+ return found!;+}++describe('the pager on a wizard page', () => {+ it('names the page and moves either way when both are open', async () => {+ const onBack = vi.fn();+ const onNext = vi.fn();+ const el = await render(+ <StepPager pageName="Connect to a server" onBack={onBack} onNext={onNext} />+ );++ expect(el.textContent).toContain('Connect to a server');++ await act(async () => arrow(el, 'Previous page').click());+ await act(async () => arrow(el, 'Next page').click());++ expect(onBack).toHaveBeenCalledOnce();+ expect(onNext).toHaveBeenCalledOnce();+ });++ // Shown rather than hidden: the bar keeps the same shape from page to page,+ // so the name does not move as the flow advances.+ it('keeps an arrow with nowhere to go on screen and dead', async () => {+ const el = await render(<StepPager pageName="Sign in" onBack={vi.fn()} onNext={null} />);++ const next = arrow(el, 'Next page');+ // However the button primitive spells it, it has to reach a screen reader+ // as unavailable — the chevron itself says nothing about where it leads.+ expect(next.matches(':disabled, [aria-disabled="true"], [data-disabled]')).toBe(true);+ });++ /**+ * The same arrow, the same handler, closed and then open.+ *+ * `aria-disabled` leaves the button clickable — that is the price of keeping+ * it in the tab order — so nothing but the missing handler stops it firing,+ * and a page whose way on commits an install would be committed by a chevron+ * labelled "next". Driving one button through both states is what makes this+ * a test: asserting on a separate always-dead arrow would pass against an+ * implementation that fires whatever it is given.+ */+ it('fires nothing while the way on is closed, and fires once when it opens', async () => {+ const onNext = vi.fn();+ const page = (open: boolean) => (+ <StepPager pageName="Sign in" onBack={null} onNext={open ? onNext : null} />+ );+ const el = await render(page(false));++ await act(async () => arrow(el, 'Next page').click());+ expect(onNext).not.toHaveBeenCalled();++ await act(async () => root!.render(page(true)));+ await act(async () => arrow(el, 'Next page').click());++ expect(onNext).toHaveBeenCalledOnce();+ });++ it('leaves the dead arrow reachable, with the reason in its label', async () => {+ // `disabled` would take it out of the tab order, and the label is the only+ // place the reason is written — so the people who cannot see the greyed-out+ // chevron would be the ones who never hear why it leads nowhere.+ const el = await render(<StepPager pageName="Sign in" onBack={null} onNext={null} />);++ for (const label of ['Previous page', 'Next page']) {+ const button = arrow(el, label);+ expect(button.hasAttribute('disabled')).toBe(false);+ expect(button.tabIndex).toBeGreaterThanOrEqual(0);+ expect(button.getAttribute('aria-label')!.length).toBeGreaterThan(label.length);+ }+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/views-without-server.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/views-without-server.test.tsxnew file mode 100644index 000000000..01fcb8ed1--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/views-without-server.test.tsx@@ -0,0 +1,27 @@+import { describe, expect, it } from 'vitest';+import { views, viewWorksWithoutServer, type ViewId } from '@renderer/app/view-registry';++/**+ * Which views may be drawn with nothing registered, named once.+ *+ * The flag lives on each view so the next one of its kind is not missed, and+ * that is the right place for it — but it also means no single file says what+ * the set is, and dropping the flag from Settings breaks ⌘, on a fresh install+ * while every other test stays green. This is the file that notices.+ *+ * Deliberately a whole-set comparison rather than a per-view assertion: the+ * failure worth catching is a flag that quietly appeared or disappeared, and+ * only the set catches both.+ *+ * A browser test because importing the registry pulls in every view, which+ * wants the preload bridge this project installs before a module evaluates.+ */+const CAN_BE_DRAWN_WITHOUT_A_SERVER = ['remoteHost', 'remoteHosts', 'settings'];++describe('the views that need no Switch server', () => {+ it('are these three and no others', () => {+ const ids = (Object.keys(views) as ViewId[]).filter(viewWorksWithoutServer).sort();++ expect(ids).toEqual(CAN_BE_DRAWN_WITHOUT_A_SERVER);+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/welcome-page.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/welcome-page.test.tsxnew file mode 100644index 000000000..d2076ba7d--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/welcome-page.test.tsx@@ -0,0 +1,204 @@+/**+ * The first page of a fresh install.+ *+ * Its whole job is to say where Switch can run and get on with a place it can.+ * Switch Cloud is only a place when this build or run names a deployment for+ * it. When none is named the page does not mention it, and nothing on the page+ * may pretend to be a choice. When one is named it is+ * a real second way on, and the unlabelled pager must not pick between the two.+ */+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const onContinue = vi.hoisted(() => vi.fn());+const onInvite = vi.hoisted(() => vi.fn());++vi.hoisted(() => {+ window.electronAPI ??= {+ invoke: () => Promise.resolve(undefined),+ eventOn: () => () => {},+ eventSend: () => {},+ } as unknown as typeof window.electronAPI;+});++import { type WelcomeCloud, WelcomePage } from '@renderer/features/onboarding/welcome-page';++let container: HTMLDivElement | null = null;+let root: Root | null = null;++beforeEach(() => {+ onContinue.mockReset();+ onInvite.mockReset();+});++afterEach(async () => {+ if (root) await act(async () => root!.unmount());+ container?.remove();+ container = null;+ root = null;+});++async function renderPage(cloud: WelcomeCloud = { kind: 'closed' }): Promise<HTMLDivElement> {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ await act(async () =>+ root!.render(<WelcomePage cloud={cloud} onContinue={onContinue} onInvite={onInvite} />)+ );+ return container;+}++function choice(el: HTMLElement, title: string): HTMLElement {+ const found = [...el.querySelectorAll<HTMLElement>('li')].find((c) =>+ c.textContent?.includes(title)+ );+ expect(found, `no option named ${title}`).toBeDefined();+ return found!;+}++function button(el: HTMLElement, label: string): HTMLButtonElement {+ const found = [...el.querySelectorAll<HTMLButtonElement>('button')].find(+ (b) => b.textContent?.trim() === label+ );+ expect(found, `no ${label} button`).toBeDefined();+ return found!;+}++describe('the welcome page with no Switch Cloud named', () => {+ it('asks where Switch should run and offers only your own server', async () => {+ const el = await renderPage();++ expect(el.textContent).toContain('Welcome to Switch');+ expect(el.textContent).toContain('Where should it run?');+ expect(choice(el, 'Your own server')).toBeDefined();+ });++ it('does not mention Switch Cloud at all', async () => {+ // Stable ships the Cloud code before the Cloud is open to it, so a build+ // with no Cloud named must not advertise one.+ const el = await renderPage();++ expect(el.textContent).not.toContain('Switch Cloud');+ expect(el.querySelectorAll('li')).toHaveLength(1);+ });++ it('does not flash a Cloud card while the configuration is read', async () => {+ const el = await renderPage({ kind: 'reading' });++ expect(el.textContent).not.toContain('Switch Cloud');+ });++ it('offers nothing to pick between, since only one answer can be had', async () => {+ // A radiogroup here was a widget with no working option in it: two+ // `role="radio"` divs, no click handler, no key handler. Announcing a+ // choice and then answering neither the keyboard nor the mouse is worse+ // than a list that never claimed to be one.+ const el = await renderPage();++ expect(el.querySelectorAll('[role="radiogroup"], [role="radio"]')).toHaveLength(0);+ // The one control on the page, and it names which of the two it takes.+ expect(button(el, 'Continue with your own server')).toBeDefined();+ });++ it('moves the flow on from Continue', async () => {+ const el = await renderPage();++ await act(async () => button(el, 'Continue with your own server').click());++ expect(onContinue).toHaveBeenCalled();+ });++ it('offers joining from an invite link instead', async () => {+ const el = await renderPage();++ await act(async () => button(el, 'Paste your invite link').click());++ expect(onInvite).toHaveBeenCalled();+ expect(onContinue).not.toHaveBeenCalled();+ });++ it('sends the pager forward to the same place as Continue', async () => {+ // The arrow is unlabelled, so it may only repeat a move the page already+ // offers — never introduce one of its own.+ const el = await renderPage();++ await act(async () => el.querySelector<HTMLButtonElement>('[aria-label="Next page"]')!.click());++ expect(onContinue).toHaveBeenCalled();+ });+});++function openCloud(overrides: Partial<Extract<WelcomeCloud, { kind: 'open' }>> = {}): WelcomeCloud {+ return {+ kind: 'open',+ url: 'https://cloud.example.com',+ connecting: false,+ error: null,+ onConnect: vi.fn(),+ ...overrides,+ };+}++describe('the welcome page with Switch Cloud named', () => {+ it('names where the Cloud is and does not call it coming soon', async () => {+ const el = await renderPage(openCloud());+ const cloud = choice(el, 'Switch Cloud');++ expect(cloud.textContent).toContain('cloud.example.com');+ expect(cloud.textContent).not.toContain('Coming soon');+ });++ it('connects to the Cloud from its own button', async () => {+ const onConnect = vi.fn();+ const el = await renderPage(openCloud({ onConnect }));++ await act(async () => button(el, 'Continue with Switch Cloud').click());++ expect(onConnect).toHaveBeenCalled();+ expect(onContinue).not.toHaveBeenCalled();+ });++ it('still offers your own server', async () => {+ const el = await renderPage(openCloud());++ await act(async () => button(el, 'Continue with your own server').click());++ expect(onContinue).toHaveBeenCalled();+ });++ it('gives the pager no forward move, since there are two to choose between', async () => {+ const el = await renderPage(openCloud());++ const next = el.querySelector<HTMLButtonElement>('[aria-label="Next page"]');+ if (next) {+ await act(async () => next.click());+ }+ expect(onContinue).not.toHaveBeenCalled();+ });++ it('shows why connecting failed', async () => {+ const el = await renderPage(openCloud({ error: 'Could not reach Switch Cloud' }));++ expect(el.querySelector('[role="alert"]')?.textContent).toContain(+ 'Could not reach Switch Cloud'+ );+ });+});++describe('the welcome page when the Cloud setting is broken', () => {+ it('says the Cloud is unavailable and why, and offers no way into it', async () => {+ const el = await renderPage({+ kind: 'failed',+ headline: 'Switch Cloud is misconfigured',+ detail: 'SWITCH_CLOUD_URL must be an https URL',+ });+ const cloud = choice(el, 'Switch Cloud');++ expect(cloud.textContent).toContain('Unavailable');+ expect(cloud.textContent).toContain('SWITCH_CLOUD_URL must be an https URL');+ expect(+ [...el.querySelectorAll('button')].some((b) => b.textContent?.includes('Switch Cloud'))+ ).toBe(false);+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/workspace-admin.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/browser/workspace-admin.test.tsnew file mode 100644index 000000000..a504c1d02--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/workspace-admin.test.ts@@ -0,0 +1,59 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const onServerInScope = vi.hoisted(() => vi.fn());+const statusFor = vi.hoisted(() => vi.fn());++vi.mock('@renderer/features/workspaces/workspaces-store', () => ({+ workspacesStore: { onServerInScope },+}));+vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({+ switchServersStore: { statusFor },+}));++import { administersWorkspaceInScope } from '@renderer/features/switch-servers/workspace-admin';++function signedInAs(role: 'admin' | 'user') {+ statusFor.mockReturnValue({ user: { id: 'u-1', role } });+}++function inWorkspaceAs(role: 'owner' | 'admin' | 'member' | null) {+ onServerInScope.mockReturnValue({ id: 'ws-1', tenantId: 't-1', role });+}++describe('administersWorkspaceInScope', () => {+ beforeEach(() => {+ onServerInScope.mockReset().mockReturnValue(null);+ statusFor.mockReset().mockReturnValue(undefined);+ });++ it('lets an owner or admin of the workspace manage it', () => {+ signedInAs('user');+ inWorkspaceAs('owner');+ expect(administersWorkspaceInScope('srv-1')).toBe(true);+ inWorkspaceAs('admin');+ expect(administersWorkspaceInScope('srv-1')).toBe(true);+ });++ it('does not let a plain member manage it', () => {+ signedInAs('user');+ inWorkspaceAs('member');+ expect(administersWorkspaceInScope('srv-1')).toBe(false);+ });++ it('does not let an account whose membership was withdrawn manage it', () => {+ signedInAs('user');+ inWorkspaceAs(null);+ expect(administersWorkspaceInScope('srv-1')).toBe(false);+ });++ it('lets the operator running the server manage any workspace', () => {+ signedInAs('admin');+ inWorkspaceAs('member');+ expect(administersWorkspaceInScope('srv-1')).toBe(true);+ });++ it('says no while there is no workspace to act in', () => {+ signedInAs('user');+ expect(administersWorkspaceInScope('srv-1')).toBe(false);+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/workspace-switcher.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/workspace-switcher.test.tsxnew file mode 100644index 000000000..72a2d723c--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/workspace-switcher.test.tsx@@ -0,0 +1,630 @@+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';+import type { Workspace, WorkspaceRole } from '@shared/core/workspaces/workspaces';++vi.hoisted(() => {+ window.electronAPI ??= {+ invoke: () => Promise.resolve(undefined),+ eventOn: () => () => {},+ eventSend: () => {},+ } as unknown as typeof window.electronAPI;+});++const state = vi.hoisted(() => ({+ servers: [] as { id: string; name: string }[],+ workspaces: [] as {+ id: string;+ serverId: string;+ name: string;+ tenantId: string | null;+ role: string | null;+ }[],+ activeId: null as string | null,+ setActive: vi.fn(),+ navigate: vi.fn(),+ toast: vi.fn(),+ unavailable: new Set<string>(),+ listPendingInvitations: vi.fn(),+ acceptPendingInvitation: vi.fn(),+ listJoinableWorkspaces: vi.fn(),+ joinByDomain: vi.fn(),+ cloud: 'open' as 'reading' | 'closed' | 'open' | 'failed',+}));++vi.mock('@renderer/lib/ipc', () => ({+ rpc: {+ switchServers: {+ listPendingInvitations: state.listPendingInvitations,+ listJoinableWorkspaces: state.listJoinableWorkspaces,+ },+ },+ events: { on: () => () => {}, emit: () => {} },+}));++vi.mock('@renderer/features/switch-servers/use-switch-cloud', () => ({+ useSwitchCloud: () =>+ state.cloud === 'open'+ ? { kind: 'open', url: 'https://cloud.example.invalid' }+ : state.cloud === 'failed'+ ? { kind: 'failed', headline: 'broken', detail: null }+ : { kind: state.cloud },+}));++vi.mock('@renderer/features/switch-servers/server-availability', () => ({+ serverAvailability: (serverId: string) =>+ state.unavailable.has(serverId) ? 'signed-out' : 'available',+}));++vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({+ switchServersStore: {+ init: () => Promise.resolve(),+ recoverStale: () => Promise.resolve(),+ get servers() {+ return state.servers;+ },+ serverById: (id: string) => state.servers.find((s) => s.id === id) ?? null,+ },+}));++vi.mock('@renderer/features/workspaces/workspaces-store', () => ({+ workspacesStore: {+ get activeId() {+ return state.activeId;+ },+ get active() {+ return state.workspaces.find((w) => w.id === state.activeId) ?? null;+ },+ onServer: (serverId: string) => state.workspaces.filter((w) => w.serverId === serverId),+ setActive: state.setActive,+ acceptPendingInvitation: state.acceptPendingInvitation,+ joinByDomain: state.joinByDomain,+ },+}));++vi.mock('@renderer/features/switch-servers/local-server-store', () => ({+ localServerStore: { init: () => Promise.resolve(), dispose: () => {}, phase: 'stopped' },+}));++vi.mock('@renderer/features/switch-servers/remote-server-store', () => ({+ remoteServerStore: { init: () => Promise.resolve(), dispose: () => {} },+}));++// Presentation of a server — its avatar, icon, status words and drift — is the+// server's business and tested with it. Stubbed so this test is about which+// workspaces the switcher offers and which it refuses.+vi.mock('@renderer/features/switch-servers/server-presentation', () => ({+ ServerAvatar: () => null,+ ServerDriftIndicator: () => null,+ ServerStatusDot: () => null,+ serverDrift: () => null,+ serverPlacementLabel: () => null,+ serverStatusLabel: (server: SwitchServer) => `${server.name} status`,+ serverSubtitleLabel: (server: SwitchServer) => `${server.name} status`,+}));++vi.mock('@renderer/features/switch-servers/server-icon', () => ({+ serverIcon: () => () => null,+}));++vi.mock('@renderer/lib/layout/navigation-provider', () => ({+ useNavigate: () => ({ navigate: state.navigate }),+}));++vi.mock('@renderer/lib/modal/modal-provider', () => ({+ useShowModal: () => () => {},+}));++vi.mock('@renderer/lib/hooks/use-toast', () => ({+ useToast: () => ({ toast: state.toast }),+}));++import {+ serverRowWorkspace,+ showsServers,+ WorkspaceSwitcher,+} from '@renderer/features/switch-servers/workspace-switcher';++let container: HTMLDivElement | null = null;+let root: Root | null = null;++function server(id: string, name: string): SwitchServer {+ return {+ id,+ name,+ gatewayUrl: `https://${id}.example.invalid`,+ apiUrl: `https://${id}.example.invalid/api`,+ managed: false,+ managementKind: null,+ sshHost: null,+ createdAt: '2026-01-01T00:00:00Z',+ updatedAt: '2026-01-01T00:00:00Z',+ };+}++function workspace(+ id: string,+ serverId: string,+ patch: { tenantId?: string | null; role?: WorkspaceRole | null } = {}+): Workspace {+ const tenantId = patch.tenantId === undefined ? `tenant-${id}` : patch.tenantId;+ return {+ id,+ serverId,+ name: id,+ tenantId,+ slug: tenantId === null ? null : id,+ role: patch.role === undefined ? 'member' : patch.role,+ createdAt: '2026-01-01T00:00:00Z',+ updatedAt: '2026-01-01T00:00:00Z',+ };+}++/** Mount the switcher on the given servers and workspaces, and open its menu. */+async function openSwitcher(+ servers: SwitchServer[],+ workspaces: Workspace[],+ activeId: string,+ trigger: 'Switch workspace' | 'Switch server' = 'Switch workspace'+): Promise<void> {+ state.servers = servers;+ state.workspaces = workspaces;+ state.activeId = activeId;++ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });+ await act(async () =>+ root!.render(+ <QueryClientProvider client={client}>+ <WorkspaceSwitcher />+ </QueryClientProvider>+ )+ );+ await settle();++ const button = container.querySelector<HTMLElement>(`[aria-label="${trigger}"]`);+ expect(button, `the switcher did not render its ${trigger} trigger`).not.toBeNull();+ await act(async () => button!.click());+}++async function settle(): Promise<void> {+ for (let i = 0; i < 8; i++) await act(async () => await Promise.resolve());+}++/** The menu row offering a workspace, by the name shown on it. */+function row(name: string): HTMLElement {+ const found = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find((item) =>+ item.textContent?.startsWith(name)+ );+ expect(found, `no row for ${name}`).toBeDefined();+ return found!;+}++beforeEach(() => {+ state.cloud = 'open';+ state.setActive.mockReset().mockResolvedValue(undefined);+ state.navigate.mockReset();+ state.toast.mockReset();+ state.unavailable.clear();+ state.listPendingInvitations.mockReset().mockResolvedValue({ kind: 'listed', invitations: [] });+ state.acceptPendingInvitation.mockReset();+ state.listJoinableWorkspaces.mockReset().mockResolvedValue({ kind: 'listed', workspaces: [] });+ state.joinByDomain.mockReset();+});++afterEach(async () => {+ if (root) await act(async () => root!.unmount());+ container?.remove();+ container = null;+ root = null;+});++describe('the workspaces the switcher offers', () => {+ // A workspace only means anything on its server — two servers can each have a+ // "Default" — so a flat list would offer two rows that read identically.+ it('lists the workspaces on a server under that server', async () => {+ await openSwitcher(+ [server('srv-1', 'Acme'), server('srv-2', 'Local dev')],+ [workspace('ws-a', 'srv-1'), workspace('ws-b', 'srv-1'), workspace('ws-c', 'srv-2')],+ 'ws-a'+ );++ const groups = [...document.querySelectorAll<HTMLElement>('[data-slot="dropdown-menu-group"]')];+ const listed = groups.map((group) => [+ group.querySelector('[data-slot="dropdown-menu-label"]')?.textContent,+ // The first span on a row is its name; a second one, where there is one,+ // is the role or the reason it cannot be opened.+ [...group.querySelectorAll('[role="menuitem"]')].map(+ (item) => item.querySelector('span')?.textContent+ ),+ ]);++ expect(listed[0]?.[0]).toContain('Acme');+ expect(listed[0]?.[1]).toEqual(['ws-a', 'ws-b']);+ expect(listed[1]?.[0]).toContain('Local dev');+ expect(listed[1]?.[1]).toEqual(['ws-c']);+ });++ it('marks the one the window is scoped to', async () => {+ await openSwitcher(+ [server('srv-1', 'Acme')],+ [workspace('ws-a', 'srv-1'), workspace('ws-b', 'srv-1')],+ 'ws-b'+ );++ expect(row('ws-a').getAttribute('aria-current')).toBeNull();+ expect(row('ws-b').getAttribute('aria-current')).toBe('true');+ });++ it('switches to the one clicked', async () => {+ await openSwitcher(+ [server('srv-1', 'Acme')],+ [workspace('ws-a', 'srv-1'), workspace('ws-b', 'srv-1')],+ 'ws-a'+ );++ await act(async () => row('ws-b').click());++ expect(state.setActive).toHaveBeenCalledWith('ws-b');+ });+});++/**+ * Two rows the gateway will refuse every call scoped to. Both are kept in the+ * list rather than hidden, because their agents are still here and the row is+ * the only thing that says where they went — so both have to be unclickable and+ * both have to say why, or the app turns a fact it already knows into an error+ * after the click.+ */+describe('a workspace that cannot be opened', () => {+ it('refuses one this account is no longer a member of', async () => {+ await openSwitcher(+ [server('srv-1', 'Acme')],+ [workspace('ws-a', 'srv-1'), workspace('ws-gone', 'srv-1', { role: null })],+ 'ws-a'+ );++ const gone = row('ws-gone');+ expect(gone.getAttribute('aria-disabled')).toBe('true');+ expect(gone.textContent).toContain('No longer a member');+ expect(gone.title).toContain('no longer a member');+ });++ /**+ * The row every server is registered with, before the gateway has been asked+ * which workspaces the account has. Once the account turns out to have more+ * than one, nothing can say which this row meant — and a call scoped to it+ * selects no tenant at all, so the gateway answers under whichever workspace+ * the session last selected.+ */+ it('refuses a placeholder the reconcile could not match', async () => {+ await openSwitcher(+ [server('srv-1', 'Acme')],+ [+ workspace('ws-placeholder', 'srv-1', { tenantId: null, role: null }),+ workspace('ws-a', 'srv-1'),+ ],+ 'ws-a'+ );++ const placeholder = row('ws-placeholder');+ expect(placeholder.getAttribute('aria-disabled')).toBe('true');+ expect(placeholder.textContent).toContain('Not matched');+ });++ /**+ * The same state on a server holding one workspace is ordinary rather than+ * broken: there is nothing to confuse it with, and the gateway resolves the+ * account's sole membership to exactly that row. Refusing it would lock the+ * window out of a freshly registered server until a reconcile had run.+ */+ it('still offers a lone workspace that has no tenant yet', async () => {+ await openSwitcher(+ [server('srv-1', 'Acme')],+ [workspace('ws-only', 'srv-1', { tenantId: null, role: null })],+ 'ws-only'+ );++ const only = row('ws-only');+ expect(only.getAttribute('aria-disabled')).toBeNull();+ expect(only.textContent).toBe('ws-only');+ });++ it('says what to do instead of sending you back through sign-in', async () => {+ await openSwitcher(+ [server('srv-1', 'Acme')],+ [+ workspace('ws-placeholder', 'srv-1', { tenantId: null, role: null }),+ workspace('ws-a', 'srv-1'),+ ],+ 'ws-a'+ );++ // Signing in re-runs the reconcile, which is what left the row unmatched and+ // would do so again — so the row must not offer it as the way out.+ const reason = row('ws-placeholder').title;+ expect(reason).toContain('Open one of the others');+ expect(reason).not.toMatch(/sign in/i);+ });+});++describe('inviting people from the switcher', () => {+ function inviteItem(): HTMLElement | undefined {+ return [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find((item) =>+ item.textContent?.startsWith('Invite people')+ );+ }++ it('is offered in a workspace the account administers', async () => {+ await openSwitcher(+ [server('srv-1', 'Acme')],+ [workspace('ws-a', 'srv-1', { role: 'admin' })],+ 'ws-a'+ );++ expect(inviteItem()?.textContent).toBe('Invite people to ws-a');+ });++ it('is not offered to a member, whom the server would refuse', async () => {+ await openSwitcher([server('srv-1', 'Acme')], [workspace('ws-a', 'srv-1')], 'ws-a');++ expect(inviteItem()).toBeUndefined();+ });+});++describe('invitations to your address in the switcher', () => {+ function invitation(id: string, workspaceName: string) {+ return {+ id,+ tenantId: `tenant-${id}`,+ workspaceName,+ role: 'member',+ expiresAt: '2026-12-01T00:00:00Z',+ invitedBy: 'Ada Lovelace',+ };+ }++ function invitationItems(): HTMLElement[] {+ return [...document.querySelectorAll<HTMLElement>('[data-testid="pending-invitation-item"]')];+ }++ it('counts them on the button and lists them under their server', async () => {+ state.listPendingInvitations.mockResolvedValue({+ kind: 'listed',+ invitations: [invitation('inv-1', 'Skunkworks'), invitation('inv-2', 'Labs')],+ });++ await openSwitcher([server('srv-1', 'Acme')], [workspace('ws-a', 'srv-1')], 'ws-a');++ expect(container!.querySelector('[aria-label="2 invitations waiting"]')).not.toBeNull();+ expect(invitationItems().map((item) => item.textContent)).toEqual([+ 'SkunkworksInvited',+ 'LabsInvited',+ ]);+ expect(invitationItems()[0]!.title).toBe('Ada Lovelace invited you as member');+ });++ it('shows nothing on a server too old to list them', async () => {+ state.listPendingInvitations.mockResolvedValue({ kind: 'unsupported' });++ await openSwitcher([server('srv-1', 'Acme')], [workspace('ws-a', 'srv-1')], 'ws-a');++ expect(container!.querySelector('[aria-label$="waiting"]')).toBeNull();+ expect(invitationItems()).toHaveLength(0);+ expect(document.body.textContent).not.toContain('invitations to your address');+ });++ it('says so when the server could not be asked', async () => {+ state.listPendingInvitations.mockRejectedValue(new Error('gateway unreachable'));++ await openSwitcher([server('srv-1', 'Acme')], [workspace('ws-a', 'srv-1')], 'ws-a');++ expect(document.body.textContent).toContain('Could not check for invitations to your address.');+ });++ it('does not ask a server you are not signed in to', async () => {+ state.unavailable.add('srv-2');++ await openSwitcher(+ [server('srv-1', 'Acme'), server('srv-2', 'Local dev')],+ [workspace('ws-a', 'srv-1'), workspace('ws-c', 'srv-2')],+ 'ws-a'+ );++ expect(state.listPendingInvitations).toHaveBeenCalledWith('srv-1');+ expect(state.listPendingInvitations).not.toHaveBeenCalledWith('srv-2');+ });++ it('accepts one, opens the workspace it joins and asks again', async () => {+ state.listPendingInvitations.mockResolvedValue({+ kind: 'listed',+ invitations: [invitation('inv-1', 'Skunkworks')],+ });+ state.acceptPendingInvitation.mockResolvedValue(workspace('ws-new', 'srv-1'));++ await openSwitcher([server('srv-1', 'Acme')], [workspace('ws-a', 'srv-1')], 'ws-a');+ await act(async () => invitationItems()[0]!.click());+ await settle();++ expect(state.acceptPendingInvitation).toHaveBeenCalledWith(+ 'srv-1',+ expect.objectContaining({ id: 'inv-1' })+ );+ expect(state.setActive).toHaveBeenCalledWith('ws-new');+ expect(state.navigate).toHaveBeenCalledWith('server', { serverId: 'srv-1' });+ expect(state.listPendingInvitations).toHaveBeenCalledTimes(2);+ });++ it('says why when accepting fails, and asks again', async () => {+ state.listPendingInvitations.mockResolvedValue({+ kind: 'listed',+ invitations: [invitation('inv-1', 'Skunkworks')],+ });+ state.acceptPendingInvitation.mockRejectedValue(new Error('This invitation has been revoked'));++ await openSwitcher([server('srv-1', 'Acme')], [workspace('ws-a', 'srv-1')], 'ws-a');+ await act(async () => invitationItems()[0]!.click());+ await settle();++ expect(state.toast).toHaveBeenCalledWith(+ expect.objectContaining({+ title: 'Could not join Skunkworks',+ description: expect.stringContaining('This invitation has been revoked'),+ })+ );+ expect(state.setActive).not.toHaveBeenCalled();+ expect(state.listPendingInvitations).toHaveBeenCalledTimes(2);+ });+});++describe('workspaces open to your e-mail domain', () => {+ function joinableItems(): HTMLElement[] {+ return [...document.querySelectorAll<HTMLElement>('[data-testid="joinable-workspace-item"]')];+ }++ it('lists them under their server without counting them as invitations', async () => {+ state.listJoinableWorkspaces.mockResolvedValue({+ kind: 'listed',+ workspaces: [{ tenantId: 't-9', workspaceName: 'Skunkworks', domain: 'acme.example' }],+ });++ await openSwitcher([server('srv-1', 'Acme')], [workspace('ws-a', 'srv-1')], 'ws-a');++ expect(container!.querySelector('[aria-label$="waiting"]')).toBeNull();+ expect(joinableItems().map((item) => item.textContent)).toEqual(['SkunkworksJoin']);+ expect(joinableItems()[0]!.title).toBe('Open to anyone at acme.example');+ });++ it('joins one, opens it and asks again', async () => {+ state.listJoinableWorkspaces.mockResolvedValue({+ kind: 'listed',+ workspaces: [{ tenantId: 't-9', workspaceName: 'Skunkworks', domain: 'acme.example' }],+ });+ state.joinByDomain.mockResolvedValue(workspace('ws-new', 'srv-1'));++ await openSwitcher([server('srv-1', 'Acme')], [workspace('ws-a', 'srv-1')], 'ws-a');+ await act(async () => joinableItems()[0]!.click());+ await settle();++ expect(state.joinByDomain).toHaveBeenCalledWith(+ 'srv-1',+ expect.objectContaining({ tenantId: 't-9' })+ );+ expect(state.setActive).toHaveBeenCalledWith('ws-new');+ expect(state.listJoinableWorkspaces).toHaveBeenCalledTimes(2);+ });++ it('says so when the server could not be asked', async () => {+ state.listJoinableWorkspaces.mockRejectedValue(new Error('gateway unreachable'));++ await openSwitcher([server('srv-1', 'Acme')], [workspace('ws-a', 'srv-1')], 'ws-a');++ expect(document.body.textContent).toContain(+ 'Could not check for workspaces open to your e-mail domain.'+ );+ });+});++describe('which switcher a build shows', () => {+ it('shows workspaces when the build can reach Switch Cloud', () => {+ expect(showsServers('open')).toBe(false);+ });++ it('shows workspaces when the Cloud configuration is broken, so it is not hidden', () => {+ expect(showsServers('failed')).toBe(false);+ });++ it('shows servers on a build without Switch Cloud', () => {+ expect(showsServers('closed')).toBe(true);+ expect(showsServers('reading')).toBe(true);+ });+});++describe('the workspace a server row opens', () => {+ it('stays in the active workspace when it is on that server', () => {+ const ws = [workspace('ws-a', 'srv-1'), workspace('ws-b', 'srv-1')];+ expect(serverRowWorkspace(ws, 'ws-b').workspace?.id).toBe('ws-b');+ });++ it('otherwise opens the first one that can be opened', () => {+ const ws = [workspace('ws-a', 'srv-1', { tenantId: null }), workspace('ws-b', 'srv-1')];+ expect(serverRowWorkspace(ws, 'elsewhere').workspace?.id).toBe('ws-b');+ });++ it('opens nothing on a server with no workspace', () => {+ expect(serverRowWorkspace([], null)).toEqual({ workspace: null, unavailable: null });+ });+});++describe('the server switcher on a build without Switch Cloud', () => {+ beforeEach(() => {+ state.cloud = 'closed';+ });++ function serverRow(name: string): HTMLElement {+ const found = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find((item) =>+ item.querySelector('span span')?.textContent?.startsWith(name)+ );+ expect(found, `no row for ${name}`).toBeDefined();+ return found!;+ }++ it('lists servers, not workspaces, and offers no workspace actions', async () => {+ await openSwitcher(+ [server('srv-1', 'Acme'), server('srv-2', 'Local dev')],+ [workspace('ws-a', 'srv-1', { role: 'owner' }), workspace('ws-c', 'srv-2')],+ 'ws-a',+ 'Switch server'+ );++ expect(serverRow('Acme').getAttribute('aria-current')).toBe('true');+ expect(serverRow('Local dev').getAttribute('aria-current')).toBeNull();+ expect(document.body.textContent).not.toContain('New workspace');+ expect(document.body.textContent).not.toContain('Invite people');+ });++ it("switches to a server's workspace when the server is clicked", async () => {+ await openSwitcher(+ [server('srv-1', 'Acme'), server('srv-2', 'Local dev')],+ [workspace('ws-a', 'srv-1'), workspace('ws-c', 'srv-2')],+ 'ws-a',+ 'Switch server'+ );++ await act(async () => serverRow('Local dev').click());++ expect(state.setActive).toHaveBeenCalledWith('ws-c');+ expect(state.navigate).toHaveBeenCalledWith('server', { serverId: 'srv-2' });+ });++ it('refuses a server that has no workspace yet, and says why', async () => {+ await openSwitcher(+ [server('srv-1', 'Acme'), server('srv-2', 'Half set up')],+ [workspace('ws-a', 'srv-1')],+ 'ws-a',+ 'Switch server'+ );++ const half = serverRow('Half set up');+ expect(half.getAttribute('title')).toContain('not finished being set up');+ await act(async () => half.click());+ expect(state.setActive).not.toHaveBeenCalled();+ });++ it('keeps the server list when a server holds two workspaces', async () => {+ await openSwitcher(+ [server('srv-1', 'Acme'), server('srv-2', 'Local dev')],+ [workspace('ws-a', 'srv-1'), workspace('ws-b', 'srv-1'), workspace('ws-c', 'srv-2')],+ 'ws-c',+ 'Switch server'+ );++ expect(document.body.textContent).not.toContain('ws-b');+ await act(async () => serverRow('Acme').click());+ expect(state.setActive).toHaveBeenCalledWith('ws-a');+ });+});diff --git a/console/apps/switch-console-desktop/src/shared/core/agents/agents.ts b/console/apps/switch-console-desktop/src/shared/core/agents/agents.tsindex 2b31eba5a..5f8912eb0 100644--- a/console/apps/switch-console-desktop/src/shared/core/agents/agents.ts+++ b/console/apps/switch-console-desktop/src/shared/core/agents/agents.ts@@ -6,9 +6,8 @@ import type { AgentProviderId } from '@shared/core/providers/agent-provider-regi* location (a working directory on this machine or an SSH host). Many agents* may share a location. `switchAgentId` / `apiEndpoint` carry the Switch* identity detected from the location dir's `.claude/settings.local.json`.- * `serverId` is the registered Switch server the agent belongs to (resolved- * from `apiEndpoint`); null means unlinked — the server it points at is not- * registered in this app.+ * `workspaceId` is the workspace the agent belongs to; null means unlinked —+ * the workspace it was in is no longer registered in this app.*/export type Agent = {id: string;@@ -20,6 +19,12 @@ export type Agent = {providerId: AgentProviderId;switchAgentId: string | null;apiEndpoint: string | null;+ workspaceId: string | null;+ /**+ * The server hosting `workspaceId`, denormalised onto the agent: null exactly+ * when `workspaceId` is. Reaching an agent's gateway means reaching its+ * workspace's server, and this saves every caller repeating that one hop.+ */serverId: string | null;status: string | null;/** When true, Switch Console launches this agent's CLI with its auto-approve /@@ -43,10 +48,10 @@ export type CreateAgentParams = {providerId: AgentProviderId;switchAgentId: string | null;apiEndpoint: string | null;- /** The Switch server this agent belongs to. Every agent must have one — it is+ /** The workspace this agent belongs to. Every agent must have one — it is* chosen and verified at onboarding (legacy rows may still be null until the* user assigns one). */- serverId: string;+ workspaceId: string;/** Seed for the per-agent bypass-permissions flag: false for local agents,* true for remote agents. */autoApprove: boolean;diff --git a/console/apps/switch-console-desktop/src/shared/core/switch-servers/add-server-steps.ts b/console/apps/switch-console-desktop/src/shared/core/switch-servers/add-server-steps.tsindex 9dc9f3228..42f525fc9 100644--- a/console/apps/switch-console-desktop/src/shared/core/switch-servers/add-server-steps.ts+++ b/console/apps/switch-console-desktop/src/shared/core/switch-servers/add-server-steps.ts@@ -20,8 +20,9 @@ export type AddServerStepName = (typeof ADD_SERVER_STEPS)[number];* Which kind of server the wizard is setting up.** `none` is the first screen, where nothing has been chosen yet — so a drop-off- * before choosing is distinguishable from one after.+ * before choosing is distinguishable from one after. `cloud` is connecting to+ * Switch Cloud: an external server too, but one nobody typed the address of.*/-export const ADD_SERVER_CHOICES = ['none', 'local', 'remoteHost', 'external'] as const;+export const ADD_SERVER_CHOICES = ['none', 'local', 'remoteHost', 'external', 'cloud'] as const;export type AddServerChoiceName = (typeof ADD_SERVER_CHOICES)[number];diff --git a/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-cloud.ts b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-cloud.tsnew file mode 100644index 000000000..d3d345bc8--- /dev/null+++ b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-cloud.ts@@ -0,0 +1,24 @@+import type { SwitchServer } from './switch-servers';++/** The name a Switch Cloud connection is registered under. */+export const SWITCH_CLOUD_NAME = 'Switch Cloud';++/**+ * Where Switch Cloud is, as far as this build or run has been told.+ *+ * One URL, not the gateway/API pair an arbitrary server is registered with: a+ * hosted deployment serves the management API under `/gateway` and the agent+ * API at the root of the same origin, so both are that origin.+ */+export type SwitchCloudEndpoint = {+ url: string;+};++/**+ * The server an invite link points at: one this install can already sign in+ * to, and how it was reached — or one it has never heard of, named by the web+ * address the link carries and nothing more.+ */+export type InviteServer =+ | { kind: 'known'; server: SwitchServer; via: 'external' | 'cloud' }+ | { kind: 'unknown'; origin: string };diff --git a/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.tsindex 655892b4f..5c39045f8 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@@ -265,7 +265,7 @@ export type RemoteRoomDetail = RemoteRoomSummary & {/** The room fields Switch Console can change. Anything omitted is left alone;* an empty string clears the field rather than leaving it. */export type UpdateRoomParams = {- serverId: string;+ workspaceId: string;roomId: string;description?: string;instructions?: string;@@ -414,7 +414,7 @@ export type RemoteBridgeType = {* never logged, and never sent back to the renderer.*/export type CreateBridgeParams = {- serverId: string;+ workspaceId: string;bridgeType: string;displayName: string;connectionConfig: Record<string, string | boolean>;@@ -450,7 +450,7 @@ export type CreateBridgeResult =* own partial-update contract.*/export type UpdateBridgeParams = {- serverId: string;+ workspaceId: string;bridgeId: string;channelCreationEnabled?: boolean;};@@ -468,7 +468,7 @@ export type UpdateBridgeResult =/** Parameters for disconnecting a bridge from a server* (`DELETE /collaborations/{id}`). */export type DeleteBridgeParams = {- serverId: string;+ workspaceId: string;bridgeId: string;};@@ -555,7 +555,7 @@ export type BridgeDirectorySearchResult =/** Claim a platform identity for the signed-in Switch user (CHOO-2137). */export type ClaimIdentityParams = {- serverId: string;+ workspaceId: string;bridgeId: string;/** The platform's own id, not an `ExternalUser` row id — the row may not* exist yet, and the server creates it on demand. */@@ -669,7 +669,7 @@ export type AgentProviderKind = 'anthropic' | 'third-party';* its credentials into the directory's `.claude/settings.local.json`.*/export type ProvisionAgentParams = {- serverId: string;+ workspaceId: string;/** The agent's working directory; the settings file is written here and used* as `repo_dir` so an offline-session command can `cd` into it. */dir: string;@@ -688,7 +688,7 @@ export type ProvisionAgentParams = {* is no local directory: the agent's config lives entirely on the host.*/export type ProvisionRemoteAgentParams = {- serverId: string;+ workspaceId: string;/** SSH alias of the onboarded host the agent runs on. */sshHost: string;/** The agent's working directory on the host; the settings file is written@@ -741,7 +741,7 @@ export type ProvisionAgentResult =* useful room, so there is no internal-only path here.*/export type CreateRoomParams = {- serverId: string;+ workspaceId: string;name: string;description: string;/** Room-specific system prompt shown to agents on connect. Optional. */diff --git a/console/apps/switch-console-desktop/src/shared/core/telemetry/renderer-events.ts b/console/apps/switch-console-desktop/src/shared/core/telemetry/renderer-events.tsindex c4302d099..6aa013d4b 100644--- a/console/apps/switch-console-desktop/src/shared/core/telemetry/renderer-events.ts+++ b/console/apps/switch-console-desktop/src/shared/core/telemetry/renderer-events.ts@@ -46,8 +46,15 @@ export type RendererTelemetryEvents = {onboarding_checklist_dismissed: Record<never, never>;/** Every step of the checklist is done. */onboarding_completed: Record<never, never>;- /** The add-server wizard reached a step. Where people stop is the question. */- add_server_step: { step: AddServerStepName; choice: AddServerChoiceName };+ /**+ * The add-server wizard reached a step. Where people stop is the question.+ *+ * `first_run` separates the two places the same steps are drawn: the wizard+ * in a dialog, and the full-window pages a fresh install opens on. Giving up+ * before you have any server at all is a different answer from giving up+ * adding your second, and one funnel covering both could not tell them apart.+ */+ add_server_step: { step: AddServerStepName; choice: AddServerChoiceName; first_run: boolean };/** A screen failed and the error boundary caught it. */renderer_crashed: Record<never, never>;};diff --git a/console/apps/switch-console-desktop/src/shared/core/workspaces/invitations.ts b/console/apps/switch-console-desktop/src/shared/core/workspaces/invitations.tsnew file mode 100644index 000000000..ba8bb412b--- /dev/null+++ b/console/apps/switch-console-desktop/src/shared/core/workspaces/invitations.ts@@ -0,0 +1,151 @@+import type { WorkspaceRole } from './workspaces';++/** An invitation to a workspace, as the gateway lists it to the workspace's admins. */+export type Invitation = {+ id: string;+ role: WorkspaceRole;+ /** The one address that may accept it, or null for anyone holding the link. */+ email: string | null;+ /** ISO 8601. */+ expiresAt: string;+ usesRemaining: number;+ /** ISO 8601, or null while it has not been revoked. */+ revokedAt: string | null;+ createdAt: string;+};++/**+ * What became of the e-mail an invitation asked for.+ *+ * `not_requested` is an invitation that named no address; `not_configured` a+ * server with no mail relay; `failed` a relay that refused or could not be+ * reached; `unsupported` a server older than e-mailed invitations, which never+ * sends one. The invitation stands in every case, and its link is the way in.+ */+export type InvitationEmailDelivery =+ | 'sent'+ | 'not_configured'+ | 'failed'+ | 'not_requested'+ | 'unsupported';++export type CreateInvitationParams = {+ workspaceId: string;+ role: WorkspaceRole;+ email: string | null;+ expiresInHours: number;+ usesRemaining: number;+};++/**+ * A new invitation and the link to it.+ *+ * The link is only ever available here: the server keeps a hash of the token,+ * so once this is dismissed nobody can show it again.+ */+export type CreatedInvitation = {+ invitation: Invitation;+ link: string;+ emailDelivery: InvitationEmailDelivery;+};++/**+ * A workspace's invitations, and whether an addressed one is e-mailed.+ *+ * `emailEnabled` is null on a server older than e-mailed invitations: it never+ * sends one, but "no e-mail set up" would name a setting it does not have.+ */+export type WorkspaceInvitations = {+ invitations: Invitation[];+ emailEnabled: boolean | null;+};++export type InvitationStatus = 'active' | 'revoked' | 'expired' | 'used';++/** Whether an invitation can still be accepted, and if not, why not. */+export function invitationStatus(invitation: Invitation, now: number): InvitationStatus {+ if (invitation.revokedAt !== null) return 'revoked';+ if (new Date(invitation.expiresAt).getTime() <= now) return 'expired';+ if (invitation.usesRemaining <= 0) return 'used';+ return 'active';+}++/**+ * The link an invitee opens or pastes into Switch Console.+ *+ * Built from the gateway's own address, as the server's dashboard builds it+ * from the page it is served on: both are the origin that answers `/gateway`.+ * The token rides in the fragment, which a browser never sends, so it stays out+ * of proxy and access logs.+ */+export function inviteLink(gatewayUrl: string, token: string): string {+ return `${gatewayUrl.replace(/\/+$/, '')}/invite#token=${encodeURIComponent(token)}`;+}++/**+ * An invitation addressed to the signed-in account, in a workspace it is not a+ * member of yet. Accepted by id: the account's own address stands in for the+ * link, so there is no token to hold.+ */+export type PendingInvitation = {+ id: string;+ /** The gateway's id for the workspace it would join. */+ tenantId: string;+ workspaceName: string;+ role: WorkspaceRole;+ /** ISO 8601. */+ expiresAt: string;+ /** The inviter's name, as the server has it. */+ invitedBy: string;+};++/**+ * The invitations waiting for the signed-in account on one server.+ *+ * `unsupported` is a server older than the route that lists them. It is not the+ * same answer as an empty list — that server cannot say whether anyone invited+ * you — so it is kept apart for the views to leave the section out rather than+ * claim there is nothing in it.+ */+export type PendingInvitations =+ | { kind: 'listed'; invitations: PendingInvitation[] }+ | { kind: 'unsupported' };++/**+ * A workspace open to the domain of the signed-in account's address, that the+ * account is not a member of yet. Joining it needs no invitation and grants+ * the member role.+ */+export type JoinableWorkspace = {+ /** The gateway's id for the workspace. */+ tenantId: string;+ workspaceName: string;+ /** The domain it is open to — the account's own. */+ domain: string;+};++/**+ * The workspaces the signed-in account may join by its domain on one server.+ * `unsupported` is a server older than the route, kept apart from an empty+ * list for the reason `PendingInvitations` gives.+ */+export type JoinableWorkspaces =+ | { kind: 'listed'; workspaces: JoinableWorkspace[] }+ | { kind: 'unsupported' };++/**+ * The e-mail domains a workspace lets people join from, as its admins see+ * them, and whether the signed-in admin could add their own.+ *+ * An admin may open a workspace only to the domain of their own address, so+ * `ownDomain` is the one domain on offer and `ownDomainRefusal` says why it+ * cannot be added when it cannot — a public e-mail provider's, say.+ */+export type WorkspaceJoinDomains =+ | {+ kind: 'listed';+ domains: string[];+ ownDomain: string;+ ownDomainRefusal: string | null;+ }+ | { kind: 'unsupported' };diff --git a/console/apps/switch-console-desktop/src/shared/core/workspaces/invite-link.test.ts b/console/apps/switch-console-desktop/src/shared/core/workspaces/invite-link.test.tsnew file mode 100644index 000000000..c210989fd--- /dev/null+++ b/console/apps/switch-console-desktop/src/shared/core/workspaces/invite-link.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it } from 'vitest';+import { parseInviteLink } from './invite-link';++describe('parseInviteLink', () => {+ it('reads the origin and token from a server invite link', () => {+ expect(parseInviteLink('https://switch.example.com/invite#token=abc123')).toEqual({+ origin: 'https://switch.example.com',+ token: 'abc123',+ });+ });++ it('keeps a port and tolerates surrounding whitespace and a trailing slash', () => {+ expect(parseInviteLink(' http://localhost:5173/invite/#token=t%2Bk \n')).toEqual({+ origin: 'http://localhost:5173',+ token: 't+k',+ });+ });++ it('refuses an empty paste', () => {+ expect(() => parseInviteLink(' ')).toThrow(/Paste the invite link/);+ });++ it('refuses text that is not a link', () => {+ expect(() => parseInviteLink('abc123')).toThrow(/not a link/);+ });++ it('refuses a link that is not an http one', () => {+ expect(() => parseInviteLink('ftp://switch.example.com/invite#token=abc')).toThrow(+ /not a link/+ );+ });++ it('refuses a link to some other page', () => {+ expect(() => parseInviteLink('https://switch.example.com/rooms#token=abc')).toThrow(+ /not an invitation/+ );+ });++ it('refuses an invite link with the token cut off', () => {+ expect(() => parseInviteLink('https://switch.example.com/invite')).toThrow(/no token/);+ expect(() => parseInviteLink('https://switch.example.com/invite#token=')).toThrow(/no token/);+ });+});diff --git a/console/apps/switch-console-desktop/src/shared/core/workspaces/invite-link.ts b/console/apps/switch-console-desktop/src/shared/core/workspaces/invite-link.tsnew file mode 100644index 000000000..02b0a5a17--- /dev/null+++ b/console/apps/switch-console-desktop/src/shared/core/workspaces/invite-link.ts@@ -0,0 +1,45 @@+/**+ * An invitation to a workspace, as the link a Switch server hands out.+ *+ * The server's dashboard and its invitation e-mail both write the same shape,+ * `<origin>/invite#token=<token>`. The origin is the only thing in it that says+ * which server the workspace is on, so it is kept alongside the token rather+ * than discarded once the token is out.+ */+export type InviteLink = {+ /** The server's origin, as the link names it: scheme, host and port. */+ origin: string;+ token: string;+};++/**+ * Read a pasted invite link, or raise saying what is wrong with it.+ *+ * Deliberately narrow. Anything that is not a link to an `/invite` page with a+ * token is refused rather than guessed at, because a guess here means signing+ * in to some server and accepting nothing, and the user would be left looking+ * for a workspace the link never named.+ */+export function parseInviteLink(text: string): InviteLink {+ const trimmed = text.trim();+ if (trimmed.length === 0) throw new Error('Paste the invite link you were sent.');++ let url: URL;+ try {+ url = new URL(trimmed);+ } catch {+ throw new Error('That is not a link. Paste the whole invite link, starting with https://.');+ }+ if (url.protocol !== 'https:' && url.protocol !== 'http:') {+ throw new Error('That is not a link. Paste the whole invite link, starting with https://.');+ }+ if (url.pathname.replace(/\/+$/, '') !== '/invite') {+ throw new Error('That link is not an invitation. Invite links end in /invite#token=…');+ }++ const token = new URLSearchParams(url.hash.replace(/^#/, '')).get('token')?.trim();+ if (!token) {+ throw new Error('That invite link has no token in it. Copy the whole link and paste it again.');+ }+ return { origin: url.origin, token };+}diff --git a/console/apps/switch-console-desktop/src/shared/core/workspaces/workspaceEvents.ts b/console/apps/switch-console-desktop/src/shared/core/workspaces/workspaceEvents.tsnew file mode 100644index 000000000..6591daeb3--- /dev/null+++ b/console/apps/switch-console-desktop/src/shared/core/workspaces/workspaceEvents.ts@@ -0,0 +1,13 @@+import { defineEvent } from '@shared/lib/ipc/events';++/**+ * The set of workspaces this install holds changed in the main process.+ *+ * Fired by the reconcile, which is the one thing that adds, matches and drops+ * workspace rows without a window having asked for it — the boot sweep, and+ * every sign-in. Without it a membership added or withdrawn since the last+ * launch stays invisible for the whole session, and a placeholder the sweep+ * deleted goes on being offered in the switcher by a renderer holding the list+ * it read at startup.+ */+export const workspacesChangedChannel = defineEvent<void>('workspaces:changed');diff --git a/console/apps/switch-console-desktop/src/shared/core/workspaces/workspaces.ts b/console/apps/switch-console-desktop/src/shared/core/workspaces/workspaces.tsnew file mode 100644index 000000000..6fb5eec85--- /dev/null+++ b/console/apps/switch-console-desktop/src/shared/core/workspaces/workspaces.ts@@ -0,0 +1,92 @@+/**+ * Shared types for workspaces: what a Switch Console window is scoped to, and+ * the thing agents belong to.+ *+ * A workspace sits one level below a registered server. On a server with+ * tenancy it mirrors a tenant the signed-in user is a member of; the server's+ * own identity (its URLs, its session cookie, its auth method) stays at the+ * server, because one session cookie covers every workspace on it.+ */++/** The caller's standing in a workspace, as the gateway reports it. */+export type WorkspaceRole = 'owner' | 'admin' | 'member';++/** A workspace on a registered Switch server. */+export type Workspace = {+ id: string;+ serverId: string;+ name: string;+ /**+ * The workspace's tenant id on the gateway.+ *+ * Null means the workspace has not been matched to a tenant yet — the state+ * every workspace starts in, since one is created locally the moment a server+ * is registered and the gateway is only asked afterwards. It is a transient+ * "not reconciled yet", not a description of the server.+ */+ tenantId: string | null;+ /** The gateway's slug for the workspace; null alongside a null `tenantId`. */+ slug: string | null;+ /**+ * Null alongside a null `tenantId`, where the notion does not apply yet — and+ * null beside a tenant id once the membership has been withdrawn, which is+ * what {@link isWithdrawnWorkspace} reads.+ */+ role: WorkspaceRole | null;+ createdAt: string;+ updatedAt: string;+};++/**+ * Whether this account runs a workspace — invites people to it, connects its+ * messaging apps — which the gateway also enforces.+ */+export function administersWorkspace(workspace: Workspace): boolean {+ return workspace.role === 'owner' || workspace.role === 'admin';+}++/**+ * Whether this account has lost its membership of a workspace still held here.+ *+ * The row is kept so the agents registered through it stay attached to+ * something, but nothing scoped to it can be answered any more: the gateway+ * refuses a session selecting a tenant the account does not belong to. Views+ * say so rather than offering it, so the refusal is read before the click+ * rather than after it.+ */+export function isWithdrawnWorkspace(workspace: Workspace): boolean {+ return workspace.tenantId !== null && workspace.role === null;+}++/**+ * Whether a row that names no tenant is one nothing can answer for.+ *+ * Every server's first workspace is created tenant-less and matched to a+ * membership by the reconcile, so on a server holding one workspace this state+ * is ordinary: there is nothing to confuse it with, and the gateway resolves+ * the account's sole membership to exactly that row. Beside siblings it is the+ * placeholder the reconcile could not match, kept only because it holds agents+ * — and a call scoped to it selects no tenant, so the gateway answers with+ * whichever workspace the session last selected, under this one's name.+ *+ * `onSameServer` is every workspace on the server, this one included.+ */+export function isUnmatchedWorkspace(workspace: Workspace, onSameServer: number): boolean {+ return workspace.tenantId === null && onSameServer > 1;+}++/** Why a workspace cannot be opened, or null when it can. */+export type WorkspaceUnavailability = 'withdrawn' | 'unmatched';++/**+ * The two ways a workspace held here can be one nothing scoped to it will be+ * answered for, as one question — so a view offering workspaces cannot rule out+ * the first and go on offering the second.+ */+export function workspaceUnavailability(+ workspace: Workspace,+ onSameServer: number+): WorkspaceUnavailability | null {+ if (isWithdrawnWorkspace(workspace)) return 'withdrawn';+ return isUnmatchedWorkspace(workspace, onSameServer) ? 'unmatched' : null;+}diff --git a/console/apps/switch-console-desktop/src/types/env.d.ts b/console/apps/switch-console-desktop/src/types/env.d.tsindex 11f02fe2a..4ed484aad 100644--- a/console/apps/switch-console-desktop/src/types/env.d.ts+++ b/console/apps/switch-console-desktop/src/types/env.d.ts@@ -1 +1,6 @@/// <reference types="vite/client" />++interface ImportMetaEnv {+ /** Switch Cloud's origin for a packaged build; see `main/core/switch-servers/switch-cloud.ts`. */+ readonly MAIN_VITE_SWITCH_CLOUD_URL?: string;+}diff --git a/console/apps/switch-console-desktop/tooling/fixtures/baseline.db b/console/apps/switch-console-desktop/tooling/fixtures/baseline.dbindex 23caa2637..c1759e17b 100644Binary files a/console/apps/switch-console-desktop/tooling/fixtures/baseline.db and b/console/apps/switch-console-desktop/tooling/fixtures/baseline.db differdiff --git a/console/apps/switch-console-desktop/tooling/fixtures/baseline.db-shm b/console/apps/switch-console-desktop/tooling/fixtures/baseline.db-shmnew file mode 100644index 000000000..fe9ac2845Binary files /dev/null and b/console/apps/switch-console-desktop/tooling/fixtures/baseline.db-shm differdiff --git a/console/apps/switch-console-desktop/tooling/fixtures/baseline.db-wal b/console/apps/switch-console-desktop/tooling/fixtures/baseline.db-walnew file mode 100644index 000000000..e69de29bbdiff --git a/console/apps/switch-console-desktop/tooling/fixtures/empty.db b/console/apps/switch-console-desktop/tooling/fixtures/empty.dbindex 3bf798903..ef513691c 100644Binary files a/console/apps/switch-console-desktop/tooling/fixtures/empty.db and b/console/apps/switch-console-desktop/tooling/fixtures/empty.db differdiff --git a/console/apps/switch-console-desktop/tooling/fixtures/empty.db-shm b/console/apps/switch-console-desktop/tooling/fixtures/empty.db-shmnew file mode 100644index 000000000..fe9ac2845Binary files /dev/null and b/console/apps/switch-console-desktop/tooling/fixtures/empty.db-shm differdiff --git a/console/apps/switch-console-desktop/tooling/fixtures/empty.db-wal b/console/apps/switch-console-desktop/tooling/fixtures/empty.db-walnew file mode 100644index 000000000..e69de29bbdiff --git a/console/packages/core/src/agents/plugins/capabilities/repo-agents.ts b/console/packages/core/src/agents/plugins/capabilities/repo-agents.tsindex 2e96fc14a..2a00b79f8 100644--- a/console/packages/core/src/agents/plugins/capabilities/repo-agents.ts+++ b/console/packages/core/src/agents/plugins/capabilities/repo-agents.ts@@ -134,19 +134,19 @@ export type RepoAgentLaunchDefinition = Record<string, string | string[] | numbe* provider's business and lives behind this behavior; the main process supplies a* `PluginFs` for the IO and owns the provider-neutral gateway reconciliation.*- * `workspaceFs` is rooted at the agent's working directory; `homeFs` at the user's+ * `workdirFs` is rooted at the agent's working directory; `homeFs` at the user's* home — definitions may resolve in either scope.*/export type IRepoAgentsBehavior = {/** Runnable agents, from the working dir's on-disk credentials + definitions. */- discoverLocal(workspaceFs: PluginFs, homeFs: PluginFs): Promise<LocalRepoAgent[]>;+ discoverLocal(workdirFs: PluginFs, homeFs: PluginFs): Promise<LocalRepoAgent[]>;/** Agent definitions in the working dir, for onboarding (project scope). */- discoverDefinitions(workspaceFs: PluginFs): Promise<RepoAgentDefinition[]>;+ discoverDefinitions(workdirFs: PluginFs): Promise<RepoAgentDefinition[]>;/** Provider-specific CLI args that run the CLI as the named agent. Pure — the* caller passes them to `buildCommand` as `agentArgs` (not user extra args). */launchArgs(workingDir: string, agentName: string): string[];/** The named agent's Switch credentials as env vars, for the launched session. */- readLaunchEnv(workspaceFs: PluginFs, agentName: string): Promise<Record<string, string>>;+ readLaunchEnv(workdirFs: PluginFs, agentName: string): Promise<Record<string, string>>;/** The attribute fields this provider supports, in display order. Drives the* create/edit form; the first two are always `name` and `description`. */attributeFields(): RepoAgentField[];@@ -167,16 +167,16 @@ export type IRepoAgentsBehavior = {*/launchDefinition(attributes: RepoAgentAttributes): RepoAgentLaunchDefinition;/** Create or overwrite a named agent's on-disk definition from its attributes- * (workspace scope). `attributes.name` selects the agent. */- writeDefinition(workspaceFs: PluginFs, attributes: RepoAgentAttributes): Promise<void>;+ * (workdir scope). `attributes.name` selects the agent. */+ writeDefinition(workdirFs: PluginFs, attributes: RepoAgentAttributes): Promise<void>;/** The current attribute values for an existing agent definition, keyed to* {@link attributeFields}, or null if no definition exists. */- readDefinition(workspaceFs: PluginFs, name: string): Promise<RepoAgentAttributes | null>;+ readDefinition(workdirFs: PluginFs, name: string): Promise<RepoAgentAttributes | null>;/** Remove a named agent's provider-specific files — its definition and any- * legacy per-agent settings (workspace scope). The provider-neutral Switch+ * legacy per-agent settings (workdir scope). The provider-neutral Switch* credentials are not this hook's to remove: they are written for every* provider, so they are torn down by the caller for every provider too. */- removeLocal(workspaceFs: PluginFs, name: string): Promise<void>;+ removeLocal(workdirFs: PluginFs, name: string): Promise<void>;};/**diff --git a/console/packages/plugins/src/agents/impl/claude/subagents.test.ts b/console/packages/plugins/src/agents/impl/claude/subagents.test.tsindex 367ca65ff..773d86e88 100644--- a/console/packages/plugins/src/agents/impl/claude/subagents.test.ts+++ b/console/packages/plugins/src/agents/impl/claude/subagents.test.ts@@ -56,7 +56,7 @@ describe('claudeRepoAgentsBehavior.launchArgs', () => {describe('claudeRepoAgentsBehavior.discoverDefinitions', () => {it('parses definitions, eligibility, and registered state', async () => {- const workspaceFs = fakeFs({+ const workdirFs = fakeFs({[defRel('reviewer')]:'---\nname: reviewer\ndescription: Reviews code\nmodel: opus\n---\nbody',// No `tools` line → eligible (inherits all tools), and registered (creds exist).@@ -65,7 +65,7 @@ describe('claudeRepoAgentsBehavior.discoverDefinitions', () => {[defRel('linter')]: '---\ndescription: Lints\ntools: Read, Edit\n---\n',});- const defs = await claudeRepoAgentsBehavior.discoverDefinitions(workspaceFs);+ const defs = await claudeRepoAgentsBehavior.discoverDefinitions(workdirFs);expect(defs).toEqual([{ name: 'linter', description: 'Lints', model: null, eligible: false, registered: false },@@ -82,7 +82,7 @@ describe('claudeRepoAgentsBehavior.discoverDefinitions', () => {describe('claudeRepoAgentsBehavior.discoverLocal', () => {it('reads creds env and definition meta, project scope then home', async () => {- const workspaceFs = fakeFs({+ const workdirFs = fakeFs({[settingsRel('reviewer')]:'{"env":{"SWITCH_AGENT_ID":"a1","SWITCH_API_ENDPOINT":"https://s"}}',[defRel('reviewer')]: '---\ndescription: Reviews\nmodel: opus\n---\n',@@ -92,7 +92,7 @@ describe('claudeRepoAgentsBehavior.discoverLocal', () => {[defRel('helper')]: '---\ndescription: From home\n---\n',});- const local = await claudeRepoAgentsBehavior.discoverLocal(workspaceFs, homeFs);+ const local = await claudeRepoAgentsBehavior.discoverLocal(workdirFs, homeFs);expect(local).toEqual([{@@ -115,12 +115,12 @@ describe('claudeRepoAgentsBehavior.discoverLocal', () => {describe('claudeRepoAgentsBehavior.readLaunchEnv', () => {it('returns only non-empty SWITCH_* keys', async () => {- const workspaceFs = fakeFs({+ const workdirFs = fakeFs({[settingsRel('reviewer')]:'{"env":{"SWITCH_AGENT_ID":"a1","SWITCH_API_TOKEN":"t","SWITCH_API_ENDPOINT":" ","OTHER":"x"}}',});- expect(await claudeRepoAgentsBehavior.readLaunchEnv(workspaceFs, 'reviewer')).toEqual({+ expect(await claudeRepoAgentsBehavior.readLaunchEnv(workdirFs, 'reviewer')).toEqual({SWITCH_AGENT_ID: 'a1',SWITCH_API_TOKEN: 't',});@@ -133,22 +133,22 @@ describe('claudeRepoAgentsBehavior.readLaunchEnv', () => {describe('claudeRepoAgentsBehavior.writeDefinition / readDefinition', () => {it('writes frontmatter + body without a tools line, and round-trips attributes', async () => {- const workspaceFs = fakeFs({});- await claudeRepoAgentsBehavior.writeDefinition(workspaceFs, {+ const workdirFs = fakeFs({});+ await claudeRepoAgentsBehavior.writeDefinition(workdirFs, {name: 'reviewer',description: 'Reviews diffs',model: 'opus',instructions: 'You are a careful reviewer.',});- const raw = await workspaceFs.read(defRel('reviewer'));+ const raw = await workdirFs.read(defRel('reviewer'));expect(raw).toBe('---\nname: reviewer\ndescription: Reviews diffs\nmodel: opus\n---\n\nYou are a careful reviewer.\n');// No `tools:` line → the subagent inherits all tools and is Switch-eligible.expect(raw).not.toContain('tools:');- const attrs = await claudeRepoAgentsBehavior.readDefinition(workspaceFs, 'reviewer');+ const attrs = await claudeRepoAgentsBehavior.readDefinition(workdirFs, 'reviewer');expect(attrs).toMatchObject({name: 'reviewer',description: 'Reviews diffs',@@ -159,14 +159,14 @@ describe('claudeRepoAgentsBehavior.writeDefinition / readDefinition', () => {});it('falls back to the description for the body when there are no instructions', async () => {- const workspaceFs = fakeFs({});- await claudeRepoAgentsBehavior.writeDefinition(workspaceFs, {+ const workdirFs = fakeFs({});+ await claudeRepoAgentsBehavior.writeDefinition(workdirFs, {name: 'reviewer',description: 'Reviews diffs',});// Claude Code reads the body as the system prompt, so it cannot be empty.- expect(await workspaceFs.read(defRel('reviewer'))).toBe(+ expect(await workdirFs.read(defRel('reviewer'))).toBe('---\nname: reviewer\ndescription: Reviews diffs\n---\n\nReviews diffs\n');});@@ -174,13 +174,13 @@ describe('claudeRepoAgentsBehavior.writeDefinition / readDefinition', () => {it('does not read the description stand-in back as instructions', async () => {// Otherwise the round trip invents a prompt the user never wrote, and the// next write pins it as if they had.- const workspaceFs = fakeFs({});- await claudeRepoAgentsBehavior.writeDefinition(workspaceFs, {+ const workdirFs = fakeFs({});+ await claudeRepoAgentsBehavior.writeDefinition(workdirFs, {name: 'reviewer',description: 'Reviews diffs',});- const attrs = await claudeRepoAgentsBehavior.readDefinition(workspaceFs, 'reviewer');+ const attrs = await claudeRepoAgentsBehavior.readDefinition(workdirFs, 'reviewer');expect(attrs?.instructions).toBe('');});@@ -204,24 +204,24 @@ describe('claudeRepoAgentsBehavior.writeDefinition / readDefinition', () => {});it('always merges the Switch tools into a non-empty tools list', async () => {- const workspaceFs = fakeFs({});- await claudeRepoAgentsBehavior.writeDefinition(workspaceFs, {+ const workdirFs = fakeFs({});+ await claudeRepoAgentsBehavior.writeDefinition(workdirFs, {name: 'reviewer',description: 'Reviews diffs',tools: ['Read', 'Grep'],instructions: 'body',});- const raw = (await workspaceFs.read(defRel('reviewer'))) ?? '';+ const raw = (await workdirFs.read(defRel('reviewer'))) ?? '';expect(raw).toContain('tools: Read, Grep, mcp__switch');// Read-back strips the Switch rules so the form shows only the user's tools.- const attrs = await claudeRepoAgentsBehavior.readDefinition(workspaceFs, 'reviewer');+ const attrs = await claudeRepoAgentsBehavior.readDefinition(workdirFs, 'reviewer');expect(attrs?.tools).toEqual(['Read', 'Grep']);});it('strips the retired connector-plugin rules an older Switch Console wrote', async () => {- const workspaceFs = fakeFs({+ const workdirFs = fakeFs({[defRel('reviewer')]: ['---','name: reviewer',@@ -233,20 +233,20 @@ describe('claudeRepoAgentsBehavior.writeDefinition / readDefinition', () => {].join('\n'),});- const attrs = await claudeRepoAgentsBehavior.readDefinition(workspaceFs, 'reviewer');+ const attrs = await claudeRepoAgentsBehavior.readDefinition(workdirFs, 'reviewer');expect(attrs?.tools).toEqual(['Read']);// And it is not written back: only the rule Switch Console still authors is.- await claudeRepoAgentsBehavior.writeDefinition(workspaceFs, attrs ?? {});- const raw = (await workspaceFs.read(defRel('reviewer'))) ?? '';+ await claudeRepoAgentsBehavior.writeDefinition(workdirFs, attrs ?? {});+ const raw = (await workdirFs.read(defRel('reviewer'))) ?? '';expect(raw).toContain('tools: Read, mcp__switch\n');expect(raw).not.toContain('switch-connector');expect(raw).not.toContain('switch-channel');});it('serialises optional scalar, number, and boolean fields and omits empty ones', async () => {- const workspaceFs = fakeFs({});- await claudeRepoAgentsBehavior.writeDefinition(workspaceFs, {+ const workdirFs = fakeFs({});+ await claudeRepoAgentsBehavior.writeDefinition(workdirFs, {name: 'worker',description: 'line one\nline two',model: '',@@ -257,7 +257,7 @@ describe('claudeRepoAgentsBehavior.writeDefinition / readDefinition', () => {instructions: 'do work',});- const raw = (await workspaceFs.read(defRel('worker'))) ?? '';+ const raw = (await workdirFs.read(defRel('worker'))) ?? '';expect(raw).toContain('description: line one line two');expect(raw).toContain('color: blue');expect(raw).toContain('maxTurns: 5');@@ -265,7 +265,7 @@ describe('claudeRepoAgentsBehavior.writeDefinition / readDefinition', () => {expect(raw).not.toContain('model:');expect(raw).not.toContain('permissionMode:');- const attrs = await claudeRepoAgentsBehavior.readDefinition(workspaceFs, 'worker');+ const attrs = await claudeRepoAgentsBehavior.readDefinition(workdirFs, 'worker');expect(attrs).toMatchObject({ color: 'blue', maxTurns: 5, background: true, model: '' });});@@ -285,27 +285,27 @@ describe('claudeRepoAgentsBehavior.attributeFields', () => {describe('claudeRepoAgentsBehavior.removeLocal', () => {it('deletes the definition and the legacy per-agent settings', async () => {- const workspaceFs = fakeFs({+ const workdirFs = fakeFs({[defRel('reviewer')]: '---\nname: reviewer\ndescription: x\n---\n',[settingsRel('reviewer')]: '{"env":{}}',});- await claudeRepoAgentsBehavior.removeLocal(workspaceFs, 'reviewer');+ await claudeRepoAgentsBehavior.removeLocal(workdirFs, 'reviewer');- expect(await workspaceFs.exists(defRel('reviewer'))).toBe(false);- expect(await workspaceFs.exists(settingsRel('reviewer'))).toBe(false);+ expect(await workdirFs.exists(defRel('reviewer'))).toBe(false);+ expect(await workdirFs.exists(settingsRel('reviewer'))).toBe(false);});it('leaves the provider-neutral credentials to the caller, which removes them for every provider', async () => {const neutralRel = '.switch/agents/reviewer.json';- const workspaceFs = fakeFs({+ const workdirFs = fakeFs({[defRel('reviewer')]: '---\nname: reviewer\ndescription: x\n---\n',[neutralRel]: '{"env":{}}',});- await claudeRepoAgentsBehavior.removeLocal(workspaceFs, 'reviewer');+ await claudeRepoAgentsBehavior.removeLocal(workdirFs, 'reviewer');- expect(await workspaceFs.exists(neutralRel)).toBe(true);+ expect(await workdirFs.exists(neutralRel)).toBe(true);});});diff --git a/console/packages/plugins/src/agents/impl/claude/subagents.ts b/console/packages/plugins/src/agents/impl/claude/subagents.tsindex 1a62280a1..0c427a2f7 100644--- a/console/packages/plugins/src/agents/impl/claude/subagents.ts+++ b/console/packages/plugins/src/agents/impl/claude/subagents.ts@@ -408,12 +408,12 @@ function neutralSettingsRelPath(name: string): string {* yet migrated (CHOO-1440).*/async function readCredsObject(- workspaceFs: PluginFs,+ workdirFs: PluginFs,name: string): Promise<Record<string, unknown>> {- const neutral = await workspaceFs.read(neutralSettingsRelPath(name));+ const neutral = await workdirFs.read(neutralSettingsRelPath(name));if (neutral !== null) return parseSettingsObject(neutral);- return parseSettingsObject(await workspaceFs.read(settingsRelPath(name)));+ return parseSettingsObject(await workdirFs.read(settingsRelPath(name)));}function definitionRelPath(name: string): string {@@ -422,11 +422,11 @@ function definitionRelPath(name: string): string {/** Description/model from a subagent's definition, project scope then user scope. */async function readDefinitionMeta(- workspaceFs: PluginFs,+ workdirFs: PluginFs,homeFs: PluginFs,name: string): Promise<{ description: string | null; model: string | null }> {- const project = await workspaceFs.read(definitionRelPath(name));+ const project = await workdirFs.read(definitionRelPath(name));if (project !== null) {const fm = parseFrontmatter(project);return { description: fm.description, model: fm.model };@@ -440,27 +440,27 @@ async function readDefinitionMeta(}export const claudeRepoAgentsBehavior: IRepoAgentsBehavior = {- async discoverLocal(workspaceFs, homeFs): Promise<LocalRepoAgent[]> {+ async discoverLocal(workdirFs, homeFs): Promise<LocalRepoAgent[]> {// Names come from either credentials location — the neutral `.switch/agents`// dir and the legacy `.claude/switch-subagents` dir — so both migrated and// un-migrated installs are discovered (CHOO-1440). Plain agents' creds files// live in the neutral dir too (keyed by agent id, no `.claude/agents/<name>.md`// definition); a neutral file counts as a subagent only when it has a// definition, so those are filtered out here.- const neutralCandidates = (await workspaceFs.list(SWITCH_AGENT_SETTINGS_DIR))+ const neutralCandidates = (await workdirFs.list(SWITCH_AGENT_SETTINGS_DIR)).filter((entry) => entry.endsWith('.json')).map((entry) => entry.slice(0, -'.json'.length)).filter((name) => name.length > 0);const neutralNames: string[] = [];for (const name of neutralCandidates) {if (- (await workspaceFs.exists(definitionRelPath(name))) ||+ (await workdirFs.exists(definitionRelPath(name))) ||(await homeFs.exists(definitionRelPath(name)))) {neutralNames.push(name);}}- const legacyNames = (await workspaceFs.list(CLAUDE_SUBAGENTS.dirRelative))+ const legacyNames = (await workdirFs.list(CLAUDE_SUBAGENTS.dirRelative)).filter((entry) => entry.endsWith(CLAUDE_SUBAGENTS.settingsSuffix)).map((entry) => entry.slice(0, -CLAUDE_SUBAGENTS.settingsSuffix.length));const names = [...new Set([...neutralNames, ...legacyNames])]@@ -469,9 +469,9 @@ export const claudeRepoAgentsBehavior: IRepoAgentsBehavior = {return Promise.all(names.map(async (name) => {- const settings = await readCredsObject(workspaceFs, name);+ const settings = await readCredsObject(workdirFs, name);const env = (settings.env ?? {}) as Record<string, unknown>;- const { description, model } = await readDefinitionMeta(workspaceFs, homeFs, name);+ const { description, model } = await readDefinitionMeta(workdirFs, homeFs, name);return {name,description,@@ -483,8 +483,8 @@ export const claudeRepoAgentsBehavior: IRepoAgentsBehavior = {);},- async discoverDefinitions(workspaceFs): Promise<RepoAgentDefinition[]> {- const entries = await workspaceFs.list(CLAUDE_SUBAGENTS.definitionsDirRelative);+ async discoverDefinitions(workdirFs): Promise<RepoAgentDefinition[]> {+ const entries = await workdirFs.list(CLAUDE_SUBAGENTS.definitionsDirRelative);const files = entries.filter((entry) => entry.endsWith(MD_SUFFIX)).sort((a, b) => a.localeCompare(b));@@ -492,10 +492,10 @@ export const claudeRepoAgentsBehavior: IRepoAgentsBehavior = {return Promise.all(files.map(async (file) => {const content =- (await workspaceFs.read(`${CLAUDE_SUBAGENTS.definitionsDirRelative}/${file}`)) ?? '';+ (await workdirFs.read(`${CLAUDE_SUBAGENTS.definitionsDirRelative}/${file}`)) ?? '';const fm = parseFrontmatter(content);const name = fm.name ?? file.slice(0, -MD_SUFFIX.length);- const registered = await workspaceFs.exists(settingsRelPath(name));+ const registered = await workdirFs.exists(settingsRelPath(name));return {name,description: fm.description,@@ -520,8 +520,8 @@ export const claudeRepoAgentsBehavior: IRepoAgentsBehavior = {];},- async readLaunchEnv(workspaceFs, agentName): Promise<Record<string, string>> {- const settings = await readCredsObject(workspaceFs, agentName);+ async readLaunchEnv(workdirFs, agentName): Promise<Record<string, string>> {+ const settings = await readCredsObject(workdirFs, agentName);const env = (settings.env ?? {}) as Record<string, unknown>;const result: Record<string, string> = {};for (const key of SWITCH_ENV_KEYS) {@@ -547,13 +547,13 @@ export const claudeRepoAgentsBehavior: IRepoAgentsBehavior = {return launchDefinitionFor(attributes);},- async writeDefinition(workspaceFs, attributes: RepoAgentAttributes): Promise<void> {+ async writeDefinition(workdirFs, attributes: RepoAgentAttributes): Promise<void> {const name = toScalar(attributes.name);- await workspaceFs.write(definitionRelPath(name), serializeDefinition(attributes));+ await workdirFs.write(definitionRelPath(name), serializeDefinition(attributes));},- async readDefinition(workspaceFs, name): Promise<RepoAgentAttributes | null> {- const content = await workspaceFs.read(definitionRelPath(name));+ async readDefinition(workdirFs, name): Promise<RepoAgentAttributes | null> {+ const content = await workdirFs.read(definitionRelPath(name));if (content === null) return null;const fields = parseFrontmatterFields(content);@@ -585,8 +585,8 @@ export const claudeRepoAgentsBehavior: IRepoAgentsBehavior = {return attributes;},- async removeLocal(workspaceFs, name): Promise<void> {- await workspaceFs.delete(definitionRelPath(name));- await workspaceFs.delete(settingsRelPath(name));+ async removeLocal(workdirFs, name): Promise<void> {+ await workdirFs.delete(definitionRelPath(name));+ await workdirFs.delete(settingsRelPath(name));},};diff --git a/core/switch_core/bridges/agent/api/activity_routes.py b/core/switch_core/bridges/agent/api/activity_routes.pyindex 27b47589c..e2e8060b5 100644--- a/core/switch_core/bridges/agent/api/activity_routes.py+++ b/core/switch_core/bridges/agent/api/activity_routes.py@@ -24,16 +24,20 @@ from switch_core.bridges.agent.dependencies import (from switch_core.db.models import Agent, ApprovalRequestfrom switch_core.session_activity.service import (MAX_DETAIL_CHARS,+ MAX_MODEL_CHARS,+ MAX_MODELS_PER_TURN,MAX_OPTIONS,MAX_QUESTION_OPTIONS,MAX_QUESTIONS,MAX_TEXT_CHARS,MAX_TITLE_CHARS,+ MAX_TOKENS,ApprovalOption,Decision,Question,QuestionOption,SessionActivityService,+ TokenSpend,)from switch_core.telemetry import TelemetryServicefrom switch_core.telemetry.session_start import (@@ -50,14 +54,6 @@ Limiter = Annotated[SessionStartLimiter, Depends(get_session_start_limiter)]_Id = Annotated[str, Field(min_length=1, max_length=200)]-# Per-tenant usage metering was removed, but shipped Switch Console 0.37 still-# posts a `usage` array on every activity report and `ActivityReport` forbids-# extra fields, so the schema is kept only to accept those reports; the value-# is validated and then discarded.-_MAX_MODEL_CHARS = 200-_MAX_MODELS_PER_TURN = 50-_MAX_TOKENS = 2**53 - 1-class SessionStart(BaseModel):model_config = ConfigDict(extra="forbid")@@ -72,11 +68,11 @@ class SessionStartReceipt(BaseModel):class TokenUsageIn(BaseModel):model_config = ConfigDict(extra="forbid")- model: str = Field(max_length=_MAX_MODEL_CHARS)- input_tokens: int = Field(ge=0, le=_MAX_TOKENS)- output_tokens: int = Field(ge=0, le=_MAX_TOKENS)- cache_read_tokens: int = Field(ge=0, le=_MAX_TOKENS)- cache_write_tokens: int = Field(ge=0, le=_MAX_TOKENS)+ model: str = Field(max_length=MAX_MODEL_CHARS)+ input_tokens: int = Field(ge=0, le=MAX_TOKENS)+ output_tokens: int = Field(ge=0, le=MAX_TOKENS)+ cache_read_tokens: int = Field(ge=0, le=MAX_TOKENS)+ cache_write_tokens: int = Field(ge=0, le=MAX_TOKENS)class ActivityReport(BaseModel):@@ -95,9 +91,9 @@ class ActivityReport(BaseModel):thread_id: _Id | Nonemessage_id: _Id | Noneoccurred_at: datetime- # Accepted from Switch Console 0.37 and ignored; see the note above.+ # Hosts that predate usage reporting do not send it.usage: list[TokenUsageIn] = Field(- default_factory=list, max_length=_MAX_MODELS_PER_TURN+ default_factory=list, max_length=MAX_MODELS_PER_TURN)@@ -218,6 +214,16 @@ async def report_activity(thread_id=body.thread_id,message_id=body.message_id,occurred_at=body.occurred_at,+ usage=[+ TokenSpend(+ model=u.model,+ input_tokens=u.input_tokens,+ output_tokens=u.output_tokens,+ cache_read_tokens=u.cache_read_tokens,+ cache_write_tokens=u.cache_write_tokens,+ )+ for u in body.usage+ ],)return ActivityReceipt(recorded=recorded)diff --git a/core/switch_core/bridges/agent/api/handlers.py b/core/switch_core/bridges/agent/api/handlers.pyindex a1bebd5e4..1e96064ba 100644--- a/core/switch_core/bridges/agent/api/handlers.py+++ b/core/switch_core/bridges/agent/api/handlers.py@@ -105,6 +105,7 @@ from switch_core.bridges.agent.registration_bootstrap import (REGISTRATION_KEY_TYPES,resolve_registration_owner_id,)+from switch_core.budgets import BudgetExceededfrom switch_core.db.models import Agent, Taskfrom switch_core.db.stores.api_key_store import ApiKeyStorefrom switch_core.db.stores.feature_flag_store import FeatureFlagStore@@ -463,6 +464,8 @@ async def send_message(logger.debug("Recieved message from agent %s: %s", agent.name, req.content)try:event_id = await protocol.send_message(agent.id, req.room_id, req.content)+ except BudgetExceeded as e:+ raise HTTPException(status_code=429, detail=str(e)) from eexcept ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from eexcept PermissionError as e:@@ -549,6 +552,8 @@ async def upload_media(caption=caption,thread_id=thread_id,)+ except BudgetExceeded as e:+ raise HTTPException(status_code=429, detail=str(e)) from eexcept ValueError as e:raise HTTPException(status_code=400, detail=str(e)) from eexcept PermissionError as e:@@ -1297,6 +1302,8 @@ async def delegate_task(description=req.description,)task = await protocol.get_task(agent.id, result.task_id)+ except BudgetExceeded as e:+ raise HTTPException(status_code=429, detail=str(e)) from eexcept ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from eexcept PermissionError as e:diff --git a/core/switch_core/bridges/agent/api/operations.py b/core/switch_core/bridges/agent/api/operations.pyindex af547f55f..53fc928c9 100644--- a/core/switch_core/bridges/agent/api/operations.py+++ b/core/switch_core/bridges/agent/api/operations.py@@ -34,6 +34,7 @@ from switch_core.bridges.agent.operations.callctx import ()from switch_core.bridges.agent.protocol.connections import UnknownConnectionErrorfrom switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.budgets import BudgetExceededfrom switch_core.db.models import Agentlogger = logging.getLogger(__name__)@@ -238,6 +239,8 @@ async def post_operation(raise HTTPException(status_code=404, detail=str(exc)) from excexcept BadArgumentsError as exc:raise HTTPException(status_code=400, detail=str(exc)) from exc+ except BudgetExceeded as exc:+ raise HTTPException(status_code=429, detail=str(exc)) from excexcept PermissionError as exc:raise HTTPException(status_code=403, detail=str(exc)) from excexcept ValueError as exc:diff --git a/core/switch_core/bridges/agent/operations/definitions.py b/core/switch_core/bridges/agent/operations/definitions.pyindex 64edffc89..10c3274c6 100644--- a/core/switch_core/bridges/agent/operations/definitions.py+++ b/core/switch_core/bridges/agent/operations/definitions.py@@ -2216,8 +2216,10 @@ async def update_room(bridge instead of provisioning a new one — e.g. to move a roomback onto a channel it previously used (channels are left in placeon a bridge change, so the old one still exists). The id must be a- real channel on the target bridge whose bridge bot is a member.- Ignored unless `bridge_id` is given.+ real channel on the target bridge whose bridge bot is a member,+ and one the bridge serves: a channel belonging to another Discord+ server than the bridge's is refused. Ignored unless `bridge_id` is+ given.aliases: Per-room agent aliases to set, keyed by agent name → alias.`@<alias>` then addresses that agent in the room like its realname. Pass an empty string ("") as the value to clear an agent'sdiff --git a/core/switch_core/bridges/agent/protocol/service.py b/core/switch_core/bridges/agent/protocol/service.pyindex 5b738ae11..be7d9cce5 100644--- a/core/switch_core/bridges/agent/protocol/service.py+++ b/core/switch_core/bridges/agent/protocol/service.py@@ -58,6 +58,7 @@ from switch_core.bridges.agent.registration_bootstrap import (resolve_registration_owner_id,)from switch_core.bridges.resource.service import ResourceService+from switch_core.budgets import BudgetGuardfrom switch_core.clients.admin_messages import PLATFORM_MARKER as _PLATFORM_MARKERfrom switch_core.clients.admin_messages import (platform_on_behalf_of,@@ -79,6 +80,7 @@ from switch_core.db.models import (Task,Tool,User,+ require_tenant_id,)from switch_core.db.session_scope import tenant_sessionfrom switch_core.db.stores.agent_runtime_state_store import (@@ -87,6 +89,7 @@ from switch_core.db.stores.agent_runtime_state_store import (from switch_core.db.stores.agent_runtime_state_store import (AgentRuntimeStateStore,)+from switch_core.db.stores.budget_store import BudgetStorefrom switch_core.db.stores.message_store import MessageStorefrom switch_core.db.stores.room_group_store import RoomGroupStorefrom switch_core.db.stores.room_role_store import RoomRoleStore@@ -289,6 +292,7 @@ class ProtocolService:self.room_role_store = RoomRoleStore()self.room_group_store = RoomGroupStore()self.message_store = MessageStore()+ self.budget_guard = BudgetGuard(BudgetStore())self.user_store = UserStore()self.room_store = room_storeself.room_service = room_service@@ -993,9 +997,23 @@ class ProtocolService:async def require_room_member(self, agent_id: str, room_id: str) -> RoomDescriptor:"""Get room and verify agent is a member. Raises PermissionError if not."""async with self.session_factory() as session:- found = await self.room_store.get_with_membership(- session, room_id, agent_id+ return await self._room_member_in(session, agent_id, room_id)++ async def require_room_poster(self, agent_id: str, room_id: str) -> RoomDescriptor:+ """`require_room_member`, and raise `BudgetExceeded` if the agent has+ reached a budget covering it. One session for both, so a post still+ costs one pool checkout."""+ async with self.session_factory() as session:+ room = await self._room_member_in(session, agent_id, room_id)+ await self.budget_guard.require_within(+ session, tenant_id=require_tenant_id(), agent_id=agent_id)+ return room++ async def _room_member_in(+ self, session: AsyncSession, agent_id: str, room_id: str+ ) -> RoomDescriptor:+ found = await self.room_store.get_with_membership(session, room_id, agent_id)if found is None:raise ValueError(f"Room not found: {room_id}")room, is_member = found@@ -1143,7 +1161,7 @@ class ProtocolService:bridges — the resource manager isn't a bridge participant, so its ownnotices wouldn't reach Slack/Mattermost."""try:- await client.send_message(matrix_room_id, body)+ await client.send_message(matrix_room_id, body, metered=False)except Exception:logger.exception("Failed to post agent activity notice to %s", matrix_room_id@@ -1196,7 +1214,7 @@ class ProtocolService:logger.debug("[AGENT-MSG] agent=%s room=%s content=%s", agent_id, room_id, content[:80])- room = await self.require_room_member(agent_id, room_id)+ room = await self.require_room_poster(agent_id, room_id)client = self.client_lifecycle.get_by_agent_id(agent_id)if client is None:raise ValueError("Agent client not running")@@ -1206,7 +1224,10 @@ class ProtocolService:client, room.matrix_room_id, thread_id)event_id = await client.send_message(- room.matrix_room_id, content, thread_root_id=thread_root_id+ room.matrix_room_id,+ content,+ thread_root_id=thread_root_id,+ metered=True,)if event_id is None:raise ValueError("Failed to send message")@@ -1268,7 +1289,7 @@ class ProtocolService:f"attachment '{filename}' is {len(data)} bytes, over the "f"{max_bytes}-byte limit (AGENT_MEDIA_MAX_BYTES)")- room = await self.require_room_member(agent_id, room_id)+ room = await self.require_room_poster(agent_id, room_id)client = self.client_lifecycle.get_by_agent_id(agent_id)if client is None:raise ValueError("Agent client not running")@@ -1300,6 +1321,7 @@ class ProtocolService:if group_id is not Noneelse None),+ metered=True,)if event_id is None:raise ValueError(f"Failed to send media message for '{filename}'")@@ -1567,7 +1589,9 @@ class ProtocolService:client = self.client_lifecycle.get_by_agent_id(agent_id)if client is None:raise ValueError("Agent client not running")- await client.send_message(room.matrix_room_id, f"*{detail}*", format="markdown")+ await client.send_message(+ room.matrix_room_id, f"*{detail}*", format="markdown", metered=True+ )async def set_runtime_state(self,@@ -2146,9 +2170,10 @@ class ProtocolService:"""Delegate a task from one agent to another.Returns task_id and the performer's reachability status at delegation time.- Raises ValueError if agents or room not found, or agents not in room.+ Raises ValueError if agents or room not found, or agents not in room,+ and `BudgetExceeded` if either agent has reached a budget covering it."""- room = await self.require_room_member(requester_id, room_id)+ room = await self.require_room_poster(requester_id, room_id)async with self.session_factory() as session:performer = await self.agent_store.get(session, performer_id)@@ -2170,6 +2195,9 @@ class ProtocolService:group_id=room_row.group_id if room_row is not None else None,sender_agent_id=requester_id,)+ await self.budget_guard.require_within(+ session, tenant_id=require_tenant_id(), agent_id=performer_id+ )async with self.session_factory() as session:task = Task(@@ -2299,7 +2327,9 @@ class ProtocolService:"outcome": outcome,},)- await client.send_message(room.matrix_room_id, outcome, format="markdown")+ await client.send_message(+ room.matrix_room_id, outcome, format="markdown", metered=True+ )async def cancel_task(self, agent_id: str, task_id: str, reason: str) -> None:"""Cancel a task (requester only)."""diff --git a/core/switch_core/bridges/collaboration/adapter.py b/core/switch_core/bridges/collaboration/adapter.pyindex 3abee0639..977d19549 100644--- a/core/switch_core/bridges/collaboration/adapter.py+++ b/core/switch_core/bridges/collaboration/adapter.py@@ -1,11 +1,12 @@from __future__ import annotationsimport logging+import mathfrom abc import ABC, abstractmethodfrom collections.abc import Awaitable, Callablefrom dataclasses import dataclass, fieldfrom datetime import datetime-from typing import Any, ClassVar, Literal+from typing import Any, ClassVar, Literal, Protocol, runtime_checkablefrom switch_core.agent_display_name import defuse_label_markupfrom switch_core.agent_icon import default_icon_url@@ -192,6 +193,31 @@ class RichContentFailed(Exception):self.text = text+class ChannelNotBindable(ValueError):+ """A room was asked to bind to a channel that is not this bridge's to bind.++ A `ValueError` because it is the caller's input that is wrong, and every+ path that binds a channel already answers those as a bad request.+ """+++class DirectorySearchBusy(RuntimeError):+ """The platform's directory is being searched too often to take one more.++ Refused at once rather than queued: a search is someone waiting on a+ dialog, and one that sat behind a spent budget would only time out later.+ A `RuntimeError`, so anything that reads directory failures as the+ platform's still does.+ """++ def __init__(self, retry_after: float) -> None:+ super().__init__(+ "Too many directory searches right now — try again in "+ f"{math.ceil(retry_after)} seconds"+ )+ self.retry_after = retry_after++class RemovalFailed(Exception):"""A published message could not be taken back, or not provably.@@ -279,6 +305,27 @@ class ActivityMarkRefused(RuntimeError):ActivityMark = Literal["working", "queued"]+@runtime_checkable+class SupportsSharedConnection(Protocol):+ """An adapter that runs on a shared, deployment-level connection it does not+ own, attached after it starts rather than dialled at start.++ A distributed bridge (currently only Discord) starts inert and is handed the+ one shared connection once it is up — at boot for installs that already+ exist, and lazily on first event for one added at runtime. Attaching also+ re-runs whatever start-time work needed the connection (agent identities).++ Structural on purpose: the lifecycle, the gateway and boot narrow to this+ with `isinstance` and stay ignorant of the concrete adapter, and an adapter+ with no shared connection (Slack, Mattermost, Teams, Telegram) never matches+ and is left alone.+ """++ def attach_shared_connection(self, connection: Any) -> None: ...++ def set_on_attached(self, callback: Callable[[], None]) -> None: ...++class CollaborationAdapter(ABC):#: Whether this platform draws agents' session activity: each turn step by#: step, and the approval and question cards a session waits on.@@ -1119,6 +1166,23 @@ class CollaborationAdapter(ABC):missing. Markdown-free plain text; None when there is nothing to add."""return None+ async def require_bindable_channel(self, channel_id: str) -> None:+ """Refuse a channel id someone asked to bind a room to, unless it is+ this bridge's own.++ Asked before a room is bound to an existing channel by id, when a room+ is created or moved, and never for a channel the platform delivered to+ this bridge. The id is the caller's, and binding decides where the+ room's messages are posted.++ Nothing to refuse by default: a bridge whose credential is its own can+ reach only what that credential reaches. A bridge on a connection+ shared between organisations can reach every organisation's channels,+ so being able to see one says nothing about whose it is, and it has to+ say here which are its own. Raises `ChannelNotBindable`.+ """+ return None+@abstractmethodasync def get_channel_type(self, channel_id: str) -> ChannelType: ...diff --git a/core/switch_core/bridges/collaboration/bridge_core.py b/core/switch_core/bridges/collaboration/bridge_core.pyindex f22df2487..4b093742d 100644--- a/core/switch_core/bridges/collaboration/bridge_core.py+++ b/core/switch_core/bridges/collaboration/bridge_core.py@@ -19,6 +19,7 @@ from switch_core.bridges.agent.commands import stop_control_framefrom switch_core.bridges.collaboration.adapter import (AgentPresentation,CollaborationAdapter,+ SupportsSharedConnection,)from switch_core.bridges.collaboration.models import (ChannelType,@@ -386,6 +387,12 @@ class BridgeCore:await self._load_existing_puppets()self._adapter.set_channel_migration_handler(self._handle_channel_migrated)self._adapter.set_agent_presentation_resolver(self._agent_presentation)+ # A bridge on a shared connection that started before the connection+ # was up is attached later (when it comes up, or on its first event).+ # Provisioning that ran at start unattached would have failed, so it is+ # re-run on attach.+ if isinstance(self._adapter, SupportsSharedConnection):+ self._adapter.set_on_attached(self._provision_identities_on_attach)if self._approval_answers is not None:self._adapter.set_interaction_handler(self._traced("interaction", self._handle_inbound_interaction)@@ -498,6 +505,28 @@ class BridgeCore:if client:self._puppet_matrix_ids.add(client.matrix_user_id)+ def _provision_identities_on_attach(self) -> None:+ """Re-run identity provisioning when a shared connection attaches.++ The start-time run failed for a shared bridge because it had no+ connection yet. Attaching gives it one, so provision now — a fresh+ background task, not awaited, for the same reason `start` gives.++ Guarded against overwriting a still-running task. The start-time run+ spends most of its life in the agent read (`_create_agent_identities`+ awaits `get_all` before the per-agent loop), so an attach during that+ window must not spawn a second provisioner: two concurrent+ `create_agent_identity` calls can double a role through its+ check-then-create window, and overwriting the handle would orphan the+ task `stop` cancels. If the start-time task is still going it will reach+ the per-agent loop against the now-attached connection and provision+ itself; if it has finished — the usual case, since the per-agent loop+ fails fast while unattached — this replaces the completed handle.+ """+ if self._identity_task is not None and not self._identity_task.done():+ return+ self._identity_task = asyncio.create_task(self._run_agent_identities())+async def _run_agent_identities(self) -> None:"""Wrapper for the background provisioning task.@@ -810,6 +839,7 @@ class BridgeCore:content,format="markdown",thread_root_id=thread_root_id,+ metered=True,)if event_id is None:logger.error(@@ -859,6 +889,7 @@ class BridgeCore:if group_id is not Noneelse None),+ metered=True,)if event_id is None:logger.error(diff --git a/core/switch_core/bridges/collaboration/discord/adapter.py b/core/switch_core/bridges/collaboration/discord/adapter.pyindex 609aad61a..3040d28b3 100644--- a/core/switch_core/bridges/collaboration/discord/adapter.py+++ b/core/switch_core/bridges/collaboration/discord/adapter.py@@ -1,6 +1,5 @@from __future__ import annotations-import asyncioimport hashlibimport ioimport logging@@ -10,11 +9,11 @@ from collections.abc import Awaitable, Callable, Coroutinefrom contextvars import ContextVarfrom dataclasses import replacefrom datetime import UTC, datetime, timedelta-from typing import Any, ClassVar+from typing import Any, ClassVar, Literalimport discord-from discord import app_commands-from pydantic import Field+from pydantic import Field, model_validator+from pydantic.json_schema import SkipJsonSchemafrom switch_core.bridges.agent.commands import COMMANDS_BY_NAMEfrom switch_core.bridges.agent.commands import Command as InRoomCommand@@ -22,6 +21,7 @@ from switch_core.bridges.collaboration.adapter import (ActivityMark,ActivityMarkRefused,ActivitySnapshot,+ ChannelNotBindable,CollaborationAdapter,RemovalFailed,RequestCard,@@ -35,6 +35,7 @@ from switch_core.bridges.collaboration.discord.chunking import (MAX_MESSAGE,chunk_message,)+from switch_core.bridges.collaboration.discord.connection import DiscordConnectionfrom switch_core.bridges.collaboration.discord.slash import (SlashArgError,build_app_commands,@@ -85,7 +86,13 @@ _WEBHOOK_NAME = "Switch Bridge"# when the only record left to read is the channel history._PUBLICATION_WEBHOOK_NAME = "Switch Sessions"-_READY_TIMEOUT = 30.0+# Message types we treat as real posts: plain messages and replies. Everything+# else (pins, joins, boosts, thread starters, …) is skipped. Module-level so the+# shared Gateway client can drop them before it spends a tenant resolution on+# them, and the per-guild adapter drops the same set again on its own path.+ALLOWED_MESSAGE_TYPES = frozenset(+ {discord.MessageType.default, discord.MessageType.reply}+)# Put on the message an agent is working on for as long as its turn lasts._REACTION: dict[ActivityMark, str] = {"working": "👀", "queued": "⏳"}@@ -421,8 +428,26 @@ class _WebhookIdentity:class DiscordConnectionConfig(BridgeConnectionConfig):- bot_token: str+ #: Optional because it depends on `event_delivery`, which the validator+ #: below enforces: the self-registered bridge opens its own connection and+ #: needs a token; the distributed bridge routes through the one shared+ #: connection and carries none — its token is deployment config.+ bot_token: str | None = Noneguild_id: str+ #: How this bridge's events reach it, and which is decided by which Discord+ #: app the install came from rather than by an operator's preference.+ #:+ #: `own_connection` is the self-registered app: Switch opens a Gateway+ #: connection scoped to this guild with the token above. `shared` is the+ #: distributed app: the bridge opens nothing and registers its guild with+ #: the one deployment-level connection instead, so it holds no token.+ #:+ #: Hidden from the registration form because it is not a question the+ #: operator filling that form can be asked: reaching the form means the+ #: self-registered app, and the shared value is written by the install flow.+ event_delivery: SkipJsonSchema[Literal["own_connection", "shared"]] = (+ "own_connection"+ )# Both registration forms build themselves from this schema, so what is# written here is the only explanation an operator gets next to the# checkbox.@@ -435,6 +460,29 @@ class DiscordConnectionConfig(BridgeConnectionConfig):),)+ @model_validator(mode="after")+ def _token_matches_delivery(self) -> DiscordConnectionConfig:+ """Refuse the two half-states that look configured and cannot work.++ An own-connection bridge with no bot token opens no Gateway connection,+ so it would receive nothing — the silent failure the token is there to+ prevent. A shared bridge carrying a token is the opposite mistake: a+ credential for a connection this bridge does not own, read as evidence+ that it does.+ """+ if self.event_delivery == "own_connection" and not self.bot_token:+ raise ValueError(+ "bot_token is required: without it Switch opens no Gateway "+ "connection and this bridge would receive no Discord events."+ )+ if self.event_delivery == "shared" and self.bot_token:+ raise ValueError(+ "bot_token must be empty for a shared-connection bridge; the "+ "distributed Discord app's token is deployment config, not "+ "this install's."+ )+ return self+class DiscordAdapter(CollaborationAdapter):"""Discord collaboration bridge adapter.@@ -502,10 +550,33 @@ class DiscordAdapter(CollaborationAdapter):super().__init__()self._config = configself._guild_id = int(config.guild_id)- self._client: discord.Client | None = None- self._tree: app_commands.CommandTree[Any] | None = None- self._connect_task: asyncio.Task[None] | None = None- self._bot_user_id: int = 0+ # The Gateway socket lives on the connection, not the adapter: the+ # socket is per bot token and the adapter is per guild. Intents are+ # built here and handed over, so the socket owner does not decide them.+ #+ # A self-registered bridge owns its connection, built now from its+ # token. A distributed (shared-delivery) bridge owns none: it is inert+ # until it is attached to the one deployment-level connection, which is+ # not built yet — so `_connection` stays None and every outbound path+ # fails loud through `_require_connection` rather than pretending.+ #+ # Ownership is recorded here, not inferred from `_connection` later: once+ # a shared bridge is attached, `_connection` points at the deployment's+ # one shared socket, and `stop()` must detach from it rather than close+ # it — closing it would drop every other tenant's Discord traffic too.+ self._owns_connection = config.event_delivery == "own_connection"+ self._connection: DiscordConnection | None = None+ if self._owns_connection:+ assert config.bot_token is not None # guaranteed by the validator+ self._connection = DiscordConnection(+ bot_token=config.bot_token,+ intents=self._build_intents(),+ command_guild_id=self._guild_id,+ )+ # Fired the moment a shared connection is attached, so the start-time+ # work that needed it (agent-identity provisioning) can re-run. Set by+ # BridgeCore; None on an own-connection bridge, which is never attached.+ self._on_attached: Callable[[], None] | None = None# (channel id, webhook name) -> webhook the bridge posts through there.self._webhooks: dict[tuple[int, str], discord.Webhook] = {}# Ids of webhooks the bridge has minted/adopted, for echo dropping.@@ -553,104 +624,44 @@ class DiscordAdapter(CollaborationAdapter):self._on_user_joined = on_user_joinedself._on_app_joined = on_app_joined- intents = discord.Intents.none()- intents.guilds = True- intents.guild_messages = True- intents.dm_messages = True- intents.message_content = True- intents.members = True-- client = discord.Client(intents=intents)- client.event(self._make_on_message())- # Presses on a card's buttons. Registered alongside the command tree- # rather than through it: the tree is handed application-command- # interactions only, and a component interaction is dispatched as the- # plain `interaction` event whether or not anything is listening.- client.event(self._make_on_interaction())- self._tree = app_commands.CommandTree(client)- guild = discord.Object(id=self._guild_id)- for app_command in build_app_commands(self._handle_slash_command):- # Bound to the guild, not global — see _sync_slash_commands. Adding- # them globally here would leave the guild-scoped sync below with an- # empty payload, registering nothing at all.- self._tree.add_command(app_command, guild=guild)- self._client = client-- await client.login(self._config.bot_token)- self._connect_task = asyncio.create_task(- client.connect(), name=f"discord-gateway-{self._config.guild_id}"- )- ready = asyncio.ensure_future(client.wait_until_ready())- done, _ = await asyncio.wait(- {ready, self._connect_task},- timeout=_READY_TIMEOUT,- return_when=asyncio.FIRST_COMPLETED,- )- if self._connect_task in done:- ready.cancel()- exc = self._connect_task.exception()- raise RuntimeError("Discord gateway connection failed") from exc- if ready not in done:- ready.cancel()- await self.stop()- raise RuntimeError(f"Discord gateway not ready after {_READY_TIMEOUT:.0f}s")-- assert client.user is not None- self._bot_user_id = client.user.id- logger.info(- "Discord adapter connected as %s (guild %s)",- client.user,- self._config.guild_id,- )- await self._sync_slash_commands()-- async def _sync_slash_commands(self) -> None:- """Publish the in-room command set as guild-scoped application commands.-- Guild-scoped rather than global, because the adapter is single-guild by- construction (`DiscordConnectionConfig.guild_id` is required and every- lookup is scoped to it). Guild commands also apply immediately, where- global ones propagate for up to an hour, and global registration is- per-application — so on an instance running several Discord bridges it- would leak each bridge's commands into the others' guilds, where they- could only fail. Syncing is a bulk overwrite, so re-running it on every- start reconciles renames and removals rather than accumulating them.-- Any sync failure is logged and left non-fatal — hence the broad catch:- the bridge still works over `!`-commands and messages, and dropping the- whole bridge over a missing `applications.commands` scope is a worse- outcome than running without the slash surface. The degradation is- visible in the logs rather than silent.- """- if self._tree is None:- return- try:- synced = await self._tree.sync(guild=discord.Object(id=self._guild_id))- except Exception:- logger.exception(- "Failed to sync Discord slash commands for guild %s — the bridge "- "will run without them (check the bot's applications.commands scope)",+ if self._config.event_delivery == "shared":+ # Inert: a shared-delivery bridge opens no connection of its own and+ # is not yet attached to the shared one. It exists as a bridge — its+ # rooms, the operator's list, moderation — but neither sends nor+ # receives until the shared Gateway connection is built and hands it+ # its guild. The callbacks are kept for that moment.+ logger.info(+ "Discord bridge for guild %s registered inert (shared delivery); "+ "awaiting the shared Gateway connection",self._config.guild_id,)return++ # One guild, one handler; the DM handler is the same adapter so direct+ # messages still reach it. The connection routes each message by guild+ # id, which for a single-guild bridge is exactly the old filter.+ conn = self._require_connection()+ conn.register_message_handler(self._guild_id, self._handle_message)+ conn.set_dm_handler(self._handle_message)+ conn.set_interaction_handler(self._make_on_interaction())+ await conn.connect(+ commands=build_app_commands(self._handle_slash_command),+ )logger.info(- "Synced %d Discord slash commands to guild %s",- len(synced),+ "Discord adapter connected as %s (guild %s)",+ conn.client.user,self._config.guild_id,)- def _make_on_message(- self,- ) -> Callable[[discord.Message], Coroutine[Any, Any, None]]:- # client.event registers by function __name__, so hand it a closure- # named exactly like the gateway event.- async def on_message(message: discord.Message) -> None:- try:- await self._handle_message(message)- except Exception:- logger.exception("Failed to handle inbound Discord message")-- return on_message+ @staticmethod+ def _build_intents() -> discord.Intents:+ intents = discord.Intents.none()+ intents.guilds = True+ intents.guild_messages = True+ intents.dm_messages = True+ intents.message_content = True+ intents.members = True+ return intentsdef _make_on_interaction(self,@@ -664,29 +675,91 @@ class DiscordAdapter(CollaborationAdapter):return on_interactionasync def stop(self) -> None:- if self._client:- try:- await self._client.close()- except Exception:- pass- task = self._connect_task- self._connect_task = None- if task:- task.cancel()- try:- await task- except (asyncio.CancelledError, Exception):- pass- self._client = None- self._tree = None+ # Only an own-connection bridge closes the socket, because only it owns+ # one. A shared-delivery bridge detaches from the shared socket instead:+ # closing it here would take down every other tenant's Discord traffic,+ # and dropping the reference lets a restarted bridge re-attach to the+ # live connection on its next event rather than hold a stale one.+ if self._owns_connection:+ if self._connection is not None:+ await self._connection.close()+ else:+ self._connection = Noneself._webhooks.clear()self._owned_webhooks.clear()logger.info("Discord adapter stopped")+ def set_on_attached(self, callback: Callable[[], None]) -> None:+ self._on_attached = callback++ def attach_shared_connection(self, connection: DiscordConnection) -> None:+ """Attach the shared Gateway connection to an inert shared bridge.++ A shared-delivery bridge is built inert (no connection of its own); the+ deployment-level Gateway client injects its connection here so the+ adapter's inbound handling and its outbound posting both run against it.+ A bridge started while the connection is up is attached as it starts,+ before anything in it runs; the rest are attached when the connection+ first comes up, and an event reaching a bridge attaches it too, as a+ backstop. An attach after start fires `_on_attached`, which re-runs the+ start-time provisioning that needed the connection (agent identities).+ Idempotent and set-once: an own-connection bridge already has one and+ is left alone, and repeated calls after the first are no-ops.+ """+ if self._connection is not None:+ return+ self._connection = connection+ if self._on_attached is not None:+ self._on_attached()++ async def dispatch_inbound(self, message: discord.Message) -> None:+ """Handle one inbound Gateway message the shared client routed here.++ The shared connection resolves a guild to this bridge and calls this;+ the self-registered connection calls the same handler directly. Kept a+ thin public entry so the shared client does not reach into the adapter.+ """+ await self._handle_message(message)++ async def dispatch_slash(+ self,+ interaction: discord.Interaction,+ command: InRoomCommand,+ values: dict[str, Any],+ ) -> None:+ """Handle one slash invocation the shared client routed here by guild.++ The self-registered connection reaches the same handler through the+ command tree it owns; the shared connection registers commands globally+ and routes each invocation to the bridge its guild resolves to.+ """+ await self._handle_slash_command(interaction, command, values)++ async def dispatch_interaction(self, interaction: discord.Interaction) -> None:+ """Handle one press on a card's button the shared client routed here.++ The self-registered connection calls the same handler directly; the+ shared connection receives every guild's presses and routes each by+ guild, as it does slash invocations.+ """+ await self._handle_interaction(interaction)++ def _require_connection(self) -> DiscordConnection:+ """The bridge's Gateway connection, or a loud error if it has none.++ A shared-delivery bridge is inert until it is attached to the shared+ connection; reaching an outbound path before that is a bug, and this+ surfaces it rather than letting the call no-op or crash obscurely.+ """+ if self._connection is None:+ raise RuntimeError(+ "this Discord bridge uses shared delivery and is not attached to "+ "the shared Gateway connection yet"+ )+ return self._connection+def _require_client(self) -> discord.Client:- if self._client is None:- raise RuntimeError("Discord client not connected")- return self._client+ return self._require_connection().client# ── Messaging ────────────────────────────────────────────────────────────@@ -1680,7 +1753,7 @@ class DiscordAdapter(CollaborationAdapter):finding the webhook that posted the card, are both steps before thedeletion; a 404 from either is about the step, not about the card."""- if self._client is None:+ if self._require_connection().client_or_none is None:raise RemovalFailed("Discord client not connected.")location_id, message_id = self._parse_message_ref(message_ref)@@ -1845,7 +1918,7 @@ class DiscordAdapter(CollaborationAdapter):channel_id,)return None- client = self._client+ client = self._require_connection().client_or_noneif client is None:logger.warning("Cannot look for card %s in Discord channel %s: not connected.",@@ -1937,7 +2010,7 @@ class DiscordAdapter(CollaborationAdapter):"""parent = getattr(place, "parent", None) or placeif self._channel_type_of(parent) == "lobby":- return self._bot_user_id or None+ return self._require_connection().bot_user_id or Nonetry:return (await self._publication_webhook(parent.id)).idexcept Exception as e:@@ -1983,7 +2056,7 @@ class DiscordAdapter(CollaborationAdapter):message the room never sees."""thread_id = self._thread_channel_id(root_ref)- if thread_id is None or self._client is None:+ if thread_id is None or self._require_connection().client_or_none is None:logger.warning("Cannot read the Discord thread under %s in %s, so %s does not ""answer the card there.",@@ -2059,8 +2132,9 @@ class DiscordAdapter(CollaborationAdapter):target: Any = Noneif thread_root_id:thread_id = self._thread_channel_id(thread_root_id)- if thread_id is not None and self._client is not None:- target = self._client.get_channel(thread_id)+ client = self._require_connection().client_or_none+ if thread_id is not None and client is not None:+ target = client.get_channel(thread_id)if target is None:try:target = await self._get_channel(int(channel_id))@@ -2187,6 +2261,7 @@ class DiscordAdapter(CollaborationAdapter):if not term:return []+ self._require_connection().take_member_search()guild = await self._get_guild()try:members = await guild.query_members(query=term, limit=100)@@ -2264,6 +2339,24 @@ class DiscordAdapter(CollaborationAdapter):return Nonereturn f"https://discord.com/channels/{self._config.guild_id}"+ async def require_bindable_channel(self, channel_id: str) -> None:+ """Only a channel in this bridge's own guild.++ The shared bot is in every tenant's guild, and even a bot of the+ tenant's own serves one guild per bridge. A guild-less channel is a DM,+ which shared delivery does not carry, so on the shared connection one+ is not this bridge's either.+ """+ target = await self._get_channel(int(channel_id))+ if (+ getattr(target, "guild", None) is None+ and self._config.event_delivery == "shared"+ ):+ raise ChannelNotBindable(+ f"Discord channel {channel_id} is a direct message, which this "+ "connection does not carry."+ )+async def get_channel_type(self, channel_id: str) -> ChannelType:target = await self._get_channel(int(channel_id))return self._channel_type_of(target)@@ -2449,7 +2542,8 @@ class DiscordAdapter(CollaborationAdapter):)def _guild_from_cache(self) -> Any:- return self._client.get_guild(self._guild_id) if self._client else None+ client = self._require_connection().client_or_none+ return client.get_guild(self._guild_id) if client else Nonedef _role_name(self, role_id: int) -> str | None:guild = self._guild_from_cache()@@ -2538,9 +2632,8 @@ class DiscordAdapter(CollaborationAdapter):return f"@{name}" if name else match.group(0)def _replace_channel(match: re.Match[str]) -> str:- channel = (- self._client.get_channel(int(match.group(1))) if self._client else None- )+ client = self._require_connection().client_or_none+ channel = client.get_channel(int(match.group(1))) if client else Nonename = getattr(channel, "name", None)return f"#{name}" if name else match.group(0)@@ -2550,26 +2643,20 @@ class DiscordAdapter(CollaborationAdapter):# ── Gateway event handling ───────────────────────────────────────────────- # Message types we treat as real posts: plain messages and replies.- # Everything else (pins, joins, boosts, thread starters, …) is skipped.- _ALLOWED_MESSAGE_TYPES = frozenset(- {discord.MessageType.default, discord.MessageType.reply}- )-async def _handle_message(self, message: Any) -> None:- guild = getattr(message, "guild", None)- if guild is not None and guild.id != self._guild_id:- return-+ # The connection routes each message here by guild id (or as a DM), so+ # this handler only ever sees its own guild's messages and DMs — the+ # guild filter that used to live here now lives in DiscordConnection.author = message.author+ bot_user_id = self._require_connection().bot_user_id# Drop only our own posts (loop prevention): the bot itself and the# bridge's webhooks. Third-party bots/webhooks are still bridged.- if author.id == self._bot_user_id:+ if author.id == bot_user_id:returnwebhook_id = getattr(message, "webhook_id", None)if webhook_id and webhook_id in self._webhook_ids:return- if message.type not in self._ALLOWED_MESSAGE_TYPES:+ if message.type not in ALLOWED_MESSAGE_TYPES:returnif message.id in self._seen_ids:@@ -2630,8 +2717,7 @@ class DiscordAdapter(CollaborationAdapter):getattr(message, "attachments", []) or [])self_mention = (- bool(self._bot_user_id)- and re.search(rf"<@!?{self._bot_user_id}>", content) is not None+ bool(bot_user_id) and re.search(rf"<@!?{bot_user_id}>", content) is not None)await self._on_message(InboundMessage(@@ -2645,7 +2731,7 @@ class DiscordAdapter(CollaborationAdapter):channel_name=channel_name,attachments=attachments,attachment_failures=attachment_failures,- self_mention_token=str(self._bot_user_id) if self_mention else None,+ self_mention_token=str(bot_user_id) if self_mention else None,))@@ -3308,10 +3394,21 @@ class DiscordAdapter(CollaborationAdapter):# ── Webhooks & channels ──────────────────────────────────────────────────async def _get_channel(self, channel_id: int) -> Any:+ """The channel, refused if it is in another guild.++ Every path to a channel comes through here — binding, sending, webhooks,+ threads — so a bridge reaches no guild but its own even if something+ above it names one.+ """client = self._require_client()channel = client.get_channel(channel_id)if channel is None:channel = await client.fetch_channel(channel_id)+ guild = getattr(channel, "guild", None)+ if guild is not None and guild.id != self._guild_id:+ raise ChannelNotBindable(+ f"Discord channel {channel_id} is not in this connection's server."+ )return channelasync def _get_guild(self) -> Any:@@ -3401,9 +3498,8 @@ class DiscordAdapter(CollaborationAdapter):them; one fetched by its token says nothing about who made it."""creator = getattr(webhook, "user", None)- return creator is not None and bool(- self._bot_user_id and creator.id == self._bot_user_id- )+ bot_user_id = self._require_connection().bot_user_id+ return creator is not None and bool(bot_user_id and creator.id == bot_user_id)def _offers_buttons(self, channel_id: int) -> bool:"""Whether a card published in this guild channel may have buttons.diff --git a/core/switch_core/bridges/collaboration/discord/connection.py b/core/switch_core/bridges/collaboration/discord/connection.pynew file mode 100644index 000000000..4191dccef--- /dev/null+++ b/core/switch_core/bridges/collaboration/discord/connection.py@@ -0,0 +1,372 @@+from __future__ import annotations++import asyncio+import logging+import time+from collections import deque+from collections.abc import Awaitable, Callable, Coroutine+from typing import Any++import discord+from discord import app_commands++from switch_core.bridges.collaboration.adapter import DirectorySearchBusy++logger = logging.getLogger(__name__)++_READY_TIMEOUT = 30.0++# A member search is a Gateway send, and discord.py holds every send past 110 a+# minute on one socket until the minute is up. On the shared connection that+# budget is every organisation's at once, so searches get about half of it and+# the rest is left for everything else the socket sends.+_MEMBER_SEARCHES_PER_WINDOW = 60+_MEMBER_SEARCH_WINDOW = 60.0+_clock = time.monotonic+++class DiscordConnection:+ """Owns the Discord Gateway socket, separate from per-guild message handling.++ A `DiscordConnection` holds the `discord.Client`, the application command+ tree, the connect task and the bot's own user id, and it owns the socket+ lifecycle: login, the readiness race, slash-command sync and shutdown.+ `DiscordAdapter` composes one and reads its client through here rather than+ holding the socket itself.++ Splitting the socket out of the adapter is the first step toward a single+ shared, multi-tenant connection: the adapter is per guild, but the socket is+ per bot token, so the two have genuinely different lifetimes. Intents are+ supplied by the caller — the seam a shared connection uses to request a+ different set (e.g. dropping DM intents, gating message content) without the+ socket owner deciding them.++ `command_guild_id` scopes slash-command registration. When set, commands are+ published guild-scoped (immediate, and confined to that guild); when None,+ they are registered globally (per application, across every guild).+ """++ def __init__(+ self,+ *,+ bot_token: str,+ intents: discord.Intents,+ command_guild_id: int | None,+ ) -> None:+ self._bot_token = bot_token+ self._intents = intents+ self._command_guild_id = command_guild_id+ self._client: discord.Client | None = None+ self._tree: app_commands.CommandTree[Any] | None = None+ self._connect_task: asyncio.Task[None] | None = None+ self._bot_user_id: int = 0+ self._member_searches: deque[float] = deque()+ # Inbound message routing. A guild's messages go to the handler+ # registered for its id; a direct message (no guild) goes to the DM+ # handler if one is set, and is dropped otherwise. The self-registered+ # adapter registers one guild handler plus the DM handler; a shared+ # multi-tenant connection registers a handler per installed guild and+ # leaves the DM slot empty, so DMs — which carry no guild to attribute+ # them to a tenant — are dropped.+ self._message_handlers: dict[+ int, Callable[[discord.Message], Awaitable[None]]+ ] = {}+ # A single handler for *every* guild's messages, used by the shared+ # multi-tenant connection: it routes each event by resolving the guild+ # to its tenant fresh, rather than keeping a per-guild registry that+ # would cache which tenant a guild belongs to on the connection. When+ # set it takes precedence over the per-guild registry (a connection is+ # only ever one shape or the other).+ self._guild_message_handler: (+ Callable[[discord.Message], Awaitable[None]] | None+ ) = None+ self._dm_handler: Callable[[discord.Message], Awaitable[None]] | None = None+ # A press on a card's button (a component interaction). One handler for+ # the whole socket: the self-registered adapter sets its own; a shared+ # connection sets a router that resolves the interaction's guild to a+ # bridge. Unset means presses are dropped.+ self._interaction_handler: (+ Callable[[discord.Interaction], Awaitable[None]] | None+ ) = None+ # The bot being removed from / added to a guild. Only the shared+ # connection wires these; the self-registered adapter serves the one+ # guild it was configured with.+ self._guild_remove_handler: (+ Callable[[discord.Guild], Awaitable[None]] | None+ ) = None+ self._guild_join_handler: Callable[[discord.Guild], Awaitable[None]] | None = (+ None+ )++ def set_interaction_handler(+ self, handler: Callable[[discord.Interaction], Awaitable[None]] | None+ ) -> None:+ self._interaction_handler = handler++ def register_message_handler(+ self, guild_id: int, handler: Callable[[discord.Message], Awaitable[None]]+ ) -> None:+ self._message_handlers[guild_id] = handler++ def unregister_message_handler(self, guild_id: int) -> None:+ self._message_handlers.pop(guild_id, None)++ def set_guild_message_handler(+ self, handler: Callable[[discord.Message], Awaitable[None]] | None+ ) -> None:+ self._guild_message_handler = handler++ def set_guild_lifecycle_handlers(+ self,+ *,+ on_remove: Callable[[discord.Guild], Awaitable[None]],+ on_join: Callable[[discord.Guild], Awaitable[None]],+ ) -> None:+ """Handlers for the bot being removed from / added to a guild.++ Used by the shared connection to end an install when its guild removes+ the bot, and to note an out-of-band join. Set before `connect`; the+ self-registered adapter, which serves one guild it was configured with,+ leaves them unset.+ """+ self._guild_remove_handler = on_remove+ self._guild_join_handler = on_join++ def set_dm_handler(+ self, handler: Callable[[discord.Message], Awaitable[None]] | None+ ) -> None:+ self._dm_handler = handler++ @property+ def client(self) -> discord.Client:+ if self._client is None:+ raise RuntimeError("Discord client not connected")+ return self._client++ @property+ def client_or_none(self) -> discord.Client | None:+ return self._client++ @property+ def bot_user_id(self) -> int:+ return self._bot_user_id++ def take_member_search(self) -> None:+ """Spend one of this socket's member searches, or refuse at once.++ Refused rather than left to discord.py, which would hold the search+ until its minute is up — long enough for the person waiting on it to+ see a timeout instead of being told to try again.+ """+ now = _clock()+ while (+ self._member_searches+ and now - self._member_searches[0] >= _MEMBER_SEARCH_WINDOW+ ):+ self._member_searches.popleft()+ if len(self._member_searches) >= _MEMBER_SEARCHES_PER_WINDOW:+ raise DirectorySearchBusy(+ _MEMBER_SEARCH_WINDOW - (now - self._member_searches[0])+ )+ self._member_searches.append(now)++ async def connect(+ self,+ *,+ commands: list[app_commands.Command[Any, ..., Any]],+ ) -> None:+ """Open the Gateway connection and block until it is ready.++ Message handlers are registered separately (before or after this call)+ via `register_message_handler` / `set_dm_handler`, and are looked up+ live per message — so a shared connection can register a guild's handler+ the moment its install resolves, after the socket is already open.++ Raises if the connection fails or does not become ready within+ `_READY_TIMEOUT`. On timeout the half-open client is torn down; on a+ connect-task failure it is left as-is for the caller's `close()`.+ """+ client = discord.Client(intents=self._intents)+ client.event(self._make_on_message())+ # Presses on a card's buttons. Registered alongside the command tree+ # rather than through it: the tree is handed application-command+ # interactions only, and a component interaction is dispatched as the+ # plain `interaction` event whether or not anything is listening. Routed+ # through the handler set via `set_interaction_handler`, or dropped when+ # none is set.+ client.event(self._make_on_interaction())+ if self._guild_remove_handler is not None:+ client.event(self._make_on_guild_remove())+ if self._guild_join_handler is not None:+ client.event(self._make_on_guild_join())+ self._tree = app_commands.CommandTree(client)+ guild = (+ discord.Object(id=self._command_guild_id)+ if self._command_guild_id is not None+ else None+ )+ for command in commands:+ # Bound to the guild when scoped — see _sync_slash_commands. Adding+ # them globally when a guild sync follows would leave that sync with+ # an empty payload, registering nothing at all.+ if guild is not None:+ self._tree.add_command(command, guild=guild)+ else:+ self._tree.add_command(command)+ self._client = client++ await client.login(self._bot_token)+ self._connect_task = asyncio.create_task(+ client.connect(), name=f"discord-gateway-{self._command_guild_id}"+ )+ ready = asyncio.ensure_future(client.wait_until_ready())+ done, _ = await asyncio.wait(+ {ready, self._connect_task},+ timeout=_READY_TIMEOUT,+ return_when=asyncio.FIRST_COMPLETED,+ )+ if self._connect_task in done:+ ready.cancel()+ exc = self._connect_task.exception()+ raise RuntimeError("Discord gateway connection failed") from exc+ if ready not in done:+ ready.cancel()+ await self.close()+ raise RuntimeError(f"Discord gateway not ready after {_READY_TIMEOUT:.0f}s")++ assert client.user is not None+ self._bot_user_id = client.user.id+ logger.info(+ "Discord gateway connected as %s (guild %s)",+ client.user,+ self._command_guild_id,+ )+ await self._sync_slash_commands()++ async def _sync_slash_commands(self) -> None:+ """Publish the in-room command set as application commands.++ Guild-scoped when `command_guild_id` is set — which the self-registered+ adapter always is, since it serves one guild. Guild commands apply+ immediately, where global ones propagate for up to an hour, and global+ registration is per-application — so on an instance running several+ single-guild Discord bridges it would leak each bridge's commands into+ the others' guilds, where they could only fail. Syncing is a bulk+ overwrite, so re-running it on every start reconciles renames and+ removals rather than accumulating them.++ Any sync failure is logged and left non-fatal — hence the broad catch:+ the bridge still works over `!`-commands and messages, and dropping the+ whole bridge over a missing `applications.commands` scope is a worse+ outcome than running without the slash surface. The degradation is+ visible in the logs rather than silent.+ """+ if self._tree is None:+ return+ try:+ if self._command_guild_id is not None:+ synced = await self._tree.sync(+ guild=discord.Object(id=self._command_guild_id)+ )+ else:+ synced = await self._tree.sync()+ except Exception:+ logger.exception(+ "Failed to sync Discord slash commands for guild %s — the bridge "+ "will run without them (check the bot's applications.commands scope)",+ self._command_guild_id,+ )+ return+ logger.info(+ "Synced %d Discord slash commands to guild %s",+ len(synced),+ self._command_guild_id,+ )++ def _make_on_message(+ self,+ ) -> Callable[[discord.Message], Coroutine[Any, Any, None]]:+ # client.event registers by function __name__, so hand it a closure+ # named exactly like the gateway event.+ async def on_message(message: discord.Message) -> None:+ # Route to the handler registered for this message's guild, or the+ # DM handler for a guild-less message. Look up live per message so+ # handlers registered after connect() still receive events. An event+ # for a guild (or a DM) with no registered handler is dropped.+ guild = message.guild+ if guild is None:+ handler = self._dm_handler+ elif self._guild_message_handler is not None:+ handler = self._guild_message_handler+ else:+ handler = self._message_handlers.get(guild.id)+ if handler is None:+ return+ try:+ await handler(message)+ except Exception:+ logger.exception("Failed to handle inbound Discord message")++ return on_message++ def _make_on_interaction(+ self,+ ) -> Callable[[discord.Interaction], Coroutine[Any, Any, None]]:+ async def on_interaction(interaction: discord.Interaction) -> None:+ # Look up live so a handler set after connect() still receives+ # presses; a press with no handler set is dropped.+ handler = self._interaction_handler+ if handler is None:+ return+ try:+ await handler(interaction)+ except Exception:+ logger.exception("Failed to handle a press on a Discord card")++ return on_interaction++ def _make_on_guild_remove(+ self,+ ) -> Callable[[discord.Guild], Coroutine[Any, Any, None]]:+ async def on_guild_remove(guild: discord.Guild) -> None:+ handler = self._guild_remove_handler+ if handler is None:+ return+ try:+ await handler(guild)+ except Exception:+ logger.exception("Failed to handle Discord guild removal")++ return on_guild_remove++ def _make_on_guild_join(+ self,+ ) -> Callable[[discord.Guild], Coroutine[Any, Any, None]]:+ async def on_guild_join(guild: discord.Guild) -> None:+ handler = self._guild_join_handler+ if handler is None:+ return+ try:+ await handler(guild)+ except Exception:+ logger.exception("Failed to handle Discord guild join")++ return on_guild_join++ async def close(self) -> None:+ if self._client:+ try:+ await self._client.close()+ except Exception:+ pass+ task = self._connect_task+ self._connect_task = None+ if task:+ task.cancel()+ try:+ await task+ except (asyncio.CancelledError, Exception):+ pass+ self._client = None+ self._tree = None+ logger.info("Discord connection closed")diff --git a/core/switch_core/bridges/collaboration/discord/gateway.py b/core/switch_core/bridges/collaboration/discord/gateway.pynew file mode 100644index 000000000..6b9c982eb--- /dev/null+++ b/core/switch_core/bridges/collaboration/discord/gateway.py@@ -0,0 +1,340 @@+"""The one deployment-level Discord Gateway connection.++The distributed Discord app authenticates to every tenant's guild with a single+application bot token, and one token means one Gateway connection (see+`DISCORD_DISTRIBUTED_APP.md`). This client owns that connection: it holds the+bot token, opens the socket, and **binds no tenant** — each event is routed to a+guild's inert bridge, and every tenant binding happens below, per room.++It is not a bridge and does not go through the collaboration lifecycle. It is a+single deployment-level object, started at boot alongside the bridges and living+in the one switch-core pod (a forced singleton), so there is never a second+owner of the socket and no leader election to arrange.++It opens the shared socket with the right intents, routes each guild message,+each global slash invocation and each press on a card's button to the bridge its+guild resolves to (fresh per event, no tenant cached — guards G1/G3), and+registers the command set globally once for the application. Removal / out-of-band-join handling lands after.+"""++from __future__ import annotations++import asyncio+import logging+from collections.abc import Awaitable, Callable+from typing import Any++import discord++from switch_core.bridges.agent.commands import Command as InRoomCommand+from switch_core.bridges.collaboration.adapter import CollaborationAdapter+from switch_core.bridges.collaboration.discord.adapter import (+ ALLOWED_MESSAGE_TYPES,+ DiscordAdapter,+)+from switch_core.bridges.collaboration.discord.connection import DiscordConnection+from switch_core.bridges.collaboration.discord.slash import build_app_commands+from switch_core.bridges.collaboration.install_service import (+ MessagingInstallService,+ WebhookBridgeUnavailable,+ WebhookWorkspaceUnknown,+)+from switch_core.tenant_context import no_tenant++logger = logging.getLogger(__name__)++_PLATFORM = "discord"++# Backoff for the initial connect: the socket is not up yet and nothing routes+# until it is, so keep retrying rather than leaving Discord dark for the process+# life. Transient drops after the first connect are discord.py's own to reconnect.+_INITIAL_RETRY_DELAY = 5.0+_MAX_RETRY_DELAY = 300.0+++class DiscordGatewayClient:+ def __init__(+ self,+ *,+ bot_token: str,+ message_content: bool,+ members: bool,+ install_service: MessagingInstallService,+ on_connected: Callable[[DiscordConnection], Awaitable[None]],+ ) -> None:+ self._message_content = message_content+ self._members = members+ self._install_service = install_service+ # Fired once, after the first successful connect: boot walks the running+ # bridges and attaches the ones on a shared connection (see main.py).+ self._on_connected = on_connected+ # Set once the first connect succeeds, and never cleared: discord.py+ # reconnects a dropped socket on the same connection object.+ self._live = False+ # command_guild_id=None → commands register globally, once for the+ # application across every guild (decision #7); guild-scoped registration+ # is the self-registered adapter's, which serves one guild.+ self._connection = DiscordConnection(+ bot_token=bot_token,+ intents=self._build_intents(message_content, members),+ command_guild_id=None,+ )++ @staticmethod+ def _build_intents(message_content: bool, members: bool) -> discord.Intents:+ """The least intents a multi-tenant shared connection needs.++ No `dm_messages`: a DM carries no guild, so it cannot be attributed to a+ tenant, and the connection leaves its DM handler unset so any that+ arrive are dropped (guard G4).++ `message_content` and `members` are both *privileged* and default off:+ requesting either unapproved closes the connection past Discord's+ ~100-guild verification threshold, which the distributed app crosses+ quickly. Off, the connection still opens — the bot sees messages that+ mention it and its own, and member lookups fall back to API fetches;+ each is turned on independently once the app is verified for it.+ """+ intents = discord.Intents.none()+ intents.guilds = True+ intents.guild_messages = True+ intents.message_content = message_content+ intents.members = members+ return intents++ @property+ def connection(self) -> DiscordConnection:+ return self._connection++ def attach_if_live(self, adapter: CollaborationAdapter) -> None:+ """Hand a starting Discord bridge the shared connection, if it is up.++ Called as each bridge starts, before anything in it runs, so a new+ install can post and search straight away rather than after the first+ message in its guild. Not before the connection is up: the bridge would+ run its start-time provisioning against a client that is not there,+ and the attach on connect would then be a no-op that never re-runs it.+ Those bridges are attached when the connection first comes up instead.+ """+ if self._live and isinstance(adapter, DiscordAdapter):+ adapter.attach_shared_connection(self._connection)++ async def start(self) -> None:+ # One handler for every guild's messages, and one for every press on a+ # card's button: each event resolves its guild to a tenant fresh, so+ # nothing about which tenant a guild belongs to is cached on the+ # connection (guard G1). The DM handler is deliberately left unset+ # (guard G4).+ self._connection.set_guild_message_handler(self._on_guild_message)+ self._connection.set_interaction_handler(self._on_interaction)+ self._connection.set_guild_lifecycle_handlers(+ on_remove=self._on_guild_remove,+ on_join=self._on_guild_join,+ )+ # Commands register globally, once for the application, and each+ # invocation is routed to a bridge by the guild it carries (decision #7).+ await self._connection.connect(commands=build_app_commands(self._on_slash))+ logger.info(+ "Discord shared Gateway connection started (message_content=%s)",+ self._message_content,+ )++ async def start_with_retry(self) -> None:+ """Connect, retrying the initial connect with backoff, then attach.++ Run as a supervised background task so a configured-but-unreachable+ Discord app never blocks or fails boot. Only the *initial* connect is+ retried here — once it is up, discord.py reconnects transient drops on+ its own (the same connection object, so attached bridges keep working).+ On the first success `on_connected` fires, which walks the running+ bridges and attaches the ones on a shared connection.+ """+ delay = _INITIAL_RETRY_DELAY+ while True:+ try:+ await self.start()+ break+ except asyncio.CancelledError:+ raise+ except Exception:+ logger.exception(+ "Discord shared Gateway connection failed to start; Discord "+ "installs are inert until it connects. Retrying in %.0fs",+ delay,+ )+ await self._connection.close()+ await asyncio.sleep(delay)+ delay = min(delay * 2, _MAX_RETRY_DELAY)+ # Before the walk, with no await between: a bridge starting from here+ # on is attached as it starts, and every one started before is in the+ # walk, so none falls between the two.+ self._live = True+ await self._on_connected(self._connection)++ async def stop(self) -> None:+ await self._connection.close()++ async def _on_guild_message(self, message: discord.Message) -> None:+ """Route one guild message to the bridge its guild resolves to.++ Runs with **no tenant bound** and resolves the guild fresh on every+ event (G1): the shared connection is multi-tenant and long-lived, so a+ tenant is never cached on it and each event is scoped from scratch.+ A guild with no active install resolves to nothing and is dropped, never+ routed to a default or first tenant (G3) — the system fails closed.+ Each handler below binds the tenant of the room it acts on, matching the+ socket and webhook delivery paths.+ """+ guild = message.guild+ if guild is None:+ # The connection only routes guild messages here, so this is+ # defensive; a DM would have gone to the (unset) DM handler.+ return+ # Drop the events that need no tenant and no DB before resolving one:+ # the bot's own posts (loop prevention) and non-post message types+ # (pins, joins, boosts, …). The adapter drops the same set again on its+ # own path, plus the webhook-echo drop it alone can make; this only+ # spares the shared, multi-tenant socket a resolution per skipped event.+ if message.author.id == self._connection.bot_user_id:+ return+ if message.type not in ALLOWED_MESSAGE_TYPES:+ return+ with no_tenant():+ try:+ target = await self._install_service.resolve_by_workspace(+ platform=_PLATFORM, workspace_id=str(guild.id)+ )+ except (WebhookWorkspaceUnknown, WebhookBridgeUnavailable) as exc:+ logger.info("Dropping Discord message for guild %s: %s", guild.id, exc)+ return++ adapter = target.adapter+ if not isinstance(adapter, DiscordAdapter):+ logger.error(+ "Bridge %s for Discord guild %s is not a Discord adapter (%s); "+ "dropping the message",+ target.bridge_id,+ guild.id,+ type(adapter).__name__,+ )+ return++ # Inert until now: hand it the shared connection so its inbound+ # handling and outbound posting run against the one socket.+ adapter.attach_shared_connection(self._connection)+ await adapter.dispatch_inbound(message)++ async def _on_slash(+ self,+ interaction: discord.Interaction,+ command: InRoomCommand,+ values: dict[str, Any],+ ) -> None:+ """Route one global slash invocation to the bridge its guild resolves to.++ Global commands appear in every guild the bot is in, including ones with+ no Switch install, so those are refused rather than dropped.+ """+ with no_tenant():+ adapter = await self._interaction_adapter(+ interaction,+ outside_a_server="This command only works inside a server.",+ )+ if adapter is not None:+ await adapter.dispatch_slash(interaction, command, values)++ async def _on_interaction(self, interaction: discord.Interaction) -> None:+ """Route one press on a card's button to the bridge its guild resolves to.++ The connection hands every interaction here, slash invocations+ included; those reach `_on_slash` through the command tree instead, so+ only presses are taken. A press from a guild no longer installed (a+ card left behind after a disconnect) is refused like a slash command.+ """+ if interaction.type is not discord.InteractionType.component:+ return+ with no_tenant():+ adapter = await self._interaction_adapter(+ interaction,+ outside_a_server="This button only works inside a server.",+ )+ if adapter is not None:+ await adapter.dispatch_interaction(interaction)++ async def _interaction_adapter(+ self, interaction: discord.Interaction, *, outside_a_server: str+ ) -> DiscordAdapter | None:+ """The bridge an interaction's guild resolves to, attached, or None.++ Resolved fresh per event, and called with no tenant bound, like the+ message path (G1). An interaction that resolves to no bridge is+ answered with an ephemeral refusal rather than dropped: Discord shows+ "interaction failed" for one left unacknowledged.+ """+ guild_id = interaction.guild_id+ if guild_id is None:+ await self._refuse(interaction, outside_a_server)+ return None+ try:+ target = await self._install_service.resolve_by_workspace(+ platform=_PLATFORM, workspace_id=str(guild_id)+ )+ except (WebhookWorkspaceUnknown, WebhookBridgeUnavailable) as exc:+ logger.info(+ "Refusing a Discord interaction from guild %s: %s", guild_id, exc+ )+ await self._refuse(interaction, "Switch is not connected to this server.")+ return None++ adapter = target.adapter+ if not isinstance(adapter, DiscordAdapter):+ logger.error(+ "Bridge %s for Discord guild %s is not a Discord adapter (%s); "+ "refusing the interaction",+ target.bridge_id,+ guild_id,+ type(adapter).__name__,+ )+ await self._refuse(interaction, "Switch is not connected to this server.")+ return None++ adapter.attach_shared_connection(self._connection)+ return adapter++ @staticmethod+ async def _refuse(interaction: discord.Interaction, message: str) -> None:+ try:+ await interaction.response.send_message(message, ephemeral=True)+ except discord.HTTPException:+ logger.exception("Failed to refuse a Discord interaction")++ async def _on_guild_remove(self, guild: discord.Guild) -> None:+ """The bot was removed from a guild: end that guild's install.++ Routed through the platform-initiated end path — the same one a Slack+ `app_uninstalled` takes — which marks the install inactive and detaches+ its bridge but revokes nothing (decision #8; there is no per-install+ token to revoke). A guild no tenant has installed resolves to nobody and+ is a no-op there, so a removal we were never serving is harmless.+ """+ await self._install_service.revoked(+ platform=_PLATFORM,+ workspace_id=str(guild.id),+ reason="the bot was removed from the Discord server",+ )++ async def _on_guild_join(self, guild: discord.Guild) -> None:+ """The bot was added to a guild.++ Nothing is provisioned here: only a recorded install (via the OAuth+ flow) makes a guild's events route anywhere, and a guild with none is+ ignored — its messages resolve to nobody and are dropped (G3). A guild+ added outside the install flow therefore does nothing but this line,+ which is what makes an out-of-band join visible rather than silent.+ """+ logger.info(+ "The Discord bot was added to guild %s (%s); it serves Switch only "+ "once an install has been recorded for it",+ guild.id,+ getattr(guild, "name", "?"),+ )diff --git a/core/switch_core/bridges/collaboration/discord/install.py b/core/switch_core/bridges/collaboration/discord/install.pynew file mode 100644index 000000000..fa27b1d8a--- /dev/null+++ b/core/switch_core/bridges/collaboration/discord/install.py@@ -0,0 +1,222 @@+"""Installing the distributed Discord app into a customer's server (guild).++The counterpart to `DISCORD_SETUP.md`'s self-registered app, and a different+Discord application from it. See `docs/old/bridges/DISCORD_DISTRIBUTED_APP.md`+for the registration walkthrough; `SCOPES` and `PERMISSIONS` below are pinned in+that document too, and a test compares them so the two cannot drift.++Two structural differences from Slack's installer run through everything here,+and both come from one fact — Discord grants no per-install credential:++- `redeem` returns a **tokenless** grant. The code exchange tells us the guild+ the bot was added to (its id and name) and hands back a user token we do not+ need; the bot authenticates to every guild with the one deployment-level+ application token, which is config and never rides inside an install.+- There is **no webhook**. Discord delivers messages and interactions over the+ Gateway, so the inbound half of the `MessagingAppInstaller` ABC —+ `verify_webhook`, `parse_webhook`, `workspace_of_event`, `revocation_of_event`+ — has nothing to implement. Those are stubbed to raise: nothing routes+ `/messaging/discord/events` traffic, so they are never reached, and splitting+ the ABC into an install half and a webhook half is deferred until a second+ non-webhook platform makes it pay off. `revoke` is stubbed for the same+ reason — a tokenless install has nothing to revoke and `disconnect` never+ calls it.+"""++from __future__ import annotations++import logging+from collections.abc import Mapping+from typing import Any, ClassVar+from urllib.parse import urlencode++import httpx++from switch_core.bridges.collaboration.install import (+ InboundWebhook,+ InstallGrant,+ MessagingAppInstaller,+ MessagingInstallError,+ WebhookEndpoint,+)++logger = logging.getLogger(__name__)++AUTHORIZE_URL = "https://discord.com/oauth2/authorize"+TOKEN_URL = "https://discord.com/api/oauth2/token"++#: The OAuth scopes the *Add to Server* URL asks for. `bot` adds the bot to the+#: guild; `applications.commands` is what lets Switch register its in-room+#: commands as native slash commands. Pinned in DISCORD_DISTRIBUTED_APP.md and+#: compared by a test.+SCOPES: tuple[str, ...] = ("bot", "applications.commands")++#: The least-privilege guild permissions the authorize URL requests, as named+#: bits summed into the bitfield Discord takes. Each is a capability the adapter+#: actually exercises — nothing here is speculative, and adding one is a+#: decision this table records. The permission table in DISCORD_DISTRIBUTED_APP.md+#: lists the same bits, and a test pins the resulting integer.+_PERMISSION_BITS: dict[str, int] = {+ "view_channel": 1 << 10,+ "send_messages": 1 << 11,+ "create_public_threads": 1 << 35, # open a thread off a message (_ensure_thread)+ "send_messages_in_threads": 1 << 38,+ "manage_webhooks": 1 << 29, # mint the per-channel webhook agents post under+ "manage_channels": 1 << 4, # provision channel access / private rooms+ "manage_roles": 1 << 28, # per-agent mentionable role for @-autocomplete+ "read_message_history": 1 << 16,+ "attach_files": 1 << 15,+ "add_reactions": 1 << 6, # mark the message an agent is working on+}++#: The decimal bitfield the authorize URL carries in `permissions`.+PERMISSIONS: int = sum(_PERMISSION_BITS.values())+++class DiscordAppInstaller(MessagingAppInstaller):+ platform: ClassVar[str] = "discord"++ def __init__(+ self,+ *,+ client_id: str,+ client_secret: str,+ application_id: str,+ ) -> None:+ self._client_id = client_id+ self._client_secret = client_secret+ # Held so a caller can reason about which app the connection speaks for;+ # the bot token itself is deployment config injected into the shared+ # connection, not the installer's to hold.+ self._application_id = application_id++ def authorize_url(self, *, state: str, redirect_uri: str) -> str:+ return f"{AUTHORIZE_URL}?" + urlencode(+ {+ "client_id": self._client_id,+ "scope": " ".join(SCOPES),+ "permissions": str(PERMISSIONS),+ "redirect_uri": redirect_uri,+ "response_type": "code",+ "state": state,+ }+ )++ async def redeem(self, *, code: str, redirect_uri: str) -> InstallGrant:+ """Exchange the code for the guild the bot was added to.++ Returns a tokenless grant: the response carries a user access token we+ do not keep, and — because the `bot` scope was authorized — a `guild`+ object naming the server the bot now belongs to, which is the only thing+ the install records.+ """+ async with httpx.AsyncClient() as http:+ response = await http.post(+ TOKEN_URL,+ data={+ "client_id": self._client_id,+ "client_secret": self._client_secret,+ "grant_type": "authorization_code",+ "code": code,+ "redirect_uri": redirect_uri,+ },+ headers={"Content-Type": "application/x-www-form-urlencoded"},+ )+ if response.status_code != httpx.codes.OK:+ raise MessagingInstallError(+ f"Discord refused the install ({response.status_code}): "+ f"{response.text[:200]}"+ )+ try:+ payload: dict[str, Any] = response.json()+ except ValueError as error:+ raise MessagingInstallError(+ "Discord accepted the install but returned a body that is not "+ "JSON, so there is nothing to record. Nothing was saved."+ ) from error++ guild = payload.get("guild")+ if not isinstance(guild, dict):+ raise MessagingInstallError(+ "Discord accepted the install but returned no guild, which means "+ "the bot was not added to a server (the `bot` scope was dropped, "+ "or the user cancelled). Nothing was saved."+ )+ guild_id = guild.get("id")+ if not isinstance(guild_id, str) or not guild_id:+ raise MessagingInstallError(+ "Discord returned a guild with no id, so the install cannot be "+ "attributed to a server. Nothing was saved."+ )+ name = guild.get("name")+ return InstallGrant(+ external_workspace_id=guild_id,+ workspace_name=name if isinstance(name, str) and name else guild_id,+ # The one that makes this a Discord grant: no per-install token.+ bot_token=None,+ scopes=payload.get("scope") or "",+ )++ def workspace_of_bridge(+ self, connection_config: Mapping[str, object]+ ) -> str | None:+ if connection_config.get("event_delivery") != "shared":+ return None+ guild_id = connection_config.get("guild_id")+ return str(guild_id) if guild_id is not None else None++ def connection_config(self, grant: InstallGrant) -> dict[str, object]:+ return {+ "guild_id": grant.external_workspace_id,+ # The difference between the two Discord apps, mirroring Slack's+ # `event_delivery`. Under `shared` the bridge opens no connection of+ # its own and carries no token; leaving it out would validate as a+ # self-registered bridge missing its bot token and fail at+ # registration rather than at anything a reader would look at.+ "event_delivery": "shared",+ }++ # ── The webhook half the ABC declares and Discord does not have ───────────+ #+ # Discord delivers over the Gateway (DISCORD_DISTRIBUTED_APP.md, "the one+ # public URL"), so none of these carries real traffic: no+ # `/messaging/discord/events` event is ours to read, and `disconnect` skips+ # `revoke` for a tokenless install.+ #+ # `verify_webhook` is the one an unauthenticated stranger can reach — it runs+ # first for any POST to `/messaging/discord/{events,interactive,commands}`.+ # It raises `MessagingInstallError`, which the route turns into a 404 (the+ # same answer as an unregistered platform), rather than an unhandled error+ # that would be a repeatable 500 plus a traceback for anyone who found the+ # URL. The rest raise loudly: they are only reachable from code that would+ # have had to wire a Discord webhook up by mistake.++ async def revoke(self, *, bot_token: str) -> None:+ raise NotImplementedError(+ "a Discord install has no per-install token to revoke; the bot token "+ "is deployment config shared by every install"+ )++ def verify_webhook(self, *, headers: Mapping[str, str], body: bytes) -> None:+ raise MessagingInstallError(+ "the distributed Discord app has no webhook; events arrive over the Gateway"+ )++ def parse_webhook(+ self, *, endpoint: WebhookEndpoint, headers: Mapping[str, str], body: bytes+ ) -> InboundWebhook:+ raise NotImplementedError(+ "the distributed Discord app has no webhook; events arrive over the Gateway"+ )++ def workspace_of_event(self, payload: Mapping[str, object]) -> str:+ raise NotImplementedError(+ "the distributed Discord app has no webhook; a guild id is read off "+ "the Gateway event, not an HTTP payload"+ )++ def revocation_of_event(self, payload: Mapping[str, object]) -> str | None:+ raise NotImplementedError(+ "the distributed Discord app has no webhook; a removal is a Gateway "+ "event, not an HTTP payload"+ )diff --git a/core/switch_core/bridges/collaboration/install.py b/core/switch_core/bridges/collaboration/install.pyindex ceb5c16a8..28e912f42 100644--- a/core/switch_core/bridges/collaboration/install.py+++ b/core/switch_core/bridges/collaboration/install.py@@ -175,6 +175,14 @@ class InstallGrant:where the alternative is a row of opaque platform ids. It is the customer'sown text and is never matched on.+ `bot_token` is `None` for a platform whose credential is not per-install.+ A Discord install grants no per-guild token — the bot authenticates to+ every guild with the one deployment-level application token — so its grant+ is a guild id and a name and nothing to store. A Slack grant always carries+ one; the requirement lives on that platform's `connection_config` validator,+ not here (`SlackConnectionConfig.bot_token` is required), so an optional+ field here does not weaken it.+`scopes` is the platform's own spelling, kept verbatim. A scope string thatmeans nothing to us is still the thing to show an operator asking why acall was refused, and parsing it into a list here would be a parser to keep@@ -183,7 +191,7 @@ class InstallGrant:external_workspace_id: strworkspace_name: str- bot_token: str+ bot_token: str | Nonescopes: str@@ -308,6 +316,20 @@ class MessagingAppInstaller(ABC):like :meth:`workspace_of_event` it must not touch the database."""+ def workspace_of_bridge(+ self, connection_config: Mapping[str, object]+ ) -> str | None:+ """The workspace a bridge on the deployment's own credential serves.++ Set by a platform whose installed bridges all run on one credential+ the deployment holds (Discord's one bot), so a bridge naming a+ workspace is a bridge that can reach it. Such a bridge may only start+ for the tenant whose live install that workspace is, and this is what+ names the workspace to check. None for every other bridge, which+ reaches only what its own credential reaches.+ """+ return None+@abstractmethoddef connection_config(self, grant: InstallGrant) -> dict[str, object]:"""Render a grant as the connection config this platform's adapter takes.diff --git a/core/switch_core/bridges/collaboration/install_service.py b/core/switch_core/bridges/collaboration/install_service.pyindex 2a3beafa5..c5a256d41 100644--- a/core/switch_core/bridges/collaboration/install_service.py+++ b/core/switch_core/bridges/collaboration/install_service.py@@ -74,6 +74,7 @@ from switch_core.bridges.collaboration.install_state import (from switch_core.bridges.collaboration.lifecycle_service import (CollaborationBridgeLifecycleService,)+from switch_core.bridges.collaboration.models import BridgeStartRefusedfrom switch_core.crypto import decrypt_token, encrypt_tokenfrom switch_core.db.models import MessagingInstallfrom switch_core.db.session_scope import tenant_session@@ -239,7 +240,14 @@ class MessagingInstallService:session,platform=platform,external_workspace_id=grant.external_workspace_id,- encrypted_bot_token=encrypt_token(grant.bot_token, self._secret),+ # A grant with no token is a platform whose credential is+ # deployment-level (Discord), not per-install; there is+ # nothing to encrypt and the column is nullable for it.+ encrypted_bot_token=(+ encrypt_token(grant.bot_token, self._secret)+ if grant.bot_token is not None+ else None+ ),scopes=grant.scopes,user_id=burnt.created_by_user_id,)@@ -277,6 +285,44 @@ class MessagingInstallService:)return attached+ async def refuse_uninstalled_bridge(+ self,+ *,+ bridge_id: str,+ tenant_id: str,+ bridge_type: str,+ connection_config: Mapping[str, object],+ ) -> None:+ """Refuse a bridge on the deployment's credential that no install of its+ tenant built. A start guard, so a refused bridge never runs.++ Such a bridge reaches whatever workspace its config names through the+ one credential every tenant shares, so naming a workspace is not+ evidence of owning it. The tenant's live install of that workspace is:+ it came from the platform's own consent screen, and the unique index+ lets only one tenant hold a workspace. The install's bridge pointer is+ still empty while the install flow registers the bridge, which is what+ the empty case admits.+ """+ if bridge_type not in self._installers.platforms():+ return+ workspace_id = self._installers.get(bridge_type).workspace_of_bridge(+ connection_config+ )+ if workspace_id is None:+ return+ async with tenant_session(self._session_factory, tenant_id) as session:+ install = await self._store.get_for_workspace(+ session, platform=bridge_type, external_workspace_id=workspace_id+ )+ if install is None or install.bridge_id not in (None, bridge_id):+ raise BridgeStartRefused(+ f"Bridge {bridge_id} names {bridge_type} workspace {workspace_id}, "+ "which its tenant has not installed this deployment's app into. "+ "A bridge on that app is created by installing it, and serves "+ "only what it was installed into."+ )+async def list_installs(self, session: AsyncSession) -> list[MessagingInstall]:"""The bound tenant's installs, for the operator's own list.@@ -461,7 +507,17 @@ class MessagingInstallService:)async def resolve(self, *, platform: str, event: InboundWebhook) -> WebhookTarget:- """Turn a workspace id into the one bridge entitled to the event.+ """Turn a webhook event's workspace into the bridge entitled to it."""+ installer = self._installers.get(platform)+ workspace_id = installer.workspace_of_event(event.payload)+ return await self.resolve_by_workspace(+ platform=platform, workspace_id=workspace_id+ )++ async def resolve_by_workspace(+ self, *, platform: str, workspace_id: str+ ) -> WebhookTarget:+ """Turn a workspace id into the one bridge entitled to its events.The tenant comes from the exempt lookup (`db/tenant_lookup.py`), whichis the only way to answer it: the caller authenticated to nothing, and@@ -469,10 +525,13 @@ class MessagingInstallService:*again* under that tenant rather than returned by the lookup — adeliberate second check, so a wrong answer above is a miss here insteadof a cross-tenant read.- """- installer = self._installers.get(platform)- workspace_id = installer.workspace_of_event(event.payload)+ Split from `resolve` so a caller that already holds the workspace id+ reaches it without a webhook: the Discord shared connection reads the+ guild id straight off the Gateway event, and calling this keeps the+ exempt-lookup caller inside this already-allowlisted module and inherits+ the scoped re-read for free.+ """tenant_id = await tenant_of_messaging_install(self._session_factory, platform, workspace_id)diff --git a/core/switch_core/bridges/collaboration/lifecycle_service.py b/core/switch_core/bridges/collaboration/lifecycle_service.pyindex 9243dc1fc..66d1d08ec 100644--- a/core/switch_core/bridges/collaboration/lifecycle_service.py+++ b/core/switch_core/bridges/collaboration/lifecycle_service.py@@ -4,7 +4,8 @@ import asyncioimport loggingimport reimport time-from typing import TYPE_CHECKING+from collections.abc import Callable, Iterator, Mapping+from typing import TYPE_CHECKING, Protocolfrom uuid import uuid4import aiohttp@@ -283,6 +284,19 @@ def _bridge_client_localpart(bridge_type: str, display_name: str) -> str:return f"switch-bridge-{bridge_type}-{safe_name}-{uuid4().hex[:8]}"+class BridgeStartGuard(Protocol):+ """Asked before a bridge starts whether it may; raises `BridgeStartRefused`."""++ async def __call__(+ self,+ *,+ bridge_id: str,+ tenant_id: str,+ bridge_type: str,+ connection_config: Mapping[str, object],+ ) -> None: ...++class CollaborationBridgeLifecycleService:# See RoomService: a test may assemble this without `__init__`._telemetry: TelemetryService | None = None@@ -327,6 +341,10 @@ class CollaborationBridgeLifecycleService:self._session_activity_listener = session_activity_listenerself._session_activity_service = session_activity_serviceself._connections = connections+ self._bridge_starting_listeners: list[+ Callable[[CollaborationAdapter], None]+ ] = []+ self._bridge_start_guards: list[BridgeStartGuard] = []self._adapter_registry: dict[str, type[CollaborationAdapter]] = {}self._config_registry: dict[str, type[BridgeConnectionConfig]] = {}@@ -408,6 +426,59 @@ class CollaborationBridgeLifecycleService:bridge = self._bridges.get(bridge_id)return bridge.adapter if bridge is not None else None+ def add_bridge_starting_listener(+ self, listener: Callable[[CollaborationAdapter], None]+ ) -> None:+ """Be handed each bridge's adapter as it starts, before it runs.++ For whatever the adapter needs from outside itself before its first+ move — a bridge on a shared connection is given that connection here,+ so it can reach its platform from the start. Called synchronously, and+ with no await between the call and the bridge joining `iter_adapters`,+ so a listener that also walks the running bridges misses none.+ """+ self._bridge_starting_listeners.append(listener)++ def add_bridge_start_guard(self, guard: BridgeStartGuard) -> None:+ """Be asked before each bridge starts whether it may, and refuse by raising.++ For a condition outside the bridge's own config — whether whatever it+ claims to serve is really this tenant's. Awaited before the adapter is+ built, so a refused bridge runs nothing, and on an edit before the new+ config is stored. A guard raises `BridgeStartRefused`.+ """+ self._bridge_start_guards.append(guard)++ async def check_start_guards(+ self,+ *,+ bridge_id: str,+ tenant_id: str,+ bridge_type: str,+ connection_config: Mapping[str, object],+ ) -> None:+ """Raise `BridgeStartRefused` unless every guard lets this bridge start."""+ for guard in self._bridge_start_guards:+ await guard(+ bridge_id=bridge_id,+ tenant_id=tenant_id,+ bridge_type=bridge_type,+ connection_config=connection_config,+ )++ def iter_adapters(self) -> Iterator[CollaborationAdapter]:+ """The live adapter of every running bridge, as a snapshot.++ Platform-agnostic on purpose: a caller narrows with `isinstance` to the+ capability it wants (e.g. `SupportsSharedConnection`) rather than this+ exposing anything platform-specific.++ Snapshotted so a caller may await between adapters — a runtime install+ mutating `_bridges` mid-iteration would otherwise raise `dictionary+ changed size during iteration`."""+ for bridge in list(self._bridges.values()):+ yield bridge.adapter+def supports_channel_creation(self, bridge_type: str) -> bool:"""Whether this platform can create a channel from Switch at all.@@ -796,6 +867,12 @@ class CollaborationBridgeLifecycleService:)typed_config = config_cls.model_validate(bridge.connection_config or {})+ await self.check_start_guards(+ bridge_id=bridge_id,+ tenant_id=tenant_id,+ bridge_type=bridge.type,+ connection_config=bridge.connection_config or {},+ )adapter = adapter_cls(config=typed_config) # type: ignore[call-arg]adapter.set_service_url_persister(lambda service_url: self._persist_service_url(@@ -866,6 +943,9 @@ class CollaborationBridgeLifecycleService:transport_factory=self._client_factory.transport_for,)+ for listener in self._bridge_starting_listeners:+ listener(adapter)+# Stashed rather than passed: `_run_bridge`'s signature is what# the tenant-binding tests patch.self._bridge_facts[bridge_id] = (bridge.type, bridge.created_at)@@ -1292,7 +1372,25 @@ class CollaborationBridgeLifecycleService:self._connect_started.pop(bridge_id, None)def get(self, bridge_id: str) -> BridgeCore | None:- return self._bridges.get(bridge_id)+ """The running bridge for ``bridge_id``, if it is the bound tenant's.++ The registry holds every tenant's bridges, so a caller acting for one+ tenant must not be handed another's. With no tenant bound (boot and+ the per-tenant fan-outs) there is nothing to compare against.+ """+ bridge_core = self._bridges.get(bridge_id)+ if bridge_core is None:+ return None+ bound = current_tenant_id()+ if bound is not None and bridge_core.tenant_id != bound:+ logger.warning(+ "Refused bridge %s to tenant %s: it belongs to tenant %s",+ bridge_id,+ bound,+ bridge_core.tenant_id,+ )+ return None+ return bridge_coredef expected_count(self) -> int:"""Bridges that were started and have not been stopped deliberately."""diff --git a/core/switch_core/bridges/collaboration/models.py b/core/switch_core/bridges/collaboration/models.pyindex dce97d37e..5b53062ca 100644--- a/core/switch_core/bridges/collaboration/models.py+++ b/core/switch_core/bridges/collaboration/models.py@@ -215,6 +215,15 @@ class BridgeCredentialError(Exception):"""+class BridgeStartRefused(RuntimeError):+ """A start guard refused to let a bridge run, with the reason.++ Raised before the bridge's adapter is built, so nothing of it ran. Also+ answers an edit that would leave a bridge unable to start, before the edit+ is stored.+ """++class BridgeOperationError(RuntimeError):"""A platform refused an operation the bridge asked it to perform.diff --git a/core/switch_core/budgets.py b/core/switch_core/budgets.pynew file mode 100644index 000000000..58bc94938--- /dev/null+++ b/core/switch_core/budgets.py@@ -0,0 +1,63 @@+"""The one check every path an agent spends through makes before it spends.++An agent that has reached a budget covering it is stopped until the period+turns over: addressed room messages are answered with a refusal instead of+delivered (so no session is started or prompted for them), and its own posts+are refused. People are never stopped — a budget caps what agents spend.++What a person types into a session from Switch Console goes straight to the+session's host and never passes through Switch, so it is not stopped here.++Usage is counted after the fact (a turn's tokens arrive when it ends), so the+check stops the next piece of work, not the one in flight, and a budget can be+overshot by whatever was already running when it was reached.+"""++from sqlalchemy.ext.asyncio import AsyncSession++from switch_core.db.stores.budget_store import BudgetStanding, BudgetStore+++def _describe(standing: BudgetStanding) -> str:+ whose = (+ f"Agent {standing.agent_name}"+ if standing.agent_name is not None+ else "This workspace"+ )+ metric = standing.metric.replace("_", " ")+ model = f" on {standing.model}" if standing.model else ""+ resets = standing.resets_at.strftime("%Y-%m-%d %H:%M UTC")+ return (+ f"{whose} has reached its budget of {standing.amount_limit:,} {metric}"+ f"{model} per {standing.period_hours}h. It resets at {resets}."+ )+++class BudgetExceeded(Exception):+ """An agent has reached a budget covering it. The message is written for+ the people in the room, since they are who see it."""++ def __init__(self, standing: BudgetStanding) -> None:+ super().__init__(_describe(standing))+ self.standing = standing+++class BudgetGuard:+ def __init__(self, store: BudgetStore) -> None:+ self._store = store++ async def require_within(+ self, session: AsyncSession, *, tenant_id: str, agent_id: str+ ) -> None:+ """Raise `BudgetExceeded` if the agent has reached any budget covering+ it. When several have, the one that resets last is reported, because+ that is how long the agent is actually stopped for."""+ exhausted = [+ standing+ for standing in await self._store.standings(+ session, tenant_id=tenant_id, agent_id=agent_id+ )+ if standing.exhausted+ ]+ if exhausted:+ raise BudgetExceeded(max(exhausted, key=lambda s: s.resets_at))diff --git a/core/switch_core/clients/admin_client.py b/core/switch_core/clients/admin_client.pyindex b50ac07b8..89dd86149 100644--- a/core/switch_core/clients/admin_client.py+++ b/core/switch_core/clients/admin_client.py@@ -125,6 +125,7 @@ class AdminClient(ClientBase[ClientConfig]):format=format,thread_root_id=thread_root_id,extra_content=admin_extra_content(AdminMessageType.COMMAND_RESULT),+ metered=False,)# ── Platform messages ───────────────────────────────────────────────────@@ -168,6 +169,7 @@ class AdminClient(ClientBase[ClientConfig]):format="markdown",thread_root_id=thread_root_id,extra_content={PLATFORM_MARKER: marker_value},+ metered=False,)# ── Admin notices ─────────────────────────────────────────────────────────@@ -299,6 +301,7 @@ class AdminClient(ClientBase[ClientConfig]):mentions=mentions,thread_root_id=thread_root_id,extra_content=admin_extra_content(message_type),+ metered=False,)def _sender_handle(self, event: InboundMessage) -> str:diff --git a/core/switch_core/clients/agent_client.py b/core/switch_core/clients/agent_client.pyindex 65412b25b..8e323aba1 100644--- a/core/switch_core/clients/agent_client.py+++ b/core/switch_core/clients/agent_client.py@@ -33,6 +33,7 @@ from switch_core.bridges.agent.protocol.types import (TaskFinalisePayload,TaskUpdatePayload,)+from switch_core.budgets import BudgetExceeded, BudgetGuardfrom switch_core.clients.admin_messages import (AUTO_REPLY_FLAG,PLATFORM_MARKER,@@ -58,6 +59,7 @@ from switch_core.db.models import Agentfrom switch_core.db.session_scope import tenant_sessionfrom switch_core.db.stores.agent_session_store import AgentSessionStorefrom switch_core.db.stores.agent_store import AgentStore+from switch_core.db.stores.budget_store import BudgetStorefrom switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStorefrom switch_core.db.stores.document_store import DocumentStorefrom switch_core.db.stores.external_user_store import ExternalUserStore@@ -269,6 +271,7 @@ class AgentClient(ClientBase[ClientConfig]):external_user_store=external_user_store,live_connection_ids=connections.live_connection_ids,)+ self._budget_guard = BudgetGuard(BudgetStore())self._room_meta: dict[str, RoomMeta | None] = {}# In-flight multi-attachment groups, by group id, with their safety-net# timers. Both are cleared when a group completes or times out, so a@@ -338,7 +341,9 @@ class AgentClient(ClientBase[ClientConfig]):greeting = f"Hi! I'm {name} — how can I help?"else:greeting = random.choice(AGENT_GREETINGS).format(name=name)- await self.send_message(room.room_id, greeting, format="markdown")+ await self.send_message(+ room.room_id, greeting, format="markdown", metered=False+ )async def on_removed(self, room: RoomRef, event: InboundMembership) -> None:"""Forget the room's events, everywhere this agent could still read them.@@ -850,7 +855,11 @@ class AgentClient(ClientBase[ClientConfig]):"""Post a command result as this agent (an agent-owned command like`!run-cmd` answers in the agent's own voice, not as a system message)."""await self.send_message(- room_id, body, format=format, thread_root_id=thread_root_id+ room_id,+ body,+ format=format,+ thread_root_id=thread_root_id,+ metered=False,)async def _resolve_room_meta(self, matrix_room_id: str) -> RoomMeta | None:@@ -1119,7 +1128,9 @@ class AgentClient(ClientBase[ClientConfig]):async def on_task_delegate(self, room: RoomRef, event: TaskDelegate) -> None:if event.performer_agent_id != self.agent.id:return- await self.send_message(room.room_id, "Working on it.", format="markdown")+ await self.send_message(+ room.room_id, "Working on it.", format="markdown", metered=False+ )meta = await self._resolve_room_meta(room.room_id)if meta is None:return@@ -1315,8 +1326,8 @@ class AgentClient(ClientBase[ClientConfig]):) -> _GateOutcome:"""Apply the scoped addressing policy to a message that tags this agent.- When the sender is not permitted by the agent's policy, the message is- demoted to unaddressed room chatter and the caller is handed a refusal+ When the sender is not permitted by the agent's policy, or the agent+ has reached a budget covering it, the message is demoted to unaddressed room chatter and the caller is handed a refusalto post (once, guarded by AUTO_REPLY_FLAG so two agents can'tping-pong). Zero cost for the common case: only messages that alreadytag this agent are ever checked, and open policies short-circuit.@@ -1325,10 +1336,19 @@ class AgentClient(ClientBase[ClientConfig]):session, agent, event.sender, meta.room_id, event.content)if decision.allowed:- return _GateOutcome(addressed=True, refusal=None)+ try:+ await self._budget_guard.require_within(+ session, tenant_id=self.tenant_id, agent_id=agent.id+ )+ except BudgetExceeded as exc:+ refusal = str(exc)+ else:+ return _GateOutcome(addressed=True, refusal=None)+ else:+ refusal = decision.refusalif self._triggered_by_auto_reply(event):return _GateOutcome(addressed=False, refusal=None)- return _GateOutcome(addressed=False, refusal=decision.refusal)+ return _GateOutcome(addressed=False, refusal=refusal)@staticmethoddef _triggered_by_auto_reply(event: InboundMessage) -> bool:@@ -1352,6 +1372,7 @@ class AgentClient(ClientBase[ClientConfig]):mentions=[event.sender],thread_root_id=thread_root_id,extra_content={AUTO_REPLY_FLAG: True},+ metered=False,)def _args_tag_my_name(self, text: str) -> bool:diff --git a/core/switch_core/clients/client_base.py b/core/switch_core/clients/client_base.pyindex c21634e87..b9cc288b6 100644--- a/core/switch_core/clients/client_base.py+++ b/core/switch_core/clients/client_base.py@@ -476,6 +476,7 @@ class ClientBase[ConfigT: ClientConfig]:room_id: str,body: str,*,+ metered: bool,format: Literal["text", "markdown"] = "text",mentions: list[str] | None = None,thread_root_id: str | None = None,@@ -486,6 +487,7 @@ class ClientBase[ConfigT: ClientConfig]:room_id,body,sender_name=self.display_name,+ metered=metered,format=format,mentions=mentions,thread_root_id=thread_root_id,@@ -525,6 +527,7 @@ class ClientBase[ConfigT: ClientConfig]:mimetype: str,size: int,*,+ metered: bool,msgtype: str,caption: str | None = None,thread_root_id: str | None = None,@@ -552,6 +555,7 @@ class ClientBase[ConfigT: ClientConfig]:mimetype,size,sender_name=self.display_name,+ metered=metered,msgtype=msgtype,caption=caption,thread_root_id=thread_root_id,diff --git a/core/switch_core/clients/client_factory.py b/core/switch_core/clients/client_factory.pyindex 50b75b1e8..a68fb64ee 100644--- a/core/switch_core/clients/client_factory.py+++ b/core/switch_core/clients/client_factory.py@@ -12,6 +12,7 @@ from switch_core.db.stores.client_store import ClientStorefrom switch_core.db.stores.media_store import MediaStorefrom switch_core.db.stores.message_store import MessageStorefrom switch_core.db.stores.room_store import RoomStore+from switch_core.db.stores.usage_store import UsageStorefrom switch_core.messages.notify import MessageListenerfrom switch_core.transport import MessageTransportfrom switch_core.transport.ephemeral import EphemeralBus@@ -30,6 +31,7 @@ class ClientFactory:config: SwitchConfig,room_store: RoomStore,message_store: MessageStore,+ usage_store: UsageStore,media_store: MediaStore,listener: MessageListener,invites: InviteBus,@@ -40,6 +42,7 @@ class ClientFactory:self._config = configself._room_store = room_storeself._message_store = message_store+ self._usage_store = usage_storeself._media_store = media_storeself._listener = listenerself._invites = invites@@ -95,6 +98,7 @@ class ClientFactory:session_factory=self._session_factory,room_store=self._room_store,message_store=self._message_store,+ usage_store=self._usage_store,media_store=self._media_store,listener=self._listener,invites=self._invites,diff --git a/core/switch_core/clients/client_lifecycle_service.py b/core/switch_core/clients/client_lifecycle_service.pyindex 9291ed96b..72ff96a76 100644--- a/core/switch_core/clients/client_lifecycle_service.py+++ b/core/switch_core/clients/client_lifecycle_service.py@@ -140,7 +140,16 @@ class ClientLifecycleService:async with tenant_session(self._session_factory, tenant.id) as session:await self._tenant_store.create(session, tenant)await session.commit()- await self.ensure_system_client("admin")+ try:+ await self.ensure_system_client("admin")+ except Exception:+ logger.error(+ "Tenant %s (slug %s) was created but provisioning admin clients "+ "failed; the next boot's ensure_system_client fills the gap.",+ tenant.id,+ slug,+ )+ raisereturn tenantasync def start_all(self) -> None:diff --git a/core/switch_core/config.py b/core/switch_core/config.pyindex 678e84a14..1c52fc49e 100644--- a/core/switch_core/config.py+++ b/core/switch_core/config.py@@ -2,6 +2,7 @@ import reimport sslimport uuidfrom pathlib import Path+from typing import Literalfrom urllib.parse import urlsplitfrom pydantic import model_validator@@ -141,6 +142,23 @@ class SwitchConfig(BaseSettings):# docs/old/multi-tenancy-phase2-tenants.md, §4.gateway_tenant_choice_enabled: bool = False+ # What a person signing in through the IdP for the first time gets.+ #+ # "default_tenant": joined to the deployment's one pre-existing workspace,+ # tenant zero. Right for a single-organisation deployment, and what every+ # deployment did before sign-up existed.+ # "invite_only": an account and no workspace. They get in by accepting an+ # invitation; only an operator may create a workspace.+ # "open": an account and no workspace, and they may create their own, up to+ # gateway_max_workspaces_per_user.+ #+ # Who may sign in at all is the IdP's decision, not this one: this only+ # decides where a new account lands. Accounts an administrator creates+ # (`POST /users`) always join that administrator's workspace.+ gateway_signup_mode: Literal["default_tenant", "invite_only", "open"] = (+ "default_tenant"+ )+# How many workspaces one person may own here. 0 turns `POST /tenants` into# a 403 outright, so this single value is both the cap and the gate.#@@ -158,6 +176,24 @@ class SwitchConfig(BaseSettings):# docs/old/multi-tenancy-phase2-tenants.md, §5.gateway_max_workspaces_per_user: int = 3+ # Outbound mail for invitations addressed to an e-mail. Setting the host+ # turns it on; any SMTP relay works. Unset, an addressed invitation is+ # still created and the admin is told nothing was sent, so they can share+ # the link themselves. The link is built from `frontend_base_url` — never+ # from the request's Host header, which the requester controls.+ gateway_smtp_host: str | None = None+ gateway_smtp_port: int = 587+ # "starttls" upgrades a plain connection (port 587), "tls" connects over+ # TLS from the start (port 465), "none" is for a local relay only.+ gateway_smtp_tls: Literal["starttls", "tls", "none"] = "starttls"+ gateway_smtp_username: str | None = None+ gateway_smtp_password: str | None = None+ gateway_smtp_from: str | None = None+ # How many e-mailed invitations one workspace may send in 24 hours. With+ # sign-up open anyone can own a workspace, so without this the server is+ # a relay for mail to arbitrary addresses. Operators are not limited.+ gateway_invite_emails_per_day: int = 50+# ── Logging ──────────────────────────────────────────────────────────────# "text" for a terminal, "json" for a log pipeline that parses fields.log_format: str = "text"@@ -293,6 +329,37 @@ class SwitchConfig(BaseSettings):slack_app_client_secret: str | None = Noneslack_app_signing_secret: str | None = None+ # The distributed Discord app (`DISCORD_DISTRIBUTED_APP.md`): the one app+ # *we* register and a customer adds to their server, distinct from the+ # self-registered app whose token an operator pastes in.+ #+ # Four values and not three, and the shape difference from Slack is the last+ # one: Discord grants no per-install token, so the bot token is deployment+ # config that lives *here* and is injected into the one shared Gateway+ # connection — not captured per install the way a Slack workspace token is.+ # As with Slack, setting all of them is what enables installs (registration+ # is the feature flag) and setting some is a startup error.+ discord_app_client_id: str | None = None+ discord_app_client_secret: str | None = None+ discord_app_bot_token: str | None = None+ discord_app_application_id: str | None = None++ # Whether the shared Gateway connection requests the privileged message-+ # content intent. Off by default (mention-only): the connection opens+ # unapproved and agents still see mentions of the bot and its own messages.+ # Requesting it while unapproved closes the connection past Discord's+ # ~100-guild verification threshold, so it is a deliberate flag flipped once+ # the app is verified — not something inferred (decision #5).+ discord_app_message_content: bool = False++ # Whether the shared Gateway connection requests the privileged server-+ # members intent. Off by default, and privileged the same way message+ # content is: requesting it unapproved closes the connection past the+ # ~100-guild threshold. Off, member lookups fall back to API fetches; on+ # (once verified), the bot fills its member cache. Its own flag rather than+ # riding message content's, because the two are approved independently.+ discord_app_members: bool = False+# Public origin (scheme + host, no path) that a messaging platform reaches# Switch on: the base of the OAuth redirect and of the three event URLs# under `/messaging`, and the one registered with the app.@@ -612,6 +679,36 @@ class SwitchConfig(BaseSettings):def observability_enabled(self) -> bool:return self.otlp_endpoint is not None+ @property+ def invite_email_enabled(self) -> bool:+ return bool(self.gateway_smtp_host)++ @model_validator(mode="after")+ def _validate_smtp(self) -> "SwitchConfig":+ if self.gateway_invite_emails_per_day < 1:+ raise ValueError(+ "GATEWAY_INVITE_EMAILS_PER_DAY must be at least 1, got "+ f"{self.gateway_invite_emails_per_day!r}."+ )+ if bool(self.gateway_smtp_username) != bool(self.gateway_smtp_password):+ raise ValueError(+ "GATEWAY_SMTP_USERNAME and GATEWAY_SMTP_PASSWORD must be set "+ "together or not at all."+ )+ if not self.invite_email_enabled:+ return self+ if not self.gateway_smtp_from:+ raise ValueError(+ "GATEWAY_SMTP_FROM is required when GATEWAY_SMTP_HOST is set: "+ "it is the address invitation e-mails are sent from."+ )+ if not self.frontend_base_url:+ raise ValueError(+ "FRONTEND_BASE_URL is required when GATEWAY_SMTP_HOST is set: "+ "invitation e-mails link to the dashboard at that origin."+ )+ return self+@model_validator(mode="after")def _validate_max_workspaces_per_user(self) -> "SwitchConfig":if self.gateway_max_workspaces_per_user < 0:@@ -783,6 +880,36 @@ class SwitchConfig(BaseSettings):)return self+ @model_validator(mode="after")+ def _validate_discord_app(self) -> "SwitchConfig":+ required = (+ self.discord_app_client_id,+ self.discord_app_client_secret,+ self.discord_app_bot_token,+ self.discord_app_application_id,+ )+ set_count = sum(1 for value in required if value)+ if 0 < set_count < len(required):+ raise ValueError(+ "Partial distributed Discord app config: set all of "+ "DISCORD_APP_CLIENT_ID / DISCORD_APP_CLIENT_SECRET / "+ "DISCORD_APP_BOT_TOKEN / DISCORD_APP_APPLICATION_ID, or none "+ "of them."+ )+ # The OAuth redirect is built from the public origin, and Discord checks+ # it matches the one registered with the app byte for byte. Without the+ # origin a deployment offering the install button would build the+ # redirect against nothing, so it is a startup error rather than an+ # install that fails at Discord with nothing in our logs.+ if set_count and not self.messaging_public_url:+ raise ValueError(+ "A distributed Discord app is configured but MESSAGING_PUBLIC_URL "+ "is not. The install redirect is built from it, and Discord "+ "rejects a redirect that does not match the one registered with "+ "the app."+ )+ return self+@propertydef gateway_oidc_enabled(self) -> bool:return bool(diff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.pyindex e3ecf2580..a08245db9 100644--- a/core/switch_core/db/models.py+++ b/core/switch_core/db/models.py@@ -1,5 +1,6 @@import uuidfrom datetime import datetime+from enum import StrEnumfrom sqlalchemy import (DDL,@@ -344,6 +345,46 @@ class Invitation(TenantScoped, Base):)+class TenantJoinDomain(TenantScoped, Base):+ """An e-mail domain whose people may join a tenant without an invitation.++ Anyone signed in with an address at `domain` is offered the tenant and+ joins it as a member. The natural key is `(tenant_id, domain)`, so+ `tenant_id` joins the primary key directly, as on `reference_types`, and+ two tenants may each open themselves to the same domain.++ `domain` is stored lower-case, and the constraint is what makes that true+ rather than a convention: the lookup that finds these rows+ (`tenants_open_to_domain`, `db/tenant_lookup.py`) compares by equality,+ and a mixed-case row would be one nobody could ever match.++ Who may add a domain, and which, is the gateway's decision rather than this+ row's — today an admin may open a tenant only to the domain of their own+ address, and never to a public e-mail provider's.+ """++ __tablename__ = "tenant_join_domains"+ __table_args__ = (+ CheckConstraint(+ "domain = lower(domain)", name="ck_tenant_join_domains_lower_case"+ ),+ )++ tenant_id: Mapped[str] = mapped_column(+ Text,+ ForeignKey("tenants.id", name="fk_tenant_join_domains_tenant"),+ primary_key=True,+ default=require_tenant_id,+ )+ domain: Mapped[str] = mapped_column(Text, primary_key=True)+ created_by: Mapped[str] = mapped_column(+ Text, ForeignKey("users.id"), nullable=False+ )+ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), server_default=func.now(), nullable=False+ )++# ── Clients ────────────────────────────────────────────────────────────────────@@ -2354,6 +2395,131 @@ for _table, _triggers in (event.listen(_table, "after_create", DDL(_ddl).execute_if(dialect="postgresql"))+# ── Usage metering ───────────────────────────────────────────────────────────+++class UsageMetric(StrEnum):+ """What is counted. Cache reads and writes are kept apart from input+ tokens because providers price them apart."""++ MESSAGES = "messages"+ TURNS = "turns"+ INPUT_TOKENS = "input_tokens"+ OUTPUT_TOKENS = "output_tokens"+ CACHE_READ_TOKENS = "cache_read_tokens"+ CACHE_WRITE_TOKENS = "cache_write_tokens"+++class TenantUsage(TenantScoped, Base):+ """What a tenant has consumed, counted as it happens, one row per hour.++ The record that quotas are enforced against and that billing will read,+ so it is kept apart from the rows it counts: deleting a room cascades to+ its messages, and a count derived from `messages` would forget usage the+ tenant has already spent. Written in the same transaction as the thing it+ counts, so the two cannot disagree.++ Hourly buckets because a budget period is configurable: any period of a+ whole number of hours is a sum over these rows, while a coarser bucket+ would fix the shortest period a budget can have.++ `client_id` is who consumed it: the sender of a message, or the client of+ the agent a turn ran for. No foreign key, so a count outlives the client it+ names. `model` is empty where a metric has none.+ """++ __tablename__ = "tenant_usage"+ __table_args__ = (+ # Leads on the metric so "this tenant's turns since a moment" — the+ # shape every budget check asks — is a range scan on the key itself.+ PrimaryKeyConstraint(+ "tenant_id", "metric", "bucket_start", "client_id", "model"+ ),+ CheckConstraint(+ "metric IN ({})".format(", ".join(f"'{m}'" for m in UsageMetric)),+ name="ck_tenant_usage_metric",+ ),+ CheckConstraint("amount > 0", name="ck_tenant_usage_amount"),+ )++ metric: Mapped[str] = mapped_column(Text, nullable=False)+ bucket_start: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False+ )+ client_id: Mapped[str] = mapped_column(Text, nullable=False)+ model: Mapped[str] = mapped_column(Text, nullable=False)+ amount: Mapped[int] = mapped_column(BigInteger, nullable=False)+++# A budget's period is at most a leap year, and its limit at most the largest+# integer a JavaScript client reads exactly. Both keep the period arithmetic+# and the gateway's numbers from overflowing.+MAX_BUDGET_PERIOD_HOURS = 8784+MAX_BUDGET_AMOUNT = 2**53 - 1+++class UsageBudget(TenantScoped, Base):+ """A ceiling on one metric over a repeating period.++ `agent_id` null covers every agent in the tenant; otherwise the one agent.+ `model` empty covers every model. An agent that has reached any budget+ covering it is stopped until the period turns over; people are never+ stopped. A tenant with no budgets is unlimited.++ Periods are whole hours counted from the Unix epoch in UTC, so a daily+ budget turns over at midnight UTC and every writer agrees when.+ """++ __tablename__ = "usage_budgets"+ __table_args__ = (+ ForeignKeyConstraint(+ ["tenant_id", "agent_id"],+ ["agents.tenant_id", "agents.id"],+ name="fk_usage_budgets_agent",+ ondelete="CASCADE",+ ),+ CheckConstraint(+ "metric IN ({})".format(", ".join(f"'{m}'" for m in UsageMetric)),+ name="ck_usage_budgets_metric",+ ),+ CheckConstraint(+ f"amount_limit > 0 AND amount_limit <= {MAX_BUDGET_AMOUNT}",+ name="ck_usage_budgets_amount_limit",+ ),+ CheckConstraint(+ f"period_hours > 0 AND period_hours <= {MAX_BUDGET_PERIOD_HOURS}",+ name="ck_usage_budgets_period_hours",+ ),+ Index(+ "uq_usage_budgets_tenant_wide",+ "tenant_id",+ "metric",+ "model",+ unique=True,+ postgresql_where=text("agent_id IS NULL"),+ ),+ Index(+ "uq_usage_budgets_agent",+ "tenant_id",+ "agent_id",+ "metric",+ "model",+ unique=True,+ postgresql_where=text("agent_id IS NOT NULL"),+ ),+ )++ id: Mapped[str] = mapped_column(Text, primary_key=True, default=_uuid)+ agent_id: Mapped[str | None] = mapped_column(Text, nullable=True)+ metric: Mapped[str] = mapped_column(Text, nullable=False)+ model: Mapped[str] = mapped_column(Text, nullable=False)+ amount_limit: Mapped[int] = mapped_column(BigInteger, nullable=False)+ period_hours: Mapped[int] = mapped_column(Integer, nullable=False)+ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), server_default=func.now(), nullable=False+ )++# Same reasoning as the notify trigger above: `create_all` has to build the# row-level-security policies too, or the isolation test would pass against a# schema that has none. See `db/rls_ddl.py` for the DDL and why it takes thisdiff --git a/core/switch_core/db/stores/budget_store.py b/core/switch_core/db/stores/budget_store.pynew file mode 100644index 000000000..12cb9aaba--- /dev/null+++ b/core/switch_core/db/stores/budget_store.py@@ -0,0 +1,186 @@+from dataclasses import dataclass+from datetime import datetime++from sqlalchemy import BigInteger, ColumnElement, and_, cast, delete, func, or_, select+from sqlalchemy.ext.asyncio import AsyncSession+from sqlalchemy.orm import aliased++from switch_core.db.models import Agent, TenantUsage, UsageBudget, UsageMetric+++@dataclass(frozen=True)+class BudgetStanding:+ """A budget and what has been spent against it in the current period.++ `agent_id` and `agent_name` are null for a budget covering every agent.+ """++ id: str+ agent_id: str | None+ agent_name: str | None+ metric: str+ model: str+ amount_limit: int+ period_hours: int+ spent: int+ resets_at: datetime++ @property+ def exhausted(self) -> bool:+ return self.spent >= self.amount_limit+++class BudgetNotFound(LookupError):+ pass+++def _period_start() -> ColumnElement[datetime]:+ """The start of the budget's current period, on the database's clock.++ Periods are counted from the Unix epoch in whole hours, which puts a daily+ boundary at midnight UTC and lines every period up with the hourly usage+ buckets it sums.+ """+ seconds = cast(UsageBudget.period_hours, BigInteger) * 3600+ return func.to_timestamp(+ func.floor(func.extract("epoch", func.now()) / seconds) * seconds+ )+++class BudgetStore:+ async def standings(+ self, session: AsyncSession, *, tenant_id: str, agent_id: str | None+ ) -> list[BudgetStanding]:+ """The tenant's budgets with their current spend.++ With `agent_id`, only the budgets covering that agent: its own and the+ tenant-wide ones. Without, every budget the tenant has.++ A tenant-wide budget sums what the tenant's agents spent, not what its+ people and bridges did, since it is agents that a budget stops.++ Names the tenant explicitly as well as relying on the bound session,+ for the reason `UsageStore.totals` gives.+ """+ period_start = _period_start()+ agent_clients = aliased(Agent)+ spent = (+ select(func.coalesce(func.sum(TenantUsage.amount), 0))+ .where(+ TenantUsage.tenant_id == UsageBudget.tenant_id,+ TenantUsage.metric == UsageBudget.metric,+ TenantUsage.bucket_start >= period_start,+ or_(UsageBudget.model == "", TenantUsage.model == UsageBudget.model),+ or_(+ and_(+ UsageBudget.agent_id.is_(None),+ TenantUsage.client_id.in_(+ select(agent_clients.client_id).where(+ agent_clients.tenant_id == UsageBudget.tenant_id+ )+ ),+ ),+ TenantUsage.client_id == Agent.client_id,+ ),+ )+ .correlate(UsageBudget, Agent)+ .scalar_subquery()+ )+ statement = (+ select(+ UsageBudget,+ Agent.name,+ spent,+ period_start + func.make_interval(0, 0, 0, 0, UsageBudget.period_hours),+ )+ .outerjoin(+ Agent,+ and_(+ Agent.tenant_id == UsageBudget.tenant_id,+ Agent.id == UsageBudget.agent_id,+ ),+ )+ .where(UsageBudget.tenant_id == tenant_id)+ .order_by(+ UsageBudget.agent_id.nulls_first(),+ UsageBudget.metric,+ UsageBudget.model,+ )+ )+ if agent_id is not None:+ statement = statement.where(+ or_(UsageBudget.agent_id.is_(None), UsageBudget.agent_id == agent_id)+ )+ rows = await session.execute(statement)+ return [+ BudgetStanding(+ id=budget.id,+ agent_id=budget.agent_id,+ agent_name=agent_name,+ metric=budget.metric,+ model=budget.model,+ amount_limit=budget.amount_limit,+ period_hours=budget.period_hours,+ spent=int(amount),+ resets_at=resets_at,+ )+ for budget, agent_name, amount, resets_at in rows+ ]++ async def create(+ self,+ session: AsyncSession,+ *,+ tenant_id: str,+ agent_id: str | None,+ metric: UsageMetric,+ model: str,+ amount_limit: int,+ period_hours: int,+ ) -> UsageBudget:+ """Add a budget. A second budget on the same agent (or tenant-wide),+ metric and model fails on the unique index; the caller decides what+ that means to its user."""+ budget = UsageBudget(+ tenant_id=tenant_id,+ agent_id=agent_id,+ metric=metric.value,+ model=model,+ amount_limit=amount_limit,+ period_hours=period_hours,+ )+ session.add(budget)+ await session.flush()+ return budget++ async def update(+ self,+ session: AsyncSession,+ *,+ tenant_id: str,+ budget_id: str,+ amount_limit: int,+ period_hours: int,+ ) -> UsageBudget:+ budget = await session.scalar(+ select(UsageBudget).where(+ UsageBudget.tenant_id == tenant_id, UsageBudget.id == budget_id+ )+ )+ if budget is None:+ raise BudgetNotFound(budget_id)+ budget.amount_limit = amount_limit+ budget.period_hours = period_hours+ await session.flush()+ return budget++ async def delete(+ self, session: AsyncSession, *, tenant_id: str, budget_id: str+ ) -> None:+ result = await session.execute(+ delete(UsageBudget).where(+ UsageBudget.tenant_id == tenant_id, UsageBudget.id == budget_id+ )+ )+ if result.rowcount == 0: # type: ignore[attr-defined]+ raise BudgetNotFound(budget_id)diff --git a/core/switch_core/db/stores/invitation_store.py b/core/switch_core/db/stores/invitation_store.pyindex 0e6b73d1e..1dd8ba908 100644--- a/core/switch_core/db/stores/invitation_store.py+++ b/core/switch_core/db/stores/invitation_store.py@@ -157,6 +157,59 @@ class InvitationStore:)return list(result.scalars().all())+ async def list_live_addressed_to(+ self, session: AsyncSession, tenant_id: str, email: str+ ) -> list[Invitation]:+ """The live invitations of `tenant_id` addressed to `email`, compared+ case-insensitively as acceptance compares it.++ Called once per tenant from a fan-out over `tenants_inviting_email`,+ which is why it names the tenant in its own `WHERE` rather than leaning+ on the policy: on a connection the policy does not apply to, the same+ read would return every tenant's rows on every pass+ (`db/tenant_lookup.py`, on fan-outs).+ """+ result = await session.execute(+ select(Invitation)+ .where(+ Invitation.tenant_id == tenant_id,+ func.lower(Invitation.email) == email.lower(),+ _usable(),+ )+ .order_by(Invitation.created_at)+ )+ return list(result.scalars().all())++ async def get_in_tenant(+ self, session: AsyncSession, tenant_id: str, invitation_id: str+ ) -> Invitation | None:+ """The invitation `invitation_id`, if it belongs to `tenant_id`.++ The tenant is checked here as well as by the policy, for the same+ reason `list_live_addressed_to` names it: an id arriving from a+ request must not reach another tenant's row on a connection the policy+ does not bind.+ """+ result = await session.execute(+ select(Invitation).where(+ Invitation.id == invitation_id, Invitation.tenant_id == tenant_id+ )+ )+ return result.scalar_one_or_none()++ async def count_addressed_since(+ self, session: AsyncSession, since: datetime+ ) -> int:+ """How many of the bound tenant's invitations named an e-mail and were+ minted after `since` — the measure the daily e-mail cap is kept on.+ Per tenant through the policy, like `list_for_tenant`."""+ result = await session.execute(+ select(func.count())+ .select_from(Invitation)+ .where(Invitation.email.is_not(None), Invitation.created_at > since)+ )+ return int(result.scalar_one())+async def revoke(self, session: AsyncSession, invitation_id: str) -> Invitation:invitation = await session.get(Invitation, invitation_id)if invitation is None:diff --git a/core/switch_core/db/stores/join_domain_store.py b/core/switch_core/db/stores/join_domain_store.pynew file mode 100644index 000000000..594ce09b4--- /dev/null+++ b/core/switch_core/db/stores/join_domain_store.py@@ -0,0 +1,71 @@+from __future__ import annotations++from sqlalchemy import delete, select+from sqlalchemy.exc import IntegrityError+from sqlalchemy.ext.asyncio import AsyncSession++from switch_core.db.models import TenantJoinDomain+++class JoinDomainAlreadyAdded(Exception):+ """The bound tenant is already open to this domain."""+++class JoinDomainNotFound(Exception):+ """The bound tenant is not open to this domain."""+++class JoinDomainStore:+ """The e-mail domains a tenant lets people join from without an invitation.++ Every read names its tenant as well as relying on the policy: the same+ methods run on the owner connection the policy does not apply to, and a+ read that leaned on row-level security alone would answer for every+ tenant there.+ """++ async def list_for_tenant(+ self, session: AsyncSession, tenant_id: str+ ) -> list[TenantJoinDomain]:+ result = await session.execute(+ select(TenantJoinDomain)+ .where(TenantJoinDomain.tenant_id == tenant_id)+ .order_by(TenantJoinDomain.domain)+ )+ return list(result.scalars().all())++ async def is_open_to(+ self, session: AsyncSession, tenant_id: str, domain: str+ ) -> bool:+ result = await session.execute(+ select(TenantJoinDomain.domain).where(+ TenantJoinDomain.tenant_id == tenant_id,+ TenantJoinDomain.domain == domain.lower(),+ )+ )+ return result.scalar_one_or_none() is not None++ async def add(+ self, session: AsyncSession, *, domain: str, created_by: str+ ) -> TenantJoinDomain:+ """Open the bound tenant to `domain`, raising if it already is."""+ row = TenantJoinDomain(domain=domain.lower(), created_by=created_by)+ try:+ async with session.begin_nested():+ session.add(row)+ await session.flush()+ except IntegrityError as exc:+ raise JoinDomainAlreadyAdded(domain) from exc+ return row++ async def remove(self, session: AsyncSession, tenant_id: str, domain: str) -> None:+ result = await session.execute(+ delete(TenantJoinDomain)+ .where(+ TenantJoinDomain.tenant_id == tenant_id,+ TenantJoinDomain.domain == domain.lower(),+ )+ .returning(TenantJoinDomain.domain)+ )+ if result.scalar_one_or_none() is None:+ raise JoinDomainNotFound(domain)diff --git a/core/switch_core/db/stores/messaging_install_store.py b/core/switch_core/db/stores/messaging_install_store.pyindex 5e6ae18e8..97479cfbf 100644--- a/core/switch_core/db/stores/messaging_install_store.py+++ b/core/switch_core/db/stores/messaging_install_store.py@@ -118,7 +118,7 @@ class MessagingInstallStore:*,platform: str,external_workspace_id: str,- encrypted_bot_token: str,+ encrypted_bot_token: str | None,scopes: str,user_id: str,) -> MessagingInstall:@@ -133,6 +133,11 @@ class MessagingInstallStore:Installs that have ended are not in the index, so re-installing aworkspace somebody released is an ordinary insert and needs no check ofits own.++ `encrypted_bot_token` is `None` for a platform whose credential is not+ per-install (Discord's is deployment-level). The column is nullable for+ exactly that; a token-based platform's requirement is enforced by its+ connection-config validator, not here."""install = MessagingInstall(platform=platform,diff --git a/core/switch_core/db/stores/session_activity_store.py b/core/switch_core/db/stores/session_activity_store.pyindex 44cce1404..c271fbc25 100644--- a/core/switch_core/db/stores/session_activity_store.py+++ b/core/switch_core/db/stores/session_activity_store.py@@ -101,6 +101,27 @@ class ApprovalRequestStore:class SessionActivityStore:+ async def status_for_update(+ self,+ session: AsyncSession,+ agent_id: str,+ session_id: str,+ turn_id: str,+ item_id: str,+ ) -> str | None:+ """The row's stored status, locked until the transaction ends, or None."""+ status: str | None = await session.scalar(+ select(SessionActivityItem.status)+ .where(+ SessionActivityItem.agent_id == agent_id,+ SessionActivityItem.session_id == session_id,+ SessionActivityItem.turn_id == turn_id,+ SessionActivityItem.item_id == item_id,+ )+ .with_for_update()+ )+ return status+async def upsert(self, session: AsyncSession, item: SessionActivityItem) -> bool:"""Record `item` unless a revision at least as new is stored.diff --git a/core/switch_core/db/stores/tenant_store.py b/core/switch_core/db/stores/tenant_store.pyindex 79e1bd2bd..67afd9d09 100644--- a/core/switch_core/db/stores/tenant_store.py+++ b/core/switch_core/db/stores/tenant_store.py@@ -1,9 +1,28 @@from __future__ import annotations+from sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncSessionfrom switch_core.db.models import Tenant+# Postgres's default name for `tenants.slug`'s unique constraint, from the+# migration that created the table.+_SLUG_CONSTRAINT = "tenants_slug_key"+++class TenantSlugTaken(Exception):+ """The slug belongs to another tenant. Nothing was written."""++ def __init__(self, slug: str) -> None:+ super().__init__(f"Tenant slug {slug!r} is taken")+ self.slug = slug+++def _violated_constraint(err: IntegrityError) -> str | None:+ # asyncpg's own exception, which carries the constraint name, is the+ # cause of the DBAPI adapter's.+ return getattr(getattr(err.orig, "__cause__", None), "constraint_name", None)+class TenantStore:"""Writes tenants. Reading which ones exist is not a store's question.@@ -30,7 +49,16 @@ class TenantStore:The session it is handed must be bound to the tenant being created:`tenants`' policy compares on `id`, so that binding is what satisfies`with check`, and no other one can.++ A taken slug raises `TenantSlugTaken` — the one failure a caller can+ answer by picking another slug. Every other integrity error propagates+ as it is."""session.add(tenant)- await session.flush()+ try:+ await session.flush()+ except IntegrityError as err:+ if _violated_constraint(err) == _SLUG_CONSTRAINT:+ raise TenantSlugTaken(tenant.slug) from err+ raisereturn tenantdiff --git a/core/switch_core/db/stores/usage_store.py b/core/switch_core/db/stores/usage_store.pynew file mode 100644index 000000000..0ea4b13f6--- /dev/null+++ b/core/switch_core/db/stores/usage_store.py@@ -0,0 +1,124 @@+from dataclasses import dataclass+from datetime import datetime++from sqlalchemy import and_, func, literal, select+from sqlalchemy.dialects.postgresql import insert+from sqlalchemy.ext.asyncio import AsyncSession++from switch_core.db.models import Client, TenantUsage, UsageMetric+++@dataclass(frozen=True)+class UsageTotal:+ """One consumer's total of one metric over a window.++ `client_name` and `client_type` are null for a client that no longer+ exists; the usage it spent is still the tenant's.+ """++ metric: str+ client_id: str+ client_name: str | None+ client_type: str | None+ model: str+ amount: int+++class UsageStore:+ async def record(+ self,+ session: AsyncSession,+ *,+ tenant_id: str,+ metric: UsageMetric,+ client_id: str,+ model: str,+ amount: int,+ ) -> None:+ """Add `amount` to the current hour's count, in the caller's transaction.++ The bucket is the database's clock, not this process's, so every writer+ agrees on which hour it is. Hours are taken in UTC so a deployment's+ `TimeZone` setting cannot move a bucket boundary.+ """+ if amount <= 0:+ raise ValueError(f"usage amount must be positive, got {amount}")+ bucket = func.date_trunc("hour", func.now(), literal("UTC"))+ statement = insert(TenantUsage).values(+ tenant_id=tenant_id,+ metric=metric.value,+ bucket_start=bucket,+ client_id=client_id,+ model=model,+ amount=amount,+ )+ statement = statement.on_conflict_do_update(+ index_elements=[+ "tenant_id",+ "metric",+ "bucket_start",+ "client_id",+ "model",+ ],+ set_={"amount": TenantUsage.amount + statement.excluded.amount},+ )+ await session.execute(statement)++ async def totals(+ self,+ session: AsyncSession,+ *,+ tenant_id: str,+ since: datetime,+ until: datetime,+ ) -> list[UsageTotal]:+ """Totals per metric, consumer and model for buckets in `[since, until)`.++ Buckets are whole hours, so `since` is rounded down to the hour it+ falls in and a bucket counts if it starts before `until`.++ Names the tenant explicitly as well as relying on the bound session:+ the policy does not apply on an owner connection, and a fan-out that+ leaned on it alone would count every tenant's rows as this one's.+ """+ rows = await session.execute(+ select(+ TenantUsage.metric,+ TenantUsage.client_id,+ Client.display_name,+ Client.type,+ TenantUsage.model,+ func.sum(TenantUsage.amount),+ )+ .outerjoin(+ Client,+ and_(+ Client.id == TenantUsage.client_id,+ Client.tenant_id == TenantUsage.tenant_id,+ ),+ )+ .where(+ TenantUsage.tenant_id == tenant_id,+ TenantUsage.bucket_start >= func.date_trunc("hour", since, "UTC"),+ TenantUsage.bucket_start < until,+ )+ .group_by(+ TenantUsage.metric,+ TenantUsage.client_id,+ Client.display_name,+ Client.type,+ TenantUsage.model,+ )+ .order_by(TenantUsage.metric, TenantUsage.client_id, TenantUsage.model)+ )+ return [+ UsageTotal(+ metric=metric,+ client_id=client_id,+ client_name=client_name,+ client_type=client_type,+ model=model,+ amount=int(amount),+ )+ for metric, client_id, client_name, client_type, model, amount in rows+ ]diff --git a/core/switch_core/db/stores/user_store.py b/core/switch_core/db/stores/user_store.pyindex 51b0d2283..c4293e675 100644--- a/core/switch_core/db/stores/user_store.py+++ b/core/switch_core/db/stores/user_store.py@@ -22,6 +22,8 @@ logger = logging.getLogger(__name__)# would mean something other than the race this exists for._MAX_ATTEMPTS = 2+_LAST_TENANT_KEY = "last_tenant_id"+class OidcIdentityConflictError(Exception):"""An unverified OIDC login's email already belongs to a different account.@@ -203,10 +205,18 @@ class UserStore:name: str,sub: str,email_verified: bool,+ join_tenant: bool,) -> User:"""Resolve an OIDC identity to a gateway user, provisioning on firstlogin (JIT).+ `join_tenant` decides whether an account this creates, or links, is+ given a membership in the tenant bound to the caller's context. With+ it false, the account is left with none: that is how a deployment with+ self-service sign-up hands a newcomer to onboarding — create a+ workspace or accept an invitation — instead of placing them somewhere+ on its own (`gateway_signup_mode`).+Accounts are keyed on verified email, not on login method: a subjectalready linked to a user is returned as-is (looked up on theimmutable ``(iss, sub)`` pair, never the mutable email). Otherwise, a@@ -249,7 +259,11 @@ class UserStore:try:async with session.begin_nested():await self._link_identity(- session, user=existing, iss=iss, sub=sub+ session,+ user=existing,+ iss=iss,+ sub=sub,+ join_tenant=join_tenant,)except IntegrityError:self._raise_if_exhausted(attempt)@@ -259,8 +273,18 @@ class UserStore:user = User(name=name, email=email.lower(), role="user", password_hash=None)try:async with session.begin_nested():- await self.create(session, user)- await self._link_identity(session, user=user, iss=iss, sub=sub)+ if join_tenant:+ await self.create(session, user)+ else:+ session.add(user)+ await session.flush()+ await self._link_identity(+ session,+ user=user,+ iss=iss,+ sub=sub,+ join_tenant=join_tenant,+ )except IntegrityError:self._raise_if_exhausted(attempt)continue@@ -278,7 +302,13 @@ class UserStore:)async def _link_identity(- self, session: AsyncSession, *, user: User, iss: str, sub: str+ self,+ session: AsyncSession,+ *,+ user: User,+ iss: str,+ sub: str,+ join_tenant: bool,) -> None:session.add(OidcIdentity(user_id=user.id, iss=iss, sub=sub))await session.flush()@@ -293,8 +323,31 @@ class UserStore:# Linking reaches accounts this store did not create, including any# that predate memberships — and an account with none can never sign# in again. The startup admin seeding repairs the deployment's own- # admin; this repairs anyone else who signs in through an IdP.- await self.ensure_membership(session, user)+ # admin; this repairs anyone else who signs in through an IdP. Under+ # self-service sign-up an account with none is not stranded — it is+ # sent to onboarding — so there is nothing to repair.+ if join_tenant:+ await self.ensure_membership(session, user)++ def last_tenant_id(self, user: User) -> str | None:+ """The workspace `user` last selected, as recorded by+ `record_last_tenant`, or None if they never have.++ Only a preference: it names a tenant, it does not grant one. Whoever+ reads it must check it against the user's current memberships, since+ they may have been removed since it was written.+ """+ metadata = user.metadata_ or {}+ value = metadata.get(_LAST_TENANT_KEY)+ return value if isinstance(value, str) else None++ async def record_last_tenant(+ self, session: AsyncSession, user: User, tenant_id: str+ ) -> None:+ """Remember `tenant_id` as the workspace `user` last selected, so the+ next sign-in lands there rather than asking again."""+ user.metadata_ = {**(user.metadata_ or {}), _LAST_TENANT_KEY: tenant_id}+ await session.flush()async def get_all(self, session: AsyncSession) -> list[User]:result = await session.execute(select(User))diff --git a/core/switch_core/db/tenant_lookup.py b/core/switch_core/db/tenant_lookup.pyindex 371a457da..43241edd8 100644--- a/core/switch_core/db/tenant_lookup.py+++ b/core/switch_core/db/tenant_lookup.py@@ -1,4 +1,4 @@-"""The whole exemption from row-level security, written out as nine functions.+"""The whole exemption from row-level security, written out as eleven functions.Row-level security is enforced by `require_tenant_id()` (`db/rls_ddl.py`),which raises when no tenant is bound. That is the property everything else@@ -129,6 +129,28 @@ this would otherwise answer twice — refusing a customer's live traffic on thestrength of an install they themselves ended. The predicate here and the oneon the index are the same predicate, and have to stay that way.+**`tenants_inviting_email` is the tenth, and the only one keyed on a+person's address rather than on something they hold.** An invitation+addressed to someone is theirs to accept whichever workspace they are signed+in to, or with none selected at all; listing those means reading+`invitations`, which is scoped, across every tenant that might have written+one. So this answers which tenants hold a live invitation addressed to an+e-mail — the gates `InvitationStore`'s `_usable` applies, compared+case-insensitively as the acceptance does — and the caller binds each tenant+in turn and reads its own invitations through the ordinary scoped store. Like+every lookup here it discloses a tenant id and no row. What it adds to the+metadata above is which workspaces have invited a given address, to anyone+holding the runtime role's credentials; the endpoint that calls it only ever+passes the signed-in caller's own address.++**`tenants_open_to_domain` is the eleventh**, and the same shape one step+wider: keyed on the domain of a person's address rather than on the address.+A workspace can let anyone at a domain join it without an invitation, and+offering those workspaces means reading `tenant_join_domains` across every+tenant before any is bound. It discloses which workspaces are open to a+domain; the endpoint that calls it only ever passes the domain of the+signed-in caller's own address.+Why not the obvious alternatives is argued in`docs/old/multi-tenancy-phase1-db.md`, "The bootstrap problem"; the shortversion is that returning rows instead of tenant ids would put a second copy@@ -221,7 +243,7 @@ class TenantLookup:return f"{self.name}({', '.join('text' for _ in self.arguments)})"-# The nine of them. Ordered as the three shapes above: enumeration, then+# The eleven of them. Ordered as the three shapes above: enumeration, then# credential resolution, then deriving a tenant from an identifier in hand.TENANT_LOOKUPS: tuple[TenantLookup, ...] = (TenantLookup(@@ -307,6 +329,36 @@ TENANT_LOOKUPS: tuple[TenantLookup, ...] = ("refuses to a session with nothing bound yet."),),+ TenantLookup(+ name="tenants_inviting_email",+ arguments=("email",),+ query=(+ "SELECT DISTINCT tenant_id FROM invitations "+ "WHERE lower(email) = lower(p_email) "+ "AND revoked_at IS NULL AND expires_at > now() AND uses_remaining > 0 "+ "ORDER BY tenant_id"+ ),+ purpose=(+ "Which tenants hold a live invitation addressed to an e-mail, so a "+ "signed-in person can be shown the invitations waiting for them "+ "before any of those tenants is bound. Live by the same three "+ "gates `InvitationStore` applies; the rows themselves are read "+ "afterwards, one bound tenant at a time."+ ),+ ),+ TenantLookup(+ name="tenants_open_to_domain",+ arguments=("domain",),+ query=(+ "SELECT tenant_id FROM tenant_join_domains "+ "WHERE domain = lower(p_domain) ORDER BY tenant_id"+ ),+ purpose=(+ "Which tenants let anyone with an address at a domain join them "+ "without an invitation, so a signed-in person can be offered those "+ "workspaces before any of them is bound."+ ),+ ),TenantLookup(name="tenant_of_messaging_install",arguments=("platform", "external_workspace_id"),@@ -380,12 +432,12 @@ def attach_tenant_lookups(metadata: MetaData) -> None:# ── Calling them ──────────────────────────────────────────────────────────────# One `text()` per lookup, written out rather than assembled from `lookup.name`-# at call time: the nine names are fixed and known here, so there is nothing+# at call time: the eleven names are fixed and known here, so there is nothing# for a call site to build. Each bind is named after the lookup's own argument,# which is what lets `_call` zip them positionally against the dataclass and# fail loudly on a mismatch rather than binding the workspace to the platform.# The assertion below is what keeps this dict from quietly falling behind-# `TENANT_LOOKUPS` — a tenth lookup with no entry here fails at import, not+# `TENANT_LOOKUPS` — a twelfth lookup with no entry here fails at import, not# with a `KeyError` on whatever request reaches it first._LOOKUP_STATEMENTS: dict[str, TextClause] = {"all_tenant_ids": text("SELECT tenant_id FROM all_tenant_ids() AS tenant_id"),@@ -411,6 +463,12 @@ _LOOKUP_STATEMENTS: dict[str, TextClause] = {"tenant_of_invitation": text("SELECT tenant_id FROM tenant_of_invitation(:token_hash) AS tenant_id"),+ "tenants_inviting_email": text(+ "SELECT tenant_id FROM tenants_inviting_email(:email) AS tenant_id"+ ),+ "tenants_open_to_domain": text(+ "SELECT tenant_id FROM tenants_open_to_domain(:domain) AS tenant_id"+ ),"tenant_of_messaging_install": text("SELECT tenant_id FROM ""tenant_of_messaging_install(:platform, :external_workspace_id) AS tenant_id"@@ -516,6 +574,22 @@ async def tenant_of_invitation(return _at_most_one(lookup, await _call(session_factory, lookup, token_hash))+async def tenants_inviting_email(+ session_factory: async_sessionmaker[AsyncSession], email: str+) -> list[str]:+ return await _call(+ session_factory, TENANT_LOOKUPS_BY_NAME["tenants_inviting_email"], email+ )+++async def tenants_open_to_domain(+ session_factory: async_sessionmaker[AsyncSession], domain: str+) -> list[str]:+ return await _call(+ session_factory, TENANT_LOOKUPS_BY_NAME["tenants_open_to_domain"], domain+ )++async def tenant_of_messaging_install(session_factory: async_sessionmaker[AsyncSession],platform: str,diff --git a/core/switch_core/gateway/app.py b/core/switch_core/gateway/app.pyindex 83d4ea3c4..b33f31680 100644--- a/core/switch_core/gateway/app.py+++ b/core/switch_core/gateway/app.py@@ -19,13 +19,16 @@ from switch_core.clients.client_lifecycle_service import ClientLifecycleServicefrom switch_core.config import SwitchConfigfrom switch_core.db.stores.agent_store import AgentStorefrom switch_core.db.stores.api_key_store import ApiKeyStore+from switch_core.db.stores.budget_store import BudgetStorefrom switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStorefrom switch_core.db.stores.external_user_store import ExternalUserStorefrom switch_core.db.stores.invitation_store import InvitationStore+from switch_core.db.stores.join_domain_store import JoinDomainStorefrom switch_core.db.stores.room_group_store import RoomGroupStorefrom switch_core.db.stores.room_store import RoomStorefrom switch_core.db.stores.server_connector_store import ServerConnectorStorefrom switch_core.db.stores.template_store import TemplateStore+from switch_core.db.stores.usage_store import UsageStorefrom switch_core.db.stores.user_store import UserStorefrom switch_core.gateway.agent_sessions import router as agent_sessions_routerfrom switch_core.gateway.agents import router as agents_router@@ -36,6 +39,7 @@ from switch_core.gateway.connectors import router as connectors_routerfrom switch_core.gateway.dependencies import init_dependenciesfrom switch_core.gateway.documents import router as documents_routerfrom switch_core.gateway.ecosystem import router as ecosystem_router+from switch_core.gateway.invite_mail import InviteMailerfrom switch_core.gateway.messaging_installs import (router as messaging_installs_router,)@@ -71,10 +75,14 @@ def create_gateway_app(external_user_store: ExternalUserStore,api_key_store: ApiKeyStore,invitation_store: InvitationStore,+ join_domain_store: JoinDomainStore,template_store: TemplateStore,+ usage_store: UsageStore,+ budget_store: BudgetStore,resource_service: ResourceService,protocol: ProtocolService,install_service: MessagingInstallService | None,+ invite_mailer: InviteMailer | None,config: SwitchConfig,) -> FastAPI:init_dependencies(@@ -93,10 +101,14 @@ def create_gateway_app(external_user_store=external_user_store,api_key_store=api_key_store,invitation_store=invitation_store,+ join_domain_store=join_domain_store,template_store=template_store,+ usage_store=usage_store,+ budget_store=budget_store,resource_service=resource_service,protocol=protocol,install_service=install_service,+ invite_mailer=invite_mailer,config=config,)diff --git a/core/switch_core/gateway/auth.py b/core/switch_core/gateway/auth.pyindex 4fda74632..d2737cd85 100644--- a/core/switch_core/gateway/auth.py+++ b/core/switch_core/gateway/auth.py@@ -4,7 +4,7 @@ import datetimeimport loggingfrom collections.abc import AsyncIteratorfrom dataclasses import dataclass-from typing import Annotated+from typing import Annotated, Literalimport bcryptimport jwt@@ -17,14 +17,23 @@ from switch_core.db.models import Room, Tenant, Userfrom switch_core.db.session_scope import tenant_sessionfrom switch_core.db.stores.room_store import RoomStorefrom switch_core.db.stores.user_store import UserStore-from switch_core.db.tenant_lookup import tenant_of_invitation, tenants_of_user+from switch_core.db.tenant_lookup import (+ tenant_of_invitation,+ tenants_inviting_email,+ tenants_of_user,+ tenants_open_to_domain,+)from switch_core.gateway.dependencies import (get_config,get_session,get_session_factory,get_user_store,)-from switch_core.gateway.schemas import TenantMembershipResponse+from switch_core.gateway.schemas import (+ SessionStateResponse,+ SessionStateUser,+ TenantMembershipResponse,+)from switch_core.logging_context import log_contextfrom switch_core.tenant_context import tenant_scope@@ -163,6 +172,36 @@ async def get_authenticated_user_id(return payload["sub"] # type: ignore[no-any-return]+@dataclass(frozen=True)+class AuthenticatedSession:+ """An authenticated caller's id and the tenant their session selects, if+ any — the claim as minted, not yet checked against a membership."""++ user_id: str+ tenant_claim: str | None+++async def get_authenticated_session(+ request: Request,+ session_factory: Annotated[+ async_sessionmaker[AsyncSession], Depends(get_session_factory)+ ],+ user_store: Annotated[UserStore, Depends(get_user_store)],+ config: Annotated[SwitchConfig, Depends(get_config)],+) -> AuthenticatedSession:+ """Like `get_authenticated_user_id`, plus the session's tenant claim.++ Backs `GET /auth/session`, which reports what tenant resolution *would*+ do with this session rather than doing it — so it needs the claim that+ `get_current_user` would resolve, without the 403 or 409 that resolving+ it can raise.+ """+ payload = await _authenticate(request, session_factory, user_store, config)+ return AuthenticatedSession(+ user_id=payload["sub"], tenant_claim=payload.get("tenant_id")+ )++@dataclass(frozen=True)class AuthenticatedCaller:"""An authenticated caller with no tenant bound — read from `users`, which@@ -226,6 +265,31 @@ async def tenant_of_invitation_token(return await tenant_of_invitation(session_factory, token_hash)+async def tenants_with_invitations_for(+ session_factory: async_sessionmaker[AsyncSession], email: str+) -> list[str]:+ """Which tenants hold a live invitation addressed to `email`.++ A thin wrapper around `db.tenant_lookup.tenants_inviting_email`, here for+ the same reason as `tenant_of_invitation_token` above: the exemption is+ reached through this one module. The only caller passes the signed-in+ caller's own address, never one taken from a request.+ """+ return await tenants_inviting_email(session_factory, email)+++async def tenants_open_to(+ session_factory: async_sessionmaker[AsyncSession], domain: str+) -> list[str]:+ """Which tenants let anyone at `domain` join them without an invitation.++ A thin wrapper around `db.tenant_lookup.tenants_open_to_domain`, for the+ same reason as the wrappers above. The only caller passes the domain of+ the signed-in caller's own address.+ """+ return await tenants_open_to_domain(session_factory, domain)++async def is_tenant_member(session_factory: async_sessionmaker[AsyncSession], user_id: str, tenant_id: str) -> bool:@@ -305,6 +369,105 @@ async def list_tenant_memberships()+async def initial_tenant_claim(+ session_factory: async_sessionmaker[AsyncSession],+ user_store: UserStore,+ user: User,+) -> str | None:+ """The tenant a freshly signed-in session should select, if one is+ unambiguous: the workspace the user last selected, while they still+ belong to it; otherwise their only workspace; otherwise none.++ A null claim would ask a person with two workspaces to choose again on+ every visit. This stays a selection, not a+ grant — `_resolve_tenant_id` re-checks the claim on every request — and it+ is checked against current memberships here too, so signing in again is+ still how a session whose workspace was taken away recovers.+ """+ memberships = await tenants_of_user(session_factory, user.id)+ last = user_store.last_tenant_id(user)+ if last is not None and last in memberships:+ return last+ if len(memberships) == 1:+ return memberships[0]+ return None+++def workspace_creation_refusal(+ config: SwitchConfig, *, is_operator: bool, workspaces_created: int+) -> str | None:+ """Why this caller may not create a workspace, or None if they may.++ Operators always may. Otherwise `invite_only` sign-up refuses outright,+ and every other mode allows `gateway_max_workspaces_per_user` creations+ over a person's lifetime — each workspace is work for every per-tenant+ sweep (`docs/old/multi-tenancy-phase2-tenants.md`, §5). Returned as a+ message rather than raised so `GET /auth/session` can report the same+ answer `POST /tenants` enforces.+ """+ if is_operator:+ return None+ if config.gateway_signup_mode == "invite_only":+ return (+ "Creating workspaces is turned off on this server. Ask a "+ "workspace admin for an invitation."+ )+ limit = config.gateway_max_workspaces_per_user+ if limit == 0:+ return "Workspace creation is disabled on this deployment"+ if workspaces_created >= limit:+ return (+ f"You have created {workspaces_created} workspaces, and "+ f"this deployment allows {limit}"+ )+ return None+++def describe_session_state(+ config: SwitchConfig,+ user: User,+ tenant_claim: str | None,+ tenants: list[TenantMembershipResponse],+) -> SessionStateResponse:+ """What `_resolve_tenant_id` would make of this session, as data.++ Follows its order exactly — a claim is honoured only if it names one of+ `tenants`, and a bad claim is *not* rescued by a sole membership — so a+ client told "ready" is never refused by the next request, and one told+ otherwise knows which of `/tenants/{id}/switch`, `POST /tenants` or+ `/invitations/accept` gets it unstuck.+ """+ tenant: TenantMembershipResponse | None = None+ if tenant_claim is not None:+ tenant = next((t for t in tenants if t.id == tenant_claim), None)+ elif len(tenants) == 1:+ tenant = tenants[0]++ if tenant is not None:+ state: Literal["ready", "needs_selection", "needs_workspace"] = "ready"+ elif tenants:+ state = "needs_selection"+ else:+ state = "needs_workspace"++ is_operator = user.role == "admin"+ return SessionStateResponse(+ user=SessionStateUser(+ id=user.id, name=user.name, email=user.email, is_operator=is_operator+ ),+ tenant=tenant,+ tenants=tenants,+ state=state,+ can_create_workspace=workspace_creation_refusal(+ config,+ is_operator=is_operator,+ workspaces_created=user.workspaces_created,+ )+ is None,+ invite_email_enabled=config.invite_email_enabled,+ )++async def _resolve_tenant_id(session_factory: async_sessionmaker[AsyncSession],user_store: UserStore,@@ -319,10 +482,10 @@ async def _resolve_tenant_id(2. A claim naming a tenant the caller does not belong to → 403`tenant_selection_invalid`. The caller can fix this unaided — `GET/tenants` and `POST /tenants/{id}/switch` both authenticate without- binding a tenant, and signing in again mints a null claim — so the- message says so rather than sending them to an administrator. It is- not a rare state either: removing a member puts everyone it touches- here on their next request.+ binding a tenant, and signing in again selects only from current+ memberships — so the message says so rather than sending them to an+ administrator. It is not a rare state either: removing a member puts+ everyone it touches here on their next request.The cookie is not cleared here: it is `lax`, so a cross-sitenavigation can reach this path, and any page resetting someone'sdiff --git a/core/switch_core/gateway/auth_routes.py b/core/switch_core/gateway/auth_routes.pyindex 8050d2b42..5bfb0e194 100644--- a/core/switch_core/gateway/auth_routes.py+++ b/core/switch_core/gateway/auth_routes.py@@ -4,7 +4,7 @@ import loggingfrom typing import Annotatedfrom fastapi import APIRouter, Depends, HTTPException, Request, Response-from sqlalchemy.ext.asyncio import AsyncSession+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.config import SwitchConfigfrom switch_core.db.models import User@@ -12,8 +12,13 @@ from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgefrom switch_core.db.stores.external_user_store import ExternalUserStorefrom switch_core.db.stores.user_store import UserStorefrom switch_core.gateway.auth import (+ AuthenticatedSession,+ describe_session_state,+ get_authenticated_session,get_current_user,hash_password,+ initial_tenant_claim,+ list_tenant_memberships,require_admin,set_session_cookie,verify_password,@@ -23,6 +28,7 @@ from switch_core.gateway.dependencies import (get_config,get_external_user_store,get_session,+ get_session_factory,get_system_session,get_user_store,)@@ -33,6 +39,7 @@ from switch_core.gateway.schemas import (LinkedIdentity,LoginRequest,ServerDeclaration,+ SessionStateResponse,SessionUserResponse,UserResponse,)@@ -86,22 +93,33 @@ async def login(req: LoginRequest,response: Response,session: Annotated[AsyncSession, Depends(get_system_session)],+ session_factory: Annotated[+ async_sessionmaker[AsyncSession], Depends(get_session_factory)+ ],user_store: Annotated[UserStore, Depends(get_user_store)],config: Annotated[SwitchConfig, Depends(get_config)],) -> SessionUserResponse:# `get_system_session`, not `get_session`: there is no caller to take a# tenant from until this route decides there is one. It only ever reads# `users`, which is global (a person is one account across tenants), so- # there is nothing here a tenant would scope even once policies land.+ # there is nothing here a tenant would scope. Which workspace the new+ # session selects comes from the membership lookup, on a session of its own.if not config.gateway_password_login_enabled:raise HTTPException(status_code=403, detail="Password login is disabled")user = await user_store.get_by_email(session, req.email)if user is None or not verify_password(req.password, user.password_hash):raise HTTPException(status_code=401, detail="Invalid email or password")+ # Ends the read so its connection goes back to the pool before the+ # membership lookup takes one: a request holds one connection at a time.+ await session.commit()set_session_cookie(- response, user, config.jwt_secret_key, config.gateway_cookie_secure, None+ response,+ user,+ config.jwt_secret_key,+ config.gateway_cookie_secure,+ await initial_tenant_claim(session_factory, user_store, user),)return _session_response(user)@@ -149,9 +167,38 @@ async def auth_config(password_login_enabled=config.gateway_password_login_enabled,oidc_enabled=config.gateway_oidc_enabled,oidc_provider_label=config.gateway_oidc_provider_label,+ signup_mode=config.gateway_signup_mode,)[email protected]("/auth/session")+async def session_state(+ auth: Annotated[AuthenticatedSession, Depends(get_authenticated_session)],+ session: Annotated[AsyncSession, Depends(get_system_session)],+ session_factory: Annotated[+ async_sessionmaker[AsyncSession], Depends(get_session_factory)+ ],+ user_store: Annotated[UserStore, Depends(get_user_store)],+ config: Annotated[SwitchConfig, Depends(get_config)],+) -> SessionStateResponse:+ """Who is signed in, which workspace this session is in, and — when it+ is in none — what would get it into one.++ Answers for every signed-in caller, including the ones `/auth/me` refuses:+ someone with no workspace yet, or with several and none selected. That is+ exactly who a client needs to ask, which is why this reports what tenant+ resolution would decide (`describe_session_state`) instead of depending on+ `get_current_user`, which raises for them.+ """+ user = await user_store.get(session, auth.user_id)+ if user is None:+ raise HTTPException(status_code=401, detail="User not found")+ # One connection at a time: release this one before the lookup opens its own.+ await session.commit()+ tenants = await list_tenant_memberships(session_factory, user_store, user.id)+ return describe_session_state(config, user, auth.tenant_claim, tenants)++@router.get("/auth/me")async def me(user: Annotated[User, Depends(get_current_user)],diff --git a/core/switch_core/gateway/collaborations.py b/core/switch_core/gateway/collaborations.pyindex b07dae68e..aedab0964 100644--- a/core/switch_core/gateway/collaborations.py+++ b/core/switch_core/gateway/collaborations.py@@ -1,6 +1,7 @@from __future__ import annotationsimport logging+import mathfrom collections.abc import Iterablefrom typing import Annotated, Literal@@ -8,12 +9,14 @@ from fastapi import APIRouter, Depends, HTTPExceptionfrom pydantic import ValidationErrorfrom sqlalchemy.ext.asyncio import AsyncSession+from switch_core.bridges.collaboration.adapter import DirectorySearchBusyfrom switch_core.bridges.collaboration.lifecycle_service import (CollaborationBridgeLifecycleService,)from switch_core.bridges.collaboration.models import (BridgeCredentialError,BridgeInstallLink,+ BridgeStartRefused,DirectoryUser,)from switch_core.db.models import CollaborationBridge, ExternalUser, User@@ -173,6 +176,18 @@ async def create_bridge(# whose authz is owner-or-admin) — registering one is an admin action._user: Annotated[User, Depends(require_tenant_admin)],) -> BridgeDetail:+ # A shared bridge runs on this deployment's own app, which is in every+ # tenant's workspaces, so it is made only by installing the app — the one+ # path that proves the workspace is the caller's. Registered here, it+ # would reach whichever workspace its config named.+ if req.connection_config.get("event_delivery") == "shared":+ raise HTTPException(+ status_code=422,+ detail=(+ "A shared connection is created by installing the app, not "+ "registered here."+ ),+ )try:bridge = await collab_lifecycle.register(bridge_type=req.bridge_type,@@ -293,11 +308,31 @@ async def update_bridge(session, bridge_id, payload.preconfigured)if payload.connection_config is not None:- merged = {**(bridge.connection_config or {}), **payload.connection_config}+ current = bridge.connection_config or {}+ merged = {**current, **payload.connection_config}+ # How a bridge receives its events is decided by where it came from —+ # an install, or someone's own bot — and changing it on the edit form+ # would turn one into the other with none of what that takes.+ if merged.get("event_delivery") != current.get("event_delivery"):+ raise HTTPException(+ status_code=422,+ detail="event_delivery cannot be changed on an existing connection.",+ )try:collab_lifecycle.validate_connection_config(bridge.type, merged)+ # Asked now rather than at the restart below, so an edit that would+ # point a shared bridge at a workspace this tenant never installed+ # into is refused instead of stored and then failing to start.+ await collab_lifecycle.check_start_guards(+ bridge_id=bridge_id,+ tenant_id=bridge.tenant_id,+ bridge_type=bridge.type,+ connection_config=merged,+ )except ValidationError as exc:raise HTTPException(status_code=422, detail=str(exc)) from exc+ except BridgeStartRefused as exc:+ raise HTTPException(status_code=422, detail=str(exc)) from excbridge = await bridge_store.merge_connection_config(session, bridge_id, dict(payload.connection_config))@@ -423,6 +458,8 @@ async def search_bridge_directory(source = "known"note = str(e)found = _known_as_directory_users(known.values(), query)+ except DirectorySearchBusy as e:+ raise _search_busy(e) from eexcept RuntimeError as e:raise HTTPException(status_code=502, detail=str(e)) from e@@ -483,6 +520,15 @@ def _known_as_directory_users()+def _search_busy(e: DirectorySearchBusy) -> HTTPException:+ """A directory refusing more searches for now, as a 429 saying when to retry."""+ return HTTPException(+ status_code=429,+ detail=str(e),+ headers={"Retry-After": str(math.ceil(e.retry_after))},+ )++async def _require_directory_account(collab_lifecycle: CollaborationBridgeLifecycleService,*,@@ -518,6 +564,8 @@ async def _require_directory_account("seen. Send one message in the workspace, then link it."),) from e+ except DirectorySearchBusy as e:+ raise _search_busy(e) from eexcept RuntimeError as e:raise HTTPException(status_code=502, detail=str(e)) from ediff --git a/core/switch_core/gateway/dependencies.py b/core/switch_core/gateway/dependencies.pyindex 4e5aecbd4..7e1f4bdef 100644--- a/core/switch_core/gateway/dependencies.py+++ b/core/switch_core/gateway/dependencies.py@@ -21,15 +21,19 @@ from switch_core.clients.client_lifecycle_service import ClientLifecycleServicefrom switch_core.config import SwitchConfigfrom switch_core.db.stores.agent_store import AgentStorefrom switch_core.db.stores.api_key_store import ApiKeyStore+from switch_core.db.stores.budget_store import BudgetStorefrom switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStorefrom switch_core.db.stores.external_user_store import ExternalUserStorefrom switch_core.db.stores.invitation_store import InvitationStore+from switch_core.db.stores.join_domain_store import JoinDomainStorefrom switch_core.db.stores.messaging_install_store import MessagingInstallStorefrom switch_core.db.stores.room_group_store import RoomGroupStorefrom switch_core.db.stores.room_store import RoomStorefrom switch_core.db.stores.server_connector_store import ServerConnectorStorefrom switch_core.db.stores.template_store import TemplateStore+from switch_core.db.stores.usage_store import UsageStorefrom switch_core.db.stores.user_store import UserStore+from switch_core.gateway.invite_mail import InviteMailerfrom switch_core.room_service import RoomServicefrom switch_core.rooms_yaml import RoomYamlServicefrom switch_core.telemetry import TelemetryService@@ -54,10 +58,14 @@ def init_dependencies(external_user_store: ExternalUserStore,api_key_store: ApiKeyStore,invitation_store: InvitationStore,+ join_domain_store: JoinDomainStore,template_store: TemplateStore,+ usage_store: UsageStore,+ budget_store: BudgetStore,resource_service: ResourceService,protocol: ProtocolService,install_service: MessagingInstallService | None,+ invite_mailer: InviteMailer | None,config: SwitchConfig,) -> None:_state["agent_store"] = agent_store@@ -75,10 +83,14 @@ def init_dependencies(_state["external_user_store"] = external_user_store_state["api_key_store"] = api_key_store_state["invitation_store"] = invitation_store+ _state["join_domain_store"] = join_domain_store_state["template_store"] = template_store+ _state["usage_store"] = usage_store+ _state["budget_store"] = budget_store_state["resource_service"] = resource_service_state["protocol"] = protocol_state["install_service"] = install_service+ _state["invite_mailer"] = invite_mailer_state["config"] = config@@ -194,6 +206,18 @@ def get_invitation_store() -> InvitationStore:return _state["invitation_store"] # type: ignore[no-any-return]+def get_join_domain_store() -> JoinDomainStore:+ return _state["join_domain_store"] # type: ignore[no-any-return]+++def get_usage_store() -> UsageStore:+ return _state["usage_store"] # type: ignore[no-any-return]+++def get_budget_store() -> BudgetStore:+ return _state["budget_store"] # type: ignore[no-any-return]++def get_connector_lifecycle() -> ServerSideConnectorLifecycleService:return _state["connector_lifecycle"] # type: ignore[no-any-return]@@ -242,6 +266,12 @@ def get_install_store() -> MessagingInstallStore:return MessagingInstallStore()+def get_invite_mailer() -> InviteMailer | None:+ """None when no SMTP relay is configured: an addressed invitation is+ still minted, and the response says nothing was sent."""+ return _state["invite_mailer"] # type: ignore[no-any-return]++def get_install_service() -> MessagingInstallService | None:"""None when this deployment registered no messaging app of its own.diff --git a/core/switch_core/gateway/email_domain_lists/disposable.txt b/core/switch_core/gateway/email_domain_lists/disposable.txtnew file mode 100644index 000000000..6792eac35--- /dev/null+++ b/core/switch_core/gateway/email_domain_lists/disposable.txt@@ -0,0 +1,9188 @@+# Disposable e-mail providers, from disposable-email-domains/disposable-email-domains+# (CC0 1.0), disposable_email_blocklist.conf at commit 0655284b6a0b5c674789756ce8b6b35441b800bc,+# keeping only well-formed domains. One lower-case domain per line.+0-mail.com+0-mailer.dynv6.net+000-webmail.myhome-server.de+000000000000000.theworkpc.com+000000000000000000.dynv6.net+000webmail.ddnss.de+000webmail.ddnss.org+000webmail.dyn-ip24.de+000webmail.dyn.ddnss.de+000webmail.dyn.home-webserver.de+000webmail.dyndns.ddnss.de+000webmail.dyndns1.de+000webmail.home-webserver.de+00jac.com+01022.hk+010530.xyz+01130.hk+020307.xyz+027168.com+045692.xyz+062e.com+0815.ru+0815.su+0845.ru+092088.xyz+0box.eu+0cd.cn+0clickemail.com+0cpub2.tech+0n0ff.net+0nelce.com+0rg.fr+0v.ro+0w.ro+0wnd.net+0wnd.org+0x207.info+1-8.biz+1-mintue-mail.ddnsgeek.com+1-second-mail.site+1-tm.com+10-minute-mail.com+1000acres.co.uk+1000rebates.stream+100likers.com+102.io.vn+103.ink+105kg.ru+10dk.email+10inbox.online+10mail.com+10mail.org+10mail.tk+10mail.xyz+10min.email+10minemail.com+10minmail.de+10minmail.org+10minut.com.pl+10minut.xyz+10minute.email+10minutemail.be+10minutemail.cf+10minutemail.co.uk+10minutemail.co.za+10minutemail.com+10minutemail.de+10minutemail.ga+10minutemail.gq+10minutemail.ml+10minutemail.net+10minutemail.nl+10minutemail.pro+10minutemail.us+10minutemailbox.com+10minutemails.in+10minutenemail.de+10minutenmail.xyz+10minutesmail.com+10minutesmail.fr+10minutmail.pl+10x9.com+1111111111111.dynv6.net+11163.com+11166666.xyz+114514279.xyz+115yu.cc.cd+123-m.com+12312312312.cfd+123312.cc.cd+1234211.xyz+123456789.life+123clone.com+123mails.org+12bclass.us+12friday.space+12hosting.net+12houremail.com+12minutemail.com+12minutemail.net+12storage.com+130723.xyz+13282298.xyz+1337.care+13512863687.store+140unichars.com+142code.me+147.cl+14club.org.uk+14n.co.uk+151668.xyz+15553.eu.cc+15555.eu.cc+15557.eu.cc+15963.fr.nf+15qm.com+164109038.xyz+16816889.xyz+179297.xyz+17tb.io.vn+1820mail.vip+189.email+18t5b.shop+191117636.cfd+191mariobet.com+199411.store+1blackmoon.com+1ce.us+1chuan.com+1clck2.com+1fsdfdsfsdf.tk+1mail.ml+1nom.org+1pad.de+1pice.io.vn+1s.fr+1sec.site+1secmail.com+1secmail.net+1secmail.org+1secmail.space+1secmail.website+1st-forms.com+1sworld.com+1t-mail.com+1to1mail.org+1trick.net+1usemail.com+1webmail.info+1win.life+1xp.fr+1zhuan.com+2-b.icu+200192.indevs.in+20030310.com+2003066.xyz+2012-2016.ru+20253025.xyz+20260501.ccwu.cc+20260503.ccwu.cc+202608221.xyz+2048unblocked.com+20email.eu+20email.it+20mail.eu+20mail.in+20mail.it+20minutemail.com+20minutemail.it+20minutesmail.com+20mm.eu+2120001.net+216222.xyz+21cn.com+21mail.top+2200freefonts.com+22345377.xyz+2333.live+247chats.com+247web.net+24faw.com+24hinbox.com+24hourmail.com+24hourmail.net+24mail.top+25kcreditveo3.io.vn+25kg2gveo3.io.vn+25kmans.io.vn+25kmembers.io.vn+25kseller.io.vn+25kselll.io.vn+25kveo.io.vn+25kveo3.io.vn+25kvideo.io.vn+25u.com+264341.xyz+269966.xyz+2932919455.dynv6.net+2anom.com+2chmail.net+2ether.net+2fdgdfgdfgdf.tk+2likemobile.site+2likemobile.tech+2likemobile.top+2likemobile.xyz+2mail.eu.cc+2odem.com+2prong.com+2wc.info+300book.info+30mail.ir+30minutemail.com+30wave.com+3202.com+32132.ccwu.cc+326645.indevs.in+326646.indevs.in+326646302.indevs.in+3333366.xyz+3435637.xyz+365boxmail.com+36duongtau.live+36ru.com+38yz.help+39393.eu.cc+39393.me+3a88.dev+3bbb.cc.cd+3d-painting.com+3dkai.com+3fdn.com+3jf.cn+3l6.com+3littlemiracles.com+3mail.ga+3trtretgfrfe.tk+3xu.studio+4-n.us+401010.xyz+4057.com+415dacjder.qzz.io+418.dk+42o.org+42web.io+45kg2gveo3.io.vn+45kselller.io.vn+45kveo.io.vn+45kveo3.io.vn+48dz.com+48hr.email+497000.xyz+499713376.xyz+4bbb.cc.cd+4bus.io.vn+4gfdsgfdgfd.tk+4k5.net+4mail.cf+4mail.ga+4nextmail.com+4nmv.ru+4pu.com+4save.net+4tb.host+4warding.com+4warding.net+4warding.org+50set.ru+51baidu.tech+51mail.shop+51www.us+521883.xyz+522885.xyz+52mails.com+55hosting.net+5ghgfhfghfgh.tk+5gramos.com+5ixmonth.xyz+5july.org+5mail.cf+5mail.ga+5minutemail.net+5oz.ru+5semail.com+5tb.in+5x25.com+5xu.vn+5y.loseyourip.com+5yaochu.top+5ymail.com+60minutemail.com+628868.xyz+636364.xyz+66-77.cc+662602718.xyz+668fmail.com+66b1it.eu.org+672643.net+675hosting.com+675hosting.net+675hosting.org+6789.io.vn+67899vip.com+681mail.com+689345.xyz+6974.click+69flix.site+6gdfg.zone.id+6hjgjhgkilkj.tk+6ip.us+6mail.cf+6mail.ga+6mail.ml+6n9.net+6paq.com+6somok.ru+6th.pp.ua+6url.com+6ys.tech+709183.freeddns.org+719182.accesscam.org+729406.xyz+7362354.xyz+75hosting.com+75hosting.net+75hosting.org+778891.icu+78.edu.kg+78.school+78511939.xyz+792792.xyz+794613.accesscam.org+7days-printing.com+7mail.ga+7mail.ml+7novels.com+7tags.com+7xusq8vbim5d47.icu+80665.com+80fight.cn+8127ep.com+816qs.com+83.io.vn+862808.xyz+875888.xyz+88cloud.cc+8d7kh.com+8mail.cf+8mail.ga+8mail.ml+911666.xyz+912684.abrdns.com+91tanhua.top+920325.xyz+931123.xyz+94587293.xyz+94an.com+950410.xyz+957jp.cc+971007.xyz+981027.xyz+98104.cn+99.com+992551.xyz+99cows.com+99experts.com+99mail.us+9mail.cf+9me.site+9mot.ru+9ox.net+9q.ro+a--i.top+a-bc.net+a-germandu.de+a45.in+a7996.com+aa5zy64.com+aaago.cyou+aabkmail.com+aachendate.de+aaconservation.org+aakingcompany.shop+aakk.link+aakkmail.com+aaoo.me+aaqwe.ru+aaqwe.store+aard.org.uk+aasdarq.eu.cc+aasdasd.eu.cc+abacuswe.us+abaib.bond+abajb.bond+abakiss.com+abalb.bond+abamb.bond+abanb.bond+abapb.bond+abasb.bond+abatido.com+abaub.bond+abaxb.bond+abayb.bond+abazb.bond+abc179312.shop+abcmail.email+aberllefenni.co.uk+abevw.com+abilityaccesslegal.org+abilitywe.us+abo-free.fr.nf+aboodbab.com+abouse.space+abovewe.us+absolutewe.us+abundantwe.us+abusemail.de+abuser.eu+abusultann.com+abusultansmarty.co.uk+abusultanvip.com+abusultanvipo2.co.uk+abyis.com+abyssmail.com+ac-malin.fr.nf+ac20mail.in+academiccommunity.com+academywe.us+acaic.bond+acanok.com+acc1s.com+acc1s.net+accclone.com+acceleratewe.us+accentwe.us+acceptwe.us+accis.net+acclaimwe.us+accora.io.vn+accordwe.us+accountscenter.support+accreditedwe.us+acdag.indevs.in+acedby.com+acg-news.com+acgdb.eu.org+acgn.click+acgnnews.com+achievementwe.us+achievewe.us+acidservices.xyz+acornwe.us+acqq.dev+acreadingroom.co.uk+acrossgracealley.com+acrylicwe.us+actarus.infos.st+activatewe.us+activitywe.us+acucre.com+acuitywe.us+acumenwe.us+ad-managment.run.place+adaid.bond+adaptivewe.us+adaptwe.us+adarsa.me+adawd.bond+add3000.pp.ua+addadsasd.icu+addictingtrailers.com+addmails.com+addrin.uk+adeptwe.us+adfskj.com+adios.email+adiq.eu+aditus.info+admiralwe.us+adn3t.com+ado888.biz+adobeccepdm.com+adoniswe.us+ados.cc.cd+adpugh.org+adresse.infos.st+adroh.com+ads24h.top+adsd.org+adsensekorea.com+adubiz.info+adult-work.info+adv-dep-eng.jo3.org+advantagewe.us+advantageyoungpeople.com+advantimo.com+adventurewe.us+adventwe.us+advisorwe.us+advitise.com+advocatewe.us+adwaterandstir.com+aeace.bond+aeale.bond+aeame.bond+aeape.bond+aeare.bond+aeaue.bond+aeaxe.bond+aebz.makeup+aecmedya.com+aeerso.space+aegde.com+aegia.net+aegiscorp.net+aegiswe.us+aelo.es+aeonpsi.com+aerionx25k.io.vn+aeronyx.cfd+aesel.me+aetheron.cfd+afalf.bond+afarek.com+afarf.bond+afeeyah.store+affecting.org+affiliate-nebenjob.info+affiliatedwe.us+affilikingz.de+affinitywe.us+affluentwe.us+affordablewe.us+afgpuk.co.uk+afia.pro+afrobacon.com+afse-gh.top+aftercorporation.com+afterhourswe.us+afternea.sbs+afw.fr.nf+ag77brc.ddnsfree.com+agabg.bond+agallagher.id+agedmail.com+agencysq.store+agendawe.us+agenpremium.store+agentloop.sbs+agger.ro+agilewe.us+agiuse.com+agmbowie.com+agorawe.us+agri4life.io.vn+agtx.net+agylzuv.top+ahavaexperience.com+aheadwe.us+ahem.email+ahk.jp+ahmadfamily.net+ahmadizhar.net+ahmedkhlef.com+ahvin.com+ai100999.com+aiaccount.click+aiapes.publicvm.com+aibase.bond+aiclit.asia+aidesign.work.gd+aidesigner.2bd.net+aifmusic.top+aifreeuk.com+aifreeuk.info+aifreeuk.net+aifreeuk.store+aihubtools.space+aihuohua.online+aikunkun.com+ailicke.com+aineapi.com+aiphotoeditor.io+aiphotoenhancer.me+air2token.com+aircourriel.com+airhemp.com+airmailbox.website+airsworld.net+airychen.com+aisub.store+aisubpro.click+aisubstore.click+aisupply.click+aiuu.tech+aiworldx.com+aixnv.com+aizhongzhuan.cc+ajaxapp.net+ajinimoto.me+ak02fca.loseyourip.com+ak6lay.shop+akapost.com+akbip.com+akerd.com+akfoin.us.ci+akgq701.com+akhl.autos+akirapowered.com+akjaey.space+akmail.in+akolay.tech+akugu.com+akunlama.com+akunlemah.biz.id+al-qaeda.us+al1ya.app+alarafoundation.com+albill.com+albionwe.us+alchemywe.us+aleh.de+alfaceti.com+alhsalumni.org+aliaswe.us+aliban.org+alienware13.com+aligamel.com+alightmotion.cloud+alightmotion.id+alightmotion.top+alightmotion.website+aligroup.uk+alilot.com+alin.cc.cd+alin.eu.cc+alina-schiesser.ch+alisaol.com+alisongamel.com+alisree.com+alivance.com+alivewe.us+all-cats.ru+allaccesswe.us+allamericanwe.us+allaroundwe.us+alldirectbuy.com+allegiancewe.us+allegrowe.us+allemojikeyboard.com+allez.io.vn+allfreemail.net+allgoodwe.us+alliancewe.us+allinonewe.us+allofthem.net+alloutwe.us+allowed.org+alloywe.us+allprowe.us+allreview4u.com+allseasonswe.us+allstarwe.us+allthegoodnamesaretaken.org+allumhall.co.uk+allurewe.us+allwebemails.com+almatips.com+almiswelfare.org+almondwe.us+alosp.com+alph.wtf+alpha-web.net+alphaomegawe.us+alphatronic25k.io.vn+alphax.fr.nf+alpinewe.us+alreval.com+altairwe.us+altitudewe.us+altmails.com+altrans.fr.nf+altuswe.us+aluimport.com+alvaxio.com+alves.fr.nf+alwayss.uno+ama-trade.de+ama-trans.de+amadeuswe.us+amail.club+amail.com+amail1.com+amail4.me+amazinggift.life+amazingly.online+amazon-aws.org+amberwe.us+ambiancewe.us+ambitiouswe.us+ameady.com+ameeppoossaa.dedyn.io+amelabs.com+americanawe.us+americancivichub.com+americasbestwe.us+americaswe.us+amex409.monster+amicuswe.us+amilegit.com+aminating.com+amiri.net+amiriindustries.com+amiyah.cloud+amiyiy.xyz+amplewe.us+amplifiedwe.us+amplifywe.us+ampsylike.com+anajakstore.site+analogwe.us+analysiswe.us+analyticalwe.us+analyticswe.us+analyticwe.us+anappfor.com+anappthat.com+anarac.com+anbinh.io.vn+andalanglobal.app+andreihusanu.ro+andrewclaude.eu+andrewclaude.fr+andrewclaude.org+andrewclaude.store+andrewcluh.top+androl.cfd+andthen.us+angiiidayyy.click+anhiqojkaq1.abrdns.com+anhvip9999.com+anie.io.vn+animesos.com+aniross.com+anit.ro+ankiclub.space+ann.qzz.io+annd.us+annnekkk.com+ano-mail.net+ano2.co.uk+anogz.com+anon-mail.de+anonbox.net+anonmail.top+anonmails.de+anonymail.dk+anonymbox.com+anonymized.org+anonymousness.com+anotherdomaincyka.tk+anquandx.com+ansibleemail.com+anthony-junkmail.com+anti.io.vn+antireg.com+antireg.ru+antispam.de+antispam.fr.nf+antispam24.de+antispammail.de+antttool.us+anversa.com.co+anvjobvnu.top+any.pink+anyalias.com+anypng.com+anywebmail.com+aobl.hair+aoeuhtns.com+aohl.io.vn+aokkad.com+aokkap.my.id+aokkas.com+aoyh.hair+ap535fu.ddnsfree.com+ape-tech.run.place+apedesigns.jo3.org+apedesigns.linkpc.net+apes-ai.linkpc.net+apex.io.vn+apexnovaser.com+apexone.top+apfelkorps.de+aphlog.com+apimi.icu+apkmd.com+apocaw.com+appc.se+appinventor.nl+appixie.com+apple.edu.pl+appmail.uk+appremiums.pro+apps.dj+appsdjheru.site+appzily.com+aprinastore.web.id+aprte.com+aqilakomputer.com+aqim.skin+aquaguide.ru+ar26710.cc.cd+arapgege.app+arapps.me+arcadein.com+arcadium.lat+arcentra.cfd+ardsp.shop+arduino.hk+arenahiveai.com+ares.edu.pl+ares.io.vn+ariaz.jetzt+arkoo.site+armyspy.com+aron.us+arrabyte.com+arrb.autos+arroisijewellery.com+art-en-ligne.pro+art2mart.com+arthiq.life+artleoncommunications.com+artman-conception.com+artsdigi.store+artsdigital.store+arur01.tk+arurgitu.gq+arvato-community.de+arxxwalls.com+asajv2ray.site+asaption.com+aschenbrandt.net+asciibinder.net+asd903102.online+asdascas.dpdns.org+asdasd.nl+asdasd.ru+asdcxijkj.eu.cc+asedeeqaweds.dedyn.io+asgzs.top+ashleyandrew.com+ashnkarsh.life+asia-hq.jo3.org+asiafootball.org.uk+asimarif.com+asistx.net+ask-mail.com+asleepity.com+asorent.com+aspireviastudios.org+ass.pp.ua+assurmail.net+astonut.tk+astroempires.info+asu.mx+asu.su+asurad.com+at.hm+at0mik.org+atelierdelune.shop+atkshop.shop+atkshopp.space+atlas4381.me+atlasimple.com+atmemail.top+atnet.top+atnetcloud.space+atnextmail.com+atombomb.online+attnetwork.com+atxc.space+au1688x.us+aubady.com+augmentationtechnology.com+aumails.us+auralith.cfd+aureliandata.space+ausgefallen.info+auth2fa.com+auti.st+autofixmax.com+automisly.org+automizelymail.info+automizly.net+autommo.net+autorobotica.com+autosouvenir39.ru+autotwollow.com+autowb.com+autoxugiare.com+autre.fr.nf+autu11n.lol+available-home.com+avalentra.cfd+averdov.com+avia-tonic.fr+avls.pt+avq69cb.loseyourip.com+avtolev.com+awa.pics+awatum.de+awdrt.org+awesome47.com+awesomesaucemail.org+awgarstone.com+awiki.org+awoiiwowma11001.indevs.in+aws-mail-2.dynv6.net+aws-mail-free-1017.dynv6.net+aws-mail-free-102.dynv6.net+aws-mail-free-1056.dynv6.net+aws-mail-free-1304.dynv6.net+aws-mail-free-1705.dynv6.net+aws-mail-free-1842.dynv6.net+aws-mail-free-1884.dynv6.net+aws-mail-free-2156.dynv6.net+aws-mail-free-2236.dynv6.net+aws-mail-free-2290.dynv6.net+aws-mail-free-2383.dynv6.net+aws-mail-free-2409.dynv6.net+aws-mail-free-2454.dynv6.net+aws-mail-free-2524.dynv6.net+aws-mail-free-2704.dynv6.net+aws-mail-free-2737.dynv6.net+aws-mail-free-2775.dynv6.net+aws-mail-free-2795.dynv6.net+aws-mail-free-2845.dynv6.net+aws-mail-free-2892.dynv6.net+aws-mail-free-2906.dynv6.net+aws-mail-free-2923.dynv6.net+aws-mail-free-3038.dynv6.net+aws-mail-free-3335.dynv6.net+aws-mail-free-3381.dynv6.net+aws-mail-free-3620.dynv6.net+aws-mail-free-3711.dynv6.net+aws-mail-free-3796.dynv6.net+aws-mail-free-385.dynv6.net+aws-mail-free-4014.dynv6.net+aws-mail-free-4017.dynv6.net+aws-mail-free-4131.dynv6.net+aws-mail-free-4206.dynv6.net+aws-mail-free-4257.dynv6.net+aws-mail-free-4289.dynv6.net+aws-mail-free-4531.dynv6.net+aws-mail-free-4550.dynv6.net+aws-mail-free-4573.dynv6.net+aws-mail-free-4711.dynv6.net+aws-mail-free-4726.dynv6.net+aws-mail-free-4761.dynv6.net+aws-mail-free-4816.dynv6.net+aws-mail-free-4885.dynv6.net+aws-mail-free-4920.dynv6.net+aws-mail-free-493.dynv6.net+aws-mail-free-4937.dynv6.net+aws-mail-free-5119.dynv6.net+aws-mail-free-518.dynv6.net+aws-mail-free-5241.dynv6.net+aws-mail-free-5380.dynv6.net+aws-mail-free-5392.dynv6.net+aws-mail-free-5537.dynv6.net+aws-mail-free-5670.dynv6.net+aws-mail-free-5781.dynv6.net+aws-mail-free-5786.dynv6.net+aws-mail-free-5969.dynv6.net+aws-mail-free-6032.dynv6.net+aws-mail-free-6033.dynv6.net+aws-mail-free-6080.dynv6.net+aws-mail-free-6120.dynv6.net+aws-mail-free-6253.dynv6.net+aws-mail-free-6255.dynv6.net+aws-mail-free-6306.dynv6.net+aws-mail-free-6398.dynv6.net+aws-mail-free-6552.dynv6.net+aws-mail-free-659.dynv6.net+aws-mail-free-6604.dynv6.net+aws-mail-free-6690.dynv6.net+aws-mail-free-6691.dynv6.net+aws-mail-free-6762.dynv6.net+aws-mail-free-6826.dynv6.net+aws-mail-free-7145.dynv6.net+aws-mail-free-7149.dynv6.net+aws-mail-free-7153.dynv6.net+aws-mail-free-7194.dynv6.net+aws-mail-free-7358.dynv6.net+aws-mail-free-7477.dynv6.net+aws-mail-free-764.dynv6.net+aws-mail-free-7654.dynv6.net+aws-mail-free-7838.dynv6.net+aws-mail-free-7849.dynv6.net+aws-mail-free-788.dynv6.net+aws-mail-free-7897.dynv6.net+aws-mail-free-8085.dynv6.net+aws-mail-free-8091.dynv6.net+aws-mail-free-8205.dynv6.net+aws-mail-free-8225.dynv6.net+aws-mail-free-8467.dynv6.net+aws-mail-free-8475.dynv6.net+aws-mail-free-8741.dynv6.net+aws-mail-free-9015.dynv6.net+aws-mail-free-916.dynv6.net+aws-mail-free-9161.dynv6.net+aws-mail-free-9283.dynv6.net+aws-mail-free-9409.dynv6.net+aws-mail-free-9533.dynv6.net+aws-mail-free-9596.dynv6.net+aws-mail-free-9697.dynv6.net+aws-mail-free-9703.dynv6.net+aws-mail-free-9789.dynv6.net+aws-mail.accesscam.org+aws-mailer.dynv6.net+awsoo.com+ax05.cn+axax.asia+axgrad.io+axin05.icu+axionintellex.shop+axiz.org+axon7zte.com+axrx.hair+axsup.net+ayag.cloud+ayakamail.cf+ayumas.store+az18nep.camdvr.org+azame.pw+azazazatashkent.tk+azcomputerworks.com+azeqsd.fr.nf+azly.autos+azmeil.tk+azulejoslowcost.es+azuretechtalk.net+azurien.cfd+azzancoffee.com+b0h748o.kozow.com+b1of96u.com+b1tvjn3.loseyourip.com+b20nn6.cn+b2bx.net+b2cmail.de+b3j72kr.theworkpc.com+b7s.ru+babyeat.food+babyfun.fun+back67283.eu.cc+back7654.eu.cc+backilnge.com+bacteroidmail.com+badgerland.eu+badoop.com+badopsec.lol+badpotato.tk+baechecker.com+bahlill.cfd+baicai1145.online+baicai1145.shop+baidoxe.com+baileybridge.org+baipiaodashen.cloud-ip.cc+baiyucraft.sbs+baizoto.shop+bakalos.dpdns.org+bakultelo.com+balaket.com+balawo.com+banana.linkpc.net+banancaocap.com+banclone.pro+bandtoo.com+bangban.uk+bangdieukhien.net+banhang14.com+banit.club+banit.me+bank-opros1.ru+bankinnepal.com+banri.xyz+baqx.autos+bar-ton.store+bareed.ws+barnrestaurant.pro+barooko.com+barry.dpdns.org+barryogorman.com+bartdevos.be+baselogicroute.com+basepathgrid.com+baserda.net+bashyrcn.yachts+basketrise.com+basscode.org+batdongsanhatinh.org+bathdf.co.uk+batiinsaat.net+bauwerke-online.com+baybabes.com+baybumutan.shop+bazaaboom.com+bb28.dev+bbbbyyzz.info+bbfz.makeup+bbhost.us+bbitf.com+bbitj.com+bbitq.com+bbmail.store+bbmailku.com+bboys.fr.nf+bbroot.com+bbwg.one+bbxb.fashion+bbyb.fashion+bcaoo.com+bcast.ws+bcb.ro+bccto.me+bcm.edu.pl+bcmail.pro+bcooq.com+bda.io.vn+bdgstr.com+bdm.ovh+bdmuzic.pw+bdo.io.vn+bdq8.pw+bdshar.com+beaconmessenger.com+bearsarefuzzy.com+beastmail.space+beatbok.online+beautifulblessingsbeyondborders.org+bebed.cyou+bebel.cyou+beben.cyou+bebez.cyou+beddly.com+beefmilk.com+beelsil.com+beganment.com+begemail.com+begfax1.loseyourip.com+behatifoundation.org+bekasi.me+belamail.org+belgianairways.com+belicapcut.app+belljonestax.com+beluckygame.com+benipaula.org+benphim.com+benphim.net+benshelf.com+bepureme.com+beribase.ru+beribaza.ru+berirabotay.ru+berkahfb.com+berkahjayashope.com+berwie.com+bespokehaircare.co.uk+best-hosting.biz+best-john-boats.com+best-temp-mail.com+best-vpn.xyz+bestchoiceusedcar.com+bestlistbase.com+bestoption25.club+bestparadize.com+bestsoundeffects.com+besttempmail.com+beta.edu.pl+betacinder.com+betatensor.com+betr.co+betteryoutime.com+beyondreasonabledoubt.co.uk+bflcafe.com+bgtmail.com+bgx.ro+bgyiacczy.top+bhana.xyz+bhap.me+bheps.com+bhuxp.org+bidourlnks.com+big1.us+bigmail.lol+bigprofessor.so+bigstring.com+bigwhoop.co.za+bij.pl+bilingva-ca.store+bin-ich.com+binafex.com+binancepools.cloud+binbx.net+binech.com+binich.com+binka.me+binkmail.com+binnary.com+binsh.kro.kr+bio-muesli.info+bio-muesli.net+biojuris.com+bione.co+bipochub.com+birh.hair+birminghamlife.org.uk+bishwanathuk.cc+bitmah.com+bitmens.com+bitrealm.in+bittnex.com+bitwhites.top+bitymails.us+biubiuwholeworld.cn+biweia615.icu+biyug.com+biz.st+bizimalem-support.de+bizisstance.com+bj41.help+bjorwi.rest+bjvc.top+blackgoldagency.ru+blackmarket.to+bladesmail.net+blakeagency.buzz+blenched.com+blendlog.com+blenro.com+bletilla.cc+bletsoetownclosecharity.bio+blip.ch+blip.ovh+blnkt.net+blobapps.com+block-this-for-gambling.cloud-ip.cc+block521.com+blog3.cc.cd+blogger.nyc.mn+blogmyway.org+blogos.net+blogspam.ro+blogtricks.de+blondemorkin.com+blondmail.com+blpz.hair+bltiwd.com+bluedumpling.info+bluegrassluck.com+bluewerks.com+bmoar.com+bncinema.com+bnote.com+bnrlner.shop+bnyhr.us+boatmail.us+bobgf.ru+bobgf.store+bobmail.info+bobmurchison.com+bocas.tech+boerakemail.com+bofthew.com+bokgumail.kr+bomnet.net+bonobo.email+boofx.com+bookgame.org+bookthemmore.com+boom.publicvm.com+boom114.ccwu.cc+boommail.online+boostme.es+bootssl.com+bootybay.de+boranora.com+bored.lol+borged.com+borged.net+borged.org+bosakun.com+bosakun.online+boscharena.dev+boshi-gdh.club+bot.cd+bot.nu+botasky.eu.cc+botgetlink.com+botgetlink.net+botnet.my.id+boukshilf.com+boun.cr+bouncr.com+bowlfuel.com+box-mail.ru+box-mail.store+boxem.ru+boxem.store+boxfi.uk+boxformail.in+boximail.com+boxlet.ru+boxlet.store+boxmach.com+boxmail.lol+boxmail1.com+boxomail.live+boxtemp.com.br+boyaga.com+bpotogo.com+bptfp.net+bradingtowntrust.co.uk+brand-app.biz+brandallday.net+brashbeat.online+brasx.org+brazbuzii.online+breaite.com+breakthru.com+brefmail.com+brennendesreich.de+brevionix.cfd+brevitron.cfd+bridgetonmainstreet.org+briefalpha.org+briggsmarcus.com+brightfuturescharity.org.uk+bristolstatehousefoundation.org+brivian.link+broadbandninja.com+brodipek.xyz+brokenion.com+brothershaircut.com+brownjasen.ccwu.cc+browzensew.ca+browzensew.com+browzensew.icu+browzensew.info+browzensw.com+browzensw.info+browzensw.net+browzensw.store+bsfh.beer+bskyx.fun+bsnow.net+bspamfree.org+bspooky.com+bst-72.com+btb-notes.com+btc.email+btcmail.pw+btcmod.com+btizet.pl+btsblock.com+btthyto.org+buccalmassage.ru+budaya-tionghoa.com+budayationghoa.com+buddyfly.top+buffemail.com+bugfoo.com+bugmenever.com+bugmenot.com+buhf95r.ddnsfree.com+bukanimers.com+bukatv8.com+bukhariansiddur.com+bulapolo.site+bullbaby.com+bulrushpress.com+bultoc.com+bum.net+bumail.site+bumpymail.com+bunchofidiots.com+bund.us+bundes-li.ga+bunmail.one+bunnyhub.space+bunsenhoneydew.com+burangir.com+burnermail.bond+burnermail.cyou+burnthespam.info+burry.eu.org+burstmail.info+busd-mmjd3.wiki+business-degree.live+businessbackend.com+businesssuccessislifesuccess.com+buspad.org+bussinesa.app+bussitussi.com+busyaz.tech+butteiumien.io.vn+buy-blog.com+buyapp.foo+buymoreplays.com+buyordie.info+buyreview.us+buyusdomain.com+buyusedlibrarybooks.org+buzzcluby.com+buzzcut.ws+bwm.de5.net+bwmyga.com+bx52ff4a.shop+byagu.com+byconf.com+byebyemail.com+byespm.com+byiepsxqu.top+byjkprh.top+byom.de+bytedigi.com+bytonf.com+bznrehk.giize.com+bzpc.makeup+bzvrxf8.ooguy.com+c-eric.fr.nf+c-newstv.ru+c-pkk.icu+c-tta.top+c14.mobi+c1ph3r.xyz+c28.mobi+c4.fr+c4pro.uk+c51vsgq.com+caainpt.com+cabiste.fr.nf+cachedot.net+cade.org.uk+cafesui.com+caftee.com+caigq.qzz.io+caldrexa.cfd+calendro.fr.nf+california.edu.pl+californiafitnessdeals.com+calima.asso.st+calmriver.info+calvarystreetisa.org+cam4you.cc+cameltok.com+camera47.net+cameraity.com+camping-grill.info+cancer-treatment.xyz+candassociates.com+candymail.de+cane.pw+canfga.org+cangcud.com+cangcutku.pro+cantozil.com+canvect.com+caowo.online+capct.id+capcud.shop+capcut.digital+capcut.sbs+capcut.space+capcut02.shop+capcutku.io+capcutmeflo.shop+capcutmm.shop+capcutpro.click+capcutpro.dev+capcvt.es+capitalistdilemma.com+caprasolver.xyz+captus.cyou+caqcut.top+car101.pro+carbtc.net+care-breath.com+caregradeguard.com+carpin.org+cars2.club+carsencyclopedia.com+cartelera.org+caseedu.tk+cashflow35.co+cashflow35.com+casterview.xyz+casualdx.com+catfie.app+catgroup.uk+catsredeem.com+catterickgarrisonfootballcentre.uk+cauterize.top+cavi.mx+caye.org.uk+cazlg.com+cbair.com+cbasosbr.top+cbdol.mx+cbes.net+cboc.hair+cbsbada.com+cbty.ru+cbty.store+cbvl.co.uk+cc17.name.ng+cc18.name.ng+cc3.name.ng+cc6.name.ng+cc8c1bd6.abrdns.com+ccategoryk.com+ccimran.buzz+cckuy.com+ccm8klz.camdvr.org+ccmail.uk+ccqu.top+ccsuncare.com+cctc.fashion+cctoolz.com+ccwc.fashion+ccxiao.cn+cczc.fashion+cdfaq.com+cdlpvt3.mywire.org+cdnmia.com+cdnripple.com+cdpa.cc+cdxugmy.top+ceed.se+cek.pm+cellurl.com+cengrop.com+centermail.com+centermail.net+certexx.fr.nf+certificenter.com+certve.com+cetpass.com+cfo2go.ro+cg0gcab.mywire.org+cggup.com+ch.ma+chacuo.net+chahcyrans.com+chaichuang.com+chaineor.com+chalupaurybnicku.cz+chamconnho.com+chammy.info+chanceforfuture.org+chansd.com+chantellegribbon.com+chaocosen.com+chapsmail.com+charityrcao.org.uk+charl.us+chasefreedomactivate.com+chatclaude.top+chatgptmail.shop+chatgptuk.pp.ua+chatgtporg.eu.cc+chatich.com+chatworkstation.com+chaublog.com+chauhuy.click+chauhuy.io.vn+chauhuy.online+chauhuy.site+chautuyen.click+chautuyen.io.vn+chautuyen.online+cheaphub.net+cheapmori.store+cheatmail.de+chefalicious.com+cheminsdevie.ink+chenbot.email+chenbufan.top+chessgameland.com+chessgamingworld.com+chestcloudx.com+chewydonut.com+chibakenma.ml+chickenkiller.com+chielo.com+childrenth.com+childsavetrust.org+chilkat.com+chillart.org+chilloliandfii.space+chinamkm.com+chingchongme.site+chithinh.com+chitthi.in+choco.la+chogmail.com+choicemail1.com+choichay.com+choigi.com+chomolokko.shop+choner.cn+choner.shop+chong-mail.com+chong-mail.net+chong-mail.org+chongqilai.cc+chophim.com+chosenx.com+chotgo.com+chromentis.cfd+chsi.christmas+chuan.info+chumpstakingdumps.com+chundage.help+chupanhcuoidep.com+churchestate.org.uk+churchhousemanaton.co.uk+churchinsouthampton.org.uk+cigar-auctions.com+cihai.eu.cc+cihaifhqo.eu.cc+cihuy.net+cimario.com+cipcup.site+citmo.net+civikli.com+civx.org+cj4fj2a.camdvr.org+cjdeyuiw.eu.cc+cjgq.skin+ckaazaza.tk+cketrust.org+ckiso.com+ckvn.edu.vn+cl-cl.org+cl0ne.net+claimab.com+clandest.in+classesmail.com+classio.click+claudd.com+claverfield.org+cleaninbox.dynv6.net+clearbeam.pro+clearhabitpath.com+clearwatermail.info+clfapqg.theworkpc.com+click-email.com+clickcore99.click+clickdeal.co+clipmail.eu+clixser.com+clockemail.com+clone21.io.vn+cloneemail.com+clonehv.com+clonekhoe.com+clonemailsieure.com+clonemoi.tk+clonenpa.com+clonere.net+clonetrust.com+cloud-mail.top+cloud-temp.com+cloudflare.gay+cloudgen.world+cloudgue.site+cloudsign.in+cloudtempmail.net+cloudwhitespace.cc.cd+cloudwhitezone.cc.cd+cloudyourfast.net+clousy.site+clout.wiki+clowmail.com+clrmail.com+club106.org.uk+clx0vq5.kozow.com+clyvantis.cfd+cmail.blog+cmail.club+cmail.com+cmail.net+cmail.org+cmbl.top+cmcc.indevs.in+cmdkl.com+cmhvzylmfc.com+cnamed.com+cndps.com+cnebw.eu.cc+cneemail.com+cnew.ir+cnieux.com+cnmsg.net+cnoilpress.com+cnsds.de+co.cc+coasah.com+cobal.infos.st+cobarekyo1.ml+cocoro.uk+cocovpn.com+code-gmail.com+codeandscotch.com+codeguard.net+codei.site+coderdir.com+codestar.site+codesuc.top+codexrip.vip+coding.ccwu.cc+codinggo.cn+codivide.com+codywon.top+codzy.net+coffeeazzan.com+coffeejadore.com+coffeetimer24.com+cogsapb.ddnsfree.com+coieo.com+coin-host.net+coinlink.club+cok.org.uk+colabeta.com+colaname.com+coldemail.info+collegewh.edu.pl+colorcastmail.com+colurmish.com+cometclear.com+comfythings.com+compareshippingrates.org+completegolfswing.com+compressjpg.io+comwest.de+comyze.org+concu.net+conf.work+confmin.com+congacone312.shop+congnguyen.io.vn+connected.linkpc.net+connectifyhub.sbs+connho.com+connho.net+consumerriot.com+contaco.org+contact.infos.st+contactbox.work+contactpage.online+contbay.com+convergenceindia.co.in+coocuuu.food+cood.food+cooh-2.site+cookie007.fr.nf+coolandwacky.us+coolimpool.org+cooljump.org+copyhome.win+coralhost.my+corbyrise.com+coreclip.com+corhash.net+cornwallaerospaceeducationtrust.org+corridor.bond+cosdas.com+cosmorph.com+cosoinan.com+cosycritters.co.uk+cotasen.com+cotigz.com+courriel.fr.nf+courrieltemporaire.com+cousinment.com+covisuki.icu+coza.ro+cozilla.pw+cpc.cx+cqwbn.com+crankhole.com+crapmail.org+crastination.de+craventry.cfd+crazespaces.pw+crazymailing.com+crczrsxls.top+cream.pink+creative.publicvm.com+credit-loans.xyz+crepeau12.com+cresvyn.cfd+creteanu.com+crgjw3a.giize.com+cringemonster.com+crogra.org+cross-law.ga+cross-law.gq+cross.edu.pl+crossmailjet.com+crossroadsmail.com+crunchcompass.com+cruncoau.asia+crusthost.com+crybio.com+cryptoavalonsolhub.cloud+cryptogmail.com+cs.email+csapi.dpdns.org+csh.ro+cslua.com+cspaus.com+cszbl.com+ctmailing.us+ctos.ch+cttnoot.us+cu.cc+cuahangvppn.shop+cuaks.fun+cubene.com+cubiclink.com+cucadas.com+cuendita.com+cuirushi.org+cumnnm.us.ci+cunan.store+cuoly.com+cuongaquarium.com+cupbest.com+curlhph.tk+currentmail.com+curryworld.de+cursor13402.xyz+cuscuscuspen.life+cust.in+cutefrogs.xyz+cutevi.us+cutout.club+cutradition.com+cutsup.com+cutuvye.org+cuvox.de+cuvrs.info+cwetg.co.uk+cxbl.top+cxioms.help+cxwet.com+cyber-innovation.club+cyber-phone.eu+cyberionexus.shop+cybertemp.cfd+cybertemp.xyz+cycinst.com+cyclelove.cc+cyjd.top+cykr.beer+cylab.org+cyln.beer+cypi.fr+czx.one+d1yun.com+d3p.dk+d4ngerssquy.info+d8tiya6.camdvr.org+daabox.com+dab.ro+dacoolest.com+dadaolibai.eu.cc+daemonixgames.com+daemsteam.com+daerdy.com+dahewushi.eu.cc+daibb.us+daibond.info+daily-email.com+dailynove.com+dailynutria.com+daimuedu.com+daintly.com+dakaka.org+dalanshu.org+damai.webcam+dammexe.net+damnthespam.com+damowang.eu.cc+dandikmail.com+dann.mywire.org+dantriviet.shop+dao.pp.ua+daouse.com+dapdigital.site+dapurx.me+dardr.com+darkharvestfilms.com+darkserver.ru+daryxfox.net+dasdasdascyka.tk+dash-pads.com+dataarca.com+datadudi.com+datapinacle.com+datarca.com+datazo.ca+datchuban.top+datdonshopee.site+datenschutz.ru+datgemini.io.vn+datprovn.io.vn+datprovnn.io.vn+datum2.com+daugr.com+dautubds.io.vn+davidkoh.net+davidlcreative.com+davidtrix.biz+dawin.com+dawnwick.org+dawsoncountygunclub.org+dawushihe.eu.cc+dawushihehe.eu.cc+dayizhan.top+daymail.life+daymailonline.com+dayrep.com+dbea.autos+dbmail.one+dboso.com+dboxmail.com+dbunker.com+dcctb.com+dcemail.com+dcpa.net+dcyo.skin+dd2car.com+ddat0511.click+ddcrew.com+ddfd.fashion+ddsdg34.abrdns.com+de-a.org+dea-21olympic.com+deadaddress.com+deadchildren.org+deadfake.cf+deadfake.ga+deadfake.ml+deadfake.tk+deadspam.com+deagot.com+deajeng.store+dealja.com+deallabs.org+dealrek.com+deapad.com+debitur.cam+decep.com+decodewp.com+decornido.com+dede.infos.st+deekayen.us+deenur.com+deepconverts.com+deepmails.org+deepmaster.fun+deepneko.xyz+deepyinc.com+defomail.com+degap.fr.nf+degar.xyz+degradedfun.net+dehaopay.com+deinbox.com+deisgn-ai.work.gd+delaeb.com+delayload.com+delayload.net+delikkt.de+delivrmail.com+delorex.com+deltajohnsons.com+deluxmail.com+delvionis.cfd+demen.ml+dengekibunko.ga+dengekibunko.gq+dengekibunko.ml+denipl.com+denipl.net+dentaguardmouthguard.com+deornaumail.com+depdocla.net+der-kombi.de+derkombi.de+derluxuswagen.de+desertsundesigns.com+desfrenes.fr.nf+deshnetarchadacalculator.one+designhta.work.gd+desmond.eu.cc+desoz.com+despam.it+despammed.com+dev-null.cf+dev-null.ga+dev-null.gq+dev-null.ml+dev17.tech+devbike.com+developermail.com+developtool.app+devh24.online+devnullmail.com+devsonline.studio+devthien.io.vn+deyom.com+dfghjertyh.dynv6.net+dfyuih.eu.cc+dgdf.cc+dghdfjfd.eu.cc+dh372.top+dharmatel.net+dheiwuy.eu.cc+dhkt.skin+dhm.ro+dhnow.com+dhoahn.eu.cc+dhy.cc+dialogus.com+diapaulpainting.com+dichvuxe24h.com+dicopto.com+diddyricky.com+diddyricky.fr+diddyricky.info+diddyricky.store+diemhenvn.com+digdig.org+digi-value.fr+digial.jo3.org+digibeast.my+digibeast.store+digimaster.bond+digimaster.eu.cc+diginey.com+digital-message.com+digitaldesign.run.place+digitalesbusiness.info+digitalmail.info+digitalmariachis.com+digitalsanctuary.com+digitecy.live+dildoe.cfd+dildosfromspace.com+dim-coin.com+dimalk.com+dingbone.com+dinlaan.site+dino.icu+diolang.com+diplom-voronesh.ru+directmail24.net+dis.hopto.org+disaq.com+disbox.net+disbox.org+discard.cf+discard.email+discard.ga+discard.gq+discard.ml+discard.tk+discardmail.com+discardmail.de+discos4.com+dishcatfish.com+disign-concept.eu+disign-revelation.com+dispo.in+dispomail.eu+disposable-e.ml+disposable-email.ml+disposable.cf+disposable.ga+disposable.ml+disposable.site+disposableaddress.com+disposableemailaddresses.com+disposableinbox.com+disposablemails.com+dispose.it+disposeamail.com+disposely.xyz+disposemail.com+disposemymail.com+disposly.com+dispostable.com+divad.ga+divermail.com+divismail.ru+diwaq.com+dixz.net+diyongjin.net+dizigg.com+djiv.xyz+djwekih.eu.cc+dkz.opik.net+dldweb.info+dlemail.ru+dlwv.makeup+dmail.one+dmarc.ro+dmcelements.org+dmts.fr.nf+dmxs8.com+dnbp.hair+dndent.com+dnkah.eu.cc+dns.army+dns.navy+dnsclick.com+dnses.ro+dnslog.tech+doanart.com+doantotnghiep.com+dob.jp+docash.app+docbao7.com+docse.site+dodgeit.com+dodgemail.de+dodgit.com+dodgit.org+dodsi.com+dogai.qzz.io+dogclothing.org+dogking.dpdns.org+dogmrp.com+dohoanganh.site+doiea.com+doj.one+dolofan.com+dolphinnet.net+domforfb1.tk+domforfb18.tk+domforfb19.tk+domforfb2.tk+domforfb23.tk+domforfb27.tk+domforfb29.tk+domforfb3.tk+domforfb4.tk+domforfb5.tk+domforfb6.tk+domforfb7.tk+domforfb8.tk+domforfb9.tk+domozmail.com+don.edu.pl+dona.one+dona.pw+dona.rip+donebyngle.com+donemail.my.id+donemail.ru+dongqing365.com+donkicode.top+dontreg.com+dontsendmespam.de+dontsleep404.com+donusumekatil.com+doobb.com+doojazz.com+doquier.tk+doreact.com+dorothyfoundation.org+doszo.qzz.io+dotapodemail.com+dotman.de+dotmsg.com+dotool8.top+dotos.dev+dotslashrage.com+dotvu.net+dotzi.net+doublemail.de+douchelounge.com+doudizhu.top+doulas.org+downloadigpost.com+downloadvideoig.app+dozvon-spb.ru+dp76.com+dpfrufiwo.top+dpmstore.id.vn+dpmurt.my+dpptd.com+dprasu.sbs+dr69.site+dramamixio.icu+draughtier.com+drdrb.com+drdrb.net+dreamadventure.org+dreamclarify.org+dreameg.com+dreamgreen.fr.nf+dred.ru+drevo.si+drewzen.com+driftz.net+drimex.cfd+dripzgaming.com+drivetagdev.com+drivz.net+drmail.in+droggo.engineer+droolingfanboy.de+dropcake.de+dropinboxes.com+dropjar.com+droplar.com+dropmail.me+dropons.com+dropsin.net+drovantis.cfd+drovenix.cfd+drowblock.com+drugsellers.com+druzik.pp.ua+dsbe.makeup+dsfsfdsfds.shop+dsgvo.party+dsgvo.ru+dshfjdafd.cloud+dshznonline.cc+dsiay.com+dsitip.com+dspwebservices.com+dswe-56f.xyz+dtvpn.dpdns.org+duam.net+dubokutv.com+duck2.club+duckyoursick.com+ducpham.id.vn+dudmail.com+dugmail.com+duidir.com+duk33.com+dukedish.com+dukunmodern.id+dulich360.com+dulich84.com+dulichdatlanh.com+dulichdatlanh.vn+dulieu.io.vn+dumalu.com+dumbass.nl+dump-email.info+dumpandjunk.com+dumpmail.de+dumpyemail.com+dunamispfm.org+dunkos.xyz+durandinterstellar.com+duskmail.com+dusrui.com+dustinry.com+duvips.com+duya25446.top+duyquyen.site+dv2.host+dvaren.online+dvdpit.com+dwarfmining.com+dwiworka.pro+dwse.edu.pl+dwseal.com+dyceroprojects.com+dyclsr.xyz+dyebkj.eu.cc+dyera.studio+dyfgiavcrw.eu.cc+dygovil.com+dymarent.cfd+dynarix.cfd+dz17.net+dz62.help+dzntn.io.vn+dztyhd.cn+e-mail.com+e-mail.org+e-marketstore.ru+e-pool.co.uk+e-pool.uk+e-postkasten.de+e-record.com+e-tomarigi.com+e3z.de+e4ward.com+e6hoohs.camdvr.org+eacademia.uk+ealea.fr.nf+eanok.com+eartin.net+ease.es+eastcombe.org+easy-trash-mail.com+easygbd.com+easyhomefit.com+easymailer.live+easymails.cc+easynetwork.info+easytrashmail.com+eatmea2z.club+eay.jp+ebar.site+ebbob.com+ebeschlussbuch.de+eby9h2m.giize.com+ecallheandi.com+eckpcin.giize.com+ecolo-online.fr+ecoverseworld.com+ecstor.com+edankeunwe.site+edfc.skin+edgepodlab.com+edgetopgrid.com+edgex.ru+edinburgh-airporthotels.com+edmondventures.com+edny.net+edshol.net+edu-qin.ccwu.cc+education.nyc.mn+edudingy.cfd+eduip.eu.org+edumail.edu.pl+edumail.edu.rs+edumaili.com+edumaili.edu.pl+edumaill.edu.pl+edupolska.edu.pl+edv.to+ee1.pl+ee2.pl+eedl.skin+eeedv.de+eelmail.com+eelraodo.com+eemail.eu.cc+een4dnt.ooguy.com+eewmaop.com+efdsdsdw.cloud-ip.cc+effobe.com+efxs.ca+egg5233.com+egg5233.one+eggbanjos.org+eggso.click+eggsuwz.ooguy.com+eggur.com+egirl.help+egni.beer+egvoo.com+egzones.com+einmalmail.de+einrot.com+einrot.de+eintagsmail.de+einzieg.site+eiveg.com+ekot.xyz+elafans.com+eldobhato-level.hu+elearningjournal.org+electro.mn+electrochillplanet.com+electrolabx.com+elerso.com+eligou.store+elitepixels.store+elitevipatlantamodels.com+elixora.cfd+eljawir.com+elji.autos+elki-mkzn.ru+elobits.com+elondonteam.work.gd+elpisproject.org+elumetra.cfd+elygifts.com+emaii.io.vn+email-68.com+email-fake.cf+email-fake.com+email-fake.ga+email-fake.gq+email-fake.ml+email-fake.tk+email-free.online+email-jetable.fr+email-lab.com+email-temp.com+email.edu.pl+email.net+email1.pro+email10p.org+email60.com+email84.com+emailabox.pro+emailage.cf+emailage.ga+emailage.gq+emailage.ml+emailage.tk+emailaoa.pro+emailasia1.com+emailate.com+emailawb.pro+emailax.pro+emailbbox.pro+emailbin.net+emailboxer.one+emailcbox.pro+emailcoffeehouse.com+emailcu.icu+emaildark.fr.nf+emaildbox.pro+emaildienst.de+emaildrop.io+emailfake.com+emailfake.ml+emailforyou.info+emailfoxi.pro+emailfreedom.ml+emailgen.uk+emailgenerator.de+emailgo.de+emailgratisan.fun+emailhook.site+emailias.com+emailigo.de+emailinbo.live+emailinfive.com+emailisvalid.com+emailjps.com+emailkp.com+emaillime.com+emailluu.asia+emailmiser.com+emailmuaqat.shop+emailna.co+emailnator.com+emailnax.com+emailnow.net+emailnow.one+emailo.pro+emailondeck.com+emailplay.org+emailportal.info+emailproxsy.com+emailracc.com+emailresort.com+emailrod.com+emails.ga+emailsecurer.com+emailsensei.com+emailsingularity.net+emailspam.cf+emailspam.ga+emailspam.gq+emailspam.ml+emailspam.tk+emailsy.info+emailtech.info+emailtemporanea.com+emailtemporanea.net+emailtemporar.ro+emailtemporario.com.br+emailthe.net+emailtik.com+emailtmp.com+emailto.de+emailuae.com+emailure.net+emailvb.pro+emailviet.com+emailwarden.com+emailwww.pro+emailxfer.com+emaily.pro+emailz.cf+emailz.ga+emailz.gq+emailz.ml+emalupe.com+emaxasp.com+embege.xyz+embekhoe.com+emeil.in+emeil.ir+emeraldwebmail.com+emergencymail.site+emergentvillage.org+emkei.cf+emkei.ga+emkei.gq+emkei.ml+emkei.tk+eml.pp.ua+emlhot.com+emlhub.com+emlpro.com+emltmp.com+emocan.name.tr+empireanime.ga+empva.io.vn+empva1.com+empva1.io.vn+empva11.com+empva11.io.vn+emstjzh.com+emz.net+emziegz.com+enayu.com+end.tw+endingimpunity.com+endob.com+enfq.autos+englishcriketclub.org.uk+enitempmail.xyz+enotj.com+enowgntg.site+enspinner.com+enterto.com+envy17.com+eoffice.top+eoopy.com+eosada.com+eoslux.com+eoutrbl.com+ep77.com+epaco9t.loseyourip.com+epb.ro+epbox.ru+epbox.store+epetsoft.com+ephemail.net+ephemeral.email+eposta.buzz+eposta.work+epostal.ru+epostal.store+epsteinisland.click+epurcf.org+eqgq.hair+eqiluxspam.ga+equivara.cfd+erahods.com+ereplyzy.com+ericjohnson.ml+eripo.net+ernestturcotte.us+ero-tube.org+erth.nl+esadverse.com+esbano-ru.ru+esc.la+escapehatchapp.com+esemay.com+esgeneri.com+eshimod.com+esiix.com+esprity.com+estate-invest.fr+esterace.com+estrowebservices.com+etempmail.net+etenx.com+eth2btc.info+ether123.net+ethereum1.top+ethersports.org+ethersportz.info+etickethelpdesk.net+etics.us+etotvibor.ru+etquakemultimedia.com+etramay.com+etranquil.com+etranquil.net+etranquil.org+etubemail.com+etzg.de5.net+euaqa.com+euleina.com+eulercraft.com+euroallsports.org.uk+eurokool.com+euucn.com+evairo.fun+evairo.web.id+evanfox.info+eve.dpdns.org+eveav.com+evilcomputer.com+evilgodshop.uk+evjy.skin+evnft.com+evomiserver.com+evontra.cfd+evopo.com+evusd.com+evvgo.com+evyush.com+ewebrus.com+ewma.hair+ewma.skin+exahut.com+examcentral.co.uk+examstudy.xyz+exbts.com+exclussi.com+exdonuts.com+exelica.com+exespay.com+exhaycle.com+exile.my.id+existiert.net+exitbit.com+exitstageleft.net+exkucn.ccwu.cc+exmab.com+expiredtoaster.org+explodemail.com+expltain.com+express.net.ua+extracurricularsociety.com+extraku.com+extraku.net+extraku.shop+extremail.ru+extrset.com+exweme.com+exzork.sbs+ey-hungry.top+eycfhb.com+eyee.eu.cc+eyepaste.com+eynlong.com+ez.lv+ezai.chat+ezehe.com+ezfill.com+ezimb.com+ezonemail.com+ezsj.hair+ezstest.com+ezua.com+ezztt.com+f1b.email+f1b.vn+f2b.click+f2b.email+f2b.info+f2b.site+f2b.tech+f2b.tokyo+f2b.vn+f2c.email+f2c.host+f2c.me+f2c.mobi+f2c.press+f2d.click+f2d.info+f2d.life+f2d.pro+f2e.click+f2e.email+f2e.pro+f2e.pw+f2e.world+f2f.email+f2f.pw+f3p.io.vn+f4k.es+f4wxmpu.kozow.com+f5p0y90.ooguy.com+f5v7u9a.ddnsfree.com+f6z6ica.camdvr.org+fabaos.com+facebook-email.cf+facebook-email.ga+facebook-email.ml+facebookmail.gq+facebookmail.ml+facemac.website+fackme.gq+fadingemail.com+fadsfdsfaa.indevs.in+faecesmail.me+fafa.beer+fag.wf+failbone.com+faithkills.com+faizasoft.com+fake-box.com+fake-email.pp.ua+fake-mail.cf+fake-mail.ga+fake-mail.ml+fakedemail.com+fakeinbox.cf+fakeinbox.com+fakeinbox.ga+fakeinbox.info+fakeinbox.ml+fakeinbox.tk+fakeinformation.com+fakemail.fr+fakemail.io+fakemail.net+fakemailgenerator.com+fakemailz.com+falconryadventurecentreofeducation.com+fallinhay.com+famamail.com+fammix.com+fanclub.pm+fandoe.com+fangoh.com+fangxiaobai.us.ci+fangxiaobai1.us.ci+fanicle.com+fansworldwide.de+fantastu.com+fantasy139.icu+fantasymail.de+fantatua.com+fanymail.com+fanzher.com+farah.rip+farouter.tech+farrse.co.uk+fasl4kas3.site+fasssd.ru+fasssd.store+fast-email.info+fast-mail.fr+fastacura.com+fastchevy.com+fastchrysler.com+fasternet.biz+fastestflex.com+fastinbox.one+fastkawasaki.com+fastmail.edu.pl+fastmazda.com+fastmitsubishi.com+fastnissan.com+fastnodo.click+fastsearcher.com+fastsubaru.com+fastsuzuki.com+fasttoyota.com+fastyamaha.com+fatebd.com+fatflap.com+faxico.com+faxzu.com+faybetsy.com+fazka.ovh+fazs.skin+fbb.cool+fbb.id.vn+fbb.io.vn+fbb.kim+fbb.linkpc.net+fbb.lu+fbb.vn+fbfbs.lol+fbhotro.com+fbi.one+fbins001mail.com+fbins607.com+fbkjlnry.top+fblgsl.cam+fbma.tk+fboxmail.com+fbviamail.com+fcetpkqwm.top+fddns.ml+fdfdsfds.com+fdfggh-df5.cc+fdger88.cc+fdhsui.eu.cc+fdmail.top+fdpbnzx.cn+fdsgsd.org+fdsregre.shop+fdvctte.info+featcore.com+fedayroi.online+feelmyheartwithsong.com+feiyujingxuan.top+femailtor.com+fengzheng.qzz.io+fenzhuai.top+fer-gabon.org+feralrex.com+ferd.live+ferdomnermail.com+feriwor.com+fermaxxi.ru+ferngrove.org+feroxid.com+fettometern.com+fewzc.makeup+fexbox.org+fexbox.ru+fexpost.com+fextemp.com+ffpp.store+ffps.fun+fft.edu.do+ffyf.fashion+fgmail.cyou+fgtygcop.store+fhoau.eu.cc+fhpfhp.fr.nf+fhwui.eu.cc+fhwyuoia.eu.cc+fiallaspares.com+fibmail.com+ficken.de+fictionsite.com+fidhost.com+fifafotball.org.uk+fightallspam.com+fighthunger.co.uk+fightingzebras.org+figjs.com+figshot.com+figurescoin.com+fiifke.de+filbert4u.com+filberts4u.com+file2drive.com+filetodrive.com+film-blog.biz+filmla.org+filzmail.com+finacenter.com+findemail.info+findids.net+findize.com+findmeghana.org+findu.pl+finews.biz+fingso.com+finsmine.info+fir.hk+fira.my+firemail.com.br+firemailbox.club+firerocket.site+firstaidtrainingschool.co.uk+firstlawyer.org+fisdom.vip+fitbloomlab.com+fitnesrezink.ru+fivemail.de+fivermail.com+fixmail.tk+fizmail.com+fj7v67f.camdvr.org+fjic.hair+fjic.skin+fkainc.com+fknm8.mobi+flaimenet.ir+flameoflovedegree.com+flashemail.site+flatimostore.cloud+flavourity.com+flayeraaron.eu.cc+flayerhu.eu.cc+fleckens.hu+flemail.ru+flews.app+flexvio.com+fliegender.fish+flobo.fr.nf+flock84.uk+florevia.cfd+flosek.com+flowconnect.beer+flowu.com+flu.cc+fluidsoft.us+flurred.com+fly-ts.de+flyhubs.top+flyinggeek.net+flymail.tk+flyovertrees.com+flyspam.com+flywaverun.com+flyzy.net+fmuss.com+fncp.ru+fncp.store+fngd.hair+fog.one+fommie.com+fommie.online+fommie.store+foobarbot.net+footard.com+footballgamesbd.site+foothilltoy.site+for4u.net+forapps.space+forbmmend.com+foreastate.com+forecastertests.com+foreskin.cf+foreskin.ga+foreskin.gq+foreskin.ml+foreskin.tk+forexnews.bg+forexru.com+forexzig.com+forge45k.io.vn+forgetmail.com+forgetmenotstudio.org.uk+formodapk.com+fornow.eu+forregmail.asia+forregmail.xyz+forspam.net+forum.nyc.mn+forward.cat+fosil.pro+foxja.com+foxnew.info+foxtrotter.info+fpgrabber.com+fpt-student-support.store+fqys.hair+fr.cr+fr33mail.info+fragolina2.tk+frankhealeyfoundation.org+frapmail.com+frappina.tk+frederictonlawyer.com+free-email.cf+free-email.ga+free-temp-mail.eu.org+free-temp.net+freebabysittercam.com+freeblackbootytube.com+freecat.net+freecustom.email+freedom4you.info+freedomcentremereside.org+freedompop.us+freedrops.org+freefattymovies.com+freegrok.cc.cd+freehotmail.net+freeimagehosts.org+freeimghost.org+freeinbox.email+freelance-france.eu+freeletter.me+freemail.ms+freemails.cf+freemails.ga+freemails.ml+freemails.pp.ua+freemeil.ga+freemeil.gq+freemeil.ml+freeml.net+freeplumpervideos.com+freerubli.ru+freeschoolgirlvids.com+freesistercam.com+freesourcecodes.com+freeteenbums.com+freetimer.online+freundin.ru+friday12.store+friendlymail.co.uk+friendsofbram.com+frive.site+frm.ovh+front14.org+frostmail.fr.nf+frostypeak.info+fruitservice.xyz+frwdmail.com+frza.me+fsercure.online+fsitip.com+fsotl.icu+fthcapital.com+ftlz.hair+ftp.sh+ftpinc.ca+ftrh.skin+fuckedupload.com+fuckingduh.com+fucklinuxdo.com+fuckme69.club+fuckneo.org+fucknloveme.top+fuckxxme.top+fudgerub.com+fudier.com+fuirio.com+fuk996.icu+fukaru.com+fukurou.ch+fullangle.org+fulvie.com+fumemail.com+fun4k.com+fun64.com+fundapk.com+fundproceed.com+funnycodesnippets.com+funnyfail.app+funnylolcap.com+funnylolcap.fr+funnylolcap.org+funnylolcap.store+funnymail.abrdns.com+funnymail.de+funteka.com+furzauflunge.de+fusioninbox.com+futcost.online+futcost.ru+futuramind.com+fuvk.ru+fuvk.store+fuwa.be+fuwa.li+fuwamofu.com+fuwari.be+fux0ringduh.com+fviadropinbox.com+fviainboxes.com+fviamail.com+fviamail.work+fvz7wvh.ddnsfree.com+fxavaj.com+fxnxs.com+fxos.hair+fxt.ink+fxtubes.com+fxxf.beer+fxzig.com+fyawmtu.camdvr.org+fycloud.online+fyeiwh.eu.cc+fyii.de+fynix.sbs+fyronex.cfd+fznb.hair+g-mail.biz.id+g-mail.kr+g0pg02x.theworkpc.com+g14l71lb.com+g1xmail.top+g2xmail.top+g3xmail.top+g4hdrop.us+g947lzu.kozow.com+gacharevenue.cc+gafy.net+gagcalculator.me+gage.ga+gailiuzi.icu+gakhum.com+galaxim.fr.nf+galaxy.tv+galebird.cc.cd+gally.jp+gamadaiz.shop+gamail.top+gamapa.asia+gamebcs.com+gamegregious.com+gamen.me+gamepec.com+gamerai.shop+gamerai.space+gamerai.website+gamgling.com+gandobaba.bond+ganlin.shop+garasikita.pw+garbagecollector.org+garbagemail.org+gardenscape.ca+gardu.codes+garizo.com+garliclife.com+garod1.xyz+garrymccooey.com+gashoainam.io.vn+gassmail.com+gasuda.com+gav0.com+gavrom.com+gawab.com+gaxetovemail.com+gbcmail.win+gblw.site+gbmail.top+gbui.autos+gcfv.skin+gcmail.top+gcpfas.shop+gcpmakerds.cyou+gcpowner.online+gcpripon.space+gcpriponteam.xyz+gcptoday.xyz+gdcrm.store+gddp2018.edu.vn+gdfgergrer.online+gdmail.top+gdmo.autos+gdqoe.net+gdxs.cc.cd+gear3.pro+gebrauchtwarencenter.com+gedmail.win+geekforex.com+geeksun.us.ci+geew.ru+gehensiemirnichtaufdensack.de+geldwaschmaschine.de+gelitik.in+gemapan.com+gemipro1.store+gemmarosefoundation.co.uk+gemniultra.me+gendeng.indevs.in+genderfuck.net+generator.email+generator1email.com+gentleinfopath.com+genzmaile.com+genzotp.com+genztrang.com+geometrics.icu+georgefletcher.org.uk+georgeheddon.co.uk+geronra.com+gerv.app+geschent.biz+get-mail.cf+get-mail.ga+get-mail.ml+get-mail.tk+get.pp.ua+get1mail.com+get2mail.fr+getai-hub.com+getairmail.cf+getairmail.com+getairmail.ga+getairmail.gq+getairmail.ml+getairmail.tk+getasail.com+getbloomdata.com+getbox89.xyz+geteit.com+getemail.space+getfun.men+getgptcode.com+getmail.my.id+getmail1.com+getmailfree.cc+getmails.eu+getmails.top+getmule.com+getnada.cc+getnada.com+getnowtoday.cf+getol.pro+getonemail.com+getonemail.net+getotp.fun+getover.de+getsimpleemail.com+gett.icu+gewalusitest1.cloud-ip.cc+gexik.com+gghjnvgfyjhk.top+ggmal.ml+ggoop69.kozow.com+ggrainn.com+ggu6ctm.ooguy.com+ggvendas.store+ggvk.ru+ggvk.store+ggxg.fashion+ggxhunter.com+ghfnhcf.xyz+ghk55.us+gholar.com+ghosttexter.de+ghvv.click+gi-mel.web.id+giacmosuaviet.info+giaiphapmuasam.com+giantmail.de+giare.fun+gifto12.com+gimbmail.com+gimme-cooki.es+gimpmail.com+gimuemoa.fr.nf+ginzi.be+ginzi.co.uk+ginzi.es+ginzi.net+ginzy.co.uk+ginzy.eu+giodaingan.com+gioidev.news+giratex.com+girlfriend.ru+girlmail.win+girlsindetention.com+girlsundertheinfluence.com+gishpuppy.com+gislinghamsilverband.com+github-com-disposable-email-domains.loseyourip.com+giue.hair+giveh2o.info+givememail.club+givemetoken.xin+givmail.com+gixenmixen.com+gkd2323c.in+gkyd3vu.loseyourip.com+gladogmi.fr.nf+glaventra.cfd+glaviu.icu+glcspp.top+gli.dpdns.org+glitch.sx+globalbizflow.com+globaltouron.com+glorylandconnections.com+gls-info.help+glubex.com+glucosegrin.com+gmaail.icu+gmaiil.top+gmail-xsniper.com+gmail-xsniper.site+gmail-xsniper.space+gmail.or.at+gmail2.gq+gmailedu.us+gmailinsta.com+gmaill.click+gmaill.vn+gmaillive.cloud+gmaillk.com+gmailold.com+gmailot.com+gmailxsn.com+gmailxsn.site+gmailxsn.space+gmailxyz.bond+gmali.online+gmatch.org+gmeenramy.com+gmel.biz.id+gmel.my.id+gmells.com+gmial.com+gmneel.eu.cc+gmx1mail.top+gmxmail.top+gmxmail.win+gnctr-calgary.com+gng.edu.pl+gni8.com+gnwzqaz.shop+go2farm.io.vn+go2usa.info+go2vpn.net+goalmillion.online+goatmail.uk+gob.re+godfare.com+godulygmail.com+goemailgo.com+goeschman.com+gohivezone.com+gokublue.me+golano2.co.uk+gold.edu.pl+goldenmagpies.com+goldinbox.net+goldivis.work.gd+golemico.com+goleudy.org.uk+goliszek.net+gomail.in+gomomy.sbs+gongjua.com+gonida.co.uk+gonida.com+gonida.uk+gonw3bb.camdvr.org+googl.win+goomail.club+goonby.com+gooner.cat+goplaygame.ru+gorillaswithdirtyarmpits.com+goround.info+gosarlar.com+gossipglove.uk+gosuslugi-spravka.ru+gothere.biz+gotmail.com+gotmail.net+gotmail.org+gotrak.org+gowcp.com+gowikibooks.com+gowikicampus.com+gowikicars.com+gowikifilms.com+gowikigames.com+gowikimusic.com+gowikinetwork.com+gowikitravel.com+gowikitv.com+gpt-mail-free-1200.dynv6.net+gpt-mail-free-140.dynv6.net+gpt-mail-free-1427.dynv6.net+gpt-mail-free-1550.dynv6.net+gpt-mail-free-161.dynv6.net+gpt-mail-free-1694.dynv6.net+gpt-mail-free-1721.dynv6.net+gpt-mail-free-1980.dynv6.net+gpt-mail-free-1998.dynv6.net+gpt-mail-free-2019.dynv6.net+gpt-mail-free-2049.dynv6.net+gpt-mail-free-2109.dynv6.net+gpt-mail-free-2141.dynv6.net+gpt-mail-free-2307.dynv6.net+gpt-mail-free-2310.dynv6.net+gpt-mail-free-2375.dynv6.net+gpt-mail-free-248.dynv6.net+gpt-mail-free-2491.dynv6.net+gpt-mail-free-3.dynv6.net+gpt-mail-free-3074.dynv6.net+gpt-mail-free-3093.dynv6.net+gpt-mail-free-3127.dynv6.net+gpt-mail-free-3291.dynv6.net+gpt-mail-free-3330.dynv6.net+gpt-mail-free-3348.dynv6.net+gpt-mail-free-3476.dynv6.net+gpt-mail-free-3527.dynv6.net+gpt-mail-free-366.dynv6.net+gpt-mail-free-3792.dynv6.net+gpt-mail-free-3927.dynv6.net+gpt-mail-free-4111.dynv6.net+gpt-mail-free-4547.dynv6.net+gpt-mail-free-4771.dynv6.net+gpt-mail-free-4775.dynv6.net+gpt-mail-free-4788.dynv6.net+gpt-mail-free-4821.dynv6.net+gpt-mail-free-4900.dynv6.net+gpt-mail-free-5018.dynv6.net+gpt-mail-free-5182.dynv6.net+gpt-mail-free-5211.dynv6.net+gpt-mail-free-5226.dynv6.net+gpt-mail-free-5241.dynv6.net+gpt-mail-free-5261.dynv6.net+gpt-mail-free-5386.dynv6.net+gpt-mail-free-5406.dynv6.net+gpt-mail-free-551.dynv6.net+gpt-mail-free-5539.dynv6.net+gpt-mail-free-561.dynv6.net+gpt-mail-free-5659.dynv6.net+gpt-mail-free-574.dynv6.net+gpt-mail-free-5902.dynv6.net+gpt-mail-free-6067.dynv6.net+gpt-mail-free-610.dynv6.net+gpt-mail-free-6221.dynv6.net+gpt-mail-free-6289.dynv6.net+gpt-mail-free-6320.dynv6.net+gpt-mail-free-6342.dynv6.net+gpt-mail-free-6397.dynv6.net+gpt-mail-free-6419.dynv6.net+gpt-mail-free-6603.dynv6.net+gpt-mail-free-6664.dynv6.net+gpt-mail-free-6691.dynv6.net+gpt-mail-free-6779.dynv6.net+gpt-mail-free-6812.dynv6.net+gpt-mail-free-6925.dynv6.net+gpt-mail-free-6962.dynv6.net+gpt-mail-free-7208.dynv6.net+gpt-mail-free-7298.dynv6.net+gpt-mail-free-7493.dynv6.net+gpt-mail-free-7548.dynv6.net+gpt-mail-free-7572.dynv6.net+gpt-mail-free-7582.dynv6.net+gpt-mail-free-7689.dynv6.net+gpt-mail-free-7939.dynv6.net+gpt-mail-free-8015.dynv6.net+gpt-mail-free-8049.dynv6.net+gpt-mail-free-8591.dynv6.net+gpt-mail-free-86.dynv6.net+gpt-mail-free-861.dynv6.net+gpt-mail-free-8611.dynv6.net+gpt-mail-free-8671.dynv6.net+gpt-mail-free-8773.dynv6.net+gpt-mail-free-8786.dynv6.net+gpt-mail-free-8791.dynv6.net+gpt-mail-free-882.dynv6.net+gpt-mail-free-8886.dynv6.net+gpt-mail-free-8933.dynv6.net+gpt-mail-free-8944.dynv6.net+gpt-mail-free-902.dynv6.net+gpt-mail-free-9243.dynv6.net+gpt-mail-free-9307.dynv6.net+gpt-mail-free-9446.dynv6.net+gpt-mail-free-9502.dynv6.net+gpt-mail-free-9515.dynv6.net+gpt-mail-free-9584.dynv6.net+gpt-mail-free-9609.dynv6.net+gpt-mail-free-9620.dynv6.net+gpt-mail-free-9695.dynv6.net+gpt-mail-free-9825.dynv6.net+gpt-mail-free-9935.dynv6.net+gpt-mail.myftp.org+gpt20260701.top+gptmail.cc.cd+gptmail.us.ci+gptmail.webredirect.org+gptworkone.dev+gpxmail.win+gqov.top+grabafilafoundation.org+gracetvglobal.com+grandmamail.com+grandmasmail.com+graphicanal.site+graphicbulk.site+graphicdany.site+graphicedge.click+graphicedge.io.vn+graphicedge.site+graphicedge.tokyo+graphicenda.site+graphiclean.click+graphiclean.io.vn+graphiclean.site+graphiclean.tokyo+graphiclens.site+graphiclever.site+graphicmen.site+grassdev.com+gravexia.cfd+gravityengine.cc+great-host.in+greencafe24.com+greendike.com+greenhousemail.com+greensloth.com+greenvin.io.vn+greggamel.com+greggamel.net+gregorsky.zone+gregorygamel.com+gregorygamel.net+grendel.qzz.io+grewq.makeup+grimstroke.me+grish.de+gristod.my+griuc.schule+grn.cc+groklan.com+groupbuff.com+grqccqbwg.top+grr.la+grtd.beer+gruene-no-thanks.xyz+grugrug.ru+gruz-m.ru+gs-arc.org+gsoleyfoyle.org.uk+gsredcross.org+gsrv.co.uk+gsxstring.ga+gthyjuytr.dynv6.net+gts.cc.cd+guanshuyun.com+gudanglowongan.com+gudri.com+guerillamail.biz+guerillamail.com+guerillamail.de+guerillamail.info+guerillamail.net+guerillamail.org+guerillamailblock.com+guerrillamail.biz+guerrillamail.com+guerrillamail.de+guerrillamail.info+guerrillamail.net+guerrillamail.org+guerrillamailblock.com+gufacoding.com+gufum.com+guima2.asia+gukox.org+guozivpn.cc.cd+gustr.com+guysmail.com+guzukll.camdvr.org+gxemail.men+gxmail.top+gxybkq6.theworkpc.com+gyan-netra.com+gykf.hair+gyknife.com+gynzi.co.uk+gynzi.es+gzb.ro+gzeos.com+h0tmaii.com+h2beta.com+h8s.org+ha92.store+haben-wir.com+habenwir.com+habitnestguide.com+habitue.net+hacccc.com+hackersquad.tk+hackthatbit.ch+hahawrong.com+haibabon.com+haibaipei.ccwu.cc+haida-edu.cn+hailu.publicvm.com+hairs24.ru+halamaridfcfs.site+halashao1.dpdns.org+halashao3.us.ci+halcroft.org+haleloya.site+halionex.cfd+haltospam.com+hamham.uk+handrik.com+handsofhelpinc.org+hanghai232.shop+hangxomcuatoilatotoro.ml+hanha.kozow.com+hanoinet.io.vn+happiseektest.com+happy-new-year.top+happy2023year.com+happy9toy.com+happydomik.ru+happyheadshed.org+happyhome.eu.cc+haqimi.cc.cd+harakirimail.com+hardwork.icu+haren.uk+haribu.com+harpix.org.uk+hartbot.de+hasanmail.ml+hat-geld.de+hatespam.org+hathitrannhien.edu.vn+havefundarling.xyz+havertz.tk+hawrong.com+haydoo.com+hayys.app+hazelnut4u.com+hazelnuts4u.com+hazmat.help+hazmatshipping.org+hcap.ai+hccmail.win+hcypku.cloud+hdcroom.us+hdiscord.xyz+headstrong.de+healingheartmission.org+healthforwomen.info+healxo.org+heathenhammer.com+heathenhero.com+hebase.com+hecat.es+heheee.com+heirfoundation.com+heisei.be+hellodream.mobi+helloricky.com+hellosravan.in+helpinghandtaxcenter.org+helpjobs.ru+helpthechildren.uk+heocondeisng.cc+herilev.top+herlan.co.uk+heros3.com+herp.in+herpderp.nl+hertz.ltd+hesoyam.shop+hethongtudong.store+hetzez.com+heycmm.cn+heyzalo.vn+hezll.com+hfogzua.top+hh7f.com+hhan.top+hhe.org.uk+hhyru.us+hi2.in+hi5.si+hiddentragedy.com+hideam.com+hidebox.org+hidebusiness.xyz+hidemail.de+hidemail.pro+hidemail.us+hidesmail.net+hidevak.com+hidingmail.net+hidmail.org+hidzz.com+hiemail.net+hieu.in+hieuclone.net+highapes.run.place+highbros.org+higher-tech.linkpc.net+highstar.shop+hightech.jo3.org+higogoya.com+higuruma.site+hihi.lol+hikuhu.com+hillaxiant.xyz+hilmipremindo.com+hilostar.com+hiltonvr.com+him6.com+himacreative.id+himail.infos.st+himail.online+hiredify.com+histartool.com+hitbase.net+hitbtcpool.cloud+hiverun.io+hjdkker-kdet.click+hkuv.skin+hkvtop.us+hldrive.com+hlkes.com+hmail.us+hmamail.com+hmh.ro+hnfw-ngd.top+hnfw-ngd.wiki+hoanggiaanh.com+hoanglong.tech+hochsitze.com+hohohim.com+hoichvu.ddnsfree.com+hokyflix.site+hola.org+holio.day+holl.ga+holmes.de5.net+homecut.pro+homehappy.eu.cc+homestartbromley.org.uk+homewiseleaf.com+homewrt.xx.kg+homvela.com+honesthirianinda.net+honeys.be+hongsemeixi.us.ci+honor-8.com+hook2ad.com+hookmono.click+hooooooo.store+hopemail.biz+hopesx.com+horizonspost.com+hormails.com+hornhorizon.com+hornyalwary.top+horsgit.com+host1s.com+hostcalls.com+hostguru.top+hosthalting.lol+hosthalting.site+hosthalting.store+hostingmail.me+hostlaba.com+hostpapa.dynv6.net+hot-mail.cf+hot-mail.ga+hot-mail.gq+hot-mail.ml+hot-mail.tk+hotboyckdh.shop+hotboyckdh1122.shop+hotboyckdhn55.shop+hotelpiesi.pro+hotelplazer.com+hotelplazer.fr+hotelplazer.org+hotelplazer.store+hotlinkimg.com+hotmai.com+hotmail-us.top+hotmailproduct.com+hotmailtrusted.com+hotmeil.net+hotmial.com+hotpop.com+hotprice.co+hotrokh.com+hotsmial.click+hotsoup.be+hottchurch.org.uk+hottmat.com+housat.com+housereformas.es+howardgiving.org+hpari.com+hpc.tw+hpj4l28.loseyourip.com+hqfi.hair+hqid.homes+hqpdf.com+hripleh.us.ci+hs.vc+hsmw.net+ht.cx+hta.2bd.net+hta.publicvm.com+hthlm.com+htmail.store+http.nyc.mn+httpsgreenwichmeantime.in+huage.me+hualabtech.com+huangao.xyz+huangniu8.com+hubglee.com+hubhost.store+hudisk.com+hudska.dpdns.org+huizk.com+hukkmu.tk+hulapla.de+hulisang.edu.kg+hulkteam.cyou+huluwaaaron.eu.cc+humaility.com+hungpackage.com+hungtpt.site+hunnur.com+huolala.de5.net+huongdanfb.com+huongvemientrung.store+huoyumars.cc.cd+hushmail.cf+huskion.net+husng-kang.top+hutathuww.org+hutudns.com+huychau.click+huychau.online+huynhlx.shop+huynhtran.io.vn+huytuyen.click+huytuyen.online+huytuyen.site+huyvillafb.online+hvastudiesucces.nl+hvhg.skin+hviy.skin+hvva.hair+hwax4h4.giize.com+hwqmh2g.ddnsfree.com+hwsye.net+hxopi.ru+hxopi.store+hygle.net+hyhotmail.ccwu.cc+hymenjj.cfd+hypenated-domain.com+i-dork.com+i-love-you-3000.net+i0mn8cx.mywire.org+i2b.asia+i2b.cam+i2b.com.vn+i2b.email+i2b.fun+i2b.id.vn+i2b.info+i2b.io.vn+i2b.lol+i2b.lu+i2b.mov+i2b.pw+i2b.space+i2b.vn+i2bgmail.com+i2c.email+i2c.pw+i2c.vn+i2i.vn+i2m.email+i2m.vn+i2n.vn+i2p.vn+i2pmail.org+i2u.vn+i2x.vn+i6.cloudns.cc+iafu.hair+iafu.skin+iandsec.cc.cd+iaoss.com+ibande.xyz+ibmdoors.com+ibmdoors.com.cn+ibnuh.bz+ibolinva.com+ibymail.com+icantbelieveineedtoexplainthisshit.com+icbr.us+iceans.cc.cd+icelandgcp.org.uk+icemail.club+ich-essen-fleisch.bio+ichecker.tech+ichigo.me+icidroit.info+ickletonrelief.co.uk+ickletonrelief.shop+icloudmail.kr+icloulb.com+icmans.com+iconmal.com+icotz.com+icousd.com+icubik.com+icwr.beer+icx.in+icx.ro+icznn.com+ideuse.com+idf.ovh+idfd.live+idg.io.vn+idns7v8.ooguy.com+idont.date+idu4aa4.info+idx4.com+idxue.com+ieatspam.eu+ieatspam.info+ieh-mail.de+iencm.com+ifeq.hair+iffymedia.com+ifoxdd.com+ige.es+igg.biz+ignoremail.com+igty.autos+ihateyoualot.info+ihazspam.ca+ihc3znb.theworkpc.com+iheartspam.org+ihnpo.food+ihra.hair+ikbenspamvrij.nl+ikewe.com+ikomail.com+ikuromi.com+ilck.hair+ilcvn.cn+illistnoise.com+illnessth.com+illubd.com+iloveion.com+ilovespam.com+ilyx7j5.theworkpc.com+im5z.com+imaanpharmacy.com+imagenbox.xyz+imagic.wiki+imail.edu.vn+imail1.net+imails.asso.st+imails.info+imailt.com+imap.fr.nf+imashr.com+imbo.hair+imc.io.vn+imfaya.com+img-free.com+imgof.com+imgv.de+immo-gerance.info+imnart.com+imperialcnk.com+importemail.com+imranbt.store+imranccnn.buzz+imrancm.buzz+imrancumi.buzz+imranking.buzz+imranmax.buzz+imranspc.buzz+imstations.com+imul.info+in-ulm.de+in2reach.com+inactivemachine.com+inbax.tk+inbound.plus+inbox.si+inbox2.info+inboxalias.com+inboxbear.com+inboxclean.com+inboxclean.org+inboxdesign.me+inboxed.im+inboxed.pw+inboxfast.space+inboxfly.space+inboxkitten.com+inboxly.website+inboxnow.ru+inboxnow.store+inboxopen.space+inboxorigin.com+inboxproxy.com+inboxstore.me+inclick.net+inclusiveprogress.com+incognitomail.com+incognitomail.net+incognitomail.org+incq.com+inctart.com+ind.st+inderpalsandhu.com+indevgo.com+index-mail.com+indianahorsecouncil.org+indieclad.com+indigobook.com+indirect.ws+indomaed.pw+indomina.cf+indoserver.stream+indosukses.press+indoxs.bond+indsec.online+ineec.net+inetopenwrt.dpdns.org+infix1.io.vn+inflyratech.site+infobuzzsite.com+infocom.zp.ua+infoisp.me+infolinewest.com+ingam.online+inggo.org+inilogic.com+init.ink+inkiny.com+inkomail.com+inlook.cloud+inly.vn+inmune.ddns.net+inmynetwork.tk+innovationvirtuelle.asia+inoutmail.de+inoutmail.eu+inoutmail.info+inoutmail.net+inpwa.com+inreur.com+insanony.art+insanony.one+insanony.store+insanumingeniumhomebrew.com+insgrmail.site+inshuan.com+insorg-mail.info+instaddr.ch+instaddr.uk+instaddr.win+instagr.vn+instagra.vn+instagram.io.vn+instance-email.com+instant-mail.de+instantblingmail.info+instantemailaddress.com+instantletter.net+instantmail.fr+instmail.uk+instrete.com+intady.com+internet-v-stavropole.ru+internetkeno.com+internetoftags.com+interstats.org+intersteller.com+intlgalleryheritageculture.org+intobx.com+intopwa.com+intopwa.net+intopwa.org+introex.com+inversiq.cfd+investore.co+inwagit.com+inxout.dpdns.org+ioioioio.sbs+iojn.hair+iolq.top+ionolenonos.com+ionolenonos.fr+ionolenonos.info+ionolenonos.store+ionq.pl+iotf.net+iozak.com+ip4.pp.ua+ip6.pp.ua+ipaddressforme.com+ipinf.eu.org+ipoo.org+ippandansei.tk+ipsur.org+ipusgo.cfd+ipxwan.com+iqec.skin+iqfucsod.top+iqxu.hair+irabops.com+iralborz.bid+iraniandsa.org+iraqedu.online+irc.so+irealiy.cyou+iridales.com+irinakicka.site+irish2me.com+irishspringrealty.com+iroid.com+ironbrookco.com+ironiebehindert.de+irpine.com+irssi.tv+is.af+isdaq.com+isep.fr.nf+isfew.com+ishop2k.com+ismartsense.online+isosq.com+ispeedtest.digital+ist-hier.com+istii.ro+isukrainestillacountry.com+iswin.ccwu.cc+it7.ovh+italy-mail.com+itaolo.com+itcompu.com+itduniya.online+itfast.net+itit.tk+itmj3po.ddnsfree.com+itmo.edu.pl+itos.cloudns.org+itquoted.com+itsbds.com+itsedit.click+itsjiff.com+itspid.com+itunesgiftcodegenerator.com+iuanhoi.store+iubridge.com+iuemail.men+iuno.fun+iupo219.ddnsfree.com+iwatermail.com+iwx4k98.theworkpc.com+ixaks.com+ixhale.com+ixqr.hair+ixunbo.com+ixx.io+iya.fr.nf+iysqv.com+izhowto.com+izunasan.my.id+izunasuite.biz.id+j-p.us+j3r8qd.space+j5bie4.tech+jabmag.com+jackierobinsonparkoffame.org+jafps.com+jaga.email+jagomail.com+jailbreakeverything.com+jaipas.lu+jajxz.com+jakarta.io.vn+jakemsr.com+jakl.li+jamesat.biz.id+jamesat.my.id+jamesjfattorini.rocks+jamesthynnealmshouse.co.uk+jamyjmkqdsc.com+janestore.xyz+janproz.com+japanesegirls.cc+japnc.com+jaqis.com+jarszone.com+jasminesports.com+jasonbella.online+jasonswheels.org+jav8.de+javadmin.com+javaemail.com+javaka.live+javindra.cfd+jazzvip.site+jbsu.hair+jbsze.com+jbsze.ne+jbsze.net+jc58t04.kozow.com+jcnorris.com+jdmadventures.com+jdz.ro+je-recycle.info+jejes.de+jejesfb.biz.id+jellow.ml+jellycat.eu.cc+jellyrolls.com+jeoce.com+jeremytunnell.net+jessitrust.com+jessyx.bond+jet-renovation.fr+jetable.com+jetable.fr.nf+jetable.net+jetable.org+jetable.pp.ua+jgjitffy.store+jgkcr.com+jhfnre-kjf.sbs+jhkf.beer+jhphoto.top+ji-a.cc+ji5.de+ji6.de+ji7.de+jiangwy.one+jiaoo.pp.ua+jiaxi.work+jibbo01.com+jieluv.com+jika.gg+jilingling.eu.cc+jincer.com+jingood.dpdns.org+jinkeyun.com+jinva.fr.nf+jiongguo.top+jiooq.com+jioso.com+jisan.uk+jisankhan1.site+jiuji.asia+jjfcharitabletrust.co.uk+jjice.com+jjj.ee+jjk.app+jjlj.fashion+jjmj.fashion+jjuisyj.top+jjxj.fashion+jjxt6lv.mywire.org+jkotypc.com+jksndh-afd2.wiki+jlpevents.co.uk+jmail.fr.nf+jmail.ovh+jmail.ro+jmods.me+jmt2469.xyz+jnad.skin+jndp.hair+jnwexkd.giize.com+jnxjn.com+jobbikszimpatizans.hu+jobbrett.com+jobdatei.de+jobposts.net+jobs-to-be-done.net+jobscai.com+jobsma.pp.ua+jobzyy.com+joelpet.com+joetestalot.com+jofuso.com+joihonm.shop+jojolt.shop+jojomedia.store+jonira.sbs+jonsjav.cc+jopho.com+jora.dpdns.org+joseihorumon.info+josse.ltd+jourrapide.com+joymail.cyou+joywavepoint.com+jp-ml.com+jpco.org+jrhmail.com+jsifh5i.kozow.com+jsnc.cloud+jsncos.com+jsrsolutions.com+jualakun.com+jualakunfb.co+jualfb.co+jumonji.tk+jungkamushukum.com+junk.to+junk1e.com+junkmail.ga+junkmail.gq+just-email.com+justdefinition.com+justemail.ml+juvanta.cfd+juyouxi.com+jwork.ru+jxin.hair+jxpomup.com+jywa.social+jzlvoei.cn+jzlz.hair+jzzm.top+k-global.dev+k4money.com+kabamail.com+kabarr.com+kabinbilla.com+kademen.com+kadokawa.cf+kadokawa.ga+kadokawa.gq+kadokawa.ml+kadokawa.tk+kaengu.ru+kagi.be+kajaib.social+kaka0.kr+kakadua.net+kakao-mail.com+kakaomail.kr+kakator.com+kakaveo3.io.vn+kakslsie.store+kalapi.org+kalquoris.cfd+kamen-market.ru+kamete.org+kampret.asia+kamsg.com+kankoplm.eu.cc+kanlangld.shop+kanonmail.com+kantclass.com+kaoing.com+kaovo.com+kappala.info+kapten.site+kaptencpl.com+kara-turk.net+karatraman.ml+karenkey.com+kariplan.com+karta-kykyruza.ru+kartvelo.com+kasmail.com+kasmirfx.buzz+kaspop.com+katalyst.indevs.in+kathrynis.my.id+kathrynis.web.id+katputli.world+kattthu.us+katztube.com+kavio.my.id+kaw-sar.top+kawneha.site+kaybooks.top+kayfilms.top+kaygroup.top+kayilo.com+kaynlab.com+kazava.tech+kazelink.ml+kbishwanathuk.cc+kbox.li+kcoporation.com+kcql.hair+kcrw.de+kcya.skin+kd2.org+kdpsl.org+ke1le.cyou+kee40vq.ddnsfree.com+keecs.com+keepmail.dev+keepmymail.com+kein.date+keinhirn.de+keipino.de+kejinxi.xyz+kekita.com+kelenson.com+kelimo.sbs+kellychibale-researchgroup-uct.com+kemail.uk+kempstoncharities.band+kempstoncharities.co.uk+kemptvillebaseball.com+kenari.online+kendev.id.vn+kenfern.com+kenhbanme.com+kenhphim.net+kenvanharen.com+kepkat.com+kepkat.site+kerotu.com+ket-qua.org+ketimunfam.online+ketua.id+kgfu.makeup+khaibn.com+khamu.me+khoke.nl+khtextile.com+kia-sdn.me+kiani.com+kidaroa.com+kiecchn.com+kierko.com+kiki287666.xyz+killlove.site+killmail.com+killmail.net+killyourtime.com+kimagure.ccwu.cc+kimagure1.cc.cd+kimdyn.com+kimgmail.com+kimora.space+kimsdisk.com+kimzavin.shop+kinda.email+kindamail.com+kingdais.com+kingproplan.site+kingsq.ga+kingss.de5.net+kino-100.ru+kintil.buzz+kiois.com+kismail.ru+kisoq.com+kissgy.com+kisstwink.com+kitap.az+kitnastar.com+kiwkiw.shop+kjhg.hair+kjkpc.net+kjkszpjcompany.com+kjnbtv.dedyn.io+kk.io.vn+kkdty.dynv6.net+kkkoouy.cyou+kkmail.be+kkoup.com+kksm.be+klassmaster.com+klassmaster.net+kleinanzeigen-verification.de+klick-tipp.us+kliknesia.io+klingai.asia+klipschx12.com+kloap.com+klovenode.com+kludgemush.com+klut.io+klyverra.cfd+klzlk.com+kmail.li+kmail.live+kmail.qzz.io+kmail123.com+kmhow.com+knaresboroughtownmuseum.org+knickerbockerban.de+knilok.com+knmcadibav.com+knol-power.nl+knowledgemd.com+kobrandly.com+kodeholik.site+kodpan.com+kokalo.store+kokklsd.dpdns.org+koletter.com+kommunity.biz+kon42.com+konican.com+konigyuan.us.ci+konterkulo.com+kontoko.org+konultant-jurist.ru+kook.ml+kopagas.com+kopaka.net+korimoddin.store+korona-nedvizhimosti.ru+korvanta.cfd+koshu.ru+kosmetik-obatkuat.com+kostenlosemailadresse.de+koszmail.pl+kpay.be+kpmn-design.org+kpooa.com+kpost.be+kppk.beer+kpxj.hair+kpxj.skin+kqbz.beer+kqhmln6.theworkpc.com+kravintis.cfd+krd.ag+kreabaka.site+krouter.net+krsw.tk+kruay.com+krypton.tk+krysentra.cfd+kskblzdjdwkzkbl.top+ksmtrck.tk+kswm.beer+ktisocial.asia+ktpingprox.id.vn+kuhaku.indevs.in+kuhrap.com+kuku.lu+kulmeo.com+kulturbetrieb.info+kumli.racing+kurin.sbs+kuromee.com+kuromee.store+kurumibnb.dog+kurzepost.de+kutakbisajauhjauh.gq+kv2vpn.eu.org+kvbs.hair+kvhrr.com+kvhrs.com+kvhrw.com+kwifa.com+kwift.net+kwilco.net+kwtest.io+kxbj.beer+kyal.pl+kynninc.com+kyntaris.cfd+kyois.com+kyriog.fr+kyuusei.fr.nf+kyx9sgz.loseyourip.com+kzccv.com+l-c-a.us+l2gyw37.mywire.org+l2rrz31.ddnsfree.com+l33r.eu+l6factors.com+laafd.com+labananmakmur.com+labetteraverouge.at+labforge.freeddns.org+laborderie.com+labworld.org+lacedmail.com+lackmail.net+lackmail.ru+lacraffe.fr.nf+lacto.info+lags.us+laicai8.sbs+lain.ch+lak.pp.ua+lakelivingstonrealestate.com+lakqs.com+laksamantunggalakma.me+lalayun.cyou+lalulahoot.me+lamasticots.com+lambsauce.de+landmail.co+lanuiopl.bond+laoeq.com+laoia.com+lapakqu.com+lapluz.xyz+lappies.net+laptoplonghai.com+larisia.com+larland.com+lashyd.com+last-chance.pro+laste.ml+lastexile.site+lastmail.co+lastmail.com+laulund.info+launchpadx.shop+launders.money+lawlita.com+laxex.ru+laxex.store+laxiw.org+laymro.com+lazerbade.com+lazerbade.fr+lazerbade.org+lazerbade.store+lazyinbox.com+lazyinbox.us+lbrmail666.site+lbvz.homes+lcvfdvynb.top+ldaho.biz+ldkll.cn+ldofy2e.ooguy.com+ldop.com+ldtp.com+le-tim.ru+leadwizzer.com+lebetrust.org+lecn.beer+lee.mx+leechchannel.com+leeching.net+leetmail.co+lefruit-dev.work+legalrc.loan+legendaryseller.com+leie.me+lellno.gq+lellol.dev+lellol.tech+lemonkk.cn+lenovog4.com+leoguio.site+leopik.com+lerany.com+lerbhe.com+lerch.ovh+lero3.com+leruvo.icu+lesobprovermail.com+lessismore.eu.cc+letterhaven.net+letterprotect.net+lettersboxmail.com+letthemeatspam.com+levi.cc.cd+leviacerman.store+lez.se+lfsz.beer+lftl.hair+lgxscreen.com+lhsdv.com+liadhene.com+liamcyrus.com+liang-tts.shop+liangganxiaopu.bond+libinit.com+licccons.icu+licenses.sbs+lifebitsnotes.com+lifebyfood.com+lifetimefriends.info+lifetotech.com+lifetreechurch.co.uk+lifewiseleaf.com+liggegi.com+lightv.online+ligsb.com+likeageek.fr.nf+likemovie.net+likevip.net+lilbahlil.me+lillemap.net+lilo.me+lilspam.com+lilsuite.id+lindenbaumjapan.com+link2mail.net+linkcoll.my.id+linkedindiscount.com+linkedintuts2016.pw+linkmail.info+linkspo.my.id+linlin.cloud+linlshe.com+linshiyou.com+linshiyouxiang.net+linux-do.me+linuxgo.us.ci+linuxmail.so+linxi.online+linyu.qzz.io+linzefor.asia+linzefor.shop+liocbrco.com+liondapt.com+liopsacac.shop+lista.cc+litedrop.com+littlejohns.info+littlemvh.org.uk+littsocial.com+liun.cc.cd+liuyuyu.space+liveforms.org+liveradio.tk+livinitlarge.net+lixlord.xyz+liyao.edu.kg+lizery.com+lkgn.se+llciuoau.top+llogin.ru+lloudfsxly.top+lnovic.com+lnwtt.com+loadby.us+loan101.pro+loaoa.com+loapq.com+locanto1.club+locantofuck.top+locantowsite.club+locawin.com+locomodev.net+loganister.com+logicfieldzen.com+logicstreak.com+login-email.cf+login-email.ga+login-email.ml+login-email.tk+logsmarter.net+logular.com+loh.pp.ua+lohinja.com+loin.in+lokenathassociation.co.uk+lolfreak.net+lolmail.biz+lonaxter.site+londonyouthsailing.org+longsbkt.xyz+lookugly.com+lordfortescue.news+lordfortescue.org.uk+lordofmysteries.org+lordsofts.com+lortemail.dk+losemymail.com+lostnow.org+love-your.mom+lovecalculatorname.org+lovecv.cn+lovegivingsadaqah.org+lovemeet.faith+lovemeleaveme.com+lovepet.vip+lovertboy.online+loveuu.xyz+lowprizo.com+lpfmgmtltd.com+lqkrxvc.loseyourip.com+lr7.us+lr78.com+lroid.com+lru.me+ls-server.ru+lsaar.com+lsbl6fq.mywire.org+lsd10086.ccwu.cc+lsd8866.ccwu.cc+lsereborn.com+lsfh.hair+lsirdomain.us.ci+lsyx24.com+lts35.help+lu1mtac.ooguy.com+luckfeed.com+luckymail.org+luffygadgets.com+lujialu.edu.kg+lujian.de5.net+lukecarriere.com+lukemail.info+lukop.dk+lum25kcredit.io.vn+lumeika.com+lumg.uk+luminexis.cfd+luminix1.shop+lumm25k.io.vn+lumyrix.cfd+lunarmoon.online+lunetra.shop+lunor.cfd+lushiyi.eu.cc+lushosa.com+lutech.uk+luv2.us+luxentra.cfd+luxovira.cfd+luxudata.com+lxbeta.com+lxydawang.top+lydir.com+lyfestylecreditsolutions.com+lyft.live+lympstonevillagehall.co.uk+lynex.sbs+lyngo.tech+lynwise.shop+lyricspad.net+lyxhzz.com.cn+lzoaq.com+lzum.homes+m21.cc+m4ilweb.info+ma1l.duckdns.org+mabal.fr.nf+maboard.com+mabox.eu+mac-24.com+machen-wir.com+macmail.info+macos.one+macr2.com+macromaid.com+macromice.info+magamail.com+magbit.food+maggotymeat.ga+magicbox.ro+magim.be+magspam.net+mahreenlifestyle.shop+maidlow.info+mail-card.net+mail-easy.fr+mail-filter.com+mail-help.net+mail-hosting.co+mail-hub.info+mail-mario.fr.nf+mail-now.top+mail-owl.com+mail-share.com+mail-temporaire.com+mail-temporaire.fr+mail-tester.com+mail.by+mail.gw+mail.tm+mail.wtf+mail0.ga+mail1.top+mail101.xyz+mail10m.com+mail11.xyz+mail114.net+mail12h.com+mail1a.de+mail1web.org+mail21.cc+mail22.club+mail2rss.org+mail333.com+mail4.uk+mail4qa.com+mail4trash.com+mail666.ru+mail7.io+mail707.com+mail72.com+mail789.dedyn.io+mailaddress.de+mailadresi.tk+mailapp.top+mailapril.org+mailba.uk+mailback.com+mailbai.com+mailbali.com+mailbidon.com+mailbiscuit.com+mailbiz.biz+mailblocks.com+mailbox.in.ua+mailbox.zip+mailbox49.com+mailbox52.ga+mailbox80.biz+mailbox82.biz+mailbox87.de+mailbox92.biz+mailboxify.ru+mailboxify.store+mailboxly.ru+mailboxly.store+mailboxy.fun+mailboxy.ru+mailboxy.store+mailbucket.org+mailcat.biz+mailcatch.com+mailchannels.de+mailchatgpt.eu.cc+mailchop.com+mailcker.com+mailclone2023.top+maildax.me+mailde.de+mailde.info+maildrop.cc+maildrop.cf+maildrop.ga+maildrop.gq+maildrop.ml+maildu.de+maildx.com+maildy.site+maileater.com+mailed.in+mailed.ro+mailedu.edu.pl+maileduvn.us+maileimer.de+maileme101.com+mailer.edu.pl+mailer.io.vn+mailers.edu.pl+mailexpire.com+mailf5.com+mailfa.tk+mailfall.com+mailfast.pro+mailfirefly.com+mailfirst.icu+mailfor1month.shop+mailforgo.site+mailforspam.com+mailfortiktok.us+mailfree.ga+mailfree.gq+mailfree.ml+mailfreeonline.com+mailfs.com+mailgo.cyou+mailguard.me+mailgutter.com+mailhazard.com+mailhazard.us+mailhex.com+mailhz.me+mailimate.com+mailin8r.com+mailinatar.com+mailinater.com+mailinator.co.uk+mailinator.com+mailinator.gq+mailinator.info+mailinator.net+mailinator.org+mailinator.us+mailinator0.com+mailinator1.com+mailinator2.com+mailinator2.net+mailinator3.com+mailinator4.com+mailinator5.com+mailinator6.com+mailinator7.com+mailinator8.com+mailinator9.com+mailincubator.com+mailisia.com+mailismagic.com+mailita.tk+mailjunk.cf+mailjunk.ga+mailjunk.gq+mailjunk.ml+mailjunk.tk+mailku.co+mailllshop.website+maillog.uk+mailmagnet.co+mailmate.com+mailmaxy.one+mailmay.org+mailme.gq+mailme.ir+mailme.lv+mailme24.com+mailmenot.io+mailmetrash.com+mailmoat.com+mailmoth.com+mailms.com+mailna.biz+mailna.co+mailna.in+mailna.me+mailnada.cc+mailnada.com+mailnator.com+mailnesia.com+mailnet.io.vn+mailnoop.store+mailnull.com+mailnuo.com+mailo.edu.pl+mailold.us+mailonaut.com+mailorc.com+mailorg.org+mailosaur.net+mailox.fun+mailp.org+mailphu.com+mailpick.biz+mailpluss.com+mailpooch.com+mailpoof.com+mailpress.gq+mailpro.lat+mailpro.live+mailproxsy.com+mailpts.com+mailpull.com+mailquack.com+mailrock.biz+mailrun.one+mailsa.biz.id+mailsa.my.id+mailsac.com+mailsafe.fr.nf+mailsbay.com+mailscrap.com+mailseal.de+mailserv.info+mailshan.com+mailshell.com+mailshiv.com+mailshou.com+mailshun.com+mailsiphon.com+mailslapping.com+mailslite.com+mailslurp.com+mailsucker.net+mailt.net+mailt.top+mailtao.me+mailtechx.com+mailtecom.com+mailtemp.info+mailtemple.xyz+mailtemporaire.com+mailtemporaire.fr+mailtest.ccwu.cc+mailto.plus+mailtome.de+mailtothis.com+mailtraps.com+mailtrash.net+mailtrix.net+mailtub.com+mailtv.net+mailtv.tv+mailuniverse.co.uk+mailvip.net+mailw.site+mailx.click+mailxyz.cyou+mailyan.my.id+mailzi.ru+mailzilla.com+mailzilla.org+mailzy.org+mainerfolg.info+mainkask.site+make.cc.cd+makemenaughty.club+makemetheking.com+makeraura.online+makertrial.com+makmursrondol.store+makoli.sbs+makoli.space+malahov.de+malayalamdtp.com+malioter.pro+mama3.org+mamabood.com+mamangbadrut.site+mameganteng.store+mamulenok.ru+managedisabled.online+mandraghen.cf+manhmmonew.online+manifestgenerator.com+mannawo.com+mansiondev.com+maohe.cloud+mapsguy.com+marchguidesassociation.org+marchguidesassociation.org.uk+marhumal.tech+marineso.com+mariyaa.pp.ua+mark-compressoren.ru+markableytrust.org.uk+markandvirginiarometty.org+marketlink.info+markmurfin.com+marrytodo.de+martenson-mail.mywire.org+martenson-mail.ooguy.com+martenson-mail.theworkpc.com+masbahlil.xyz+mask03.ru+maskmy.id+masonline.info+masteryforn.shop+maswae.world+matamuasu.ga+matchpol.net+matjoa.com+matmayer.com+matra.site+max-mail.org+maxresistance.com+maxseeding.com+maxtanie.com+maxturns.com+mayre.shop+mbox.re+mbx.cc+mbygjjo.mywire.org+mc-fly.be+mc088ue.loseyourip.com+mcache.net+mcdomaine.fr.nf+mchasd.eu.cc+mciek.com+mcpservers.one+mcs.cc.cd+mcunnm.ccwu.cc+mdahld.eu.cc+mdhc.tk+mdz.email+meantinc.com+mebeiuk.co.uk+mebelnu.info+mech2build.io.vn+mechanicalresumes.com+mechanicspedia.com+medevsa.com+mediaeast.uk+mediaholy.com+medicichoir.org+mediseat.com+medkabinet-uzi.ru+meef.uk+meepsheep.eu+meevpo.id+megasend.org+mehda.eu.cc+mehr-bitcoin.de+meidecn.com+meikeya.com+meinspamschutz.de+meituy.com+mekqh.eu.cc+melbourne.edu.pl+meltedbrownies.com+meltmail.com+meltp.com+memeazon.com+memoniclife.online+memsg.site+meng2026.bond+meng2026.cyou+mengma.eu.cc+mengundang.live+mentonit.net+meocon.org+meomo.store+meonvr.com+mepost.pw+merepost.com+merry.pink+meruado.uk+merumart.com+merxo.me+mesemails.fr.nf+mess-mails.fr.nf+messagebeamer.de+messibucu.click+messwiththebestdielikethe.rest+meta.aid.pl+meta.auto.pl+meta.corsica+meta.mail.pl+metadownload.org+metaintern.net+metajaya.biz.id+metalunits.com+metaorbitx.com+metas.io.vn+mexvat.com+mezimages.net+mfapi.dpdns.org+mfsa.info+mfsa.ru+mfunza.com+mfxis.com+mgdns.shop+mgtop.cc+mgxianlu.gq+mhzayt.online+miaferrari.com+mianfeibuluo.com+miaowuai.buzz+miauj.com+michaeladmin.eu+michaeladmin.fr+michaeladmin.org+michaeladmin.store+mickaben.fr.nf+midcoastcustoms.com+midcoastcustoms.net+midcoastsolutions.com+midcoastsolutions.net+middletoncheneyuc.uk+mideastlens.com+mideastview.com+midiharmonica.com+midlertidig.com+midlertidig.net+midlertidig.org+midwestpride.org+mierdamail.com+migmail.net+migmail.pl+migumail.com+mihep.com+miistermail.fr+mijnhva.nl+mikfarm.com+mikrotikvietnam.com+mikrotikvn.com+mikrotikx.com+mikumirai.top+milllogiciel.asia+miloras.fr.nf+minefieldmail.com+minhquang2000.com+minidmx.icu+minimail.gq+ministry-of-silly-walks.de+minitts.net+minsmail.com+mintemail.com+minuteafter.com+minuteinbox.com+mipg.autos+mirai.re+mirasync.tokyo+miros.cloud+missionbulldogs.org+misterpinball.de+mitico.org+mitrabisa.com+mitraprem.online+mitraprem.site+miucce.com+miwacle.com+mixmail.site+mixzu.net+mji.ro+mjj.edu.ge+mjukglass.nu+mkeya.com+mkpfilm.com+mkql.autos+mkseiuuda.top+mkvesta.io.vn+mkvo.hair+mkzaso.com+ml8.ca+mlanm.online+mlgmail.top+mliok.com+mlumzmh.cn+mm.my+mm2flip.pw+mm5.se+mmaily.com+mmcat.icu+mmdesign.work.gd+mmmggg0123.ccwu.cc+mmmo.us.ci+mmo.us.ci+mmo365.store+mmyuu.cn+mnode.me+mnvr.site+moakt.cc+moakt.co+moakt.com+moakt.ws+mobileninja.co.uk+mobilevpn.top+moburl.com+mockata.net+mockmyid.com+modirosa.com+modolku.store+moeri.org+mofu.be+mohmal.com+mohmal.im+mohmal.in+mohmal.tech+moimoi.re+mokondo.today+mokondoo.cyou+mokook.com+molabo.bond+moldind.help+molms.com+momentics.ru+momoi.uk+momopifa.cc.cd+mona.edu.kg+mona.edu.pl+mona.edu.rs+monachat.tk+monadi.ml+monchu.fr+moncourrier.fr.nf+mondial.asso.st+monemail.fr.nf+moneypipe.net+monglung.space+mongrec.top+monity.top+monmail.fr.nf+monomoho.site+monopacket.com+monumentmail.com+monyal.shop+moolee.net+moonapps.org+moondyal.com+moonfee.com+moonikent.us+moonwake.com+mooo.com+moot.es+mopess.help+mora45ktil.io.vn+moreawesomethanyou.com+moreorcs.com+morriesworld.ml+morsin.com+moruzza.com+mosswoodmissionhall.bio+motion.jo3.org+motique.de+mountainregionallibrary.net+moutianwuliu.top+mowline.com+mox.pp.ua+moy-elektrik.ru+moyang303.de5.net+moza.pl+mozej.com+mp-j.ga+mp3oxi.com+mpk.ovh+mr-email.fr.nf+mr24.co+mrcheannko45k.io.vn+mriscan.live+mriscanner.live+mrizkifreelace.dpdns.org+mrnz.skin+mrotzis.com+mrphoto.org+mrvpm.net+mrvpt.com+msarra.com+msgos.com+msn-mail-free-1.dynv6.net+msn-mail-free-1092.dynv6.net+msn-mail-free-1268.dynv6.net+msn-mail-free-1522.dynv6.net+msn-mail-free-1659.dynv6.net+msn-mail-free-1750.dynv6.net+msn-mail-free-189.dynv6.net+msn-mail-free-1974.dynv6.net+msn-mail-free-1980.dynv6.net+msn-mail-free-2112.dynv6.net+msn-mail-free-2193.dynv6.net+msn-mail-free-2205.dynv6.net+msn-mail-free-2634.dynv6.net+msn-mail-free-2681.dynv6.net+msn-mail-free-3011.dynv6.net+msn-mail-free-3229.dynv6.net+msn-mail-free-3232.dynv6.net+msn-mail-free-3270.dynv6.net+msn-mail-free-33.dynv6.net+msn-mail-free-3312.dynv6.net+msn-mail-free-3373.dynv6.net+msn-mail-free-3414.dynv6.net+msn-mail-free-3622.dynv6.net+msn-mail-free-3632.dynv6.net+msn-mail-free-3737.dynv6.net+msn-mail-free-3812.dynv6.net+msn-mail-free-4062.dynv6.net+msn-mail-free-4088.dynv6.net+msn-mail-free-4151.dynv6.net+msn-mail-free-4290.dynv6.net+msn-mail-free-4304.dynv6.net+msn-mail-free-4411.dynv6.net+msn-mail-free-4518.dynv6.net+msn-mail-free-4640.dynv6.net+msn-mail-free-4718.dynv6.net+msn-mail-free-4868.dynv6.net+msn-mail-free-5064.dynv6.net+msn-mail-free-5162.dynv6.net+msn-mail-free-5184.dynv6.net+msn-mail-free-5198.dynv6.net+msn-mail-free-5402.dynv6.net+msn-mail-free-5415.dynv6.net+msn-mail-free-554.dynv6.net+msn-mail-free-5696.dynv6.net+msn-mail-free-5718.dynv6.net+msn-mail-free-5872.dynv6.net+msn-mail-free-6047.dynv6.net+msn-mail-free-6113.dynv6.net+msn-mail-free-6326.dynv6.net+msn-mail-free-6581.dynv6.net+msn-mail-free-6589.dynv6.net+msn-mail-free-6760.dynv6.net+msn-mail-free-678.dynv6.net+msn-mail-free-6877.dynv6.net+msn-mail-free-6883.dynv6.net+msn-mail-free-6906.dynv6.net+msn-mail-free-6943.dynv6.net+msn-mail-free-6959.dynv6.net+msn-mail-free-6981.dynv6.net+msn-mail-free-708.dynv6.net+msn-mail-free-7155.dynv6.net+msn-mail-free-727.dynv6.net+msn-mail-free-733.dynv6.net+msn-mail-free-7424.dynv6.net+msn-mail-free-7429.dynv6.net+msn-mail-free-7434.dynv6.net+msn-mail-free-7509.dynv6.net+msn-mail-free-7570.dynv6.net+msn-mail-free-7742.dynv6.net+msn-mail-free-7760.dynv6.net+msn-mail-free-8047.dynv6.net+msn-mail-free-810.dynv6.net+msn-mail-free-8131.dynv6.net+msn-mail-free-8282.dynv6.net+msn-mail-free-8582.dynv6.net+msn-mail-free-86.dynv6.net+msn-mail-free-8632.dynv6.net+msn-mail-free-8704.dynv6.net+msn-mail-free-8776.dynv6.net+msn-mail-free-8841.dynv6.net+msn-mail-free-890.dynv6.net+msn-mail-free-8952.dynv6.net+msn-mail-free-8986.dynv6.net+msn-mail-free-9002.dynv6.net+msn-mail-free-9061.dynv6.net+msn-mail-free-9121.dynv6.net+msn-mail-free-9173.dynv6.net+msn-mail-free-9224.dynv6.net+msn-mail-free-9313.dynv6.net+msn-mail-free-9368.dynv6.net+msn-mail-free-9382.dynv6.net+msn-mail-free-9444.dynv6.net+msn-mail-free-9536.dynv6.net+msn-mail-free-9587.dynv6.net+msn-mail-free-9597.dynv6.net+msn-mail-free-9649.dynv6.net+msn-mail-free-9734.dynv6.net+msn-mail-free-9921.dynv6.net+msn-mail-free-9990.dynv6.net+msn-mail-free-9998.dynv6.net+mspeciosa.com+msqatl.com+msrc.ml+msssg.com+msvw.skin+mswork.ru+msxd.com+mt2009.com+mt2014.com+mt2015.com+mtdalmshouse.fitness+mtdalmshouse.uk+mtdog.xyz+mtmdev.com+mtnewtoy.us+mtshop18.io.vn+muadaingan.com+muareview.com+muataikhoan.info+muathegame.com+muchomail.com+mucincanon.com+mudahmaxwin.com+muehlacker.tk+muell.icu+muell.io+muell.monster+muell.xyz+muellemail.com+muellmail.com+muetop.store+mugadget.com+mui.cc.cd+mui.de5.net+mukn.skin+multicorse.com+muncloud.com+munik.edu.pl+munoubengoshi.gq+muonwhila.com+muralin-aja.com+muratec.eu.org+muratreis.icu+musiccode.me+musicflow.buzz+musiku.studio+mutant.me+mutudev.com+mvpmedix.com+mvrht.com+mvrht.net+mwalshabs.dev+mwarner.org+mwlp.skin+mwqj.xyz+mxclip.com+mxfuel.com+mxhquxyi.top+mxmm.hair+mxvia.com+mxwm.hair+my-pomsies.ru+my-teddyy.ru+my10minutemail.com+myamya.tech+mybitti.de+mycleaninbox.net+mycorneroftheinter.net+mycreativeinbox.com+myde.ml+mydefipet.live+mydemo.equipment+myecho.es+myemailboxy.com+myerly.com+myfxspot.com+mygeoweb.info+myhochzeitsfilm.de+myhosrn.servehalflife.com+myindohome.services+myinfoinc.com+myinterserver.ml+mykickassideas.com+myletters.online+mymail-in.net+mymail.infos.st+mymail90.com+mymaildo.kro.kr+mymailoasis.com+mymaily.lol+mymrxuyrd.top+mynes.com+mynetstore.de+mynoop.store+myntora.cfd+myopang.com+mypacks.net+mypartyclip.de+mypdj08.mywire.org+myphantomemail.com+mypk.beer+mysadfjwefwf.us.ci+mysamp.de+myself.fr.nf+myspaceinc.com+myspaceinc.net+myspaceinc.org+myspacepimpedup.com+myspamless.com+mystvpn.com+mysugartime.ru+mytemp.email+mytempemail.com+mytempmail.com+mytrashmail.com+mywarnernet.net+myweblaw.com+mywrld.site+mywrld.top+myxentra.cfd+myzx.com+mzico.com+n1nja.org+n24n8x9.giize.com+n8.gs+na-cat.com+na3qxuk.kozow.com+naacpadvancement.org+naah.ru+naah.store+nabaxox.edu.pl+nabilalo.bond+nabomail.com+nabuma.com+nada.email+nada.ltd+nagi.be+nailooong.site+naka.edu.pl+nakedtruth.biz+namdevmail2.qzz.io+namenan.me+namewok.com+nangspa.vn+naniniva.com+nanonym.ch+nanopools.info+nanoskin.vn+naobk.com+naocan.org+napthex4.com+narrowment.com+narsub.online+narsub.shop+nashapoultryshop.com+naslazhdai.ru+natachai.me+natange.org.uk+nategetvpn.store+nationalgardeningclub.com+natuanal.com+nautonk.com+navalcadets.com+naverapp.com+naverly.com+navermail.kr+navura.in+nawmin.info+naxx.dev+naylonksosmed.com+naymedia.com+nazisat.com+nbmbb.com+nbskyhope.shop+nbspace.us+nbvrluhsh.top+nbzmr.com+nbzy.hair+ncfx.beer+ncien.com+ncleap.com+ndade.eu.cc+ndnphim.io.vn+ndut.pro+neatdaynote.com+necub.com+negated.com+neghtlefi.com+neko2.net+nekochan.fr+nekosan.uk+neomailbox.com+neosstudy.work+neotlozhniy-zaim.ru+neowd.com+nepwk.com+neroki.shop+nervmich.net+nervtmich.net+nesopf.com+nespf.com+nespj.com+nespressopixie.com+nestlynotes.com+net1mail.com+netcnet.uk+netcom.ws+netfusionhub.surf+netfxd.com+netgcp.online+netherfieldvillagehall.co.uk+nethubmail.net+netmails.com+netmails.net+netn.top+netoiu.com+netricity.nl+netris.net+netviewer-france.com+networksolutionshk.asia+netzidiot.de+nevanata.com+nevermail.de+neverover.life+new-api.cc.cd+newaddr.com+newbpotato.tk+newbreedapps.com+newconnect.uk+newdelhi.io.vn+newfilm24.ru+newgreenpath.org+newideasfornewpeople.info+newmail.top+newmano.store+newsteadabbeypartnership.org+newyork.io.vn+nexarisystems.online+nexarsh.store+nexarshop.store+nexentia.cfd+nexio.sbs+nexorabio.pro.vn+nexosphere.lifestyle+next.ovh+nextmail.info+nextpomi.dynv6.net+nextstopvalhalla.com+nextsuns.com+nexus-streams.online+nexushost.site+nexverseal.shop+nezdiro.org+nezid.com+nezuka.net+nezumi.be+nezzart.com+nfast.net+nfengwu.bond+nfkah.eu.cc+nfuo.makeup+nghienplus.io.vn+nghienplus.store+nguyendanhkietisocial.com+nguyenlieu24h.com+nguyentinhblog.com+nguyenusedcars.com+nh3.ro+nhienpv1.io.vn+nhmi1.com+nhmvn.com+nhoopmail.store+nhotv.com+nhungdang.xyz+niang-sfx.biz+nianshen09.help+nianshens.help+nice-4u.com+nice.qzz.io+nicebad.com+nicemail.cc+niceminute.com+nichaoxing.cc+nick-ao.com+nickmxh.com+nicknassar.com+nicusaurelus.online+nigeriansincoventry.org+nightfood.studio+nightorb.com+nik.edu.pl+nikora.fr.nf+nimbacharity.com+nincsmail.com+nincsmail.hu+ninepacman.com+niprack.com+niseko.be+niulaibulai.me+niwave.shop+niwave.top+niwl.net+njwzzvmtin.my+nlpdy8m.ooguy.com+nm123.com+nm7.cc+nmail.cf+nnh.com+nnnetworks.com+nnot.net+nnoway.ru+no-spam.ws+no-trash.ru+no-ux.com+no2bullyingatwork.org.uk+noblepioneer.com+nobugmail.com+nobulk.com+nobuma.com+noc5yva.theworkpc.com+noclickemail.com+nocp.ru+nocp.store+nodejs.uk+nodezine.com+noexpire.top+nogmailspam.info+noicd.com+noinspect.top+noizonicfoundation.com+nokdot.com+nokiamail.com+nolemail.ga+nolettersbox.com+nomail.cf+nomail.ga+nomail.pw+nomail2me.com+nomes.fr.nf+nomomail.com+nomorespamemails.com+nomorix.cfd+nonchalantresmita.biz+nondon.site+nondon.store+nongnue.com+nonspam.eu+nonspammer.de+nonze.ro+nooploop.store+noopmail.com+noproposal.com+noref.in+noreply.fr+nori24.tv+norovpn.site+norseforce.com+northboveymeadow.business+northsixty.com+norvanta.cfd+norwegischlernen.info+noship.shop+noshiper.pro+nospam.fr.nf+nospam.today+nospam4.us+nospamfor.us+nospamthanks.info+nosubcriber.shop+notboxletters.com+nothingtoseehere.ca+notif.me+notipr.com+notlettersmail.com+notmailinator.com+notrnailinator.com+notsharingmy.info+novacontigencia.xyz+novaemail.com+novaprime.vip+novasub.click+novyrix.cfd+now.im+nowhere.org+nowmymail.com+nowmymail.net+nowrouter.store+nowtopzen.com+nowyoudme1.cc.cd+noyavip.com+noyp.fr.nf+nproxi.com+nqmo.com+nrbs.me+nrehi.com+nriza.com+nrlord.com+ns01.biz+nsvpn.com+nsyncxy.com+nthrl.com+ntlhelp.net+ntto.us+nttoadmin2.us+nu9233b.theworkpc.com+nubescontrol.com+nucleant.org+nuknjkv.ooguy.com+nulla.de5.net+nullbox.asia+nullbox.info+nuoifb.com+nuox.eu.org+nurfuerspam.de+nut.cc+nutpa.net+nuts2trade.com+nv6ei2v.kozow.com+nvhrw.com+nvqt304.xyz+nwfa.hair+nwldx.com+nwrlr.org+nwytg.com+nwytg.net+nxdbxd.top+nxirad.online+ny7.me+ny7u9qr.kozow.com+nyasan.com+nyfhk.com+nygren-realty.com+nygrenrealty.com+nypato.com+nyrmusic.com+nyxmail.pro+nyxpanel.xyz+nyxstores.id+o2stk.org+o2y50o5.loseyourip.com+o326lav.kozow.com+o7i.net+oakon.com+oalsp.com+obelion.cfd+obfusko.com+objectmail.com+obobbo.com+oborudovanieizturcii.ru+obxpestcontrol.com+ocbxpz3.camdvr.org+oceva.site+octovie.com+oczt15m.kozow.com+odaymail.com+odeask.com+odem.com+odnorazovoe.ru+oebd.hair+oepia.com+oerpub.org+ofanda.com+officecombine.com+offshore-proxies.net+ofisher.net+ogoplace.pro+ogrencikredisi.org+ohaaa.de+ohgitu.me+ohi.tw+ohm.edu.pl+oida.icu+oiioii.email+oiioii.vip+oing.cf+okauq.store+okcdeals.com+okclprojects.com+okcx.edu.rs+okcxhssgk.top+okhko.com+okiae.com+okinawa.li+okrent.us+oku.ovh+oky.ovh+okzk.com+oldao.com+oliespace.id+oliespace.site+olimp-case.ru+olipii.com+olisup.cyou+oliviadiffuser.store+oloh.ru+oloh.store+olypmall.ru+olzx.skin+omail.de+omail.pro+omanarts.com+omarnasrrr.com+omfg.run+omgheels.com+omkiujk.ddnsgeek.com+omnievents.org+omnilog.space+omnisent.cfd+omnivex.cfd+omonomon.shop+omtecha.com+onbap.com+one-mail.top+one-ml.com+one-sec-mail.site+one-time.email+one2mail.info+onekisspresave.com+onelettersmail.com+onemail.host+onemuou.com+oneoffemail.com+oneoffmail.com+onetm-ml.com+onetm.jp+onetopclick.online+oneummahorg.uk+onewaymail.com+onheb.com+onionred.com+oniventa.cfd+onlatedotcom.info+onldm.net+online.ms+onlinecmail.com+onlineidea.info+onlyapp.net+onmailflare.com+onqin.com+ontasa.com+ontyne.biz+oohioo.com+oolus.com+oonies-shoprus.ru+oooooooo.store+oopi.org+oosln.com+oovk.ru+oovk.store+ooxxoo.asia+ooynib.com+ooyv.homes+opayq.com+opelkun.net+opemails.com+openagent.cfd+openavz.com+openclawskill.shop+opendns.ro+openedclaw.top+openmail.pro+opentrash.com+openwrt.qzz.io+opihhushdjn.cyou+opmmedia.ga+opog.hair+opog.skin+oposite.org+opp24.com+opportunity-africa.com+optimaweb.me+optivex.cfd+opwebw.com+oqgd.skin+oqmy.hair+oranek.com+oravantis.cfd+oravell.cfd+orbit25k.io.vn+orbitxhive.com+orbixacoa.com+orceqjqw.top+ordinaryamerican.net+ordite.com+oreidresume.com+orgmail.pro+orgmbx.cc+orimassage.com+oroki.de+oronny.com+orsbap.com+ortogenmail.com+orwpaztm.cfd+osaxadinhos.com.br+oshietechan.link+oshjr-24.xyz+osifixtech.com.mx+oskarstalbergcitygenerator.com+ospirun.com+ostahie.com+ostinmail.com+osxofulk.com+otherinbox.com+otmail.jp+otpku.com+ottsathi.store+ouchcloud.com+ouk.me+oupul8b1k.bond+oupul8b1k.cyou+ourklips.com+ourl.me+ourpreviewdomain.com+outdaremusicdevon.org+outlawspam.com+outlook.edu.pl+outlookapp.tech+outlooks.bond+outmail.win+ovbest.com+ovomail.co+ovpn.to+owdrcro.giize.com+owleyes.ch+owlpic.com+ownsyou.de+owo-mailteam.bond+owo-mailteam.cyou+owovo.site+owube.com+oxfo.edu.pl+oxmail.homes+oxopoha.com+oxvq.hair+oyisam.my+oynsuxe.ooguy.com+oyoa.hair+oyoa.skin+ozatvn.com+ozjp.skin+ozm.fr+ozsaip.com+ozyl.de+p-aac.top+p-banlis.ru+p-kk2.icu+p-ttz.top+p-y.cc+p0dl9ik.giize.com+p2bvz.cyou+p33.org+p3t8dyv.mywire.org+p6vvvok.mywire.org+p71ce1m.com+p94y7ff.camdvr.org+pa9e.com+pachilly.com+packiu.com+padue.app+pagamenti.tk+paharpurmim.ga+pakadebu.ga+palaze.cc+paldonanamansilolo.online+paliospiti.com+pamaweb.com+pamil.fr.nf+pancakemail.com+pandorasboxproductions.org+panlix.cloud+papierkorb.me+paplease.com+para2019.ru+paratrabajar.xyz+parisdaily.fr+parlimentpetitioner.tk+parsitv.com+parthekio.live+parthxxtoasts.site+passeone.com+passeone.xyz+past-line.com+pastebitch.com+pastipremium.store+pastryofistanbul.com+patientlecadet.online+patity.com+patonce.com+pavilionx2.com+pawobby.cfd+paxlys.com+paylaar.com+payperex2.com+payspun.com+pazard.com+pazuric.com+pbhak.dev+pbis.beer+pbrg4fb.ooguy.com+pcaa.lol+pcbb.lol+pcdo.hair+pckage.com+pdf-cutter.com+pdmy.skin+pdood.com+pe.hu+peakinbox.net+pecinan.com+pecinan.net+pecinan.org+pelviro.sbs+penisgoes.in+penoto.tk+pepamail.com+pepbot.com+percyfx.com+pertera.com+peruss.biz.id+pesagilt.top+peterdethier.com+peterhe-ai.bond+petloca.com+petrzilka.net+pewpewpewpew.pw+pflege-schoene-haut.de+pfui.ru+pgxh.skin+phamay.com+phanmembanhang24h.com+phctool.com+philipdowney.com+phimib.com+phimteen.net+phmail.site+phmail.us+phone-elkey.ru+photo-impact.eu+photobrex.com+photomark.net+phpto.us+phucmmo.com+phuongnhicare.com+phuotngay.com+phyones.com+physcroenmail.com+physicaladithama.io+pi.vu+piaa.me+picdirect.net+pickuplanet.com+picturehostel.com+picturehostel.fr+picturehostel.org+picturehostel.store+pig.pp.ua+pigeonprotocol.com+pii.at+piki.si+pimpedupmyspace.com+pinehill-seattle.org+pingddns.net+pingir.com+pinkgreengenerator.me+pinpool.ai+pipemail.space+pipmmotube.store+pippoc.com+piscesbody.xyz+pisls.com+pitaniezdorovie.ru+pithu.org+pitiful.pp.ua+pivo-bar.ru+pivotylabs.pro+pixdd.com+pixelcroft.org+pixelgagnant.net+pixiil.com+pixoledge.net+pizu.ru+pizu.store+pizuhdev.work+pizzajunk.com+pjjkp.com+pkday.eu.cc+pkdigitalmart.site+pkrj.hair+placebomail10.com+plainhomehub.com+planworker.pro+playasiafootball.xyz+pleasenoham.org+plenoryx.cfd+plexfirm.com+plexflux.app+plexolan.de+plhk.ru+pliz.fr.nf+ploae.com+ploki.fr+ploncy.com+plowcreek.org+plugintonature.org.uk+plw.me+pmail.site+pnaz.skin+pngrise.com+pntvipveo45k.io.vn+pnvipveo25k.io.vn+pobbofqd.top+poc4756bb.camdvr.org+pochtac.ru+poehali-otdihat.ru+pofmagic.com+pojok.ml+pokemail.net+pokemons1.fr.nf+pokiemobile.com+polarkingxx.ml+politikerclub.de+polkaroad.net+polvexar.space+polyfaust.net+polysolextcoin.cloud+pongpong.org+ponp.be+pooae.com+poofy.org+pookmail.com+poolemethodists.org.uk+pooo.ooguy.com+poopiebutt.club+popcornfarm7.com+popcornfly.com+popesodomy.com+popgx.com+poplk.com+popol.fr.nf+porjoton.com+porsh.net+porsilapongo.cl+portaltrendsarena.com+posdz.com+positivevoiceteesvalley.co.uk+posta.store+postacin.com+postbx.ru+postbx.store+postonline.me+poubelle-du.net+poubelle.fr.nf+poutineyourface.com+powerdea.me+powered.name+powerencry.com+powerscrews.com+powlearn.com+pox2.com+pozima.rest+pp-n6.top+pp-tw.cc+pp7rvv.com+pp9vdr0.ddnsfree.com+ppdf.cc+ppedu.pp.ua+ppetw.com+ppoo.ccwu.cc+pptrvv.com+pqoia.com+pratikmail.com+pratikmail.net+pratikmail.org+prazdnik-37.ru+prc.cx+predatorrat.cf+predatorrat.ga+predatorrat.gq+predatorrat.ml+predatorrat.tk+premiapp.com+premieragents.net+premierr.site+premigu.co+premirum.shop+premium-mail.fr+premiumapk.store+premiuminternet.site+premiuminternetvpn.xyz+premiumonebd.store+premiumsigma.shop+premsy.net+prestige-leadership.org+prestore.space+pretreer.com+pricegh.com+pricegh.fun+pride-worldwi.de+primabananen.net+primalhigh.click+primebulidv1.uk+primejetnet.com+primered.shop+primtech.cn+prin.be+printz.site+prisonity.com+privacy-mail.top+privacy.net+privacyshield.cc+privatdemail.net+privmail.edu.pl+privo.edu.pl+privy-mail.com+privy-mail.de+privymail.de+priyo-mail.com+priyo.edu.pl+priyo.ovh+priyo.site+priyoemail.site+priyomail.in+priyomail.net+priyomail.top+priyomail.uk+priyomail.us+priyor.com+priyp.com+prkmail.xyz+pro-tag.org+pro5g.com+procrackers.com+productmm.shop+profast.top+prohade.com+prohisi.store+projectcl.com+promailt.com+promyvia.cfd+proprietativalcea.ro+propscore.com+prorises.com+prosocial.io.vn+protectsmail.net+protempmail.com+protonza.com+prout.be+proveity.com+proxy-gateway.net+proxymail.eu+proxyparking.com+prp-ppdt.app+prtnx.com+prtshr.com+prtz.eu+psai.run.place+psh.me+psles.com+psnator.com+psoxs.com+ptct.net+ptncereio.com+ptnstudio.vn+ptsculure.com+puabook.com+puffiqo.store+puglieisi.com+puji.pro+pulse25k.io.vn+pulsix.pw+pumpoly.com+punchbagartgallery.org.uk+punkass.com+punkproof.com+puppetmail.de+purcell.email+pureheart.org.uk+purelogistics.org+purifyzed.org+purmuttad.com+pursip.com+pushcom.store+pusmail.com+pussport.com+put2.net+puttanamaiala.tk+putthisinyourspamdatabase.com+puxa.top+pvnmax.space+pwpwa.com+pwrby.com+pwx129.love+pxlys.com+pyrosenex.cfd+pyskillsgame.com+q06htej.ddnsfree.com+q0y5ffo.kozow.com+q1zx2zj.camdvr.org+q7qipaa.kozow.com+qabq.com+qacmjeq.com+qagk.hair+qaondqs.loseyourip.com+qasti.com+qazaxmj.theworkpc.com+qbfree.us+qc.to+qcai.skin+qcgmtzhzh.top+qd.je+qd28max.eu.cc+qejjyl.com+qentic.shop+qeurtor.com+qexvhz.com+qfnt.skin+qhgs.com+qi3hav9.mywire.org+qiang66.ccwu.cc+qibl.at+qiott.com+qipmail.net+qiq.us+qisdo.com+qisoa.com+qiuvision.com+qjwlaaa.giize.com+qkwv.skin+qkxm.skin+qlbz.hair+qlhub.org.uk+qlto.hair+qmrbe.com+qodiq.com+qoika.com+qopow.com+qoq.indevs.in+qpdm.beer+qq.my+qqcomeback.me+qrt8e6v.ddnsfree.com+qrxs6eh.giize.com+qrzzq7z.ooguy.com+qsl.ro+qsmail.cc.cd+qsuo.uno+qtum-ico.com+quadrafit.com+quantorynexus.space+quantumeridian.site+quarvex.cfd+quentavo.cfd+questtechsystems.com+quick-mail.cc+quickdrop.buzz+quickemail.info+quickinbox.com+quickmail.nl+quicksend.ch+quillet.eu+quinz.me+quipas.com+quixentra.cfd+qukv.skin+quml.skin+quorixia.cfd+ququb.com+qvcq.skin+qvmao.com+qvttclass.us+qvwi.skin+qvy.me+qweasd123.cc.cd+qwertyhandsome.net+qwezxc321.cc.cd+qwickmail.com+qydxproapi.store+qytechs.cn+qzueos.com+r2money.io.vn+r4nd0m.de+r8cri1k.theworkpc.com+ra3.us+rabin.ca+rabiot.reisen+rabitex.com+racaho.com+rackabzar.com+racovor.com+radioastronomynet.com+rael.us+raetp9.com+rainbib.co.uk+rainbowly.ml+rajaiblis.com+raketenmann.de+raleigh-construction.com+ramcen.com+ramenmail.de+ramin200.site+ramizan.com+rancidhome.net+randol.infos.st+randomail.io+randomail.net+rapidefr.fr.nf+rapplo.com+rapt.be+raqid.com+ravavo.bond+ravc.beer+raveqxon.blog+raveqxon.store+rawr.foo+rax.la+raxtest.com+rayrayactive.com+razemail.com+razeny.com+razuz.com+rbb.org+rbmz.beer+rbs1.xyz+rc38643.ddnsfree.com+rcasd.com+rccgmanifestinghisglory.co.uk+rcpt.at+rdklcrv.xyz+rdlt0hi.mywire.org+rdsekaunx.top+re-gister.com+reacc.me+reality-concept.club+realize.edu.pl+reallymymail.com+realmail.co+realman.mywire.org+realmka.io+realquickemail.com+realseek.xyz+realtyalerts.ca+reapsa.com+reason.edu.pl+rebates.stream+receiveee.com+recipeforfailure.com+reclameaqui.services+recode.me+reconmail.com+recyclemail.dk+redbiodiesel.com+redfeathercrow.com+redi.fr.nf+rednotecreatoracademy.art+redproxies.com+reestore.site+refblogs.com+refk.site+reftoken.net+regapts.com+regbypass.com+regspaces.tk+regvippro.site+reimondo.com+rejectmail.com+rejo.technology+rekaer.com+relayne.top+reliable-mail.com+relieve.us.ci+remahankerupuk.com+remai.freeddns.org+remail.cf+remail.ga+remarkable.rocks+remind.edu.pl+remote.li+remoteflyer.co.uk+rensumo.top+rentaen.com+rentop.asia+renvotra.cfd+renydox.com+reovipvpn.top+replyloop.com+reportfresh.com+reptilegenetics.com+resgedvgfed.tk+resmso.com+restorationchurchtv.com+resumeforest.cn+reusable.email+reusecomputers.site+reverendneedham.co.uk+reviewfood.vn+revolvingdoorhoax.org+rewermail.com+rexabot.com+rexmoo.ccwu.cc+rexornge.net+rexornge.site+reymaticx.com+rezalabs.shop+rezato.com+rf.gd+rfc822.org+rfods.tech+rfzpnrbpv.top+rgbeastcomputers.site+rgwdomb.theworkpc.com+rhalmshouse.church+rhalmshouse.co.uk+rhyta.com+riazra.bond+ricardo0911.xyz+richfinances.pw+riddermark.de+riffproductions.co.uk+rifkian.ga+rifqysaputra.dev+rikka0612.site+rilzz.store+rimshacooking.site+rinseart.com+riposh.shop+rippb.com+risinggirl.co.uk+risingsuntouch.com+riski.cf+risu.be+riwutz-gmail.com+rjzh8vf.giize.com+rklips.com+rkomo.com+rkzpcx.top+rm2rf.com+rma.ec+rmmr.fun+rmqkr.net+rnailinator.com+rniz667.mywire.org+rnmut8pudgj0ikregqx6.dynv6.net+rnvvpn.store+ro.lt+robertspcrepair.com+roborena.com+robot-mail.com+robothandcook.cfd+robustq.com+rodhazlitt.com+roguemaster.dev+roiv.hair+rollindo.agency+ronete.com+ronger.cfd+ronghsng.buzz+ronnierage.net+rootfest.net+roratu.com+roroki.cn+rosebearmylove.ru+rosella.my.id+rotaniliam.com+rotomails.co.uk+rotomails.com+rouflav.com+route64.de+routerboardvietnam.com+rover.info+rowdydow.com+rowe-solutions.com+roweryo.com+royal.net+royaldoodles.org+royalmarket.life+royalpriesthoodagc.org.uk+royandk.com+roybl.com+rppkn.com+rr.nu+rshz.hair+rsvhr.com+rteet.com+rtrobinsbequest.org.uk+rtrtr.com+rtskiya.xyz+rua.pp.ua+rudymail.ml+ruinique.tech+rukiaops.me+rulersonline.com+rulp.skin+rumahweb.site+rumgel.com+runcubesapps.id+runi.ca+runlop6.ooguy.com+rupayamail.com+ruru.be+rustydoor.com+rustyload.com+ruu.kr+ruutukf.com+rvb.ro+rvhx.hair+rvneous.com+rw1aifc.camdvr.org+rweebz-mail-1.online+rwstatus.com+rwxsxnomo.top+rxinai.com+rxs9.cn+rygel.infos.st+rynetvpn.site+ryteto.me+ryuu.codes+ryuucn.com+ryyr.ru+ryyr.store+rzbal.xyz+s-mail.social+s-mdg.top+s0ny.net+s1q59z82q.top+s33db0x.com+s3cmt5w.kozow.com+s3k.net+s40vwj8.camdvr.org+s4sfoundation.org.uk+s8gz4ay.kozow.com+sabrestlouis.com+sackboii.com+sad23321adja.cn+sada-sd.cc+saddope.lol+sadfg.indevs.in+sadrain.shop+sads-ads-awe.top+saeoil.com+safaat.cf+safermail.info+safersignup.de+safetymail.info+safetypost.de+sagametour.com+saharanightstempe.com+sahildash.dev+sailmail.io+saisonhama.shop+sajutadollars.com+sakoonthroughcancer.com+sakurapink.top+salakoais.shop+saleis.live+salmeow.tk+sam1.eu.org+samaltour.site+samaritanfamilyfoundation.com+samblogs.nett.to+samblogs.zone.id+sampsave.tech+samsclass.info+samsung-gmail.com+sandcars.net+sandelf.de+sandwhichvideo.com+sanfinder.com+sanfnge.run+sanfnges.cc+sanim.net+sanstr.com+saovangtiles.site+sappisi.com+sarawakreport.com+sast.ro+sasukiez.shop+satisfyme.club+satorix.id+satukosong.com+saturrshop.uk+saungadaid.pro+sausen.com+save4now.com+savemydinar.com+savests.com+say0.com+saynotospams.com+sayverfox.com+scatmail.com+scatterteam.com+scay.net+schachrol.com+schafmail.de+schmeissweg.tk+schrott-email.de+scook.cfd+scottcoffman.net+scottni.com+scpulse.com+scribito.de+scrsot.com+sd3.in+sdbbs.cc+sdhaiok.eu.cc+sdi5mon.ooguy.com+sdj.fr.nf+sds-awe.top+sdsfre.blog+sdvft.com+sdvgeft.com+sdvrecft.com+search4gpt.com+seasonofgrace.org+seaworld.asia+sebbcn.net+secmail.pw+secretemail.de+secure-mail.biz+secure-mail.cc+secured-link.net+securehost.com.es+securitybot.online+sedekah-mudah.com+seduck.com+seedcorn.foundation+seedspeed.site+seekapps.com+seekjobs4u.com+sehier.fr+sejaa.lv+sekotong.store+selaciptama.com+seler25k.io.vn+selfdestructingmail.com+selfdestructingmail.org+selftrak.fit+selltub.com+selltub.me+seman.edu.kg+semester.bond+send22u.info+send4.uk+sendapp.uk+sendfree.org+sendgrid.ovh+sendingspecialflyers.com+sendnow.win+sendo.dedyn.io+sendo.giize.com+sendokai.click+sendos.fr.nf+sendos.infos.st+sendspamhere.com+sengkuni.dedyn.io+sengkuni.qzz.io+sengkuni.xx.kg+senseless-entertainment.com+sentra-premium.com+senvas.me+senyan.fun+seosnaps.com+seqerc.com+serbaprem.store+serbaserbisoftware.site+serenith.cfd+server.ms+servicee.es+services391.com+servicetr.me+sesasdl.top+setxko.com+severnday.us+sevopay.com+sewink.my.id+sex520.eu.org+sexforswingers.com+sexfrancecute.lol+sexfrancecute.tattoo+sexfrancecute.xyz+sexical.com+sexyalwasmi.top+sexymeowers.site+sexymeowers.space+sexymeowers.store+sexymeowers.xyz+sfacg.org+sfolkar.com+sfr09g1.camdvr.org+sgatra.com+sgm.ovh+shaceng.biz.id+shaceng.my.id+shadap.org+shaguaaini.click+shahabnoor.org+shalar.net+shanhaijuli.sbs+sharebot.net+sharedmailbox.org+sharkfaces.com+sharklasers.com+shchiba.uk+sheerid.top+sheinup.com+shengxia.asia+sherazhaider.com+sheryli.com+shhmail.com+shhuut.org+shieldedmail.com+shieldemail.com+shiftmail.com+shiita12.com+shipfromto.com+shiphazmat.org+shipping-regulations.com+shippingterms.org+shiptudo.com+shiro-alice.live+shitaway.tk+shitmail.de+shitmail.me+shitmail.org+shizuku-lulu.love+shkele.cyou+shmavje.mywire.org+shmeriously.com+shopaccmmo.com+shopbantkclone.com+shopcreative.cc+shopempva11.com+shopld.linkpc.net+shopprimeaccounts.com+shopvipduzk666.shop+shopvipduzk6868.shop+shopxda.com+shopy.club+shortmail.net+shortweb.live+shotmail.ru+showslow.de+shrib.com+shuelder.com+shut.name+shut.ws+shxwonew.xyz+si1ver.xyz+siap-sepuh.com+sibafo.asia+siberpay.com+siby9w6.loseyourip.com+sicmg.com+sidelka-mytischi.ru+sidement.com+sidlabs.site+sidneymichaelpoland.travel+siempre.gratis+sifan077.cc.cd+siftportal.ru+sify.com+sig.de5.net+signalxp.com+signsoflife.org.uk+sihanoma.store+sika3.com+sikux.com+silenceofthespam.com+silentmail.ccwu.cc+siliwangi.ga+silvaron.cfd+silvercoin.life+sim-simka.ru+sim-sppg.com+simaenaga.com+simoka.sbs+simpleitsecurity.info+simranaitech.space+sin.cl+sinaite.net+sind-hier.com+sind-wir.com+sindhier.com+sindwir.com+sinema.ml+sinfiltro.cl+singlespride.com+sinnlos-mail.de+sino.tw+sinorto.com+siperer.online+siroja.top+siteinfox.com+siteposter.net+sitwelltownlands.org.uk+six25.biz+sixoplus.com+sizzlemctwizzle.com+sjuaq.com+sjusngde.info+sk-ai.eu.cc+skeefmail.com+skingkong.com+skrak.com+skrhqfnya.top+skrx.tk+sky-inbox.com+sky-ts.de+skyemails.app+skyemails.tech+skyforte25k.io.vn+skygazer42.cn+skygazerhub.com+skyhope666.icu+skyhope666.shop+skyhope666.xyz+skyhopenb.shop+skyhopenb.xyz+skyhopenba.shop+skyhopetw.xyz+skyhopewd.xyz+skyhopewdf.xyz+skynet.infos.st+skyrt.de+skyserver.cyou+skytopway.com+slapsfromlastnight.com+slaskpost.se+slave-auctions.net+slimirin.com+slippery.email+slipry.net+sliverkeigo.fun+slopsbox.com+slotbeer.com+slothmail.net+slowpokerfrance.eu+slowpokerfrance.fr+slowpokerfrance.org+slowpokerfrance.store+slushmail.com+slushpools.cloud+sluteen.com+sly.io+slyouthuk.org+smailpro.com+smailwork.com+smakit.vn+smallker.tk+smapfree24.com+smapfree24.de+smapfree24.eu+smapfree24.info+smapfree24.org+smartemailbox.co+smartnator.com+smarttalent.pw+smarttickethub.com+smashmail.de+smell.sbs+smellfear.com+smellrear.com+smellypotato.tk+smeux.com+smkanba.com+smncloud.com+smpcharity.co.uk+smpnegeri4-pwt.my.id+smtp.id.vn+smtp.io.vn+smtp99.com+smwg.info+smykwb.com+snakebutt.com+snakemail.com+snapbx.com+snapmail.cc+snapmail.site+snapmail.xyz+snapwet.com+sneakmail.de+snece.com+sneydgreen-communityhall.co.uk+snpmail.fun+soc123.net+social-mailer.tk+socialfurry.org+socialist.sbs+sociallymediocre.com+socialpulse.casa+socialtrash.online+soco7.com+socoori.com+sofia.re+sofimail.com+sofort-mail.de+sofortmail.de+sofrge.com+softbank.id+softdailyguide.com+softkey-office.ru+softlitceg.com+softpls.asia+sogetthis.com+sohai.ml+sohus.cn+soioa.com+soisz.com+solar-impact.pro+solarnyx.com+solarunited.net+solarunited.org+solenox.cfd+solerbe.net+solimoddin.online+solkill.store+solquira.cfd+solvemail.info+solventtrap.wiki+somadethcdk.site+somelora.com+somoj.com+son2d.site+songsan.business+songsign.com+soniot.fr+soniot.info+soniot.online+soniot.store+sonjj.edu.pl+sonl192.theworkpc.com+sonny.tk+sonphuongthinh.com+sonrusu.com+sonshi.cf+soodmail.com+soodomail.com+soodonims.com+soombo.com+soon.it+soscandia.org+soson.shop+soul-association.com+southai.bond+southeastessexanimal.uk+soyboy.observer+sozenit.com+spacebazzar.ru+spacehotline.com+spacework.top+spacexyz.space+spacezin.space+spam-be-gone.com+spam.care+spam.ceo+spam.la+spam.org.es+spam.su+spam4.me+spamail.de+spamarrest.com+spamavert.com+spambob.com+spambob.net+spambob.org+spambog.com+spambog.de+spambog.net+spambog.ru+spambooger.com+spambox.info+spambox.me+spambox.org+spambox.us+spamcero.com+spamcon.org+spamcorptastic.com+spamcowboy.com+spamcowboy.net+spamcowboy.org+spamday.com+spamdecoy.net+spamex.com+spamfellas.com+spamfighter.cf+spamfighter.ga+spamfighter.gq+spamfighter.ml+spamfighter.tk+spamfree.eu+spamfree24.com+spamfree24.de+spamfree24.eu+spamfree24.info+spamfree24.net+spamfree24.org+spamgoes.in+spamherelots.com+spamhereplease.com+spamhole.com+spamify.com+spaminator.de+spamkill.info+spaml.com+spaml.de+spamlot.net+spammer.fail+spammotel.com+spammy.host+spamobox.com+spamoff.de+spamsalad.in+spamsandwich.com+spamslicer.com+spamsphere.com+spamspot.com+spamstack.net+spamthis.co.uk+spamthis.network+spamthisplease.com+spamtrail.com+spamtrap.ro+spamtroll.net+spamwc.cf+spamwc.ga+spamwc.gq+spamwc.ml+sparkletoc.com+sparxautomationhub.store+speak2all.com+speaknow.org.uk+specialneedscircle.co.uk+speedgaus.net+speedlooking.fun+sperma.cf+spicysoda.com+spiedemtion.store+spikio.com+spindl-e.com+spinly.net+splitparents.com+spoofmail.de+sportcornwall.org+sportrid.com+sportsfunlifestyle.org+spotiy.site+spotlightdiary.com+spr.io+spritzzone.de+spruzme.com+spybox.de+spymail.com+spymail.one+squizzy.de+squizzy.net+srame.com+sroff.com+sry.li+srzi.makeup+ss0qw9a.ddnsfree.com+ssanphone.me+ssi-bsn.infos.st+ssoia.com+sssig.one+sssvcv.uno+stacys.mom+stanfordujjain.com+star-fish.org.uk+starbalance.site+starcheck.in+stardust-2.store+starlight-breaker.net+starlight.store+starmail.net+starnlink.com+starpower.space+startfu.com+startkeys.com+statdvr.com+stathost.net+statiix.com+stayhome.li+stc-88.com+steadyhabithub.com+steam-area.ru+steam-coin.com+steambot.net+steel4work.io.vn+stepsofhope.co.uk+sterlingpointco.com+stexsy.com+stinkefinger.net+stomatogomail.ru+stonesinwater.com+stop-my-spam.cf+stop-my-spam.com+stop-my-spam.ga+stop-my-spam.ml+stop-my-spam.pp.ua+stop-my-spam.tk+stopspam.app+storebanme.com+storegmail.net+storiesonthestreet.org+storiqax.top+storj99.com+storj99.top+storybuddies.online+stpaulsgrammaralumniusa.org+stravico.cfd+strayhood.org+streamingku.live+streamtv.biz.id+streamwolf.store+streetwisemail.com+stromox.com+stuckmail.com+student.nyc.mn+studio.jo3.org+studio.publicvm.com+studyhub.edu.pl+stuffmail.de+stufmail.com+stumpfwerk.com+stylist-volos.ru+su.cloudns.biz+suarj.com+submic.com+submitreports.com+substoretools.com+substoretools.site+substoretools.store+suburbanthug.com+suckmyd.com+sudern.de+sueshaw.com+suexamplesb.com+suft.autos+suftwari.com+sugarloafstudios.net+suhasmedam.com+suioe.com+sumberakun.com+suntuy.com+super-auswahl.de+super.lgbt+superblohey.com+superbowlstarttime.org+supergreatmail.com+supergrok.site+supermailer.jp+superplatyna.com+superrito.com+supersave.net+superstachel.de+superti4r.dev+superyp.com+supplementsdiary.com+supplementwiki.org+supportorganization.online+supporttc.com+surbitonnewlifebaptist.com+suremail.info+suryain.app+sushisalmon.online+sute.jp+svetims.com+svip520.cn+svip888888888.com+svipcun.eu.org+svk.jp+svlg.hair+svvf.hair+svxr.org+swagpapa.com+swap.name.ng+sweetberry.online+sweetpotato.ml+sweetxxx.de+swi4jut.ddnsfree.com+swift-mail.net+swift10minutemail.com+swiftcroft.org+swissokalmo.org.uk+swsdz.com+sx227.top+sx235.top+sx697.top+sx856.top+sx872.top+sx882.top+sx992.top+sydney.edu.pl+syecna9.ooguy.com+syinxun.com+sylentha.cfd+sylnetdns.site+sylnetgcp.site+sylnetgcp.top+sylnetx1.top+sylvannet.com+symphonyresume.com+synarca.com+syncax.com+synovaris.cfd+syntheradynamics.site+syosetu.gq+sysout.cloud+sytchampton.directory+sytchamptoncc.co.uk+syujob.accountants+sz345p7.loseyourip.com+szerz.com+szxcfagah.online+t15ippy.giize.com+t1mo.net+t2d9n0j.ooguy.com+t2t.email+t6s7.top+t7sqtao.giize.com+t8xieb2.kozow.com+tacomail.de+tafmail.com+tafnsxo.ooguy.com+tafoi.gr+tagara.infos.st+taglead.com+tagmymedia.com+tagyourself.com+taikhoankiro.pro+taimb.com+taischaves.com+tako.skin+talemarketing.com+talkinator.com+talkmatrix.study+talkup.sbs+talmetry.com+tamthomca.click+tamttts.com+tandlplith.se+tanlanav.com+tanukis.org+tanvo.online+taobudao.com+taohucom.store+taojingrun.online+taomail.web.id+tapchicuoihoi.com+taphear.com+tapi.re+tarasbest.xyz+tartinemoi.com+tarzanmail.cf+taseek.cc.cd+taseek.top+tastmemail.com+tastrg.com+tatadidi.com+tatsu.uk+taugr.com+taukah.com+taxibmt.com+taxibmt.net+taymonera.de+tb-on-line.net+tbgroupconsultants.com+tbr.fr.nf+tbterqwzv.top+tcwlm.com+tcwlx.com+tdtda.com+teambunnyfoundation.org.uk+teamnewmexico.org+teamtitan.co+tech2grow.io.vn+tech69.com+techblast.ch+techcyber.shop+techemail.com+techgroup.me+techlhj.email+technoproxy.ru+techusa.org+teerest.com+teewars.org+tefl.ro+tehillahpraise.uk+teihu.com+telecomix.pl+teleg.eu+telegmail.com+teleworm.com+teleworm.us+teliedge.com+teligmail.site+telimail.online+tellos.xyz+telos.lat+telvetto.com+temailz.com+tembusselalu.biz.id+tembusselalu.my.id+teml.net+temp-email.de5.net+temp-link.net+temp-mail-free.dedyn.io+temp-mail-free.dynv6.net+temp-mail.best+temp-mail.cfd+temp-mail.com+temp-mail.de+temp-mail.edu.rs+temp-mail.freeddns.org+temp-mail.gg+temp-mail.lol+temp-mail.now+temp-mail.org+temp-mail.pp.ua+temp-mail.ru+temp-mailer.dynv6.net+temp-mails.com+temp.skymeshdynamics.com+temp1month.icu+tempail.com+tempalias.com+tempblockchain.com+tempe-mail.com+tempebossok.my.id+tempemail.biz+tempemail.co.za+tempemail.com+tempemail.de+tempemail.net+tempemail.nyc.mn+tempemailgen.com+tempemaill.com+tempemailo.org+tempestme.com+tempinbox.co.uk+tempinbox.com+tempmail.at+tempmail.best+tempmail.cc+tempmail.cn+tempmail.co+tempmail.de+tempmail.email+tempmail.eu+tempmail.id.vn+tempmail.ing+tempmail.io.vn+tempmail.it+tempmail.ninja+tempmail.plus+tempmail.pp.ua+tempmail.us+tempmail.vip+tempmail.world+tempmail.ws+tempmail101.com+tempmail2.com+tempmail5.com+tempmaildemo.com+tempmailer.com+tempmailer.de+tempmailer.net+tempmailfree.net+tempmailo.com+tempmailr.com+tempmails.net+tempmailto.com+tempmailyo.org+tempomail.fr+tempomail.org+tempomailo.site+temporalemail.org+temporam.com+temporam.online+temporam.xin+temporam.xyz+temporarily.de+temporarioemail.com.br+temporarly.com+temporary-mail.net+temporaryemail.dpdns.org+temporaryemail.net+temporaryemail.us+temporaryforwarding.com+temporaryinbox.com+temporarymailaddress.com+tempp-mails.com+temppppo.store+tempr.email+tempsky.com+temptami.com+tempthe.net+tempymail.com+tenhub.uk+tensi.org+tenull.com+ternaklele.ga+terre.infos.st+test-infos.fr.nf+test1byali.cfd+testore.co+testudine.com+tetestebu.online+tevstart.com+texify.online+tfbnw.asia+tfbnw.id.vn+tfbnw.in+tfbnw.info+tfbnw.io.vn+tfbnw.tech+tfbnw.xyz+tfcn.beer+tffv4a3.kozow.com+tgduck.com+tgmaiss.xyz+tgnm.hair+tgoj.skin+thaihp.net+thaitudang.xyz+thalarex.cfd+thameschamberorchestra.co.uk+thanhnhontienbao.com+thanksnospam.info+thankyou2010.com+thaotri.com+thatim.info+thc.st+thdfyrg.top+the23app.com+theaviors.com+thebearshark.com+thebest73.shop+theboys.cyou+thecarinformation.com+thechildrensfocus.com+thecity.biz+thecloudindex.com+thecwf.co.uk+thediamants.org+thedirhq.info+thedorsetcarershub.org+theeyeoftruth.com+thegrampians.net+thehjhvj.ink+thejenkins.net+thejoker5.com+theking.id+thelifecentre.org.uk+thelightningmail.net+thelimescommunitygarden.org+thelimestones.com+themailer.de+thembones.com.au+themccarneyfoundation.co.uk+themegreview.com+themostemail.com+thereddoors.online+theroyalweb.club+thescrappermovie.com+these.cc+theshahnazfoundation.com+thespamfather.com+theteastory.info+thetechnext.net+theweifamily.icu+thex.ro+thg.cc.cd+thichanthit.com+thichmmo.com+thiefness.com+thietbivanphong.asia+thirifara.com+thisisnotmyrealemail.com+thismail.net+thispy.top+thisurl.website+thnikka.com+thoas.ru+thodianamdu.com+thoitrangnam2024.shop+thomasblackerby.org.uk+thor.my.id+thraml.com+threads.io.vn+thrma.com+throam.com+thrott.com+throwam.com+throwaway.dynv6.net+throwawayemailaddress.com+throwawaymail.com+throwawaymail.pp.ua+throya.com+thrubay.com+thshyo.org+thueotp.net+thulinh.net+thunderbolt.science+thunkinator.org+thuongxg.com+thurleighchurchestate.church+thxmate.com+tianblog.top+tianmi.me+tianstudy.space+tiapz.com+tic.ec+tidaksuka.cfd+tidewick.org+tidissajiiu.com+tidylifehub.com+tiendadezapasok.com+tiffincrane.com+tigrisstem.org+tijdelijke.email+tikanony.com+tikmail.org+tiksofi.uk+tiktakgrab.com+tiktakgrab.shop+tiktakgrabber.com+tiktokngon.com+tiktokus.us+tilien.com+tilumo.cfd+tilvex.click+timbourkescholarshipfund.org+timgiarevn.com+timkassouf.com+tinhoconline.com+tinoza.org+tinpho.com+tinytimer.org+tinyurl24.com+tipsb.com+tirasya.pro+titangamezz.com+titenpa.com+tittbit.in+tiv.cc+tivendra.cfd+tivertonhospitalleagueoffriends.co.uk+tivo.camdvr.org+tizi.com+tjhn.beer+tkfb24h.com+tkitc.de+tlktok.us+tlpn.org+tmail.com+tmail.edu.rs+tmail.gg+tmail.io+tmail.link+tmail.lt+tmail.mx+tmail.ws+tmail1.org+tmail2.org+tmail3.com+tmail3.org+tmail4.org+tmail5.org+tmail6.com+tmail9.com+tmaile.net+tmailinator.com+tmailor.com+tmailor.net+tmails.net+tmmbt.net+tmpbox.net+tmpemails.com+tmpeml.com+tmpeml.info+tmpjr.me+tmpmail.net+tmpmail.org+tmpmailtor.com+tmpnator.live+tmpx.sa.com+tmxttvmail.com+tnbeta.com+toaik.com+tocuda.cloud+toddsbighug.com+tofeat.com+tohru.org+toiea.com+tokem.co+token.ro+token0v0.com+tokenmail.de+tokfly.org+tokmail.fun+tokmail.net+tokobibit.co+tokyo.edu.pl+tokyo112.top+tokyoflarex.tokyo+tomhouse.shop+tommyfommy.site+tomvnet.uk+tonaeto.com+tongle.ccwu.cc+toni.io.vn+tonne.to+tonyfarm.indevs.in+tonymanso.com+too.li+toolbox.ovh+toolnator.plus+toolourles.tech+tools-capcut.com+toolsequipment.cyou+toomail.biz+toon.ml+top-shop-tovar.ru+top101.de+top1mail.ru+top1post.ru+topdatamaster.com+topinrock.cf+topmail2.com+topmail2.net+topofertasdehoy.com+topranklist.de+topren.cyou+topren.top+toprumours.com+topupgg.app+topvu.net+torkakak.site+tormail.org+torrent411.fr.nf+torvila.sbs+tospage.com+toss.pw+tosunkaya.com+totallynotfake.net+totalvista.com+totesmail.com+totoan.info+totococo.fr.nf+toupiao7003.top+tourcc.com+tozya.com+tp-qa-mail.com+tppp.one+tppp.online+tpwlb.com+tqoai.com+tqosi.com+trackden.com+tradermail.info+tradingview.my.id+trainthem2fish.co.uk+tramynguyen.net+tranceversal.com+trandigabapoe.shop+trangiabao.click+trangzim.uk+tranhtai.com+transaksikita.tech+transferpulsa.net+translateid.com+traodoinick.com+traogiai.com+trap-mail.de+trash-amil.com+trash-mail.at+trash-mail.cf+trash-mail.com+trash-mail.de+trash-mail.ga+trash-mail.gq+trash-mail.ml+trash-mail.tk+trash-mail.webredirect.org+trash-me.com+trash2009.com+trash2010.com+trash2011.com+trashcanmail.com+trashdevil.com+trashdevil.de+trashemail.de+trashemails.de+trashinbox.com+trashmail.at+trashmail.com+trashmail.de+trashmail.fr+trashmail.gq+trashmail.hu+trashmail.io+trashmail.me+trashmail.net+trashmail.org+trashmail.se+trashmail.ws+trashmailer.com+trashmailgenerator.de+trashmails.com+trashymail.com+trashymail.net+trasz.com+travelfriend.online+travelistaworld.com+travelovelinka.club+travionex.cfd+trayna.com+trbvm.com+trbvn.com+trbvo.com+treesforderby.org+trend-maker.ru+treso.me+treterter.shop+trevourus.com+trfu.to+trgfu.com+trgovinanaveliko.info+trialmail.de+trickmail.net+trieuhao.site+trillianpro.com+trinovia.cfd+triots.com+trixtrux1.ru+trojanvmesswrt.dpdns.org+trolebrotmail.com+trollproject.com+tropicalbass.info+tropovenamail.com+trovantis.cfd+troveniq.cfd+trumingovn.online+trunghocphothong.io.vn+trungmetax.com+trungtamtoeic.com+trustcheck.cc+trustdomainvn.us+trustedadmin2.shop+trustedadmindns.site+trustguru.vip+trusticloud.us+trustmailold.us+truthfinderlogin.com+tryalert.com+tryninja.io+trythe.net+tryzoe.com+tscasalnt.top+tsderp.com+tsdpt.co.uk+tshdn.cfd+tshirtsavvy.com+tsmtp.org+tstrust.org.uk+ttirv.org+ttpo89japan.com+ttszuo.xyz+tualias.com+tuamaeaquelaursa.com+tubebox.us+tubeemail.com+tuethong.shop+tuku26012023.xyz+tulw6ae.ooguy.com+tumroc.net+tunthuta.com+tuofs.com+tupmail.com+turkeyth.com+turnimon.com+turoid.com+turual.com+turuma.com+tutuapp.bid+tuyenchau.click+tuyenchau.online+tuyenchau.site+tuyenhuy.click+tuyenhuy.online+tuyenhuy.site+tvchd.com+tverya.com+twck.hair+tweet.fr.nf+twinmail.de+twitch.work+twitchythoughtcreations.in+twitter.io.vn+twkly.ml+twocowmail.net+twoweirdtricks.com+twskyhope.top+twskyhope.xyz+twskyhopenb.shop+twzhhq.online+tx1ggv4.theworkpc.com+txcct.com+txen.de+txqx.skin+txtadvertise.com+tybz.hair+tyhe.ro+tyldd.com+tympe.net+tyoless.org.uk+tzrj.pro+u2v7nnn.mywire.org+uacro.com+uber-mail.com+uberip.com+ubinert.com+ubismail.net+ubm.md+ucche.us+ucupdong.ml+uddinfoundation.org+udingclin.com+uemail99.com+ufacturing.com+ufokeuabmail.com+ug.wtf+uggsrock.com+uguuchantele.com+uhe2.com+uhhu.ru+uiemail.com+uiu.us+ujijima1129.gq+uk.to+ukev.org+uki.io.vn+ukm.ovh+ukshop538yt.uk+ukwv.skin+ulm-dsl.de+ulteriq.cfd+ultra.fyi+ultrada.ru+ultrafive.online+ultralabs24.store+ultralux.io.vn+ultrasix.online+ultravex.cfd+ultraz1.io.vn+ultrmigos.online+uma3.be+umail.net+umil.net+umiudi.cn+umombiss.tk+undeadbank.com+underseagolf.com+undo.it+unfairship.com+unicodeworld.com+unids.com+unimain.tech+unimark.org+uniromax.com+unit7lahaina.com+unitedcharitiesosm.org.uk+universall.me+unlikeyth.com+unmail.ru+unratito.com+uofzcpg9ftykob.asia+uooos.com+uorak.com+upc.infos.st+upliftnow.com+uplipht.com+uploadnolimit.com+upozowac.info+upphim.net+upsnab.net+uqfb.hair+uqqlrdi.top+urbanvalore.info+urfunktion.se+urgentmail.ovh+urhen.com+uroid.com+urvs.skin+urzy.skin+us-x.top+us.af+us.to+usa.cc+usa.edu.pl+usaishop.shop+usako.net+usbc.be+usdtbeta.com+used-product.fr+usedus.me+usefulbriefing.com+uselesswebsites.net+ushijima1129.cf+ushijima1129.ga+ushijima1129.gq+ushijima1129.ml+ushijima1129.tk+usm.ovh+uspsp.top+usrl71x.camdvr.org+ustorp.com+usus.accesscam.org+usus.camdvr.org+usus.casacam.net+usus.ddnsfree.com+ususus.dynv6.net+utiket.us+utkarsh.tech+uu.gl+uu2.ovh+uue.edu.pl+uuf.me+uuii.in+uvaul.us.ci+uwork4.us+uyhip.com+uyqs.skin+uz8.net+v-mail.xyz+v1jhjrc.giize.com+v2v.click+v2v.email+v2v.world+v6.army+v6.navy+v6.rocks+v6omlz6.giize.com+vaasfc4.tk+vaati.org+vae.indevs.in+vafyxh.com+valanides.com+valemail.net+valhalladev.com+valueineveryone.co.uk+vankin.de+vasteron.com+vatos.gg+vaupk.org+vbgvd.com+vbv.cards+vcois.com+vctel.com+vda.ro+vddaz.com+vdig.com+vdzc.skin+veanlo.com+veb37.com+vectorbrasil.app+velatrix.cfd+veletis.bond+velloxist.site+velmoor.org+velocitronix.online+veltexline.com+vemomail.win+venariq.cfd+venompen.com+ventrovia.cfd+veo.kr+veo325k.io.vn+veo325kcredit.io.vn+veo33.io.vn+veo3ultra.sbs+veomatrix25k.io.vn+veoverse25k.io.vn+ver0.cf+ver0.ga+ver0.gq+ver0.ml+ver0.tk+vercelli.cf+vercelli.ga+vercelli.gq+vercelli.ml+verdejo.com+verel.online+verifycenter.net+verityemail.site+vermutlich.net+vernonbourne.uk+veronicamira.info+vertexinbox.com+vertexium.net+veruvercomail.com+verybigdick.cyou+veryday.ch+veryday.eu+veryday.info+veryrealemail.com+ves.ink+vesa.pw+vesdev01.shop+vetra.cyou+vevs.de+vexalor.cfd+vexaluno.xyz+vexi.my+vextora.click+vfdhks.eu.cc+vfre4w3.dynv6.net+vfwladiesauxin.org+vgfautd.mywire.org+vggh.beer+vgyi.hair+vi1ilpa.mywire.org+via.tokyo.jp+viavuive.net+vibertees.com+vibzi.net+vickaentb.tk+victime.ninja+victoriaalison.com+victoriantwins.com+vidchart.com+videoigdownload.com+videotoptop.com+viditag.com+vidwobox.com+vidxlr.me+viemarter.online+viettravel.io.vn+vietxf.com+viewbuster.ru+viewcastmedia.com+viewcastmedia.net+viewcastmedia.org+viewmuse.com+vigilantkeep.net+vigoneo.com+vikingsonly.com+villaxoa.site+vinaemail.com+vinakoop.com+vinakop.com+vinatissue.org+vinernet.com+vinhdo.shop+vintomaper.com+viole.cfd+violet0923.online+vipepe.com+vipmail.name+vipmail.pw+vipmba.cc+vips.pics+vipxm.net+viralplays.com+virelio.cfd+virgilian.com+virginsrus.xyz+virtualemail.info+virtualminerals.com+visal007.tk+visal168.cf+visal168.ga+visal168.gq+visal168.ml+visal168.tk+visignal.com+visualdep.run.place+visualnest.work+visuals.linkpc.net+vitahicks.com+vitaspherelife.com+vitrineproducoes.com+viv2.com+vividtipzone.com+vixletdev.com+vixtricks.com+vjbl.skin+vjoid.ru+vjoid.store+vjuum.com+vkbb.ru+vkbb.store+vkbt.ru+vkbt.store+vkcbt.ru+vkcbt.store+vkcode.ru+vkfu.ru+vkfu.store+vkjashdf.eu.cc+vkpr.store+vkr1.com+vkrr.ru+vkrr.store+vladhub.buzz+vlemi.com+vlrregulatory.com+vmailing.info+vmani.com+vmbx.skin+vmm.indevs.in+vmpanda.com+vn-one.com+vncctv.org+vnedu.me+vnfjsh.eu.cc+vnqi.skin+vntechhub.online+vnvmail.com+vnxdxpf.loseyourip.com+vobau.net+voerpemww.click+voicesforchangeinc.org+voidbay.com+voidmail.one+voidpop.win+volaj.com+volku.org+voltaer.com+voltr.click+voltravia.cfd+vomoto.com+vorga.org+vortalis.cfd+voryxen.com+vothanhtuan.shop+votiputox.org+voxelcore.com+voxinh.net+vpbz.skin+vpii.beer+vpkv.skin+vpn.st+vpn64.de+vpnseat.com+vps30.com+vps79.com+vps911.net+vqdz.hair+vqdz.skin+vradportal.com+vremonte24-store.ru+vrjxk.com+vrmtr.com+vsdsd23gsdf.shop+vsimcard.com+vsmailpro.com+vssms.com+vtmpj.net+vtxmail.us+vuatrochoi.nl+vubby.com+vuiy.pw+vuket.org+vulca.sbs+vulcanpioneerjers.org+vupn.me+vusra.com+vutrugay.org+vuv.indevs.in+vvatxiy.com+vwagamlk.top+vwhins.com+vxsolar.com+vystella.cfd+vztc.com+w-asertun.ru+w154ed2.giize.com+w3internet.co.uk+wacold.com+waguriagent.codes+waisfoundation.com+waitbeqa.com+waivey.com+wakingupesther.com+walala.org+walkmail.net+walkmail.ru+wallm.com+wanai.biz.id+wanaofamouscar.com+wandouyu.run+wanko.be+wansnode-dice.site+wanting2work.org.uk+wanva.shop+wargravepreschool.uk+warlus.asso.st+waroengin.com+waroengku.cc+waroengkuy.com+waroengmail.com+waroengpremium.com+warrity25k.io.vn+warunkto.com+watch-harry-potter.com+watchever.biz+watchfull.net+watchironman3onlinefreefullmovie.com+waterisgone.com+waterpalace.pro+watersoftenersystemcost.com+watrf.com+watsawang.com+waventra.cfd+waw.indevs.in+wazabi.club+wbdev.tech+wbml.net+wbslxy.cc.cd+wdhu.skin+wdrd.beer+wearkeymail.site+wearvault.biz.id+weatherbx.xyz+weaxymt.loseyourip.com+web-contact.info+web-ideal.fr+web-inc.net+web-library.net+web-mail.pp.ua+web2mailco.com+webcamness.com+webcenterfairbanks.dedyn.io+webclub.infos.st+webcontact-france.eu+webemail.me+webhook.site+webinarmoa.com+webm4il.info+webmail24.top+webmailus.com+webofip.com+webscash.com+webstore.fr.nf+webtrip.ch+webui.cc.cd+webuser.in+wecanmakehit.win+wecp.ru+wecp.store+wee.my+weekfly.com+weekzs.icu+weeline.fun+wef.gr+weg-werf-email.de+wegoo.dpdns.org+wegwerf-email-addressen.de+wegwerf-email-adressen.de+wegwerf-email.at+wegwerf-email.de+wegwerf-email.net+wegwerf-emails.de+wegwerfadresse.de+wegwerfemail.com+wegwerfemail.de+wegwerfemail.info+wegwerfemail.net+wegwerfemail.org+wegwerfemailadresse.com+wegwerfmail.de+wegwerfmail.info+wegwerfmail.net+wegwerfmail.org+wegwerpmailadres.nl+wegwrfmail.de+wegwrfmail.net+wegwrfmail.org+weiruipingji.com+weizixu.com+wejedvv.giize.com+wekawa.com+welikecookies.com+wellsfargocomcardholders.com+wemel.top+wenkuu.com+wentcity.com+wenyuanshe.com+wep.email+were-w.top+wetrainbayarea.com+wetrainbayarea.org+weyword.cfd+wfgdfhj.tk+wfpe.autos+wg0.com+wh4f.org+whaaaaaaaaaat.com+whatagarbage.com+whatemi.de+whatever.za.net+whatiaas.com+whatifanalytics.com+whatpaas.com+whatsaas.com+whf222.top+whiffles.org+whirlygirlink.org+whispermail.org+whitehousecalculator.com+whitemistral.pro+whob31o.camdvr.org+whoopza.org+whoopza.store+whopy.com+whyspam.me+wibblesmith.com+wicfolhumanservices.org+wickmail.net+widaryanto.info+widget.gg+wiemei.com+wierie.tk+wifimaple.com+wifioak.com+wikfee.com+wikidocuslava.ru+wildan.tech+wilemail.com+willhackforfood.biz+willselfdestruct.com+wimsg.com+windsurfcom.shop+winemaven.info+winocs.com+wins.com.br+wintersgf.store+wintersmail.site+wir-sind.com+wireconnected.com+wishy.fr+wivstore.com+wjah.hair+wjah.skin+wlist.ro+wlsom.com+wmail.cf+wmail.club+wmct.info+wmksuhd.cn+wnbaldwy.com+wohbc.co.uk+wokcy.com+wolfmail.ml+wolfsmail.tk+wollan.info+womp-wo.mp+woofgl.email+woofidog.fr.nf+woopros.com+workhorsefilms.com+workingtall.com+worldcoins.top+worldcricket.org.uk+worldlylife.store+worldspace.link+woshiemoman.cloud-ip.cc+wovoemj1119.icu+wpdork.com+wpg.im+wpnf.skin+wralawfirm.com+wrgee.com+writeme.us+wronghead.com+wrqj.top+wrxx.beer+ws.gy+wshu.net+wsvpsft.xyz+wsxnxce.online+wsym.de+wsypc.com+wtjinkintrust.co.uk+wtsl.hair+wudet.men+wudiai.shop+wuespdj.xyz+wupics.com+wusongdahu.cc.cd+wuuvo.com+wuzak.com+wuzup.net+wuzupmail.net+wvdg.skin+wvyt851.ddnsfree.com+wwc8.com+wwdskboiv.top+wwefd.top+wwej.cc.cd+wwjmp.com+wwtykkm.bond+wwvec.uno+wwvk.ru+wwvk.store+wwwnew.eu+wxcv.fr.nf+wxf07.shop+wxhp.hair+wxnw.net+wxxu.hair+wyoxafp.com+wywnxa.com+wzjpj.com+wzjyyds.com+wzofit.com+x-clone.asia+x-lab.net+x0bdu6n.mywire.org+x0q.net+x1ix.com+x24.com+x80.dpdns.org+x80la.shop+x8nxh3g.theworkpc.com+x9ad1.my+xagloo.co+xagloo.com+xandoria.cfd+xapimail.top+xazymarcie.space+xbaby69.top+xbrok.com+xcf.pet+xclone.asia+xcode.ro+xcodes.net+xcompress.com+xcoxc.com+xcp3iiv.ooguy.com+xcpy.com+xcsllajs.eu.cc+xcucngon.site+xcvuaylik.top+xcvv.xyz+xczv.hair+xdfrms.fun+xdnss.cc+xdpxdp.online+xehop.org+xelio.sbs+xelu.space+xemaps.com+xemne.com+xen-bypass.com+xenloria.cfd+xeno.gay+xenta.cfd+xents.com+xeovo.ru+xepa.ru+xfavaj.com+xfft.beer+xgcpking.space+xgmail.bond+xgng.skin+xhke.hair+xhke.skin+xhotmail.cyou+xi2.cc+xiajspof.eu.cc+xiangshan.eu.cc+xiaoche.ggff.net+xiaoguaishou.icu+xiaohuangyu.ccwu.cc+xiaoting.cc+xib.icu+xidealx.com+xiiqtg.com+xiiqtg.vip+xikemail.com+ximenor.site+xingmeisofa.com+xirentha.cfd+xitler.top+xiwinnie.icu+xjau.homes+xjoi.com+xkgm.hair+xktu.hair+xkx.me+xkxkud.com+xl.cx+xlcsh.icu+xmailer.be+xmailtm.com+xmaily.com+xmisom.help+xmlab.icu+xmyvgkvw.top+xn--5nx.cc+xn--9kq967o.com+xn--ai-ry2ck37oorv.com+xn--d-bga.net+xn--di5au2k.shop+xn--ihq4pool8g32cwxiiqcovaa9159jhvah03g.top+xn--jxsa73o.eu.org+xn--o38h.abrdns.com+xn--rhqv96g.tv+xn--yaho-sqa.com+xn-xp8h.bond+xo00wda.loseyourip.com+xojxe.com+xolic.me+xopmail.fun+xost.us+xoxo3.website+xoxox.cc+xperiae5.com+xpremium.pro+xpromail.xyz+xqmm.hair+xqqgegsd.eu.cc+xrap.de+xshop.bond+xsioap.eu.cc+xsnipersquad.com+xsnipersquad.site+xsnipersquad.space+xstyled.net+xswl.xyz+xt81.help+xtzg.beer+xunika.uk+xvx.us+xww.ro+xxhamsterxx.ga+xxi2.com+xxl.st+xxlocanto.us+xxmailedu.dpdns.org+xxolocanto.us+xxqx3802.com+xxvd.net+xxvk.ru+xxvk.store+xxxhi.cc+xy9ce.tk+xylanta.cfd+xylar.ru+xylar.store+xyxy.app+xyzfree.net+xzsok.com+y0fwzc2.mywire.org+y0p8gli.loseyourip.com+y1dk5vk.giize.com+y4plv.cyou+y6jxjln.kozow.com+yabai-oppai.tk+yabes.ovh+yahmail.top+yahooproduct.net+yahoox.cyou+yaloo.fr.nf+yamail.win+yanet.me+yangzazhong.top+yangzhai.xyz+yangzhong-sfd.cc+yanhd-jkd.top+yannmail.win+yanxuan.eu.cc+yapped.net+yaqp.com+yarnpedia.ga+yasuo.sbs+yb9ye8c.kozow.com+ybidbccmv.top+yc08.cn+ycare.de+ycglobalmovement.com+ycn.ro+ydhfks.shop+ydns.eu+ydscontingencia.com+ye.vc+yecp.ru+yecp.store+yedi.org+yeezus.ru+yellofdf2.click+yenphandinhe.com+yep.it+yermail.net+yeummo.io.vn+yfhsdb.eu.cc+yfnc.skin+ygbelira.me+ygebjd8-ktyd.top+ygpa.autos+yhg.biz+yihacihuy.top+yilue.eu.org+ying-ge.com+yingzi321.shop+yiuogmq.loseyourip.com+yjlwcbrf.top+yl66.cfd+ymonthl.com+ynagjie-66.cc+ynmrealty.com+ynnord.top+yodwg.sbs+yodx.ro+yogamaven.com+yoggm.com+yogirt.com+yomail.edu.pl+yomail.info+yomand.store+yondrix.cfd+yongdan-hstn.best+yoo.ro+yopm.zone.id+yopmail.com+yopmail.fr+yopmail.gq+yopmail.kro.kr+yopmail.loseyourip.com+yopmail.net+yopmail.ooguy.com+yopmail.pp.ua+yopmail.theworkpc.com+yopmail.webredirect.org+yoptruc.fr.nf+yordanmail.cf+yorushika.one+yotmail.fr.nf+you-spam.com+yougotgoated.com+youmail.ga+youmailr.com+youneedmore.info+youpymail.com+your5.ru+your5.store+yourdomain.com+youremail.cf+yourewronghereswhy.com+yourlms.biz+yours.tools+yourspamgoesto.space+yourtube.ml+yourwiseguide.com+youtube-com-watch-jtpdc8khnpi.accesscam.org+youtube-com-watch-jtpdc8khnpi.bond+youtube-com-watch-jtpdc8khnpi.cyou+youtube-com-watch-jtpdc8khnpi.dedyn.io+youtube-com-watch-jtpdc8khnpi.freeddns.org+youtube-com-watch-jtpdc8khnpi.gleeze.com+youtube-com-watch-jtpdc8khnpi.loseyourip.com+youtube-com-watch-jtpdc8khnpi.mywire.org+youtube-com-watch-jtpdc8khnpi.ooguy.com+youtube-com-watch-jtpdc8khnpi.theworkpc.com+youtube-com-watch-jtpdc8khnpi.webredirect.org+youxiang.dev+ypyb.hair+yroid.com+yrppwsekv.top+ysfuddr.top+ysgdjd.fun+yshdnhh.click+ysngdtw55n.top+yspend.com+ysuhd.art+yszmy.cn+ytkj.us.ci+ytnhy.com+ytoof.app+ytpayy.com+yugasandrika.com+yui.it+yujiehanjiao.cc+yuki.ren+yummymeow.eu+yummymeow.fr+yummymeow.org+yummymeow.store+yun.pics+yunxiangpnv.lol+yuoia.com+yurevia.cfd+yurovovault.shop+yuurok.com+ywiueryweqrwerqsdf.us.ci+ywzmb.top+yxdad.ru+yxdad.store+yxkm.skin+yxx1.ccwu.cc+yxxala.ccwu.cc+yxxawa.ccwu.cc+yxxawa.top+yxzx.net+yydsplus.top+yykzv53.theworkpc.com+yyolf.net+yyqzc8v.giize.com+yzcalo.com+yzm.de+z-o-e-v-a.ru+z0d.eu+z1p.biz+z86.ru+z8ebbq2.camdvr.org+zai.asia+zain.com.co+zain.site+zainmax.net+zaktouni.fr+zalesie.net.pl+zantrax.com+zapmail.one+zarabotokdoma11.ru+zarkbin.store+zasod.com+zauxpbp.cn+zaym-zaym.ru+zcdpbx.top+zcjzy.cc.cd+zcovz.ru+zcovz.store+zcrcd.com+zdenka.net+zdge.hair+ze.tc+zebins.com+zebins.eu+zehnminuten.de+zehnminutenmail.de+zeldaa.ccwu.cc+zellatrix.cfd+zellio.yachts+zemzar.net+zenbada.com+zenbyul.com+zensurpirat.de+zenthara.cfd+zenthira.cfd+zenthranet.com+zephyros.cfd+zepp.dk+zeroai.sbs+zeronerbacomail.com+zeropolly.com+zetmail.com+zevionyx.com+zexic.cyou+zfymail.com+zgg0.help+zhaji.eu.org+zhanhuokma2.wang+zhaoqian.ninja+zhaoyuanedu.cn+zhcne.com+zhengwz.dpdns.org+zhewei88.com+zhizhiwei.fun+zhjjq.tech+zhorachu.com+zhousj.eu.org+zik.dj+zikzak.site+zimf.hair+zipcad.com+zipcatfish.com+ziping.me+zipmail.one+zipo1.gq+zippymail.info+zipsendtest.com+zira.my+ziragold.com+zivox.sbs+ziyoupi.asia+zizo7.com+zkfdwz.shop+zkfr.hair+zlqkuzx.ddnsfree.com+zlzu.skin+zmail.cam+zmnai.top+zmypxprb.sbs+znext.bond+zoaxe.com+zoemail.com+zoemail.net+zoemail.org+zoetropes.org+zolamin.com+zolmiu.cfd+zombie-hive.com+zomg.info+zoomintens.com+zorg.fr.nf+zouz.fr.nf+zovion.com+zozozo123.com+zpva4pd.mywire.org+zqjq.hair+zqwn.skin+zrpu.hair+zrufe.com+zsero.com+zsmj.cc.cd+zsts.top+zudpck.com+zuldev.live+zumnime.me+zumpul.com+zutomayo.best+zv68.com+zvvzuv.com+zw5pkjm.camdvr.org+zx81.ovh+zxb8bds.loseyourip.com+zxcv.com+zxcvbn123.cc.cd+zxcvbnm.com+zxhyzlwcp.top+zxqzin.cn+zxrey.club+zymuying.com+zyns.com+zypherin.cfd+zyranova.cfd+zyvenix.cfd+zzaidah.cloud+zzeu.us+zzi.us+zzrgg.com+zzz.com+zzzzzzzzzzzzzz-1090.dynv6.net+zzzzzzzzzzzzzz-2092.dynv6.net+zzzzzzzzzzzzzz-277.dynv6.net+zzzzzzzzzzzzzz-3294.dynv6.net+zzzzzzzzzzzzzz-3330.dynv6.net+zzzzzzzzzzzzzz-3535.dynv6.net+zzzzzzzzzzzzzz-3928.dynv6.net+zzzzzzzzzzzzzz-3940.dynv6.net+zzzzzzzzzzzzzz-4283.dynv6.net+zzzzzzzzzzzzzz-4904.dynv6.net+zzzzzzzzzzzzzz-5055.dynv6.net+zzzzzzzzzzzzzz-5246.dynv6.net+zzzzzzzzzzzzzz-546.dynv6.net+zzzzzzzzzzzzzz-739.dynv6.net+zzzzzzzzzzzzzz-7619.dynv6.net+zzzzzzzzzzzzzz-7911.dynv6.net+zzzzzzzzzzzzzz-8050.dynv6.net+zzzzzzzzzzzzzz-8079.dynv6.net+zzzzzzzzzzzzzz-8874.dynv6.net+zzzzzzzzzzzzzz-969.dynv6.net+zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.loseyourip.com+zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.ooguy.comdiff --git a/core/switch_core/gateway/email_domain_lists/free.txt b/core/switch_core/gateway/email_domain_lists/free.txtnew file mode 100644index 000000000..9bcf0683d--- /dev/null+++ b/core/switch_core/gateway/email_domain_lists/free.txt@@ -0,0 +1,4465 @@+# Free e-mail providers, from willwhite/freemail (ISC licence; see NOTICE),+# data/free.txt at commit 5d69d4e6f03564c9083e3b669228479ba7d520f6,+# keeping only well-formed domains. One lower-case domain per line.+1033edge.com+11mail.com+123.com+123box.net+123india.com+123mail.cl+123mail.org+123qwe.co.uk+126.com+126.net+139.com+150mail.com+150ml.com+15meg4free.com+163.com+16mail.com+188.com+189.cn+1coolplace.com+1freeemail.com+1funplace.com+1internetdrive.com+1mail.net+1me.net+1mum.com+1musicrow.com+1netdrive.com+1nsyncfan.com+1under.com+1webave.com+1webhighway.com+2-mail.com+212.com+24horas.com+2911.net+2980.com+2bmail.co.uk+2d2i.com+2die4.com+2trom.com+3000.it+30minutesmail.com+3126.com+321media.com+3675.mooo.com+37.com+3ammagazine.com+3dmail.com+3email.com+3g.ua+3xl.net+444.net+4email.com+4email.net+4mg.com+4newyork.com+4x4man.com+50mail.com+5iron.com+5star.com+74.ru+88.am+8848.net+888.luk2.com+888.nu+97rock.com+99.com+a1.net+aa.da.mail-temp.com+aaamail.zzn.com+aamail.net+aapt.net.au+aaronkwok.net+abbeyroadlondon.co.uk+abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijk.com+abcflash.net+abdulnour.com+aberystwyth.com+abolition-now.com+about.com+abv.bg+abwesend.de+academycougars.com+acceso.or.cr+access4less.net+accessgcc.com+accountant.com+acdcfan.com+ace-of-base.com+acmecity.com+acmemail.net+acninc.net+activatormail.com+activist.com+adam.com.au+addcom.de+address.com+adelphia.net+adexec.com+adfarrow.com+adios.net+adoption.com+ados.fr+adrenalinefreak.com+advalvas.be+aeiou.pt+aemail4u.com+aeneasmail.com+afreeinternet.com+africamail.com+africamel.net+ag.us.to+agoodmail.com+ahaa.dk+ahgae-crews.us.to+ai.aax.cloudns.asia+aichi.com+aim.com+aircraftmail.com+airforce.net+airforceemail.com+airmail.cc+airpost.net+ajacied.com+ak47.hu+aknet.kg+albawaba.com+alecsmail.com+alex4all.com+alexandria.cc+algeria.com+alhilal.net+alibaba.com+alice.it+alicedsl.de+alive.cz+aliyun.com+allergist.com+allmail.net+alloymail.com+allracing.com+allsaintsfan.com+alltel.net+alpenjodel.de+alphafrau.de+alskens.dk+altavista.com+altavista.net+altavista.se+alternativagratis.com+alumni.com+alumnidirector.com+alvilag.hu+amele.com+america.hm+ameritech.net+amnetsal.com+amorki.pl+amrer.net+amuro.net+amuromail.com+ananzi.co.za+ancestry.com+andylau.net+anfmail.com+angelfan.com+angelfire.com+angelic.com+animail.net+animal.net+animalhouse.com+animalwoman.net+anjungcafe.com+annsmail.com+anonymous.to+anote.com+another.com+anotherwin95.com+anti-social.com+antisocial.com+antongijsen.com+antwerpen.com+anymoment.com+anytimenow.com+aol.co.uk+aol.com+aol.fr+aon.at+apagitu.chickenkiller.com+apexmail.com+apmail.com+apollo.lv+aport.ru+aport2000.ru+apple.dnsabr.com+appraiser.net+approvers.net+arabia.com+arabtop.net+arcademaster.com+archaeologist.com+arcor.de+arcotronics.bg+arcticmail.com+argentina.com+aristotle.org+army.net+arnet.com.ar+artlover.com+artlover.com.au+as-if.com+asean-mail.com+asheville.com+asia-links.com+asia-mail.com+asia.com+asiafind.com+asianavenue.com+asiancityweb.com+asiansonly.net+asianwired.net+asiapoint.net+assala.com+assamesemail.com+astroboymail.com+astrolover.com+astrosfan.com+astrosfan.net+asurfer.com+atheist.com+athenachu.net+atina.cl+atl.lv+atlaswebmail.com+atlink.com+ato.check.com+atozasia.com+atrus.ru+att.net+attglobal.net+attymail.com+au.ru+auctioneer.net+ausi.com+aussiemail.com.au+austin.rr.com+australia.edu+australiamail.com+austrosearch.net+autoescuelanerja.com+autograf.pl+automotiveauthority.com+autorambler.ru+aver.com+avh.hu+awsom.net+axoskate.com+ayna.com+azimiweb.com+azure.cloudns.asia+bacapedia.web.id+bachelorboy.com+bachelorgal.com+backpackers.com+backstreet-boys.com+backstreetboysclub.com+backwards.com+bagherpour.com+bahrainmail.com+baldmama.de+baldpapa.de+ballyfinance.com+bangkok.com+bangkok2000.com+bannertown.net+baptistmail.com+baptized.com+barcelona.com+bartender.net+baseballmail.com+basketballmail.com+batuta.net+baudoinconsulting.com+bboy.zzn.com+bcvibes.com+beeebank.com+beenhad.com+beep.ru+beer.com+beethoven.com+belanjaonlineku.web.id+belice.com+belizehome.com+bell.net+bellair.net+bellsouth.net+berkscounty.com+berlin.com+berlin.de+berlinexpo.de+bestmail.us+betriebsdirektor.de+bettergolf.net+bharatmail.com+bigassweb.com+bigblue.net.au+bigboab.com+bigfoot.com+bigfoot.de+bigger.com+biggerbadder.com+bigmailbox.com+bigmir.net+bigpond.com+bigpond.com.au+bigpond.net.au+bigramp.com+bigtokenican2.hmail.us+bigtokenican3.hmail.us+bikemechanics.com+bikeracer.com+bikeracers.net+bikerider.com+billsfan.com+billsfan.net+bimamail.com+bimla.net+bin-wieder-da.de+bio-muesli.info+birdlover.com+birdowner.net+bisons.com+bitmail.com+bitpage.net+bizhosting.com+bk.ru+bla-bla.com+blackburnmail.com+blackplanet.com+blader.com+blazemail.com+bleib-bei-mir.de+blockfilter.com+bluebottle.com+bluehyppo.com+bluemail.ch+bluemail.dk+bluesfan.com+blushmail.com+bmlsports.net+boardermail.com+boatracers.com+bol.com.br+bolando.com+bollywoodz.com+bolt.com+boltonfans.com+bombdiggity.com+bonbon.net+boom.com+bootmail.com+bornnaked.com+bossofthemoss.com+bostonoffice.com+bounce.net+box.az+box.ua+boxbg.com+boxemail.com+boxfrog.com+boyzoneclub.com+bradfordfans.com+brasilia.net+bratwurst.dnsabr.com+brazilmail.com+brazilmail.com.br+breathe.com+bresnan.net+brew-master.com+brew-meister.com+brfree.com.br+briefemail.com+bright.net+britneyclub.com+brittonsign.com+broadcast.net+brokenvalve.com+brusseler.com+bsdmail.com+btopenworld.co.uk+buerotiger.de+buffymail.com+buford.us.to+bullsfan.com+bullsgame.com+bumerang.ro+bumrap.com+bunko.com+buryfans.com+business-man.com+businessman.net+businessweekmail.com+busta-rhymes.com+busymail.com+busymail.comhomeart.com+buyersusa.com+bvimailbox.com+byteme.com+c.nut.emailfake.nut.cc+c2.hu+c2i.net+c3.hu+c4.com+cabacabana.com+cableone.net+cad.edu.gr+caere.it+cairomail.com+calidifontain.be+californiamail.com+callnetuk.com+callsign.net+caltanet.it+camidge.com+canada-11.com+canada.com+canadianmail.com+canoemail.com+canwetalk.com+caramail.com+care2.com+careerbuildermail.com+carioca.net+cartestraina.ro+casablancaresort.com+casema.nl+cash4u.com+cashette.com+casino.com+catcha.com+catchamail.com+catholic.org+catlover.com+catsrule.garfield.com+ccnmail.com+cd2.com+celineclub.com+celtic.com+center-mail.de+centermail.at+centermail.de+centermail.info+centoper.it+centralpets.com+centrum.cz+centrum.sk+centurytel.net+certifiedmail.com+cfl.rr.com+cgac.es+cghost.s-a-d.de+chaiyomail.com+chance2mail.com+chandrasekar.net+charmedmail.com+charter.com+charter.net+chat.ru+chattown.com+chauhanweb.com+check.com+check.com12+check1check.com+cheerful.com+chef.net+chek.com+chello.at+chello.nl+chemist.com+chequemail.com+cheyenneweb.com+chez.com+chickmail.com+childrens.md+china.com+china.net.vg+chinalook.com+chinamail.com+chirk.com+chocaholic.com.au+christianmail.net+churchusa.com+cia-agent.com+cia.hu+ciaoweb.it+cicciociccio.com+cincinow.net+citeweb.net+citiz.net+citlink.net+city-of-bath.org+city-of-birmingham.com+city-of-brighton.org+city-of-cambridge.com+city-of-coventry.com+city-of-edinburgh.com+city-of-lichfield.com+city-of-lincoln.com+city-of-liverpool.com+city-of-manchester.com+city-of-nottingham.com+city-of-oxford.com+city-of-swansea.com+city-of-westminster.com+city-of-westminster.net+city-of-york.net+city2city.com+cityofcardiff.net+cityoflondon.org+claramail.com+classicalfan.com+classicmail.co.za+clerk.com+cliffhanger.com+close2you.ne+close2you.net+club4x4.net+clubalfa.com+clubbers.net+clubducati.com+clubhonda.net+clubmember.org+clubnetnoir.com+clubvdo.net+cluemail.com+cmpmail.com+cnnsimail.com+cntv.cn+cocaine.ninja+codec.ro+codec.roemail.ro+coder.hu+coid.biz+cok.3utilities.com+coldmail.com+collectiblesuperstore.com+collector.org+collegebeat.com+collegeclub.com+collegemail.com+colleges.com+columbus.rr.com+columbusrr.com+columnist.com+comast.com+comast.net+comcast.com+comcast.net+comic.com+communityconnect.com+comprendemail.com+compuserve.com+computer-freak.com+computer4u.com+computermail.net+conexcol.com+conk.com+connect4free.net+connectbox.com+conok.com+consultant.com+contractor.net+contrasto.cu.cc+cookiemonster.com+cool.br+coole-files.de+coolgoose.ca+coolgoose.com+coolkiwi.com+coollist.com+coolmail.com+coolmail.net+coolsend.com+coolsite.net+cooooool.com+cooperation.net+cooperationtogo.net+copacabana.com+cornells.com+cornerpub.com+corporatedirtbag.com+correo.terra.com.gt+cortinet.com+cotas.net+counsellor.com+countrylover.com+cousinit.mooo.com+cox.com+cox.net+coxinet.net+cpaonline.net+cr3wmail.sytes.net+cracker.hu+crazedanddazed.com+crazysexycool.com+creo.cloudns.cc+cristianemail.com+critterpost.com+croeso.com+crosshairs.com+crosswinds.net+crwmail.com+cry4helponline.com+cs.com+csinibaba.hu+cuemail.com+cum.sborra.tk+curio-city.com+curtsmail.com+cute-girl.com+cuteandcuddly.com+cutey.com+cww.de+cyber-africa.net+cyber-matrix.com+cyber-wizard.com+cyber4all.com+cyberbabies.com+cybercafemaui.com+cyberdude.com+cyberforeplay.net+cybergal.com+cybergrrl.com+cyberinbox.com+cyberleports.com+cybermail.net+cybernet.it+cyberservices.com+cyberspace-asia.com+cybertrains.org+cyclefanz.com+cynetcity.com+dabsol.net+dadacasa.com+daha.com+dailypioneer.com+dallas.theboys.com+dallasmail.com+dangerous-minds.com+dansegulvet.com+data54.com+davegracey.com+dawnsonmail.com+dawsonmail.com+dazedandconfused.com+dbzmail.com+deadlymob.org+deal-maker.com+dearriba.com+death-star.com+dejanews.com+deliveryman.com+deneg.net+depechemode.com+deseretmail.com+desertmail.com+desilota.com+deskmail.com+deskpilot.com+destin.com+detik.com+deutschland-net.com+devotedcouples.com+dezigner.ru+dfwatson.com+dgd.mail-temp.com+di-ve.com+die-besten-bilder.de+die-genossen.de+die-optimisten.de+die-optimisten.net+diemailbox.de+digibel.be+digital-filestore.de+diplomats.com+directbox.com+dirtracer.com+dirtracers.com+disciples.com+discofan.com+discovery.com+discoverymail.com+disinfo.net+disposable.com+dmailman.com+dmaji.ddns.net+dmtc.edu.pl+dnsmadeeasy.com+doctor.com+dodo.com.au+dog.com+dogit.com+doglover.com+dogmail.co.uk+dogsnob.net+doityourself.com+doneasy.com+donjuan.com+dontgotmail.com+dontmesswithtexas.com+doramail.com+dostmail.com+dotcom.fr+dott.it+download-privat.de+dplanet.ch+dr.com+dragoncon.net+dragracer.com+dropzone.com+drotposta.hu+dubaimail.com+dublin.com+dublin.ie+dumpmail.com+dunlopdriver.com+dunloprider.com+duno.com+dutchmail.com+dvx.dnsabr.com+dwp.net+dygo.com+dynamitemail.com+dyndns.org+e-apollo.lv+e-mail.com.tr+e-mail.dk+e-mail.ru+e-mail.ua+e-mailanywhere.com+e-mails.ru+e-tapaal.com+ea.luk2.com+earthalliance.com+earthcam.net+earthdome.com+earthling.net+earthlink.net+earthonline.net+eastcoast.co.za+eastmail.com+easy.to+easypost.com+eatmydirt.com+ecardmail.com+ecbsolutions.net+echina.com+ecompare.com+edmail.com+ednatx.com+edtnmail.com+educacao.te.pt+educastmail.com+ehmail.com+eintagsmail.de+eircom.net+ekidz.com.au+elitemail.org+elsitio.com+elvis.com+elvisfan.com+email-london.co.uk+email.biz+email.com+email.cz+email.ee+email.it+email.nu+email.org+email.ro+email.ru+email.si+email.su+email.tst+email.ua+email.women.com+email2me.net+email4u.info+emailacc.com+emailaccount.com+emailasso.net+emailchoice.com+emailcorner.net+emailem.com+emailengine.net+emailengine.org+emailforyou.net+emailgroups.net+emailit.com+emailpinoy.com+emailplanet.com+emailplus.org+emails.ru+emailuser.net+emailx.net+ematic.com+embarqmail.com+eml.cc+emumail.com+end-war.com+enel.net+engineer.com+england.com+england.edu+englandmail.com+epage.ru+epatra.com+epicgamers.mooo.com+epix.net+epost.de+eposta.hu+eqqu.com+eqr.luk2.com+eramail.co.za+eresmas.com+eriga.lv+estranet.it+ethos.st+etoast.com+etrademail.com+eudoramail.com+europamel.net+europe.com+europemail.com+euroseek.com+eurosport.com+every1.net+everyday.com.kh+everymail.net+everyone.net+examnotes.net+excite.co.jp+excite.com+excite.it+execs.com+exemail.com.au+expressasia.com+extenda.net+extended.com+eyou.com+ezcybersearch.com+ezmail.egine.com+ezmail.ru+ezrs.com+f-m.fm+f1fans.net+facebook.com+fahr-zur-hoelle.org+falseaddress.com+fan.com+fan.theboys.com+fansonlymail.com+fantasticmail.com+farang.net+farifluset.mailexpire.com+faroweb.com+fast-email.com+fast-mail.org+fastem.com+fastemail.us+fastemailer.com+fastermail.com+fastest.cc+fastimap.com+fastmail.ca+fastmail.cn+fastmail.co.uk+fastmail.com+fastmail.com.au+fastmail.es+fastmail.fm+fastmail.im+fastmail.in+fastmail.jp+fastmail.mx+fastmail.net+fastmail.nl+fastmail.se+fastmail.to+fastmail.tw+fastmail.us+fastmailbox.net+fastmessaging.com+fastservice.com+fatcock.net+fathersrightsne.org+fax.ru+fbi-agent.com+fbi.hu+fea.st+federalcontractors.com+feinripptraeger.de+felicity.com+felicitymail.com+femenino.com+fetchmail.co.uk+fetchmail.com+fettabernett.de+feyenoorder.com+ffanet.com+fiberia.com+filipinolinks.com+financemail.net+financier.com+findmail.com+finebody.com+finfin.com+fire-brigade.com+fireman.net+fishburne.org+fishfuse.com+flashemail.com+flashmail.com+flashmail.net+flipcode.com+fmail.co.uk+fmailbox.com+fmgirl.com+fmguy.com+fnbmail.co.za+fnmail.com+folkfan.com+foodmail.com+football.theboys.com+footballmail.com+for-president.com+force9.co.uk+forfree.at+forpresident.com+fortuncity.com+fortunecity.com+forum.dk+foxmail.com+francemel.fr+free-online.net+free-org.com+free.com.pe+free.fr+freeaccess.nl+freeaccount.com+freeandsingle.com+freebox.com+freedom.usa.com+freedomlover.com+freegates.be+freeghana.com+freeler.nl+freemail.c3.hu+freemail.com.au+freemail.com.pk+freemail.de+freemail.et+freemail.gr+freemail.hu+freemail.it+freemail.lt+freemail.nl+freemail.org.mk+freenet.de+freenet.kg+freeola.com+freeola.net+freeserve.co.uk+freestamp.com+freestart.hu+freesurf.fr+freesurf.nl+freeuk.com+freeuk.net+freeukisp.co.uk+freeweb.org+freewebemail.com+freeyellow.com+freezone.co.uk+fresnomail.com+freudenkinder.de+friends-cafe.com+friendsfan.com+from-africa.com+from-america.com+from-argentina.com+from-asia.com+from-australia.com+from-belgium.com+from-brazil.com+from-canada.com+from-china.net+from-england.com+from-europe.com+from-france.net+from-germany.net+from-holland.com+from-israel.com+from-italy.net+from-japan.net+from-korea.com+from-mexico.com+from-outerspace.com+from-russia.com+from-spain.net+fromalabama.com+fromalaska.com+fromarizona.com+fromarkansas.com+fromcalifornia.com+fromcolorado.com+fromconnecticut.com+fromdelaware.com+fromflorida.net+fromgeorgia.com+fromhawaii.net+fromidaho.com+fromillinois.com+fromindiana.com+fromiowa.com+fromjupiter.com+fromkansas.com+fromkentucky.com+fromlouisiana.com+frommaine.net+frommaryland.com+frommassachusetts.com+frommiami.com+frommichigan.com+fromminnesota.com+frommississippi.com+frommissouri.com+frommontana.com+fromnebraska.com+fromnevada.com+fromnewhampshire.com+fromnewjersey.com+fromnewmexico.com+fromnewyork.net+fromnorthcarolina.com+fromnorthdakota.com+fromohio.com+fromoklahoma.com+fromoregon.net+frompennsylvania.com+fromrhodeisland.com+fromru.com+fromsouthcarolina.com+fromsouthdakota.com+fromtennessee.com+fromtexas.com+fromthestates.com+fromutah.com+fromvermont.com+fromvirginia.com+fromwashington.com+fromwashingtondc.com+fromwestvirginia.com+fromwisconsin.com+fromwyoming.com+front.ru+frontier.com+frontiernet.net+frostbyte.uk.net+fsmail.net+ftml.net+fubuki.shp7.cn+fullmail.com+funkfan.com+funky4.com+fuorissimo.com+furnitureprovider.com+fuse.net+fut.es+fwnb.com+fxsmails.com+g.hmail.us+galamb.net+galaxy5.com+galaxyhit.com+gamebox.net+gamegeek.com+gamespotmail.com+garbage.com+gardener.com+gaybrighton.co.uk+gaza.net+gazeta.pl+gazibooks.com+gci.net+gee-wiz.com+geecities.com+geek.com+geek.hu+geeklife.com+gencmail.com+general-hospital.com+gentlemansclub.de+geocities.com+geography.net+geologist.com+geopia.com+germanymail.com+gh2000.com+ghanamail.com+ghostmail.com+giantsfan.com+giga4u.de+gigileung.org+girl4god.com+givepeaceachance.com+glay.org+glendale.net+globalfree.it+globalpagan.com+globalsite.com.br+gmail.com+gmail.com.br+gmail.gr.com+gmail.ru+gmail.sk+gmail.zalvisual.us+gmx.at+gmx.co.uk+gmx.com+gmx.de+gmx.fr+gmx.li+gmx.net+gnwmail.com+go.com+go.ro+go.ru+go2.com.py+go2net.com+gocollege.com+gocubs.com+gofree.co.uk+goldenmail.ru+goldmail.ru+goldtoolbox.com+golfemail.com+golfilla.info+golfmail.be+gonavy.net+goodnewsmail.com+goodstick.com+googlemail.com+goplay.com+gorontalo.net+gospelfan.com+gothere.uk.com+gotomy.com+gotti.otherinbox.com+govolsfan.com+gportal.hu+grabmail.com+graduate.org+graffiti.net+gramszu.net+graphic-designer.com+grapplers.com+gratisweb.com+greenmail.net+groupmail.com+grungecafe.com+gspam.mooo.com+gtemail.net+gtmc.net+gu.luk2.com+gua.net+guessmail.com+guju.net+gurlmail.com+guy.com+guy2.com+guyanafriends.com+gyorsposta.com+gyorsposta.hu+h-mail.us+hab-verschlafen.de+habmalnefrage.de+hackermail.com+hackermail.net+hailmail.net+hairdresser.net+hamptonroads.com+handbag.com+handleit.com+hang-ten.com+hanmail.net+happemail.com+happycounsel.com+happypuppy.com+hardcorefreak.com+hawaii.rr.com+hawaiiantel.net+headbone.com+heartthrob.com+heerschap.com+heesun.net+hehe.com+hello.hu+hello.net.au+hello.to+helter-skelter.com+hempseed.com+herediano.com+heremail.com+herono1.com+herr-der-mails.de+hetnet.nl+hey.to+hhdevel.com+hhh.sytes.net+highmilton.com+highquality.com+highveldmail.co.za+hilarious.com+hiphopfan.com+hispavista.com+hitmail.com+hitthe.net+hkg.net+hkstarphoto.com+hku.us.to+hockeymail.com+hollywoodkids.com+home-email.com+home.de+home.nl+home.no.net+home.ro+home.se+homeart.com+homelocator.com+homemail.com+homestead.com+homeworkcentral.com+honduras.com+hongkong.com+hookup.net+hoopsmail.com+horrormail.com+host-it.com.sg+hot-shot.com+hot.ee+hotbot.com+hotbrev.com+hotepmail.com+hotfire.net+hotletter.com+hotmail.be+hotmail.ca+hotmail.ch+hotmail.co.il+hotmail.co.nz+hotmail.co.th+hotmail.co.uk+hotmail.com+hotmail.com.br+hotmail.com.hk+hotmail.com.tw+hotmail.de+hotmail.es+hotmail.fr+hotmail.it+hotmail.kg+hotmail.kz+hotmail.nl+hotmail.no+hotmail.roor+hotmail.ru+hotpop3.com+hotvoice.com+housefan.com+housemail.com+hsuchi.net+html.tou.com+hu2.ru+hughes.net+humanoid.net+hunsa.com+hurting.com+hush.ai+hush.com+hushmail.com+hypernautica.com+i-connect.com+i-france.com+i-mail.com.au+i-mailbox.net+i-p.com+i.am+i.amhey.to+i.ua+i12.com+i6.cloudns.cc+i6.cloudns.cx+iamawoman.com+iamwaiting.com+iamwasted.com+iamyours.com+icestorm.com+icfu.mooo.com+ich-bin-verrueckt-nach-dir.de+ich-will-net.de+icloud.com+icmsconsultants.com+icq.com+icqmail.com+icrazy.com+icu.md+id-base.com+ididitmyway.com+idigjesus.com+idirect.com+iespana.es+ifoward.com+ig.com.br+ignazio.it+ignmail.com+ihateclowns.com+iinet.net.au+ijustdontcare.com+ilkposta.com+ilovechocolate.com+ilovejesus.com+ilovethemovies.com+ilovetocollect.net+ilse.nl+imaginemail.com+imail.org+imail.ru+imailbox.com+imap-mail.com+imap.cc+imapmail.org+imel.org+imneverwrong.com+imposter.co.uk+imstressed.com+imtoosexy.com+in-box.net+in2jesus.com+iname.com+inbox.com+inbox.lt+inbox.lv+inbox.net+inbox.ru+incamail.com+includingarabia.com+incredimail.com+index.ua+indexa.fr+india.com+indiatimes.com+indo-mail.com+indocities.com+indomail.com+indyracers.com+inerted.com+info-media.de+info66.com+infohq.com+infomail.es+infomart.or.jp+infospacemail.com+infovia.com.ar+inicia.es+inmail.sk+inmail24.com+inmano.com+innocent.com+inorbit.com+inoutbox.com+insidebaltimore.net+insight.rr.com+instruction.com+instructor.net+insurer.com+interburp.com+interfree.it+interia.pl+interlap.com.ar+intermail.co.il+internet-club.com+internet-e-mail.com+internet-mail.org+internet-police.com+internetbiz.com+internetdrive.com+internetegypt.com+internetemails.net+internetmailing.net+internode.on.net+investormail.com+inwind.it+iobox.com+iobox.fi+iol.it+iowaemail.com+ip3.com+iprimus.com.au+iqemail.com+irangate.net+iraqmail.com+ireland.com+irelandmail.com+irj.hu+isellcars.com+iservejesus.com+islamonline.net+isleuthmail.com+ismart.net+isonfire.com+isp9.net+israelmail.com+ist-allein.info+ist-einmalig.de+ist-ganz-allein.de+ist-willig.de+italymail.com+itloox.com+itmom.com+ivebeenframed.com+ivillage.com+iwan-fals.com+iwmail.com+iwon.com+izadpanah.com+jahoopa.com+jakuza.hu+japan.com+jaydemail.com+jazzandjava.com+jazzfan.com+jazzgame.com+jerusalemmail.com+jetable.de+jetemail.net+jewishmail.com+jippii.fi+jmail.co.za+job4u.com+joinme.com+jokes.com+jordanmail.com+journalist.com+jovem.te.pt+joymail.com+jpopmail.com+jubiimail.dk+jump.com+jumpy.it+juniormail.com+junkmail.com+juno.com+justemail.net+justicemail.com+kaazoo.com+kaffeeschluerfer.com+kaffeeschluerfer.de+kaixo.com+kalpoint.com+kansascity.com+kapoorweb.com+karachian.com+karachioye.com+karbasi.com+katamail.com+kayafmmail.co.za+kbjrmail.com+kcks.com+keftamail.com+keg-party.com+keko.com.ar+kellychen.com+keromail.com+keyemail.com+kgb.hu+khosropour.com+kickassmail.com+killermail.com+kimo.com+kinglibrary.net+kinki-kids.com+kissfans.com+kittymail.com+kitznet.at+kiwibox.com+kiwitown.com+km.ru+kmail.com.au+kmail.mooo.com+kommespaeter.de+konx.com+korea.com+koreamail.com+kozmail.com+kpnmail.nl+krim.ws+krongthip.com+krunis.com+ksanmail.com+ksee24mail.com+kube93mail.com+kukamail.com+kumarweb.com+kuwait-mail.com+la.com+ladymail.cz+lagerlouts.com+lahoreoye.com+lakmail.com+lamer.hu+land.ru+lankamail.com+laposte.net+lass-es-geschehen.de+latemodels.com+latinmail.com+latino.com+lavache.com+law.com+lawyer.com+leehom.net+legalactions.com+legislator.com+lenta.ru+leonlai.net+letsgomets.net+letterbox.com+letterboxes.org+levele.com+levele.hu+lex.bg+lexis-nexis-mail.com+libero.it+liberomail.com+lick101.com+liebt-dich.info+link.cloudns.asia+linkmaster.com+linktrader.com+linuxfreemail.com+linuxmail.org+lionsfan.com.au+liontrucks.com+list.ru+listomail.com+littleapple.com+littleblueroom.com+live.at+live.be+live.ca+live.cl+live.cn+live.co.uk+live.co.za+live.com+live.com.ar+live.com.au+live.com.mx+live.com.my+live.com.pt+live.com.sg+live.de+live.dk+live.fr+live.ie+live.in+live.it+live.jp+live.nl+live.no+live.ru+live.se+liverpoolfans.com+lko.co.kr+llandudno.com+llangollen.com+lmxmail.sk+lobbyist.com+localbar.com+locos.com+london.com+loobie.com+looksmart.co.uk+looksmart.com+looksmart.com.au+lopezclub.com+louiskoo.com+love.cz+loveable.com+lovecat.com+lovefootball.com+lovelygirl.net+lovemail.com+lover-boy.com+lovergirl.com+lovethebroncos.com+lovethecowboys.com+loveyouforever.de+lovingjesus.com+lowandslow.com+luso.pt+luukku.com+lvey.luk2.com+lvie.com.sg+lycos.co.uk+lycos.com+lycos.de+lycos.es+lycos.it+lycos.ne.jp+lycosemail.com+lycosmail.com+m-a-i-l.com+m-hmail.com+m4.org+mac.com+macbox.com+macfreak.com+machinecandy.com+macmail.com+madcreations.com+madonnafan.com+madrid.com+maennerversteherin.com+maennerversteherin.de+maffia.hu+magicmail.co.za+mahmoodweb.com+mail-awu.de+mail-box.cz+mail-center.com+mail-central.com+mail-me.com+mail-page.com+mail.austria.com+mail.az+mail.be+mail.bg+mail.bulgaria.com+mail.byte.it+mail.co.za+mail.com+mail.com.tr+mail.defaultdomain.ml+mail.ee+mail.entrepeneurmag.com+mail.freetown.com+mail.gr+mail.hitthebeach.com+mail.htl22.at+mail.kmsp.com+mail.md+mail.misterpinball.de+mail.nu+mail.org.uk+mail.pf+mail.pharmacy.com+mail.pt+mail.r-o-o-t.com+mail.ru+mail.salu.net+mail.sisna.com+mail.spaceports.com+mail.svenz.eu+mail.theboys.com+mail.ua+mail.usa.com+mail.vasarhely.hu+mail15.com+mail1st.com+mail2007.com+mail2aaron.com+mail2abby.com+mail2abc.com+mail2actor.com+mail2admiral.com+mail2adorable.com+mail2adoration.com+mail2adore.com+mail2adventure.com+mail2aeolus.com+mail2aether.com+mail2affection.com+mail2afghanistan.com+mail2africa.com+mail2agent.com+mail2aha.com+mail2ahoy.com+mail2aim.com+mail2air.com+mail2airbag.com+mail2airforce.com+mail2airport.com+mail2alabama.com+mail2alan.com+mail2alaska.com+mail2albania.com+mail2alcoholic.com+mail2alec.com+mail2alexa.com+mail2algeria.com+mail2alicia.com+mail2alien.com+mail2allan.com+mail2allen.com+mail2allison.com+mail2alpha.com+mail2alyssa.com+mail2amanda.com+mail2amazing.com+mail2amber.com+mail2america.com+mail2american.com+mail2andorra.com+mail2andrea.com+mail2andy.com+mail2anesthesiologist.com+mail2angela.com+mail2angola.com+mail2ann.com+mail2anna.com+mail2anne.com+mail2anthony.com+mail2anything.com+mail2aphrodite.com+mail2apollo.com+mail2april.com+mail2aquarius.com+mail2arabia.com+mail2arabic.com+mail2architect.com+mail2ares.com+mail2argentina.com+mail2aries.com+mail2arizona.com+mail2arkansas.com+mail2armenia.com+mail2army.com+mail2arnold.com+mail2art.com+mail2artemus.com+mail2arthur.com+mail2artist.com+mail2ashley.com+mail2ask.com+mail2astronomer.com+mail2athena.com+mail2athlete.com+mail2atlas.com+mail2atom.com+mail2attitude.com+mail2auction.com+mail2aunt.com+mail2australia.com+mail2austria.com+mail2azerbaijan.com+mail2baby.com+mail2bahamas.com+mail2bahrain.com+mail2ballerina.com+mail2ballplayer.com+mail2band.com+mail2bangladesh.com+mail2bank.com+mail2banker.com+mail2bankrupt.com+mail2baptist.com+mail2bar.com+mail2barbados.com+mail2barbara.com+mail2barter.com+mail2basketball.com+mail2batter.com+mail2beach.com+mail2beast.com+mail2beatles.com+mail2beauty.com+mail2becky.com+mail2beijing.com+mail2belgium.com+mail2belize.com+mail2ben.com+mail2bernard.com+mail2beth.com+mail2betty.com+mail2beverly.com+mail2beyond.com+mail2biker.com+mail2bill.com+mail2billionaire.com+mail2billy.com+mail2bio.com+mail2biologist.com+mail2black.com+mail2blackbelt.com+mail2blake.com+mail2blind.com+mail2blonde.com+mail2blues.com+mail2bob.com+mail2bobby.com+mail2bolivia.com+mail2bombay.com+mail2bonn.com+mail2bookmark.com+mail2boreas.com+mail2bosnia.com+mail2boston.com+mail2botswana.com+mail2bradley.com+mail2brazil.com+mail2breakfast.com+mail2brian.com+mail2bride.com+mail2brittany.com+mail2broker.com+mail2brook.com+mail2bruce.com+mail2brunei.com+mail2brunette.com+mail2brussels.com+mail2bryan.com+mail2bug.com+mail2bulgaria.com+mail2business.com+mail2buy.com+mail2ca.com+mail2california.com+mail2calvin.com+mail2cambodia.com+mail2cameroon.com+mail2canada.com+mail2cancer.com+mail2capeverde.com+mail2capricorn.com+mail2cardinal.com+mail2cardiologist.com+mail2care.com+mail2caroline.com+mail2carolyn.com+mail2casey.com+mail2cat.com+mail2caterer.com+mail2cathy.com+mail2catlover.com+mail2catwalk.com+mail2cell.com+mail2chad.com+mail2champaign.com+mail2charles.com+mail2chef.com+mail2chemist.com+mail2cherry.com+mail2chicago.com+mail2chile.com+mail2china.com+mail2chinese.com+mail2chocolate.com+mail2christian.com+mail2christie.com+mail2christmas.com+mail2christy.com+mail2chuck.com+mail2cindy.com+mail2clark.com+mail2classifieds.com+mail2claude.com+mail2cliff.com+mail2clinic.com+mail2clint.com+mail2close.com+mail2club.com+mail2coach.com+mail2coastguard.com+mail2colin.com+mail2college.com+mail2colombia.com+mail2color.com+mail2colorado.com+mail2columbia.com+mail2comedian.com+mail2composer.com+mail2computer.com+mail2computers.com+mail2concert.com+mail2congo.com+mail2connect.com+mail2connecticut.com+mail2consultant.com+mail2convict.com+mail2cook.com+mail2cool.com+mail2cory.com+mail2costarica.com+mail2country.com+mail2courtney.com+mail2cowboy.com+mail2cowgirl.com+mail2craig.com+mail2crave.com+mail2crazy.com+mail2create.com+mail2croatia.com+mail2cry.com+mail2crystal.com+mail2cuba.com+mail2culture.com+mail2curt.com+mail2customs.com+mail2cute.com+mail2cutey.com+mail2cynthia.com+mail2cyprus.com+mail2czechrepublic.com+mail2dad.com+mail2dale.com+mail2dallas.com+mail2dan.com+mail2dana.com+mail2dance.com+mail2dancer.com+mail2danielle.com+mail2danny.com+mail2darlene.com+mail2darling.com+mail2darren.com+mail2daughter.com+mail2dave.com+mail2dawn.com+mail2dc.com+mail2dealer.com+mail2deanna.com+mail2dearest.com+mail2debbie.com+mail2debby.com+mail2deer.com+mail2delaware.com+mail2delicious.com+mail2demeter.com+mail2democrat.com+mail2denise.com+mail2denmark.com+mail2dennis.com+mail2dentist.com+mail2derek.com+mail2desert.com+mail2devoted.com+mail2devotion.com+mail2diamond.com+mail2diana.com+mail2diane.com+mail2diehard.com+mail2dilemma.com+mail2dillon.com+mail2dinner.com+mail2dinosaur.com+mail2dionysos.com+mail2diplomat.com+mail2director.com+mail2dirk.com+mail2disco.com+mail2dive.com+mail2diver.com+mail2divorced.com+mail2djibouti.com+mail2doctor.com+mail2doglover.com+mail2dominic.com+mail2dominica.com+mail2dominicanrepublic.com+mail2don.com+mail2donald.com+mail2donna.com+mail2doris.com+mail2dorothy.com+mail2doug.com+mail2dough.com+mail2douglas.com+mail2dow.com+mail2downtown.com+mail2dream.com+mail2dreamer.com+mail2dude.com+mail2dustin.com+mail2dyke.com+mail2dylan.com+mail2earl.com+mail2earth.com+mail2eastend.com+mail2eat.com+mail2economist.com+mail2ecuador.com+mail2eddie.com+mail2edgar.com+mail2edwin.com+mail2egypt.com+mail2electron.com+mail2eli.com+mail2elizabeth.com+mail2ellen.com+mail2elliot.com+mail2elsalvador.com+mail2elvis.com+mail2emergency.com+mail2emily.com+mail2engineer.com+mail2english.com+mail2environmentalist.com+mail2eos.com+mail2eric.com+mail2erica.com+mail2erin.com+mail2erinyes.com+mail2eris.com+mail2eritrea.com+mail2ernie.com+mail2eros.com+mail2estonia.com+mail2ethan.com+mail2ethiopia.com+mail2eu.com+mail2europe.com+mail2eurus.com+mail2eva.com+mail2evan.com+mail2evelyn.com+mail2everything.com+mail2exciting.com+mail2expert.com+mail2fairy.com+mail2faith.com+mail2fanatic.com+mail2fancy.com+mail2fantasy.com+mail2farm.com+mail2farmer.com+mail2fashion.com+mail2fat.com+mail2feeling.com+mail2female.com+mail2fever.com+mail2fighter.com+mail2fiji.com+mail2filmfestival.com+mail2films.com+mail2finance.com+mail2finland.com+mail2fireman.com+mail2firm.com+mail2fisherman.com+mail2flexible.com+mail2florence.com+mail2florida.com+mail2floyd.com+mail2fly.com+mail2fond.com+mail2fondness.com+mail2football.com+mail2footballfan.com+mail2found.com+mail2france.com+mail2frank.com+mail2frankfurt.com+mail2franklin.com+mail2fred.com+mail2freddie.com+mail2free.com+mail2freedom.com+mail2french.com+mail2freudian.com+mail2friendship.com+mail2from.com+mail2fun.com+mail2gabon.com+mail2gabriel.com+mail2gail.com+mail2galaxy.com+mail2gambia.com+mail2games.com+mail2gary.com+mail2gavin.com+mail2gemini.com+mail2gene.com+mail2genes.com+mail2geneva.com+mail2george.com+mail2georgia.com+mail2gerald.com+mail2german.com+mail2germany.com+mail2ghana.com+mail2gilbert.com+mail2gina.com+mail2girl.com+mail2glen.com+mail2gloria.com+mail2goddess.com+mail2gold.com+mail2golfclub.com+mail2golfer.com+mail2gordon.com+mail2government.com+mail2grab.com+mail2grace.com+mail2graham.com+mail2grandma.com+mail2grandpa.com+mail2grant.com+mail2greece.com+mail2green.com+mail2greg.com+mail2grenada.com+mail2gsm.com+mail2guard.com+mail2guatemala.com+mail2guy.com+mail2hades.com+mail2haiti.com+mail2hal.com+mail2handhelds.com+mail2hank.com+mail2hannah.com+mail2harold.com+mail2harry.com+mail2hawaii.com+mail2headhunter.com+mail2heal.com+mail2heather.com+mail2heaven.com+mail2hebe.com+mail2hecate.com+mail2heidi.com+mail2helen.com+mail2hell.com+mail2help.com+mail2helpdesk.com+mail2henry.com+mail2hephaestus.com+mail2hera.com+mail2hercules.com+mail2herman.com+mail2hermes.com+mail2hespera.com+mail2hestia.com+mail2highschool.com+mail2hindu.com+mail2hip.com+mail2hiphop.com+mail2holland.com+mail2holly.com+mail2hollywood.com+mail2homer.com+mail2honduras.com+mail2honey.com+mail2hongkong.com+mail2hope.com+mail2horse.com+mail2hot.com+mail2hotel.com+mail2houston.com+mail2howard.com+mail2hugh.com+mail2human.com+mail2hungary.com+mail2hungry.com+mail2hygeia.com+mail2hyperspace.com+mail2hypnos.com+mail2ian.com+mail2ice-cream.com+mail2iceland.com+mail2idaho.com+mail2idontknow.com+mail2illinois.com+mail2imam.com+mail2in.com+mail2india.com+mail2indian.com+mail2indiana.com+mail2indonesia.com+mail2infinity.com+mail2intense.com+mail2iowa.com+mail2iran.com+mail2iraq.com+mail2ireland.com+mail2irene.com+mail2iris.com+mail2irresistible.com+mail2irving.com+mail2irwin.com+mail2isaac.com+mail2israel.com+mail2italian.com+mail2italy.com+mail2jackie.com+mail2jacob.com+mail2jail.com+mail2jaime.com+mail2jake.com+mail2jamaica.com+mail2james.com+mail2jamie.com+mail2jan.com+mail2jane.com+mail2janet.com+mail2janice.com+mail2japan.com+mail2japanese.com+mail2jasmine.com+mail2jason.com+mail2java.com+mail2jay.com+mail2jazz.com+mail2jed.com+mail2jeffrey.com+mail2jennifer.com+mail2jenny.com+mail2jeremy.com+mail2jerry.com+mail2jessica.com+mail2jessie.com+mail2jesus.com+mail2jew.com+mail2jeweler.com+mail2jim.com+mail2jimmy.com+mail2joan.com+mail2joann.com+mail2joanna.com+mail2jody.com+mail2joe.com+mail2joel.com+mail2joey.com+mail2john.com+mail2join.com+mail2jon.com+mail2jonathan.com+mail2jones.com+mail2jordan.com+mail2joseph.com+mail2josh.com+mail2joy.com+mail2juan.com+mail2judge.com+mail2judy.com+mail2juggler.com+mail2julian.com+mail2julie.com+mail2jumbo.com+mail2junk.com+mail2justin.com+mail2justme.com+mail2k.ru+mail2kansas.com+mail2karate.com+mail2karen.com+mail2karl.com+mail2karma.com+mail2kathleen.com+mail2kathy.com+mail2katie.com+mail2kay.com+mail2kazakhstan.com+mail2keen.com+mail2keith.com+mail2kelly.com+mail2kelsey.com+mail2ken.com+mail2kendall.com+mail2kennedy.com+mail2kenneth.com+mail2kenny.com+mail2kentucky.com+mail2kenya.com+mail2kerry.com+mail2kevin.com+mail2kim.com+mail2kimberly.com+mail2king.com+mail2kirk.com+mail2kiss.com+mail2kosher.com+mail2kristin.com+mail2kurt.com+mail2kuwait.com+mail2kyle.com+mail2kyrgyzstan.com+mail2la.com+mail2lacrosse.com+mail2lance.com+mail2lao.com+mail2larry.com+mail2latvia.com+mail2laugh.com+mail2laura.com+mail2lauren.com+mail2laurie.com+mail2lawrence.com+mail2lawyer.com+mail2lebanon.com+mail2lee.com+mail2leo.com+mail2leon.com+mail2leonard.com+mail2leone.com+mail2leslie.com+mail2letter.com+mail2liberia.com+mail2libertarian.com+mail2libra.com+mail2libya.com+mail2liechtenstein.com+mail2life.com+mail2linda.com+mail2linux.com+mail2lionel.com+mail2lipstick.com+mail2liquid.com+mail2lisa.com+mail2lithuania.com+mail2litigator.com+mail2liz.com+mail2lloyd.com+mail2lois.com+mail2lola.com+mail2london.com+mail2looking.com+mail2lori.com+mail2lost.com+mail2lou.com+mail2louis.com+mail2louisiana.com+mail2lovable.com+mail2love.com+mail2lucky.com+mail2lucy.com+mail2lunch.com+mail2lust.com+mail2luxembourg.com+mail2luxury.com+mail2lyle.com+mail2lynn.com+mail2madagascar.com+mail2madison.com+mail2madrid.com+mail2maggie.com+mail2mail4.com+mail2maine.com+mail2malawi.com+mail2malaysia.com+mail2maldives.com+mail2mali.com+mail2malta.com+mail2mambo.com+mail2man.com+mail2mandy.com+mail2manhunter.com+mail2mankind.com+mail2many.com+mail2marc.com+mail2marcia.com+mail2margaret.com+mail2margie.com+mail2marhaba.com+mail2maria.com+mail2marilyn.com+mail2marines.com+mail2mark.com+mail2marriage.com+mail2married.com+mail2marries.com+mail2mars.com+mail2marsha.com+mail2marshallislands.com+mail2martha.com+mail2martin.com+mail2marty.com+mail2marvin.com+mail2mary.com+mail2maryland.com+mail2mason.com+mail2massachusetts.com+mail2matt.com+mail2matthew.com+mail2maurice.com+mail2mauritania.com+mail2mauritius.com+mail2max.com+mail2maxwell.com+mail2maybe.com+mail2mba.com+mail2me4u.com+mail2mechanic.com+mail2medieval.com+mail2megan.com+mail2mel.com+mail2melanie.com+mail2melissa.com+mail2melody.com+mail2member.com+mail2memphis.com+mail2methodist.com+mail2mexican.com+mail2mexico.com+mail2mgz.com+mail2miami.com+mail2michael.com+mail2michelle.com+mail2michigan.com+mail2mike.com+mail2milan.com+mail2milano.com+mail2mildred.com+mail2milkyway.com+mail2millennium.com+mail2millionaire.com+mail2milton.com+mail2mime.com+mail2mindreader.com+mail2mini.com+mail2minister.com+mail2minneapolis.com+mail2minnesota.com+mail2miracle.com+mail2missionary.com+mail2mississippi.com+mail2missouri.com+mail2mitch.com+mail2model.com+mail2moldova.commail2molly.com+mail2mom.com+mail2monaco.com+mail2money.com+mail2mongolia.com+mail2monica.com+mail2montana.com+mail2monty.com+mail2moon.com+mail2morocco.com+mail2morpheus.com+mail2mors.com+mail2moscow.com+mail2moslem.com+mail2mouseketeer.com+mail2movies.com+mail2mozambique.com+mail2mp3.com+mail2mrright.com+mail2msright.com+mail2museum.com+mail2music.com+mail2musician.com+mail2muslim.com+mail2my.com+mail2myboat.com+mail2mycar.com+mail2mycell.com+mail2mygsm.com+mail2mylaptop.com+mail2mymac.com+mail2mypager.com+mail2mypalm.com+mail2mypc.com+mail2myphone.com+mail2myplane.com+mail2namibia.com+mail2nancy.com+mail2nasdaq.com+mail2nathan.com+mail2nauru.com+mail2navy.com+mail2neal.com+mail2nebraska.com+mail2ned.com+mail2neil.com+mail2nelson.com+mail2nemesis.com+mail2nepal.com+mail2netherlands.com+mail2network.com+mail2nevada.com+mail2newhampshire.com+mail2newjersey.com+mail2newmexico.com+mail2newyork.com+mail2newzealand.com+mail2nicaragua.com+mail2nick.com+mail2nicole.com+mail2niger.com+mail2nigeria.com+mail2nike.com+mail2no.com+mail2noah.com+mail2noel.com+mail2noelle.com+mail2normal.com+mail2norman.com+mail2northamerica.com+mail2northcarolina.com+mail2northdakota.com+mail2northpole.com+mail2norway.com+mail2notus.com+mail2noway.com+mail2nowhere.com+mail2nuclear.com+mail2nun.com+mail2ny.com+mail2oasis.com+mail2oceanographer.com+mail2ohio.com+mail2ok.com+mail2oklahoma.com+mail2oliver.com+mail2oman.com+mail2one.com+mail2onfire.com+mail2online.com+mail2oops.com+mail2open.com+mail2ophthalmologist.com+mail2optometrist.com+mail2oregon.com+mail2oscars.com+mail2oslo.com+mail2painter.com+mail2pakistan.com+mail2palau.com+mail2pan.com+mail2panama.com+mail2paraguay.com+mail2paralegal.com+mail2paris.com+mail2park.com+mail2parker.com+mail2party.com+mail2passion.com+mail2pat.com+mail2patricia.com+mail2patrick.com+mail2patty.com+mail2paul.com+mail2paula.com+mail2pay.com+mail2peace.com+mail2pediatrician.com+mail2peggy.com+mail2pennsylvania.com+mail2perry.com+mail2persephone.com+mail2persian.com+mail2peru.com+mail2pete.com+mail2peter.com+mail2pharmacist.com+mail2phil.com+mail2philippines.com+mail2phoenix.com+mail2phonecall.com+mail2phyllis.com+mail2pickup.com+mail2pilot.com+mail2pisces.com+mail2planet.com+mail2platinum.com+mail2plato.com+mail2pluto.com+mail2pm.com+mail2podiatrist.com+mail2poet.com+mail2poland.com+mail2policeman.com+mail2policewoman.com+mail2politician.com+mail2pop.com+mail2pope.com+mail2popular.com+mail2portugal.com+mail2poseidon.com+mail2potatohead.com+mail2power.com+mail2presbyterian.com+mail2president.com+mail2priest.com+mail2prince.com+mail2princess.com+mail2producer.com+mail2professor.com+mail2protect.com+mail2psychiatrist.com+mail2psycho.com+mail2psychologist.com+mail2qatar.com+mail2queen.com+mail2rabbi.com+mail2race.com+mail2racer.com+mail2rachel.com+mail2rage.com+mail2rainmaker.com+mail2ralph.com+mail2randy.com+mail2rap.com+mail2rare.com+mail2rave.com+mail2ray.com+mail2raymond.com+mail2realtor.com+mail2rebecca.com+mail2recruiter.com+mail2recycle.com+mail2redhead.com+mail2reed.com+mail2reggie.com+mail2register.com+mail2rent.com+mail2republican.com+mail2resort.com+mail2rex.com+mail2rhodeisland.com+mail2rich.com+mail2richard.com+mail2ricky.com+mail2ride.com+mail2riley.com+mail2rita.com+mail2rob.com+mail2robert.com+mail2roberta.com+mail2robin.com+mail2rock.com+mail2rocker.com+mail2rod.com+mail2rodney.com+mail2romania.com+mail2rome.com+mail2ron.com+mail2ronald.com+mail2ronnie.com+mail2rose.com+mail2rosie.com+mail2roy.com+mail2rudy.com+mail2rugby.com+mail2runner.com+mail2russell.com+mail2russia.com+mail2russian.com+mail2rusty.com+mail2ruth.com+mail2rwanda.com+mail2ryan.com+mail2sa.com+mail2sabrina.com+mail2safe.com+mail2sagittarius.com+mail2sail.com+mail2sailor.com+mail2sal.com+mail2salaam.com+mail2sam.com+mail2samantha.com+mail2samoa.com+mail2samurai.com+mail2sandra.com+mail2sandy.com+mail2sanfrancisco.com+mail2sanmarino.com+mail2santa.com+mail2sara.com+mail2sarah.com+mail2sat.com+mail2saturn.com+mail2saudi.com+mail2saudiarabia.com+mail2save.com+mail2savings.com+mail2school.com+mail2scientist.com+mail2scorpio.com+mail2scott.com+mail2sean.com+mail2search.com+mail2seattle.com+mail2secretagent.com+mail2senate.com+mail2senegal.com+mail2sensual.com+mail2seth.com+mail2sevenseas.com+mail2sexy.com+mail2seychelles.com+mail2shane.com+mail2sharon.com+mail2shawn.com+mail2ship.com+mail2shirley.com+mail2shoot.com+mail2shuttle.com+mail2sierraleone.com+mail2simon.com+mail2singapore.com+mail2single.com+mail2site.com+mail2skater.com+mail2skier.com+mail2sky.com+mail2sleek.com+mail2slim.com+mail2slovakia.com+mail2slovenia.com+mail2smile.com+mail2smith.com+mail2smooth.com+mail2soccer.com+mail2soccerfan.com+mail2socialist.com+mail2soldier.com+mail2somalia.com+mail2son.com+mail2song.com+mail2sos.com+mail2sound.com+mail2southafrica.com+mail2southamerica.com+mail2southcarolina.com+mail2southdakota.com+mail2southkorea.com+mail2southpole.com+mail2spain.com+mail2spanish.com+mail2spare.com+mail2spectrum.com+mail2splash.com+mail2sponsor.com+mail2sports.com+mail2srilanka.com+mail2stacy.com+mail2stan.com+mail2stanley.com+mail2star.com+mail2state.com+mail2stephanie.com+mail2steve.com+mail2steven.com+mail2stewart.com+mail2stlouis.com+mail2stock.com+mail2stockholm.com+mail2stockmarket.com+mail2storage.com+mail2store.com+mail2strong.com+mail2student.com+mail2studio.com+mail2studio54.com+mail2stuntman.com+mail2subscribe.com+mail2sudan.com+mail2superstar.com+mail2surfer.com+mail2suriname.com+mail2susan.com+mail2suzie.com+mail2swaziland.com+mail2sweden.com+mail2sweetheart.com+mail2swim.com+mail2swimmer.com+mail2swiss.com+mail2switzerland.com+mail2sydney.com+mail2sylvia.com+mail2syria.com+mail2taboo.com+mail2taiwan.com+mail2tajikistan.com+mail2tammy.com+mail2tango.com+mail2tanya.com+mail2tanzania.com+mail2tara.com+mail2taurus.com+mail2taxi.com+mail2taxidermist.com+mail2taylor.com+mail2taz.com+mail2teacher.com+mail2technician.com+mail2ted.com+mail2telephone.com+mail2teletubbie.com+mail2tenderness.com+mail2tennessee.com+mail2tennis.com+mail2tennisfan.com+mail2terri.com+mail2terry.com+mail2test.com+mail2texas.com+mail2thailand.com+mail2therapy.com+mail2think.com+mail2tickets.com+mail2tiffany.com+mail2tim.com+mail2time.com+mail2timothy.com+mail2tina.com+mail2titanic.com+mail2toby.com+mail2todd.com+mail2togo.com+mail2tom.com+mail2tommy.com+mail2tonga.com+mail2tony.com+mail2touch.com+mail2tourist.com+mail2tracey.com+mail2tracy.com+mail2tramp.com+mail2travel.com+mail2traveler.com+mail2travis.com+mail2trekkie.com+mail2trex.com+mail2triallawyer.com+mail2trick.com+mail2trillionaire.com+mail2troy.com+mail2truck.com+mail2trump.com+mail2try.com+mail2tunisia.com+mail2turbo.com+mail2turkey.com+mail2turkmenistan.com+mail2tv.com+mail2tycoon.com+mail2tyler.com+mail2u4me.com+mail2uae.com+mail2uganda.com+mail2uk.com+mail2ukraine.com+mail2uncle.com+mail2unsubscribe.com+mail2uptown.com+mail2uruguay.com+mail2usa.com+mail2utah.com+mail2uzbekistan.com+mail2v.com+mail2vacation.com+mail2valentines.com+mail2valerie.com+mail2valley.com+mail2vamoose.com+mail2vanessa.com+mail2vanuatu.com+mail2venezuela.com+mail2venous.com+mail2venus.com+mail2vermont.com+mail2vickie.com+mail2victor.com+mail2victoria.com+mail2vienna.com+mail2vietnam.com+mail2vince.com+mail2virginia.com+mail2virgo.com+mail2visionary.com+mail2vodka.com+mail2volleyball.com+mail2waiter.com+mail2wallstreet.com+mail2wally.com+mail2walter.com+mail2warren.com+mail2washington.com+mail2wave.com+mail2way.com+mail2waycool.com+mail2wayne.com+mail2webmaster.com+mail2webtop.com+mail2webtv.com+mail2weird.com+mail2wendell.com+mail2wendy.com+mail2westend.com+mail2westvirginia.com+mail2whether.com+mail2whip.com+mail2white.com+mail2whitehouse.com+mail2whitney.com+mail2why.com+mail2wilbur.com+mail2wild.com+mail2willard.com+mail2willie.com+mail2wine.com+mail2winner.com+mail2wired.com+mail2wisconsin.com+mail2woman.com+mail2wonder.com+mail2world.com+mail2worship.com+mail2wow.com+mail2www.com+mail2wyoming.com+mail2xfiles.com+mail2xox.com+mail2yachtclub.com+mail2yahalla.com+mail2yemen.com+mail2yes.com+mail2yugoslavia.com+mail2zack.com+mail2zambia.com+mail2zenith.com+mail2zephir.com+mail2zeus.com+mail2zipper.com+mail2zoo.com+mail2zoologist.com+mail2zurich.com+mail3000.com+mail4u.info+mailandftp.com+mailandnews.com+mailas.com+mailasia.com+mailbolt.com+mailbomb.net+mailboom.com+mailbox.as+mailbox.co.za+mailbox.gr+mailbox.hu+mailbox.r2.dns-cloud.net+mailbr.com.br+mailc.net+mailcan.com+mailcc.com+mailchoose.co+mailcity.com+mailclub.fr+mailclub.net+mailexcite.com+mailforce.net+mailftp.com+mailgate.gr+mailgenie.net+mailhaven.com+mailhood.com+mailinatorzz.mooo.com+mailinblack.com+mailingaddress.org+mailingweb.com+mailisent.com+mailite.com+mailme.dk+mailmight.com+mailmij.nl+mailnew.com+mailops.com+mailoye.com+mailpanda.com+mailpokemon.com+mailpost.zzn.com+mailpride.com+mailpuppy.com+mailroom.com+mailru.com+mailsent.net+mailservice.ms+mailshuttle.com+mailstart.com+mailstartplus.com+mailsurf.com+mailtag.com+mailto.de+mailueberfall.de+mailup.net+mailwire.com+mailworks.org+mailz.info.tm+maktoob.com+malayalamtelevision.net+mall.tko.co.kr+maltesemail.com+manager.de+mancity.net+mantrafreenet.com+mantramail.com+mantraonline.com+marchmail.com+mariah-carey.ml.org+mariahc.com+marijuana.com+marijuana.nl+marketing.lu+married-not.com+marsattack.com+martindalemail.com+mash4077.com+masrawy.com+matmail.com+mauimail.com+mauritius.com+maxleft.com+maxmail.co.uk+mbdnsmail.mooo.com+mbox.com.au+me-mail.hu+me.com+medical.net.au+medmail.com+medscape.com+meetingmall.com+megago.com+megamail.pt+megapoint.com+mehrani.com+mehtaweb.com+meine-dateien.info+meine-diashow.de+meine-fotos.info+meine-urlaubsfotos.de+mekhong.com+melodymail.com+meloo.com+members.student.com+memeware.net+mendoan.uu.gl+merda.flu.cc+merda.igg.biz+merda.nut.cc+merda.usa.cc+message.hu+messages.to+metacrawler.com+metalfan.com+metaping.com+metta.lk+mexicomail.com+mhdsl.ddns.net+miatadriver.com+miesto.sk+mighty.co.za+miho-nakayama.com+mikrotamanet.com+millionaireintraining.com+millionairemail.com+milmail.com+milmail.com15+mindless.com+mindspring.com+mini-mail.com+minister.com+misery.net+mittalweb.com+mixmail.com+mjfrogmail.com+ml1.net+mm.st+mns.ru+mobi.web.id+mobilbatam.com+mochamail.com+mohammed.com+moldova.cc+moldova.com+moldovacc.com+momslife.com+monemail.com+money.net+montevideo.com.uy+moonman.com+moose-mail.com+mor19.uu.gl+mortaza.com+mosaicfx.com+moscowmail.com+most-wanted.com+mostlysunny.com+motormania.com+movemail.com+movieluver.com+mp4.it+mr-potatohead.com+mrpost.com+mscold.com+msgbox.com+msn.cn+msn.com+msn.com.au+msn.nl+mttestdriver.com+mundomail.net+munich.com+music.com+music.com19+musician.org+musicscene.org+muskelshirt.de+muslim.com+muslimemail.com+muslimsonline.com+mutantweb.com+mxp.dns-cloud.net+mxp.dnsabr.com+my.com+my.safe-mail.gq+mybox.it+mycabin.com+mycampus.com+mycity.com+mycool.com+mydomain.com+mydotcomaddress.com+myfamily.com+myfastmail.com+mygo.com+myiris.com+mymacmail.com+mynamedot.com+mynet.com+mynetaddress.com+myownemail.com+myownfriends.com+mypad.com+mypersonalemail.com+myplace.com+myrambler.ru+myrealbox.com+myremarq.com+myself.com+mystupidjob.com+mythirdage.com+myway.com+myworldmail.com+n2.com+n2baseball.com+n2business.com+n2mail.com+n2soccer.com+n2software.com+nabc.biz+nafe.com+nagpal.net+nakedgreens.com+name.com+nameplanet.com+nan.us.to+nandomail.com+naplesnews.net+naseej.com+nativestar.net+nativeweb.net+naui.net+naver.com+navigator.lv+navy.org+naz.com+nchoicemail.com+neeva.net+nemra1.com+nenter.com+neo.rr.com+nervhq.org+net-c.be+net-c.ca+net-c.cat+net-c.com+net-c.es+net-c.fr+net-c.it+net-c.lu+net-c.nl+net-c.pl+net-pager.net+net-shopping.com+net4b.pt+net4you.at+netbounce.com+netbroadcaster.com+netby.dk+netc.eu+netc.fr+netc.it+netc.lu+netc.pl+netcenter-vn.net+netcmail.com+netcourrier.com+netexecutive.com+netexpressway.com+netgenie.com+netian.com+netizen.com.ar+netlane.com+netlimit.com+netmanor.com+netmongol.com+netnet.com.sg+netnoir.net+netpiper.com+netposta.net+netradiomail.com+netralink.com+netscape.net+netscapeonline.co.uk+netspace.net.au+netspeedway.com+netsquare.com+netster.com+nettaxi.com+nettemail.com+netterchef.de+netzero.com+netzero.net+neue-dateien.de+neuro.md+newmail.com+newmail.net+newmail.ru+newsboysmail.com+newyork.com+nextmail.ru+nexxmail.com+nfmail.com+nhmail.com+nicebush.com+nicegal.com+nicholastse.net+nicolastse.com+nightmail.com+nikopage.com+nimail.com+ninfan.com+nirvanafan.com+noavar.com+nonpartisan.com+norika-fujiwara.com+norikomail.com+northgates.net+noways.ddns.net+nqav95zj0p.kro.kr+nqrk.luk2.com+ntscan.com+null.net+nullbox.info+nuo.co.kr+nur-fuer-spam.de+nus.edu.sg+nxt.ru+ny.com+nybella.com+nyc.com+nycmail.com+nzoomail.com+o-tay.com+o.spamtrap.ro+o2.co.uk+o2.pl+oaklandas-fan.com+oath.com+oceanfree.net+oddpost.com+odmail.com+office-dateien.de+office-email.com+officedomain.com+offroadwarrior.com+oicexchange.com+oikrach.com+okbank.com+okhuman.com+okmad.com+okmagic.com+okname.net+okuk.com+oldies1041.com+oldies104mail.com+ole.com+olemail.com+olympist.net+omaninfo.com+omeaaa124.ddns.net+omen.ru+onebox.com+onenet.com.ar+onet.com.pl+onet.eu+onet.pl+oninet.pt+online.de+online.ie+online.nl+onlinewiz.com+onmilwaukee.com+onobox.com+onvillage.com+op.pl+openmailbox.org+operafan.com+operamail.com+opoczta.pl+optician.com+optonline.net+optusnet.com.au+orange.fr+orbitel.bg+orgmail.net+orthodontist.net+osite.com.br+oso.com+otakumail.com+our-computer.com+our-office.com+our.st+ourbrisbane.com+ournet.md+outel.com+outgun.com+outlook.at+outlook.be+outlook.cl+outlook.co.id+outlook.co.il+outlook.co.nz+outlook.co.th+outlook.com+outlook.com.au+outlook.com.br+outlook.com.gr+outlook.com.pe+outlook.com.tr+outlook.com.vn+outlook.cz+outlook.de+outlook.dk+outlook.es+outlook.fr+outlook.hu+outlook.ie+outlook.in+outlook.it+outlook.jp+outlook.kr+outlook.lv+outlook.my+outlook.nl+outlook.ph+outlook.pt+outlook.sa+outlook.sg+outlook.sk+over-the-rainbow.com+ownmail.net+ozbytes.net.au+ozemail.com.au+pacbell.net+pacific-ocean.com+pacific-re.com+pacificwest.com+packersfan.com+pagina.de+pagons.org+pakistanmail.com+pakistanoye.com+palestinemail.com+parkjiyoon.com+parrot.com+parsmail.com+partlycloudy.com+partybombe.de+partyheld.de+partynight.at+parvazi.com+password.nafko.cf+passwordmail.com+pathfindermail.com+pconnections.net+pcpostal.com+pcsrock.com+pcusers.otherinbox.com+peachworld.com+pediatrician.com+pemail.net+penpen.com+peoplepc.com+peopleweb.com+perfectmail.com+perso.be+personal.ro+personales.com+petlover.com+petml.com+pettypool.com+pezeshkpour.com+phayze.com+phone.net+photographer.net+phpbb.uu.gl+phreaker.net+phus8kajuspa.cu.cc+physicist.net+pianomail.com+pickupman.com+picusnet.com+pigpig.net+pinoymail.com+piracha.net+pisem.net+pkwt.luk2.com+planet-mail.com+planet.nl+planetaccess.com+planetall.com+planetarymotion.net+planetdirect.com+planetearthinter.net+planetmail.com+planetmail.net+planetout.com+plasa.com+playersodds.com+playful.com+plus.com+plusmail.com.br+pmail.net+pobox.hu+pobox.sk+pochta.ru+poczta.fm+poczta.onet.pl+poetic.com+pokemonpost.com+pokepost.com+polandmail.com+polbox.com+policeoffice.com+politician.com+polizisten-duzer.de+pool-sharks.com+poond.com+popaccount.com+popmail.com+popsmail.com+popstar.com+populus.net+portableoffice.com+portugalmail.com+portugalmail.pt+portugalnet.com+positive-thinking.com+post.com+post.cz+post.sk+posta.net+posta.ro+posta.rosativa.ro.org+postaccesslite.com+postafree.com+postaweb.com+postfach.cc+postinbox.com+postino.ch+postmark.net+postmaster.co.uk+postpro.net+pousa.com+powerfan.com+praize.com+pray247.com+premiumservice.com+presidency.com+press.co.jp+pride.nafko.cf+priest.com+primposta.com+primposta.hu+pro.cloudns.asia+pro.hu+probemail.com+prodigy.net+progetplus.it+programist.ru+programmer.net+programozo.hu+proinbox.com+project2k.com+prolaunch.com+promessage.com+prontomail.com+prontomail.compopulus.net+protestant.com+protonmail.com+prydirect.info+psv-supporter.com+ptd.net+public-files.de+public.usa.com+publicist.com+pulp-fiction.com+purpleturtle.com+pw.r4.dns-cloud.net+q.com+qatarmail.com+qip.ru+qmail.com+qprfans.com+qq.cn+qq.com+qrio.com+qt1.ddns.net+quackquack.com+quakemail.com+qualityservice.com+quantentunnel.de+qudsmail.com+quepasa.com+quickhosts.com+quicknet.nl+quickwebmail.com+quiklinks.com+quikmail.com+qv7.info+qwest.net+qwestoffice.net+r-o-o-t.com+r4.dns-cloud.net+raakim.com+racedriver.com+racefanz.com+racingfan.com.au+racingmail.com+radicalz.com+radiku.ye.vc+radiologist.net+ragingbull.com+ralib.com+rambler.ru+ramjane.mooo.com+ranmamail.com+raspberrypi123.ddns.net+rastogi.net+ratt-n-roll.com+rattle-snake.com+raubtierbaendiger.de+ravearena.com+ravemail.com+razormail.com+rccgmail.org+realemail.net+reallyfast.biz+reallyfast.info+realradiomail.com+realtyagent.com+reborn.com+receiveee.chickenkiller.com+recycler.com+recyclermail.com+rediff.com+rediffmail.com+rediffmailpro.com+rednecks.com+redseven.de+redsfans.com+reggaefan.com+reggafan.com+regiononline.com+registerednurses.com+reincarnate.com+religious.com+renren.com+repairman.com+reply.hu+representative.com+rescueteam.com+resumemail.com+rezai.com+richmondhill.com+rickymail.com+rin.ru+riopreto.com.br+rk9.chickenkiller.com+rn.com+ro.ru+roadrunner.com+roanokemail.com+rock.com+rocketmail.com+rocketship.com+rockfan.com+rodrun.com+rogers.com+rome.com+romymichele.com+roosh.com+rootprompt.org+rotfl.com+roughnet.com+rr.com+rrohio.com+rsub.com+rubyridge.com+runbox.com+rushpost.com+ruttolibero.com+rvshop.com+rxdoc.biz+ryo.shp7.cn+s-mail.com+s6.weprof.it+sabreshockey.com+sacbeemail.com+saeuferleber.de+safarimail.com+safrica.com+sagra.lu+sagra.lumarketing.lu+sags-per-mail.de+sailormoon.com+saintly.com+saintmail.net+sale-sale-sale.com+salehi.net+salesperson.net+samerica.com+samilan.net+sammimail.com+sanfranmail.com+sanook.com+sapo.pt+sativa.ro.org+saudia.com+sayhi.net+sbcglobal.net+scandalmail.com+scarlet.nl+scbox.one.pl+schizo.com+schmusemail.de+schoolemail.com+schoolmail.com+schoolsucks.com+schreib-doch-mal-wieder.de+schweiz.org+sci.fi+science.com.au+scientist.com+scifianime.com+scotland.com+scotlandmail.com+scottishmail.co.uk+scubadiving.com+seanet.com+search.ua+searchwales.com+sebil.com+seckinmail.com+secret-police.com+secretary.net+secretservices.net+seductive.com+seekstoyboy.com+seguros.com.br+send.hu+sendme.cz+sent.as+sent.at+sent.com+sentrismail.com+serga.com.ar+servemymail.com+sesmail.com+sex.dns-cloud.net+sexmagnet.com+seznam.cz+sgbteam.hostingarif.me+shahweb.net+shaniastuff.com+shared-files.de+sharewaredevelopers.com+sharmaweb.com+she.com+shinedyoureyes.com+shitaway.cu.cc+shitaway.usa.cc+shockinmytown.cu.cc+shootmail.com+shortmail.com+shotgun.hu+shuf.com+sialkotcity.com+sialkotian.com+sialkotoye.com+sify.com+silkroad.net+sina.cn+sina.com+sinamail.com+singapore.com+singles4jesus.com+singmail.com+singnet.com.sg+singpost.com+skafan.com+skim.com+skizo.hu+sky.com+slamdunkfan.com+slingshot.com+slo.net+slotter.com+sm.westchestergov.com+smapxsmap.net+smileyface.comsmithemail.net+smoothmail.com+sms.at+snail-mail.net+snail-mail.ney+snakebite.com+sndt.net+snet.net+sniper.hu+snoopymail.com+snowboarding.com+snowdonia.net+socamail.com+socceramerica.net+soccermail.com+soccermomz.com+socialworker.net+sociologist.com+sofortmail.de+softhome.net+sogou.com+sohu.com+sol.dk+solcon.nl+soldier.hu+solution4u.com+songwriter.net+sonnenkinder.org+soon.com+soulfoodcookbook.com+sp.nl+space-bank.com+space-man.com+space-ship.com+space-travel.com+space.com+spaceart.com+spacebank.com+spacemart.com+spacetowns.com+spacewar.com+spainmail.com+spam.fassagforpresident.ga+spameater.com+spartapiet.com+spazmail.com+speedemail.net+speedpost.net+speedrules.com+speedrulz.com+speedymail.org+sperke.net+spils.com+spinfinder.com+spl.at+spoko.pl+sportemail.com+sportsmail.com+sporttruckdriver.com+spray.no+spray.se+spymac.com+srilankan.net+ssl-mail.com+st-davids.net+stade.fr+stalag13.com+stargateradio.com+starmail.com+starmail.org+starmedia.com+starplace.com+starspath.com+start.com.au+starting-point.com+startrekmail.com+stealthmail.com+stipte.nl+stockracer.com+stoned.com+stones.com+stop-my-spam.pp.ua+stopdropandroll.com+storksite.com+streber24.de+stribmail.com+strompost.com+strongguy.com+student.su+studentcenter.org+subnetwork.com+subram.com+sudanmail.net+suhabi.com+suisse.org+sukhumvit.net+sunpoint.net+sunrise-sunset.com+sunsgame.com+sunumail.sn+superdada.com+supereva.it+supermail.ru+surat.com+surf3.net+surfree.com+surfy.net+surgical.net+surimail.com+survivormail.com+swbell.net+sweb.cz+swedenmail.com+sweetville.net+swift-mail.com+swiftdesk.com+swingeasyhithard.com+swingfan.com+swipermail.zzn.com+swirve.com+swissinfo.org+swissmail.com+swissmail.net+switchboardmail.com+switzerland.org+sx172.com+syom.com+syriamail.com+t-online.de+t2mail.com+takuyakimura.com+talk21.com+talkcity.com+tamil.com+tampabay.rr.com+tankpolice.com+tatanova.com+taufik.sytes.net+taufikrt.ddns.net+tbwt.com+tds.net+teachermail.net+teachers.org+teamdiscovery.com+teamtulsa.net+tech-center.com+tech4peace.org+techemail.com+techie.com+techindo.web.id+technisamail.co.za+technologist.com+techpointer.com+techscout.com+techseek.com+techspot.com+teenagedirtbag.com+tele2.at+tele2.nl+telebot.com+telebot.net+teleline.es+telerymd.com+teleserve.dynip.com+telfort.nl+telfortglasvezel.nl+telinco.net+telkom.net+telpage.net+telstra.com+telstra.com.au+temp.cloudns.asia+tempmail.sytes.net+temtulsa.net+tenchiclub.com+tenderkiss.com+tennismail.com+terminverpennt.de+terra.cl+terra.com+terra.com.ar+terra.com.br+terra.es+test.com+test.de+tfanus.com.er+tfz.net+thai.com+thaimail.com+thaimail.net+the-african.com+the-airforce.com+the-aliens.com+the-american.com+the-animal.com+the-army.com+the-astronaut.com+the-beauty.com+the-big-apple.com+the-biker.com+the-boss.com+the-brazilian.com+the-canadian.com+the-canuck.com+the-captain.com+the-chinese.com+the-country.com+the-cowboy.com+the-davis-home.com+the-dutchman.com+the-eagles.com+the-englishman.com+the-fastest.net+the-fool.com+the-frenchman.com+the-galaxy.net+the-genius.com+the-gentleman.com+the-german.com+the-gremlin.com+the-hooligan.com+the-italian.com+the-japanese.com+the-lair.com+the-madman.com+the-mailinglist.com+the-marine.com+the-master.com+the-mexican.com+the-ministry.com+the-monkey.com+the-newsletter.net+the-pentagon.com+the-police.com+the-prayer.com+the-professional.com+the-quickest.com+the-russian.com+the-snake.com+the-spaceman.com+the-stock-market.com+the-student.net+the-whitehouse.net+the-wild-west.com+the18th.com+thecoolguy.com+thecriminals.com+thedarkmaster097.sytes.net+thedoghousemail.com+thedorm.com+theend.hu+theglobe.com+thegolfcourse.com+thegooner.com+theheadoffice.com+theinternetemail.com+thelanddownunder.com+themail.com+themillionare.net+theoffice.net+theplate.com+thepokerface.com+thepostmaster.net+theraces.com+theracetrack.com+therapist.net+thestreetfighter.com+theteebox.com+thewatercooler.com+thewebpros.co.uk+thewizzard.com+thewizzkid.com+thezhangs.net+thirdage.com+thisgirl.com+thoic.com+thundermail.com+tidni.com+timein.net+tiscali.at+tiscali.be+tiscali.co.uk+tiscali.it+tiscali.lu+tiscali.se+tkcity.com+tko.co.kr+toast.com+toke.com+tom.com+toolsource.com+toothfairy.com+topchat.com+topgamers.co.uk+topletter.com+topmail-files.de+topmail.com.ar+topsurf.com+topteam.bg+torchmail.com+torontomail.com+tortenboxer.de+totalmail.de+totalmusic.net+toughguy.net+tpg.com.au+travel.li+trialbytrivia.com+trimix.cn+tritium.net+trmailbox.com+tropicalstorm.com+truckers.com+truckerz.com+truckracer.com+truckracers.com+trust-me.com+truth247.com+truthmail.com+tsamail.co.za+ttml.co.in+tunisiamail.com+turboprinz.de+turboprinzessin.de+turkey.com+tut.by+tvstar.com+twc.com+twinstarsmail.com+tycoonmail.com+typemail.com+u2club.com+ua.fm+uae.ac+uaemail.com+ubbi.com+ubbi.com.br+uboot.com+uk2.net+uk2k.com+uk2net.com+uk7.net+uk8.net+ukbuilder.com+ukcool.com+ukdreamcast.com+ukmail.org+ukmax.com+ukr.net+uku.co.uk+ultapulta.com+ultrapostman.com+ummah.org+umpire.com+unbounded.com+unforgettable.com+uni.de+uni.demailto.de+unican.es+unihome.com+unite.cloudns.asia+universal.pt+uno.ee+uno.it+unofree.it+unomail.com+unterderbruecke.de+uol.com.ar+uol.com.br+uol.com.co+uol.com.mx+uol.com.ve+uole.com+uole.com.ve+uolmail.com+uomail.com+upc.nl+upcmail.nl+upf.org+ureach.com+urgentmail.biz+usa.com+usa.net+usaaccess.net+usanetmail.com+usermail.com+username.e4ward.com+usma.net+usmc.net+uswestmail.net+utanet.at+uymail.com+uyuyuy.com+v-sexi.com+vahoo.com+vampirehunter.com+varbizmail.com+vcmail.com+velnet.co.uk+velocall.com+verizon.net+verizonmail.com+verlass-mich-nicht.de+versatel.nl+veryfast.biz+veryspeedy.net+videotron.ca+vinbazar.com+violinmakers.co.uk+vip.126.com+vip.163.com+vip.21cn.com+vip.citiz.net+vip.gr+vip.onet.pl+vip.qq.com+vip.sina.com+vipmail.ru+virgilio.it+virgin.net+virginbroadband.com.au+virtual-mail.com+virtualactive.com+virtualmail.com+visitmail.com+visitweb.com+visto.com+visualcities.com+vivavelocity.com+vivianhsu.net+vjmail.com+vjr.luk2.com+vjtimail.com+vlmail.com+vnet.citiz.net+vnn.vn+vodafone.nl+vodafonethuis.nl+volcanomail.com+vollbio.de+volloeko.de+vorscorp.mooo.com+vorsicht-bissig.de+vorsicht-scharf.de+vote-democrats.com+vote-hillary.com+vote-republicans.com+vote4gop.org+votenet.com+vp.pl+vr9.com+w3.to+wahoye.com+wales2000.net+walla.co.il+walla.com+wam.co.za+wanadoo.es+wanadoo.fr+war-im-urlaub.de+warmmail.com+warpmail.net+warrior.hu+wasd.dropmail.me+waumail.com+wbdet.com+wearab.net+web-mail.com.ar+web-police.com+web.de+webave.com+webcammail.com+webcity.ca+webdream.com+webinbox.com+webindia123.com+webjump.com+webmail.bellsouth.net+webmail.co.yu+webmail.co.za+webmail.hu+webmails.com+webname.com+webprogramming.com+webstation.com+websurfer.co.za+webtopmail.com+weedmail.com+weekmail.com+weekonline.com+wegas.ru+wehshee.com+weibsvolk.de+weibsvolk.org+weinenvorglueck.de+welsh-lady.com+westnet.com.au+whale-mail.com+whartontx.com+wheelweb.com+whipmail.com+whoever.com+whoopymail.com+whtjddn.33mail.com+wickedmail.com+wideopenwest.com+wildmail.com+will-hier-weg.de+windowslive.com+windrivers.net+windstream.net+wingnutz.com+winmail.com.au+winning.com+wir-haben-nachwuchs.de+wir-sind-cool.org+wirsindcool.de+witty.com+wiz.cc+wkbwmail.com+wo.com.cn+woh.rr.com+wolf-web.com+wolke7.net+wombles.com+women-at-work.org+wonder-net.com+wongfaye.com+wooow.it+worker.com+workmail.com+worldemail.com+worldmailer.com+worldnet.att.net+wormseo.cn+wosaddict.com+wouldilie.com+wovz.cu.cc+wowgirl.com+wowmail.com+wowway.com+wp.pl+wptamail.com+wrestlingpages.com+wrexham.net+writeme.com+writemeback.com+wrongmail.com+wsfr.luk2.com+wtvhmail.com+wwdg.com+www.com+www.dmtc.edu.pl+www.e4ward.com+www2000.net+wx88.net+wxs.net+wyrm.supernews.com+x-mail.net+x-networks.net+x5g.com+xaker.ru+xaynetsss.ddns.net+xing886.uu.gl+xmail.com+xmastime.com+xms.nl+xmsg.com+xnmail.mooo.com+xoom.com+xoommail.com+xpressmail.zzn.com+xs4all.nl+xsecurity.org+xsmail.com+xtra.co.nz+xuno.com+xxx.sytes.net+xzapmail.com+y7mail.com+ya.ru+yada-yada.com+yaho.com+yahoo.ae+yahoo.ar+yahoo.at+yahoo.be+yahoo.ca+yahoo.ch+yahoo.cl+yahoo.cn+yahoo.co+yahoo.co.id+yahoo.co.il+yahoo.co.in+yahoo.co.jp+yahoo.co.kr+yahoo.co.nz+yahoo.co.th+yahoo.co.uk+yahoo.co.za+yahoo.com+yahoo.com.ar+yahoo.com.au+yahoo.com.br+yahoo.com.cn+yahoo.com.co+yahoo.com.hk+yahoo.com.is+yahoo.com.mx+yahoo.com.my+yahoo.com.ph+yahoo.com.ru+yahoo.com.sg+yahoo.com.tr+yahoo.com.tw+yahoo.com.vn+yahoo.cz+yahoo.de+yahoo.dk+yahoo.es+yahoo.fi+yahoo.fr+yahoo.gr+yahoo.hu+yahoo.id+yahoo.ie+yahoo.in+yahoo.it+yahoo.jp+yahoo.mx+yahoo.my+yahoo.nl+yahoo.no+yahoo.ph+yahoo.pl+yahoo.pt+yahoo.ro+yahoo.ru+yahoo.se+yahoo.uk+yahoo.vn+yahoofs.com+yalla.com+yalla.com.lb+yalook.com+yam.com+yandex.com+yandex.mail+yandex.pl+yandex.ru+yandex.ua+yapost.com+yawmail.com+yclub.com+yeah.net+yebox.com+yehaa.com+yehey.com+yemenmail.com+yepmail.net+yert.ye.vc+yesbox.net+yesey.net+yifan.net+ymail.com+ynnmail.com+yogotemail.com+yopmail.biz.st+yopmail.xxi2.com+yopolis.com+yopweb.com+youareadork.com+youmailr.com+youpy.com+your-house.com+your-mail.com+yourinbox.com+yourlifesucks.cu.cc+yourlover.net+yourname.ddns.org+yourname.freeservers.com+yournightmare.com+yours.com+yourssincerely.com+yoursubdomain.findhere.com+yoursubdomain.zzn.com+yourteacher.net+yourwap.com+youvegotmail.net+yuuhuu.net+yyhmail.com+zahadum.com+zcities.com+zdnetmail.com+zeeks.com+zeepost.nl+zensearch.net+zhaowei.net+ziggo.nl+zionweb.org+zip.net+zipido.com+ziplip.com+zipmail.com+zipmail.com.br+zipmax.com+zmail.ru+zoho.com+zonnet.nl+zoominternet.net+zubee.com+zuzzurello.com+zwallet.com+zweb.in+zybermail.com+zydecofan.com+zzn.com+zzom.co.uk+zzom.co.uk1033edge.com+zzom.co.ukgmail.com+zzom.co.ukhitmail.com+zzom.co.uksina.com0-mail.comdiff --git a/core/switch_core/gateway/email_domains.py b/core/switch_core/gateway/email_domains.pynew file mode 100644index 000000000..906cc53f5--- /dev/null+++ b/core/switch_core/gateway/email_domains.py@@ -0,0 +1,66 @@+"""The domain of an e-mail address, and the domains no workspace may claim.++A workspace can let anyone at a domain join it without an invitation. That is+only meaningful for a domain one organisation controls: opening a workspace to+a public e-mail provider's domain would open it to anyone who signs up there.++The refused domains are two published lists, vendored under+`email_domain_lists/` with their sources in each file's header, plus the+providers below that neither list carries. No list of free-mail services is+complete, so this narrows what can be claimed rather than proving a domain is+an organisation's.+"""++from __future__ import annotations++from importlib.resources import files++_LISTS = files("switch_core.gateway").joinpath("email_domain_lists")++_NOT_IN_LISTS = frozenset(+ {+ "hey.com",+ "pm.me",+ "proton.me",+ "tutanota.com",+ }+)+++def _read_domains(name: str) -> frozenset[str]:+ lines = _LISTS.joinpath(name).read_text(encoding="utf-8").splitlines()+ domains = frozenset(+ line.strip() for line in lines if line.strip() and not line.startswith("#")+ )+ if not domains:+ raise RuntimeError(f"email_domain_lists/{name} lists no domains")+ return domains+++PUBLIC_EMAIL_DOMAINS = (+ _read_domains("free.txt") | _read_domains("disposable.txt") | _NOT_IN_LISTS+)+++def email_domain(email: str) -> str:+ """The lower-cased part of `email` after its last `@`.++ Raises `ValueError` for a string with no domain, which an account address+ should never be — so a caller reaching it has a malformed account, and+ guessing a domain for it would be worse than saying so.+ """+ _, at, domain = email.rpartition("@")+ domain = domain.strip().lower()+ if not at or not domain:+ raise ValueError(f"{email!r} has no domain")+ return domain+++def join_domain_refusal(domain: str) -> str | None:+ """Why a workspace may not be opened to `domain`, or None if it may."""+ if domain in PUBLIC_EMAIL_DOMAINS:+ return (+ f"{domain} is a public e-mail provider, so opening the workspace "+ "to it would let anyone with an address there join"+ )+ return Nonediff --git a/core/switch_core/gateway/invite_mail.py b/core/switch_core/gateway/invite_mail.pynew file mode 100644index 000000000..1aaae67b3--- /dev/null+++ b/core/switch_core/gateway/invite_mail.py@@ -0,0 +1,151 @@+"""Sending an invitation to the address it is for.++Plain SMTP through the standard library, run off the event loop: any relay+an operator already has (SES SMTP, Postmark, a company relay) works, and+there is no provider SDK to depend on.+"""++from __future__ import annotations++import asyncio+import html+import smtplib+import ssl+from dataclasses import dataclass+from datetime import datetime+from email.message import EmailMessage+from email.utils import make_msgid+from typing import Protocol++from switch_core.config import SwitchConfig++_SMTP_TIMEOUT_SECONDS = 15+++class InviteEmailFailed(Exception):+ """The relay could not be reached or refused the message."""+++@dataclass(frozen=True)+class InviteEmail:+ to: str+ link: str+ workspace_name: str+ inviter_name: str+ role: str+ expires_at: datetime+++class InviteMailer(Protocol):+ async def send_invitation(self, invite: InviteEmail) -> None: ...+++def invite_link(frontend_base_url: str, token: str) -> str:+ # In the fragment, which a browser never sends: the token is a bearer+ # credential and stays out of every server and proxy log on the way.+ # Mirrors `inviteUrl` in gateway/src/data/sessionState.ts.+ return f"{frontend_base_url.rstrip('/')}/invite#token={token}"+++def _one_line(value: str) -> str:+ # A header may not carry a line break, and names are user-supplied.+ return " ".join(value.split())+++def build_invite_message(invite: InviteEmail, sender: str) -> EmailMessage:+ expires = invite.expires_at.strftime("%Y-%m-%d %H:%M UTC")+ message = EmailMessage()+ message["Subject"] = (+ f"{_one_line(invite.inviter_name)} invited you to "+ f"{_one_line(invite.workspace_name)} on Switch"+ )+ message["From"] = sender+ message["To"] = invite.to+ message["Message-ID"] = make_msgid(domain=sender.rpartition("@")[2] or None)+ message.set_content(+ f"{invite.inviter_name} invited you to join the {invite.workspace_name} "+ f"workspace on Switch as {invite.role}.\n"+ "\n"+ f"Accept the invitation:\n{invite.link}\n"+ "\n"+ f"Sign in with {invite.to} — the invitation is for that address and "+ "cannot be accepted from another account.\n"+ f"It expires {expires}.\n"+ "\n"+ "If you weren't expecting this, you can ignore it.\n"+ )+ e = html.escape+ message.add_alternative(+ "<!doctype html><html><body>"+ f"<p>{e(invite.inviter_name)} invited you to join the "+ f"<strong>{e(invite.workspace_name)}</strong> workspace on Switch as "+ f"{e(invite.role)}.</p>"+ f'<p><a href="{e(invite.link)}">Accept the invitation</a></p>'+ f"<p>Sign in with {e(invite.to)} — the invitation is for that address "+ "and cannot be accepted from another account. "+ f"It expires {e(expires)}.</p>"+ "<p>If you weren't expecting this, you can ignore it.</p>"+ "</body></html>",+ subtype="html",+ )+ return message+++class SmtpInviteMailer:+ def __init__(+ self,+ *,+ host: str,+ port: int,+ tls: str,+ username: str | None,+ password: str | None,+ sender: str,+ ) -> None:+ self._host = host+ self._port = port+ self._tls = tls+ self._username = username+ self._password = password+ self._sender = sender++ @classmethod+ def from_config(cls, config: SwitchConfig) -> SmtpInviteMailer:+ if not config.gateway_smtp_host or not config.gateway_smtp_from:+ raise ValueError("SMTP is not configured")+ return cls(+ host=config.gateway_smtp_host,+ port=config.gateway_smtp_port,+ tls=config.gateway_smtp_tls,+ username=config.gateway_smtp_username,+ password=config.gateway_smtp_password,+ sender=config.gateway_smtp_from,+ )++ async def send_invitation(self, invite: InviteEmail) -> None:+ message = build_invite_message(invite, self._sender)+ try:+ await asyncio.to_thread(self._send, message)+ except (smtplib.SMTPException, OSError) as err:+ raise InviteEmailFailed(+ f"sending via {self._host}:{self._port} failed: {err}"+ ) from err++ def _send(self, message: EmailMessage) -> None:+ context = ssl.create_default_context()+ smtp: smtplib.SMTP+ if self._tls == "tls":+ smtp = smtplib.SMTP_SSL(+ self._host,+ self._port,+ timeout=_SMTP_TIMEOUT_SECONDS,+ context=context,+ )+ else:+ smtp = smtplib.SMTP(self._host, self._port, timeout=_SMTP_TIMEOUT_SECONDS)+ with smtp:+ if self._tls == "starttls":+ smtp.starttls(context=context)+ if self._username and self._password:+ smtp.login(self._username, self._password)+ smtp.send_message(message)diff --git a/core/switch_core/gateway/messaging_installs.py b/core/switch_core/gateway/messaging_installs.pyindex ac730188d..d763bcf94 100644--- a/core/switch_core/gateway/messaging_installs.py+++ b/core/switch_core/gateway/messaging_installs.py@@ -21,7 +21,7 @@ from switch_core.bridges.collaboration.install import MessagingInstallErrorfrom switch_core.bridges.collaboration.install_service import MessagingInstallServicefrom switch_core.db.models import User, require_tenant_idfrom switch_core.db.stores.messaging_install_store import MessagingInstallNotFound-from switch_core.gateway.auth import require_admin+from switch_core.gateway.auth import require_tenant_adminfrom switch_core.gateway.dependencies import get_install_service, get_sessionlogger = logging.getLogger(__name__)@@ -86,7 +86,7 @@ def _require_installs(@router.get("")async def installable_platforms(service: Annotated[MessagingInstallService | None, Depends(get_install_service)],- _user: Annotated[User, Depends(require_admin)],+ _user: Annotated[User, Depends(require_tenant_admin)],) -> InstallablePlatforms:return InstallablePlatforms(platforms=[] if service is None else service.platforms()@@ -98,7 +98,7 @@ async def begin_install(platform: str,session: Annotated[AsyncSession, Depends(get_session)],service: Annotated[MessagingInstallService | None, Depends(get_install_service)],- user: Annotated[User, Depends(require_admin)],+ user: Annotated[User, Depends(require_tenant_admin)],) -> InstallStart:try:authorize_url = await _require_installs(service).begin(@@ -116,7 +116,7 @@ async def begin_install(async def list_installs(session: Annotated[AsyncSession, Depends(get_session)],service: Annotated[MessagingInstallService | None, Depends(get_install_service)],- _user: Annotated[User, Depends(require_admin)],+ _user: Annotated[User, Depends(require_tenant_admin)],) -> InstalledApps:"""This organisation's installs, ended ones included.@@ -139,7 +139,7 @@ async def list_installs(async def disconnect_install(install_id: str,service: Annotated[MessagingInstallService | None, Depends(get_install_service)],- user: Annotated[User, Depends(require_admin)],+ user: Annotated[User, Depends(require_tenant_admin)],) -> InstalledApp:"""End an install: revoke the credential, remove the bridge, free the workspace.diff --git a/core/switch_core/gateway/oidc_routes.py b/core/switch_core/gateway/oidc_routes.pyindex 106482b38..156941842 100644--- a/core/switch_core/gateway/oidc_routes.py+++ b/core/switch_core/gateway/oidc_routes.py@@ -2,12 +2,13 @@ from __future__ import annotationsimport jsonimport logging+from contextlib import AbstractContextManager, nullcontextfrom typing import Annotated, Anyimport httpxfrom authlib.integrations.starlette_client import OAuth, OAuthErrorfrom fastapi import APIRouter, Depends, HTTPException, Request-from sqlalchemy.ext.asyncio import AsyncSession+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom starlette.responses import RedirectResponsefrom switch_core.config import SwitchConfig@@ -17,9 +18,10 @@ from switch_core.db.stores.user_store import (OidcIdentityRaceError,UserStore,)-from switch_core.gateway.auth import set_session_cookie+from switch_core.gateway.auth import initial_tenant_claim, set_session_cookiefrom switch_core.gateway.dependencies import (get_config,+ get_session_factory,get_system_session,get_user_store,)@@ -82,6 +84,9 @@ async def oidc_callback(request: Request,config: Annotated[SwitchConfig, Depends(get_config)],session: Annotated[AsyncSession, Depends(get_system_session)],+ session_factory: Annotated[+ async_sessionmaker[AsyncSession], Depends(get_session_factory)+ ],user_store: Annotated[UserStore, Depends(get_user_store)],) -> RedirectResponse:# `get_system_session`: nobody is signed in yet, so there is no principal@@ -171,14 +176,18 @@ async def oidc_callback(iss = claims.get("iss") or config.gateway_oidc_issuer_urlif not iss:raise HTTPException(status_code=401, detail="OIDC token missing issuer")- # A first sign-in provisions the account just in time, and that account- # needs a tenant: a user with no membership can never sign in again (see- # `gateway/auth.py`). Exactly one tenant exists, and this names it rather- # than letting `TenantScoped`'s fallback pick it by accident — the two- # produce the same row today, but only one of them is a decision. Sign-up- # creating a tenant of its own is a later phase, and this is the line it- # changes.- with tenant_scope(TENANT_ZERO_ID):+ # A first sign-in provisions the account just in time. Where it lands is+ # `gateway_signup_mode`'s decision. Under "default_tenant" it joins tenant+ # zero, named here rather than left to `TenantScoped`'s fallback, which+ # would produce the same row by accident rather than by decision. Under+ # the self-service modes it joins nothing: `users` and `oidc_identities`+ # are global, so provisioning needs no tenant bound, and the newcomer is+ # sent to onboarding to create a workspace or accept an invitation.+ join_tenant = config.gateway_signup_mode == "default_tenant"+ scope: AbstractContextManager[None] = (+ tenant_scope(TENANT_ZERO_ID) if join_tenant else nullcontext()+ )+ with scope:try:user = await user_store.get_or_create_oidc_user(session,@@ -187,6 +196,7 @@ async def oidc_callback(name=name,sub=sub,email_verified=verified,+ join_tenant=join_tenant,)except OidcIdentityConflictError as exc:logger.warning("OIDC identity conflict: %s", exc)@@ -208,6 +218,10 @@ async def oidc_callback(# back on the SPA with our own session cookie set.response = RedirectResponse(url=config.frontend_base_url or "/", status_code=303)set_session_cookie(- response, user, config.jwt_secret_key, config.gateway_cookie_secure, None+ response,+ user,+ config.jwt_secret_key,+ config.gateway_cookie_secure,+ await initial_tenant_claim(session_factory, user_store, user),)return responsediff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.pyindex e8199dbcf..6ad2950a3 100644--- a/core/switch_core/gateway/schemas.py+++ b/core/switch_core/gateway/schemas.py@@ -1,11 +1,17 @@from __future__ import annotations+from datetime import datetimefrom typing import Any, Literal-from pydantic import BaseModel, Field+from pydantic import BaseModel, Field, field_validator, model_validatorfrom switch_core.addressing import AddressingPolicyfrom switch_core.bridges.collaboration.models import BridgeInstallLink+from switch_core.db.models import (+ MAX_BUDGET_AMOUNT,+ MAX_BUDGET_PERIOD_HOURS,+ UsageMetric,+)# ── Rooms ─────────────────────────────────────────────────────────────────────@@ -684,10 +690,53 @@ class TenantMembershipResponse(BaseModel):role: str+class CurrentTenantResponse(TenantMembershipResponse):+ """The tenant this request is bound to. `administers` is whether the+ caller may manage it — an `owner` or `admin` membership, or the operator+ bit, which no membership role shows."""++ administers: bool++class TenantCreateRequest(BaseModel):name: str+class SessionStateUser(BaseModel):+ id: str+ name: str+ email: str+ # The deployment operator (`users.role == "admin"`), who administers every+ # workspace and the deployment-wide user list.+ is_operator: bool+++class SessionStateResponse(BaseModel):+ """Where this session stands with respect to workspaces — the body of+ `GET /auth/session`, readable before any workspace is selected.++ `state` mirrors what tenant resolution would do with this session's claim+ on any other request:++ - "ready": a workspace resolves, and it is `tenant`.+ - "needs_selection": the caller belongs to at least one workspace but the+ session resolves none — no claim with several memberships, or a claim+ naming a workspace they no longer belong to. Selecting one of `tenants`+ (`POST /tenants/{id}/switch`) fixes it.+ - "needs_workspace": no memberships at all. Creating a workspace (when+ `can_create_workspace`) or accepting an invitation fixes it.+ """++ user: SessionStateUser+ tenant: TenantMembershipResponse | None+ tenants: list[TenantMembershipResponse]+ state: Literal["ready", "needs_selection", "needs_workspace"]+ can_create_workspace: bool+ # Whether an invitation addressed to an e-mail is sent there, or only+ # minted for the admin to share.+ invite_email_enabled: bool++class InvitationCreateRequest(BaseModel):role: str = "member"# None mints a shareable link; set, the invitation is addressed to one@@ -699,6 +748,26 @@ class InvitationCreateRequest(BaseModel):expires_in_hours: int = Field(default=168, gt=0, le=8760)uses_remaining: int = Field(default=1, ge=1)+ @field_validator("email")+ @classmethod+ def _address_shaped(cls, value: str | None) -> str | None:+ # Not full RFC 5322: enough that what is stored, compared against a+ # signed-in account and put in a To header is one plausible address.+ if value is None:+ return None+ address = value.strip().lower()+ local, at, domain = address.partition("@")+ if (+ not at+ or not local+ or "." not in domain+ or "@" in domain+ or len(address) > 320+ or any(c.isspace() or not c.isprintable() for c in address)+ ):+ raise ValueError("Not an e-mail address")+ return address+class InvitationAcceptRequest(BaseModel):# In the body rather than the path: a URL travels through proxy logs,@@ -707,6 +776,63 @@ class InvitationAcceptRequest(BaseModel):token: str+class AddressedInvitation(BaseModel):+ """An invitation waiting for the signed-in caller, as they are shown it.++ What an invitee needs to decide, and no more: the workspace, the role it+ would grant, until when, and who sent it. Never the token.+ """++ id: str+ tenant_id: str+ tenant_slug: str+ tenant_name: str+ role: str+ expires_at: str+ invited_by: str+ created_at: str+++class AddressedInvitationAcceptRequest(BaseModel):+ tenant_id: str+ invitation_id: str+++class JoinDomainDetail(BaseModel):+ domain: str+ created_by: str+ created_at: str+++class JoinDomainsResponse(BaseModel):+ """The domains a workspace is open to, and whether the caller could add+ theirs.++ An admin may open a workspace only to the domain of their own address, so+ `own_domain` is the one domain they could add, and `own_domain_refusal`+ says why they cannot when they cannot — a public e-mail provider's domain,+ say. Already being open to it is not a refusal; it is in `domains`.+ """++ domains: list[JoinDomainDetail]+ own_domain: str+ own_domain_refusal: str | None+++class JoinDomainCreateRequest(BaseModel):+ domain: str+++class JoinableTenant(BaseModel):+ """A workspace the signed-in caller may join because of their address's+ domain, as they are shown it."""++ tenant_id: str+ tenant_slug: str+ tenant_name: str+ domain: str++class InvitationDetail(BaseModel):id: strrole: str@@ -722,6 +848,11 @@ class InvitationCreateResponse(InvitationDetail):# The plaintext token. Present only here — see# `InvitationStore.create`, which is the one call that can hand it back.token: str+ # What happened to the e-mail, so the admin knows whether to share the+ # link themselves: "not_requested" when the invitation names no address,+ # "not_configured" when this server has no mail relay, "failed" when the+ # relay refused or could not be reached, "sent" otherwise.+ email_delivery: Literal["sent", "not_configured", "failed", "not_requested"]class MemberDetail(BaseModel):@@ -732,6 +863,21 @@ class MemberDetail(BaseModel):created_at: str+class UsageTotalResponse(BaseModel):+ """One consumer's total of one metric over the requested window.++ `client_name` and `client_type` are null when the client has since been+ deleted; what it spent still counts against the workspace.+ """++ metric: str+ client_id: str+ client_name: str | None+ client_type: str | None+ model: str+ amount: int++class MemberUpdateRequest(BaseModel):role: str@@ -746,6 +892,9 @@ class AuthConfigResponse(BaseModel):password_login_enabled: booloidc_enabled: booloidc_provider_label: str | None+ # Where a first sign-in lands (`SwitchConfig.gateway_signup_mode`), so the+ # page can say whether signing in also creates an account of your own.+ signup_mode: Literal["default_tenant", "invite_only", "open"]class ContractRangeResponse(BaseModel):@@ -1186,3 +1335,44 @@ class TemplateValidateResponse(BaseModel):blocked: boolerrors: list[TemplateFinding]warnings: list[TemplateFinding]+++class BudgetCreateRequest(BaseModel):+ """A new budget. `agent_id` null covers every agent in the workspace;+ `model` empty covers every model."""++ agent_id: str | None+ metric: UsageMetric+ model: str+ amount_limit: int = Field(gt=0, le=MAX_BUDGET_AMOUNT)+ period_hours: int = Field(gt=0, le=MAX_BUDGET_PERIOD_HOURS)++ @model_validator(mode="after")+ def _model_only_on_token_metrics(self) -> BudgetCreateRequest:+ if self.model and self.metric in (UsageMetric.MESSAGES, UsageMetric.TURNS):+ raise ValueError(+ f"A {self.metric.value} budget cannot name a model: "+ f"{self.metric.value} are not counted per model"+ )+ return self+++class BudgetUpdateRequest(BaseModel):+ amount_limit: int = Field(gt=0, le=MAX_BUDGET_AMOUNT)+ period_hours: int = Field(gt=0, le=MAX_BUDGET_PERIOD_HOURS)+++class BudgetResponse(BaseModel):+ """A budget and what has been spent against it in the current period,+ which ends at `resets_at`."""++ id: str+ agent_id: str | None+ agent_name: str | None+ metric: str+ model: str+ amount_limit: int+ period_hours: int+ spent: int+ resets_at: datetime+ exhausted: booldiff --git a/core/switch_core/gateway/tenants.py b/core/switch_core/gateway/tenants.pyindex 4b2065dac..6f84fe4ce 100644--- a/core/switch_core/gateway/tenants.py+++ b/core/switch_core/gateway/tenants.py@@ -3,10 +3,11 @@ from __future__ import annotationsimport hashlibimport loggingimport re+import secretsfrom datetime import UTC, datetime, timedelta-from typing import Annotated+from typing import Annotated, Literal-from fastapi import APIRouter, Depends, HTTPException, Response+from fastapi import APIRouter, Depends, HTTPException, Query, Responsefrom sqlalchemy import selectfrom sqlalchemy.exc import DBAPIError, IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker@@ -14,51 +15,96 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.bridges.agent.protocol.service import ProtocolServicefrom switch_core.clients.client_lifecycle_service import ClientLifecycleServicefrom switch_core.config import SwitchConfig-from switch_core.db.models import Invitation, Tenant, TenantMember, User+from switch_core.db.models import (+ Invitation,+ Tenant,+ TenantJoinDomain,+ TenantMember,+ User,+ require_tenant_id,+)from switch_core.db.session_scope import tenant_sessionfrom switch_core.db.stores.agent_store import AgentStorefrom switch_core.db.stores.api_key_store import ApiKeyStore+from switch_core.db.stores.budget_store import (+ BudgetNotFound,+ BudgetStanding,+ BudgetStore,+)from switch_core.db.stores.invitation_store import (InvitationNotUsableError,InvitationStore,)+from switch_core.db.stores.join_domain_store import (+ JoinDomainAlreadyAdded,+ JoinDomainNotFound,+ JoinDomainStore,+)+from switch_core.db.stores.tenant_store import TenantSlugTaken+from switch_core.db.stores.usage_store import UsageStorefrom switch_core.db.stores.user_store import UserStorefrom switch_core.gateway.auth import (AuthenticatedCaller,get_authenticated_caller,get_authenticated_user_id,get_current_user,+ get_tenant_is_admin,get_tenant_is_owner,is_tenant_member,list_tenant_memberships,require_tenant_admin,set_session_cookie,tenant_of_invitation_token,+ tenants_open_to,+ tenants_with_invitations_for,+ workspace_creation_refusal,)from switch_core.gateway.auth_routes import _session_responsefrom switch_core.gateway.dependencies import (current_telemetry,get_agent_store,get_api_key_store,+ get_budget_store,get_client_lifecycle,get_config,get_invitation_store,+ get_invite_mailer,+ get_join_domain_store,get_protocol,get_session,get_session_factory,get_system_session,+ get_usage_store,get_user_store,)+from switch_core.gateway.email_domains import email_domain, join_domain_refusal+from switch_core.gateway.invite_mail import (+ InviteEmail,+ InviteEmailFailed,+ InviteMailer,+ invite_link,+)from switch_core.gateway.schemas import (+ AddressedInvitation,+ AddressedInvitationAcceptRequest,+ BudgetCreateRequest,+ BudgetResponse,+ BudgetUpdateRequest,+ CurrentTenantResponse,InvitationAcceptRequest,InvitationCreateRequest,InvitationCreateResponse,InvitationDetail,+ JoinableTenant,+ JoinDomainCreateRequest,+ JoinDomainDetail,+ JoinDomainsResponse,MemberDetail,MemberUpdateRequest,SessionUserResponse,TenantCreateRequest,TenantMembershipResponse,+ UsageTotalResponse,)from switch_core.telemetry import emit_safelyfrom switch_core.telemetry.ages import age_hours@@ -73,13 +119,19 @@ TENANT_MEMBER_ROLES = ("owner", "admin", "member")_SLUG_INVALID_CHARS = re.compile(r"[^a-z0-9]+")+# A first choice and this many suffixed ones. Four hex characters make a+# repeat collision on the same name vanishingly unlikely, so running out means+# something other than bad luck is wrong.+_SLUG_ATTEMPTS = 4+def _derive_slug(name: str) -> str:"""A URL-safe slug from a workspace name.- A taken slug is a 409 (`create_tenant` below), never a silently- suffixed alternative — the design is explicit that a caller must be told- rather than handed a workspace under a name it did not ask for.+ The slug is an identifier, not the name: the workspace keeps the name its+ creator typed exactly, and a slug that is already taken gets a short+ random suffix (`_provision_workspace` below). Refusing instead would tell anyone+ who can sign up which workspace names exist on this server."""slug = _SLUG_INVALID_CHARS.sub("-", name.strip().lower()).strip("-")if not slug:@@ -202,11 +254,38 @@ async def list_tenants(return await list_tenant_memberships(session_factory, user_store, user_id)[email protected]("/tenants/current")+async def current_tenant(+ session: Annotated[AsyncSession, Depends(get_session)],+ user_store: Annotated[UserStore, Depends(get_user_store)],+ user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],+) -> CurrentTenantResponse:+ """The tenant this request is bound to, and the caller's standing in it.++ A client needs the id for every `/tenants/{tenant_id}/...` path, and the+ binding is settled server-side (see `_resolve_tenant_id`), so this is the+ one place it can ask rather than guess from `GET /tenants`.+ """+ tenant_id = require_tenant_id()+ tenant = await session.get(Tenant, tenant_id)+ role = await user_store.tenant_role(session, tenant_id, user.id)+ if tenant is None or role is None:+ raise HTTPException(status_code=404, detail="Tenant not found")+ return CurrentTenantResponse(+ id=tenant.id,+ slug=tenant.slug,+ name=tenant.name,+ role=role,+ administers=is_admin,+ )++_LOCK_NOT_AVAILABLE = "55P03"async def _lock_workspace_allowance(- session: AsyncSession, caller: AuthenticatedCaller, limit: int+ session: AsyncSession, caller: AuthenticatedCaller, config: SwitchConfig) -> User:"""Lock the caller's row and raise 403 unless they may create one moreworkspace. Returns the locked row, for the caller to count the creation on.@@ -216,7 +295,9 @@ async def _lock_workspace_allowance(buys the deployment steady-state work(`docs/old/multi-tenancy-phase2-tenants.md`, §5). A limit of 0 closes theroute entirely, which is how a deployment that is not ready to offer- self-service says so.+ self-service says so; so does `invite_only` sign-up. What is refused, and+ why, is `workspace_creation_refusal`'s, so `GET /auth/session` reports the+ same answer this enforces.The bound is on workspaces created (`users.workspaces_created`), not onworkspaces owned: ownership can be handed to another account, so a count of@@ -232,11 +313,6 @@ async def _lock_workspace_allowance(share on this same row from another session, and `FOR UPDATE` would makethe request wait on itself."""- if limit == 0:- raise HTTPException(- status_code=403,- detail="Workspace creation is disabled on this deployment",- )try:user = await session.scalar(select(User)@@ -252,14 +328,11 @@ async def _lock_workspace_allowance() from excif user is None:raise HTTPException(status_code=401, detail="Unknown user")- if user.workspaces_created >= limit:- raise HTTPException(- status_code=403,- detail=(- f"You have created {user.workspaces_created} workspaces, and "- f"this deployment allows {limit}"- ),- )+ refusal = workspace_creation_refusal(+ config, is_operator=False, workspaces_created=user.workspaces_created+ )+ if refusal is not None:+ raise HTTPException(status_code=403, detail=refusal)return user@@ -270,13 +343,25 @@ async def _provision_workspace(caller: AuthenticatedCaller,name: str,) -> Tenant:- slug = _derive_slug(name)- try:- tenant = await client_lifecycle.create_tenant(name, slug)- except IntegrityError as exc:+ base_slug = _derive_slug(name)+ tenant: Tenant | None = None+ for attempt in range(_SLUG_ATTEMPTS):+ slug = base_slug if attempt == 0 else f"{base_slug}-{secrets.token_hex(2)}"+ try:+ tenant = await client_lifecycle.create_tenant(name, slug)+ except TenantSlugTaken:+ continue+ break+ if tenant is None:+ logger.error(+ "Could not find a free slug for workspace %r after %d attempts",+ name,+ _SLUG_ATTEMPTS,+ )raise HTTPException(- status_code=409, detail=f"Slug already taken: {slug}"- ) from exc+ status_code=503,+ detail="Could not create the workspace; please try again",+ )try:async with tenant_session(session_factory, tenant.id) as session:@@ -300,16 +385,24 @@ async def _provision_workspace(@router.post("/tenants", status_code=201)async def create_tenant(req: TenantCreateRequest,+ response: Response,caller: Annotated[AuthenticatedCaller, Depends(get_authenticated_caller)],+ session: Annotated[AsyncSession, Depends(get_system_session)],session_factory: Annotated[async_sessionmaker[AsyncSession], Depends(get_session_factory)],user_store: Annotated[UserStore, Depends(get_user_store)],client_lifecycle: Annotated[ClientLifecycleService, Depends(get_client_lifecycle)],config: Annotated[SwitchConfig, Depends(get_config)],- allowance: Annotated[AsyncSession, Depends(get_system_session)],) -> TenantMembershipResponse:- """Create a workspace. The caller becomes its `owner`.+ """Create a workspace. The caller becomes its `owner`, and their session+ switches into it.++ Whether they may is `workspace_creation_refusal`'s decision: sign-up mode+ and a per-person cap on workspaces created, with operators exempt. It is+ authenticated with `get_authenticated_caller` because the caller who+ most needs this — someone who has just signed up — has no workspace for+ `get_current_user` to bind.How many workspaces one person may create is bounded, and the bound ischecked before anything is provisioned — see `_lock_workspace_allowance`.@@ -338,19 +431,25 @@ async def create_tenant(codebase refuses. An operator repairs it by inserting the membership."""if caller.is_operator:+ user = await user_store.get(session, caller.id)+ if user is None:+ raise HTTPException(status_code=401, detail="User not found")tenant = await _provision_workspace(session_factory, user_store, client_lifecycle, caller, req.name)else:- user = await _lock_workspace_allowance(- allowance, caller, config.gateway_max_workspaces_per_user- )+ user = await _lock_workspace_allowance(session, caller, config)tenant = await _provision_workspace(session_factory, user_store, client_lifecycle, caller, req.name)user.workspaces_created += 1- await allowance.commit()+ await session.commit()+ await user_store.record_last_tenant(session, user, tenant.id)+ await session.commit()+ set_session_cookie(+ response, user, config.jwt_secret_key, config.gateway_cookie_secure, tenant.id+ )return TenantMembershipResponse(id=tenant.id, slug=tenant.slug, name=tenant.name, role="owner")@@ -385,6 +484,8 @@ async def switch_tenant(if user is None:raise HTTPException(status_code=401, detail="User not found")+ await user_store.record_last_tenant(session, user, tenant_id)+ await session.commit()set_session_cookie(response, user, config.jwt_secret_key, config.gateway_cookie_secure, tenant_id)@@ -402,18 +503,40 @@ async def create_invitation(invitation_store: Annotated[InvitationStore, Depends(get_invitation_store)],user: Annotated[User, Depends(require_tenant_admin)],is_owner: Annotated[bool, Depends(get_tenant_is_owner)],+ config: Annotated[SwitchConfig, Depends(get_config)],+ mailer: Annotated[InviteMailer | None, Depends(get_invite_mailer)],) -> InvitationCreateResponse:"""Mint an invitation to the bound tenant. `owner`/`admin` only.An `owner` invitation is owner-only: minting one is granting ownershipwith a step of indirection, so it answers to the same gate the directgrant does (`_require_owner`).++ An invitation naming an e-mail is also sent there when a relay is+ configured. The e-mail is a convenience on top of the link, not a+ condition of the invitation: when it cannot go out the invitation still+ stands, and `email_delivery` tells the admin to share the link instead."""_require_bound_tenant(tenant_id)if req.role not in TENANT_MEMBER_ROLES:raise HTTPException(status_code=400, detail=f"Invalid role: {req.role}")if req.role == "owner":_require_owner(is_owner, "invite another owner")+ if req.email is not None and mailer is not None and user.role != "admin":+ sent_today = await invitation_store.count_addressed_since(+ session, datetime.now(UTC) - timedelta(days=1)+ )+ if sent_today >= config.gateway_invite_emails_per_day:+ await session.commit()+ raise HTTPException(+ status_code=429,+ detail=(+ "This workspace has sent its daily limit of "+ f"{config.gateway_invite_emails_per_day} invitation e-mails; "+ "try again tomorrow, or create an invitation without an "+ "e-mail and share the link"+ ),+ )expires_at = datetime.now(UTC) + timedelta(hours=req.expires_in_hours)invitation, token = await invitation_store.create(@@ -424,9 +547,226 @@ async def create_invitation(uses_remaining=req.uses_remaining,created_by=user.id,)+ tenant = await session.get(Tenant, tenant_id)+ assert tenant is not None+ await session.commit()++ delivery = await _deliver_invitation(+ mailer,+ config,+ invitation,+ token,+ workspace_name=tenant.name,+ inviter_name=user.name,+ )+ emit_safely(current_telemetry(), "invitation_sent", {"delivery": delivery})+ return InvitationCreateResponse(+ token=token, email_delivery=delivery, **_invitation_fields(invitation)+ )+++async def _deliver_invitation(+ mailer: InviteMailer | None,+ config: SwitchConfig,+ invitation: Invitation,+ token: str,+ *,+ workspace_name: str,+ inviter_name: str,+) -> Literal["sent", "not_configured", "failed", "not_requested"]:+ if invitation.email is None:+ return "not_requested"+ if mailer is None:+ logger.warning(+ "Invitation %s to tenant %s names an e-mail, but no SMTP relay is "+ "configured (GATEWAY_SMTP_HOST); nothing was sent",+ invitation.id,+ invitation.tenant_id,+ )+ return "not_configured"+ assert config.frontend_base_url is not None+ try:+ await mailer.send_invitation(+ InviteEmail(+ to=invitation.email,+ link=invite_link(config.frontend_base_url, token),+ workspace_name=workspace_name,+ inviter_name=inviter_name,+ role=invitation.role,+ expires_at=invitation.expires_at,+ )+ )+ except InviteEmailFailed:+ logger.exception(+ "Invitation %s to tenant %s was created but its e-mail was not sent",+ invitation.id,+ invitation.tenant_id,+ )+ return "failed"+ return "sent"++[email protected]("/tenants/{tenant_id}/usage")+async def get_usage(+ tenant_id: str,+ since: Annotated[datetime, Query()],+ until: Annotated[datetime, Query()],+ session: Annotated[AsyncSession, Depends(get_session)],+ usage_store: Annotated[UsageStore, Depends(get_usage_store)],+ _user: Annotated[User, Depends(require_tenant_admin)],+) -> list[UsageTotalResponse]:+ """The bound tenant's usage per metric, consumer and model over `[since, until)`.++ `owner`/`admin` only. Usage is counted in whole UTC hours, so `since` is+ widened to the start of its hour. Both bounds must carry a timezone: a+ naive time would be read in the server's zone and quietly shift the window.+ """+ _require_bound_tenant(tenant_id)+ if since.tzinfo is None or until.tzinfo is None:+ raise HTTPException(+ status_code=400, detail="since and until must include a timezone offset"+ )+ if since >= until:+ raise HTTPException(status_code=400, detail="since must be before until")+ totals = await usage_store.totals(+ session, tenant_id=tenant_id, since=since, until=until+ )+ return [+ UsageTotalResponse(+ metric=t.metric,+ client_id=t.client_id,+ client_name=t.client_name,+ client_type=t.client_type,+ model=t.model,+ amount=t.amount,+ )+ for t in totals+ ]+++def _budget_response(standing: BudgetStanding) -> BudgetResponse:+ return BudgetResponse(+ id=standing.id,+ agent_id=standing.agent_id,+ agent_name=standing.agent_name,+ metric=standing.metric,+ model=standing.model,+ amount_limit=standing.amount_limit,+ period_hours=standing.period_hours,+ spent=standing.spent,+ resets_at=standing.resets_at,+ exhausted=standing.exhausted,+ )+++async def _budget_standing(+ session: AsyncSession, budget_store: BudgetStore, tenant_id: str, budget_id: str+) -> BudgetResponse:+ for standing in await budget_store.standings(+ session, tenant_id=tenant_id, agent_id=None+ ):+ if standing.id == budget_id:+ return _budget_response(standing)+ raise HTTPException(status_code=404, detail="Budget not found")++[email protected]("/tenants/{tenant_id}/budgets")+async def list_budgets(+ tenant_id: str,+ session: Annotated[AsyncSession, Depends(get_session)],+ budget_store: Annotated[BudgetStore, Depends(get_budget_store)],+ _user: Annotated[User, Depends(require_tenant_admin)],+) -> list[BudgetResponse]:+ """Every budget of the bound tenant with its spend in the current period.+ `owner`/`admin` only."""+ _require_bound_tenant(tenant_id)+ standings = await budget_store.standings(+ session, tenant_id=tenant_id, agent_id=None+ )+ return [_budget_response(s) for s in standings]++[email protected]("/tenants/{tenant_id}/budgets", status_code=201)+async def create_budget(+ tenant_id: str,+ body: BudgetCreateRequest,+ session: Annotated[AsyncSession, Depends(get_session)],+ budget_store: Annotated[BudgetStore, Depends(get_budget_store)],+ agent_store: Annotated[AgentStore, Depends(get_agent_store)],+ _user: Annotated[User, Depends(require_tenant_admin)],+) -> BudgetResponse:+ """Add a budget to the bound tenant. `owner`/`admin` only.++ 404 when `agent_id` names no agent in this workspace; 409 when the same+ agent (or the whole workspace), metric and model already has one — edit+ that one instead.+ """+ _require_bound_tenant(tenant_id)+ if body.agent_id is not None:+ agent = await agent_store.get(session, body.agent_id)+ if agent is None or agent.tenant_id != tenant_id:+ raise HTTPException(status_code=404, detail="Agent not found")+ try:+ budget = await budget_store.create(+ session,+ tenant_id=tenant_id,+ agent_id=body.agent_id,+ metric=body.metric,+ model=body.model,+ amount_limit=body.amount_limit,+ period_hours=body.period_hours,+ )+ except IntegrityError as exc:+ raise HTTPException(+ status_code=409,+ detail="A budget for this agent, metric and model already exists",+ ) from excawait session.commit()- emit_safely(current_telemetry(), "invitation_sent", {})- return InvitationCreateResponse(token=token, **_invitation_fields(invitation))+ return await _budget_standing(session, budget_store, tenant_id, budget.id)++[email protected]("/tenants/{tenant_id}/budgets/{budget_id}")+async def update_budget(+ tenant_id: str,+ budget_id: str,+ body: BudgetUpdateRequest,+ session: Annotated[AsyncSession, Depends(get_session)],+ budget_store: Annotated[BudgetStore, Depends(get_budget_store)],+ _user: Annotated[User, Depends(require_tenant_admin)],+) -> BudgetResponse:+ """Change a budget's limit and period. `owner`/`admin` only. What it+ covers is fixed; to cover something else, add another budget."""+ _require_bound_tenant(tenant_id)+ try:+ await budget_store.update(+ session,+ tenant_id=tenant_id,+ budget_id=budget_id,+ amount_limit=body.amount_limit,+ period_hours=body.period_hours,+ )+ except BudgetNotFound as exc:+ raise HTTPException(status_code=404, detail="Budget not found") from exc+ await session.commit()+ return await _budget_standing(session, budget_store, tenant_id, budget_id)++[email protected]("/tenants/{tenant_id}/budgets/{budget_id}", status_code=204)+async def delete_budget(+ tenant_id: str,+ budget_id: str,+ session: Annotated[AsyncSession, Depends(get_session)],+ budget_store: Annotated[BudgetStore, Depends(get_budget_store)],+ _user: Annotated[User, Depends(require_tenant_admin)],+) -> Response:+ """Remove a budget. `owner`/`admin` only."""+ _require_bound_tenant(tenant_id)+ try:+ await budget_store.delete(session, tenant_id=tenant_id, budget_id=budget_id)+ except BudgetNotFound as exc:+ raise HTTPException(status_code=404, detail="Budget not found") from exc+ await session.commit()+ return Response(status_code=204)@router.get("/tenants/{tenant_id}/invitations")@@ -463,14 +803,17 @@ async def revoke_invitation(@router.post("/invitations/accept")async def accept_invitation(req: InvitationAcceptRequest,+ response: Response,caller: Annotated[AuthenticatedCaller, Depends(get_authenticated_caller)],session_factory: Annotated[async_sessionmaker[AsyncSession], Depends(get_session_factory)],user_store: Annotated[UserStore, Depends(get_user_store)],invitation_store: Annotated[InvitationStore, Depends(get_invitation_store)],+ config: Annotated[SwitchConfig, Depends(get_config)],) -> TenantMembershipResponse:- """Accept an invitation, joining its tenant.+ """Accept an invitation, joining its tenant, and switch the caller's+ session into it — someone who follows an invite link means to be there.Authenticated with `get_authenticated_caller`, not `get_current_user`:the caller's own session may be bound to a different tenant than the@@ -505,34 +848,344 @@ async def accept_invitation(raise HTTPException(status_code=404, detail="Invitation not found")_require_invitation_usable(invitation, caller.email)- existing_role = await user_store.tenant_role(session, tenant_id, caller.id)- if existing_role is None:- try:- await invitation_store.consume(session, invitation.id)- except InvitationNotUsableError as exc:- raise HTTPException(- status_code=403, detail="This invitation has already been used"- ) from exc- role = invitation.role- await user_store.add_membership(- session, tenant_id=tenant_id, user_id=caller.id, role=role+ tenant, user, role = await _join_through(+ session, invitation, caller, user_store, invitation_store+ )++ set_session_cookie(+ response, user, config.jwt_secret_key, config.gateway_cookie_secure, tenant_id+ )+ return TenantMembershipResponse(+ id=tenant.id, slug=tenant.slug, name=tenant.name, role=role+ )+++async def _join_through(+ session: AsyncSession,+ invitation: Invitation,+ caller: AuthenticatedCaller,+ user_store: UserStore,+ invitation_store: InvitationStore,+) -> tuple[Tenant, User, str]:+ """Make `caller` a member of the invitation's tenant, spending one use,+ select that tenant for them, and commit.++ `session` is bound to the invitation's tenant, and `invitation` has+ already passed `_require_invitation_usable` for this caller. Both ways of+ accepting — with the token, or by id for an invitation addressed to the+ caller — end here, so they grant membership identically.+ """+ tenant_id = invitation.tenant_id+ existing_role = await user_store.tenant_role(session, tenant_id, caller.id)+ if existing_role is None:+ try:+ await invitation_store.consume(session, invitation.id)+ except InvitationNotUsableError as exc:+ raise HTTPException(+ status_code=403, detail="This invitation has already been used"+ ) from exc+ role = invitation.role+ await user_store.add_membership(+ session, tenant_id=tenant_id, user_id=caller.id, role=role+ )+ # Only on the branch that actually joined someone. A caller who+ # was already a member takes the `else` below and has accepted+ # nothing — reporting it there would count re-clicking a link as+ # onboarding.+ emit_safely(+ current_telemetry(),+ "invitation_accepted",+ {"age_hours": age_hours(invitation.created_at)},+ )+ else:+ role = existing_role++ tenant, user = await _enter(session, tenant_id, caller, user_store)+ return tenant, user, role+++async def _enter(+ session: AsyncSession,+ tenant_id: str,+ caller: AuthenticatedCaller,+ user_store: UserStore,+) -> tuple[Tenant, User]:+ """Select the tenant `session` is bound to for `caller`, and commit.++ The last step of every way of joining a workspace, run once the caller is+ a member of it.+ """+ tenant = await session.get(Tenant, tenant_id)+ assert tenant is not None+ # `users` is global, so the caller's row is writable from a session+ # bound to any tenant — this one included.+ user = await user_store.get(session, caller.id)+ if user is None:+ raise HTTPException(status_code=401, detail="User not found")+ await user_store.record_last_tenant(session, user, tenant_id)+ await session.commit()+ return tenant, user++[email protected]("/invitations/mine")+async def list_my_invitations(+ caller: Annotated[AuthenticatedCaller, Depends(get_authenticated_caller)],+ session_factory: Annotated[+ async_sessionmaker[AsyncSession], Depends(get_session_factory)+ ],+ user_store: Annotated[UserStore, Depends(get_user_store)],+ invitation_store: Annotated[InvitationStore, Depends(get_invitation_store)],+) -> list[AddressedInvitation]:+ """The live invitations addressed to the caller's own e-mail, in+ workspaces they do not already belong to.++ Authenticated without a tenant, like `accept_invitation`: these are+ invitations to workspaces the caller is not in, so no session they could+ hold is bound to them. `tenants_with_invitations_for` names the tenants;+ each is then read on its own bound session, one after another.++ The address is the caller's, as their account holds it. An account's+ address is either asserted verified by the identity provider or set by+ the operator who created it (`gateway_oidc_require_email_verified`), so+ an invitation addressed to it is theirs to see.+ """+ found: list[AddressedInvitation] = []+ for tenant_id in await tenants_with_invitations_for(session_factory, caller.email):+ async with tenant_session(session_factory, tenant_id) as session:+ if await user_store.tenant_role(session, tenant_id, caller.id) is not None:+ continue+ invitations = await invitation_store.list_live_addressed_to(+ session, tenant_id, caller.email)- # Only on the branch that actually joined someone. A caller who- # was already a member takes the `else` below and has accepted- # nothing — reporting it there would count re-clicking a link as- # onboarding.- emit_safely(- current_telemetry(),- "invitation_accepted",- {"age_hours": age_hours(invitation.created_at)},+ if not invitations:+ continue+ tenant = await session.get(Tenant, tenant_id)+ assert tenant is not None+ for invitation in invitations:+ inviter = await user_store.get(session, invitation.created_by)+ assert inviter is not None+ found.append(+ AddressedInvitation(+ id=invitation.id,+ tenant_id=tenant.id,+ tenant_slug=tenant.slug,+ tenant_name=tenant.name,+ role=invitation.role,+ expires_at=str(invitation.expires_at),+ invited_by=inviter.name,+ created_at=str(invitation.created_at),+ )+ )+ return found++[email protected]("/invitations/mine/accept")+async def accept_my_invitation(+ req: AddressedInvitationAcceptRequest,+ response: Response,+ caller: Annotated[AuthenticatedCaller, Depends(get_authenticated_caller)],+ session_factory: Annotated[+ async_sessionmaker[AsyncSession], Depends(get_session_factory)+ ],+ user_store: Annotated[UserStore, Depends(get_user_store)],+ invitation_store: Annotated[InvitationStore, Depends(get_invitation_store)],+ config: Annotated[SwitchConfig, Depends(get_config)],+) -> TenantMembershipResponse:+ """Accept an invitation addressed to the caller, by id, without its token,+ and switch the caller's session into its workspace.++ Only for an invitation that names the caller's address: that address is+ what stands in for the token. A shareable link names no one, so its id+ alone grants nothing, and it is answered as not found — as is an+ invitation addressed to someone else, so an id does not confirm that an+ invitation exists. Everything past that is `accept_invitation`'s.+ """+ async with tenant_session(session_factory, req.tenant_id) as session:+ invitation = await invitation_store.get_in_tenant(+ session, req.tenant_id, req.invitation_id+ )+ if (+ invitation is None+ or invitation.email is None+ or invitation.email.lower() != caller.email.lower()+ ):+ raise HTTPException(status_code=404, detail="Invitation not found")+ _require_invitation_usable(invitation, caller.email)+ tenant, user, role = await _join_through(+ session, invitation, caller, user_store, invitation_store+ )++ set_session_cookie(+ response,+ user,+ config.jwt_secret_key,+ config.gateway_cookie_secure,+ req.tenant_id,+ )+ return TenantMembershipResponse(+ id=tenant.id, slug=tenant.slug, name=tenant.name, role=role+ )+++# ── Joining by e-mail domain ──────────────────────────────────────────────────+++def _join_domain_detail(row: TenantJoinDomain) -> JoinDomainDetail:+ return JoinDomainDetail(+ domain=row.domain, created_by=row.created_by, created_at=str(row.created_at)+ )++[email protected]("/tenants/{tenant_id}/join-domains")+async def list_join_domains(+ tenant_id: str,+ session: Annotated[AsyncSession, Depends(get_session)],+ join_domain_store: Annotated[JoinDomainStore, Depends(get_join_domain_store)],+ user: Annotated[User, Depends(require_tenant_admin)],+) -> JoinDomainsResponse:+ """The e-mail domains the bound tenant lets people join from, and whether+ the caller could add their own. `owner`/`admin` only."""+ _require_bound_tenant(tenant_id)+ own_domain = email_domain(user.email)+ rows = await join_domain_store.list_for_tenant(session, tenant_id)+ return JoinDomainsResponse(+ domains=[_join_domain_detail(row) for row in rows],+ own_domain=own_domain,+ own_domain_refusal=join_domain_refusal(own_domain),+ )++[email protected]("/tenants/{tenant_id}/join-domains", status_code=201)+async def add_join_domain(+ tenant_id: str,+ req: JoinDomainCreateRequest,+ session: Annotated[AsyncSession, Depends(get_session)],+ join_domain_store: Annotated[JoinDomainStore, Depends(get_join_domain_store)],+ user: Annotated[User, Depends(require_tenant_admin)],+) -> JoinDomainDetail:+ """Let anyone signed in with an address at a domain join the bound tenant+ as a member, without an invitation. `owner`/`admin` only.++ Only the domain of the admin's own address. That is the proof the domain+ is theirs to open: their account's address is either asserted verified by+ the identity provider or set by the operator who created the account. A+ public e-mail provider's domain is refused even then, since nobody's+ address there says anything about who else has one.+ """+ _require_bound_tenant(tenant_id)+ domain = req.domain.strip().lower()+ own_domain = email_domain(user.email)+ if domain != own_domain:+ raise HTTPException(+ status_code=400,+ detail=(+ f"You can only open the workspace to the domain of your own "+ f"address, {own_domain}"+ ),+ )+ refusal = join_domain_refusal(domain)+ if refusal is not None:+ raise HTTPException(status_code=400, detail=refusal.capitalize())+ try:+ row = await join_domain_store.add(session, domain=domain, created_by=user.id)+ except JoinDomainAlreadyAdded as exc:+ raise HTTPException(+ status_code=409, detail=f"The workspace is already open to {domain}"+ ) from exc+ await session.commit()+ return _join_domain_detail(row)++[email protected]("/tenants/{tenant_id}/join-domains/{domain}", status_code=204)+async def remove_join_domain(+ tenant_id: str,+ domain: str,+ session: Annotated[AsyncSession, Depends(get_session)],+ join_domain_store: Annotated[JoinDomainStore, Depends(get_join_domain_store)],+ _user: Annotated[User, Depends(require_tenant_admin)],+) -> None:+ """Stop letting people at a domain join the bound tenant. `owner`/`admin`+ only, and any domain: closing a workspace needs no proof of anything.+ Members who already joined stay members."""+ _require_bound_tenant(tenant_id)+ try:+ await join_domain_store.remove(session, tenant_id, domain)+ except JoinDomainNotFound as exc:+ raise HTTPException(+ status_code=404, detail=f"The workspace is not open to {domain}"+ ) from exc+ await session.commit()++[email protected]("/joinable-tenants")+async def list_joinable_tenants(+ caller: Annotated[AuthenticatedCaller, Depends(get_authenticated_caller)],+ session_factory: Annotated[+ async_sessionmaker[AsyncSession], Depends(get_session_factory)+ ],+ user_store: Annotated[UserStore, Depends(get_user_store)],+) -> list[JoinableTenant]:+ """The workspaces open to the domain of the caller's own address, that+ they do not already belong to.++ Authenticated without a tenant, like `list_my_invitations` and for the+ same reason: none of these is a workspace any session of theirs is bound+ to. `tenants_open_to` names the tenants; each is read on its own bound+ session.+ """+ domain = email_domain(caller.email)+ found: list[JoinableTenant] = []+ for tenant_id in await tenants_open_to(session_factory, domain):+ async with tenant_session(session_factory, tenant_id) as session:+ if await user_store.tenant_role(session, tenant_id, caller.id) is not None:+ continue+ tenant = await session.get(Tenant, tenant_id)+ assert tenant is not None+ found.append(+ JoinableTenant(+ tenant_id=tenant.id,+ tenant_slug=tenant.slug,+ tenant_name=tenant.name,+ domain=domain,+ ))- else:- role = existing_role+ return found- tenant = await session.get(Tenant, tenant_id)- assert tenant is not None- await session.commit()[email protected]("/joinable-tenants/{tenant_id}/join")+async def join_tenant_by_domain(+ tenant_id: str,+ response: Response,+ caller: Annotated[AuthenticatedCaller, Depends(get_authenticated_caller)],+ session_factory: Annotated[+ async_sessionmaker[AsyncSession], Depends(get_session_factory)+ ],+ user_store: Annotated[UserStore, Depends(get_user_store)],+ join_domain_store: Annotated[JoinDomainStore, Depends(get_join_domain_store)],+ config: Annotated[SwitchConfig, Depends(get_config)],+) -> TenantMembershipResponse:+ """Join a workspace open to the domain of the caller's address, as a+ member, and switch the caller's session into it.++ A workspace that is not open to that domain is answered as not found, so+ the route does not confirm that a workspace exists. Joining one you are+ already in returns your existing role and changes nothing.+ """+ domain = email_domain(caller.email)+ async with tenant_session(session_factory, tenant_id) as session:+ if not await join_domain_store.is_open_to(session, tenant_id, domain):+ raise HTTPException(status_code=404, detail="Workspace not found")+ role = await user_store.tenant_role(session, tenant_id, caller.id)+ if role is None:+ role = "member"+ await user_store.add_membership(+ session, tenant_id=tenant_id, user_id=caller.id, role=role+ )+ tenant, user = await _enter(session, tenant_id, caller, user_store)++ set_session_cookie(+ response, user, config.jwt_secret_key, config.gateway_cookie_secure, tenant_id+ )return TenantMembershipResponse(id=tenant.id, slug=tenant.slug, name=tenant.name, role=role)diff --git a/core/switch_core/main.py b/core/switch_core/main.pyindex 9f3119d6e..9ff1207d9 100644--- a/core/switch_core/main.py+++ b/core/switch_core/main.py@@ -46,10 +46,14 @@ from switch_core.bridges.agent.server_connectors.opencode.connector import (OpenCodeConnectionConfig,OpenCodeConnector,)+from switch_core.bridges.collaboration.adapter import SupportsSharedConnectionfrom switch_core.bridges.collaboration.discord.adapter import (DiscordAdapter,DiscordConnectionConfig,)+from switch_core.bridges.collaboration.discord.connection import DiscordConnection+from switch_core.bridges.collaboration.discord.gateway import DiscordGatewayClient+from switch_core.bridges.collaboration.discord.install import DiscordAppInstallerfrom switch_core.bridges.collaboration.install import MessagingInstallerRegistryfrom switch_core.bridges.collaboration.install_routes import (create_messaging_install_router,@@ -100,11 +104,13 @@ from switch_core.db.stores.agent_session_store import AgentSessionStorefrom switch_core.db.stores.agent_store import AgentStorefrom switch_core.db.stores.api_key_store import ApiKeyStorefrom switch_core.db.stores.bridge_message_map_store import BridgeMessageMapStore+from switch_core.db.stores.budget_store import BudgetStorefrom switch_core.db.stores.client_store import ClientStorefrom switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStorefrom switch_core.db.stores.document_store import DocumentStorefrom switch_core.db.stores.external_user_store import ExternalUserStorefrom switch_core.db.stores.invitation_store import InvitationStore+from switch_core.db.stores.join_domain_store import JoinDomainStorefrom switch_core.db.stores.media_store import MediaStorefrom switch_core.db.stores.message_store import MessageStorefrom switch_core.db.stores.messaging_event_store import MessagingEventReceiptStore@@ -120,10 +126,12 @@ from switch_core.db.stores.server_connector_store import ServerConnectorStorefrom switch_core.db.stores.task_store import TaskStorefrom switch_core.db.stores.template_store import TemplateStorefrom switch_core.db.stores.tenant_store import TenantStore+from switch_core.db.stores.usage_store import UsageStorefrom switch_core.db.stores.user_store import UserStorefrom switch_core.db.tenant_lookup import all_tenant_idsfrom switch_core.gateway.app import create_gateway_appfrom switch_core.gateway.auth import hash_password+from switch_core.gateway.invite_mail import SmtpInviteMailerfrom switch_core.logging_config import configure_loggingfrom switch_core.messages.notify import MessageListenerfrom switch_core.observability.bootstrap import (@@ -380,6 +388,7 @@ async def run(config: SwitchConfig) -> None:user_store = UserStore()api_key_store = ApiKeyStore()invitation_store = InvitationStore()+ join_domain_store = JoinDomainStore()tenant_store = TenantStore()reference_store = ReferenceStore()reference_type_store = ReferenceTypeStore()@@ -389,6 +398,8 @@ async def run(config: SwitchConfig) -> None:room_group_store = RoomGroupStore()room_role_store = RoomRoleStore()message_store = MessageStore()+ usage_store = UsageStore()+ budget_store = BudgetStore()media_store = MediaStore()template_store = TemplateStore()@@ -470,6 +481,7 @@ async def run(config: SwitchConfig) -> None:config=config,room_store=room_store,message_store=message_store,+ usage_store=usage_store,media_store=media_store,listener=message_listener,invites=invites,@@ -610,6 +622,16 @@ async def run(config: SwitchConfig) -> None:signing_secret=config.slack_app_signing_secret,))+ if config.discord_app_client_id:+ assert config.discord_app_client_secret is not None+ assert config.discord_app_application_id is not None+ installers.register(+ DiscordAppInstaller(+ client_id=config.discord_app_client_id,+ client_secret=config.discord_app_client_secret,+ application_id=config.discord_app_application_id,+ )+ )install_service: MessagingInstallService | None = Noneif installers.platforms():@@ -641,10 +663,18 @@ async def run(config: SwitchConfig) -> None:external_user_store=external_user_store,api_key_store=api_key_store,invitation_store=invitation_store,+ join_domain_store=join_domain_store,template_store=template_store,+ usage_store=usage_store,+ budget_store=budget_store,resource_service=resource_service,protocol=protocol,install_service=install_service,+ invite_mailer=(+ SmtpInviteMailer.from_config(config)+ if config.invite_email_enabled+ else None+ ),config=config,)@@ -772,8 +802,51 @@ async def run(config: SwitchConfig) -> None:# ── Start runtime ────────────────────────────────────────────────────────await client_lifecycle.start_all()+ # Before the bridges start, so none on a shared app runs without the+ # install that entitles it.+ if install_service is not None:+ collab_lifecycle.add_bridge_start_guard(+ install_service.refuse_uninstalled_bridge+ )await collab_lifecycle.start_all()+ # The one shared Discord Gateway connection. Started after the bridges so it+ # can attach to the inert ones the moment it connects — a shared-delivery+ # bridge opens no socket of its own, and attaching re-runs the agent-identity+ # provisioning that could not run at start. Supervised in the background: a+ # configured-but-unreachable Discord app must never block or fail a boot that+ # serves every other platform, so its initial connect retries with backoff+ # and Discord installs stay inert until it succeeds.+ discord_gateway: DiscordGatewayClient | None = None+ discord_gateway_task: asyncio.Task[None] | None = None+ if config.discord_app_bot_token:+ # install_service is present whenever an installer is registered, and the+ # Discord bot token being set means the Discord installer is — so this is+ # not None here. Asserted rather than branched to say that out loud.+ assert install_service is not None++ async def _attach_shared_discord_bridges(+ connection: DiscordConnection,+ ) -> None:+ # Runs once the socket is up: hand it to every already-running bridge+ # that rides a shared connection. Platform-agnostic — narrowed by+ # capability, not by knowing which platform that is.+ for adapter in collab_lifecycle.iter_adapters():+ if isinstance(adapter, SupportsSharedConnection):+ adapter.attach_shared_connection(connection)++ discord_gateway = DiscordGatewayClient(+ bot_token=config.discord_app_bot_token,+ message_content=config.discord_app_message_content,+ members=config.discord_app_members,+ install_service=install_service,+ on_connected=_attach_shared_discord_bridges,+ )+ collab_lifecycle.add_bridge_starting_listener(discord_gateway.attach_if_live)+ discord_gateway_task = asyncio.create_task(+ discord_gateway.start_with_retry(), name="discord-gateway-start"+ )+# Backfill room membership: system clients (e.g. the admin client) added# after a room was created, and any agent whose invite did not land. The# just-started clients accept the invites on their first sync.@@ -807,6 +880,8 @@ async def run(config: SwitchConfig) -> None:collab_lifecycle,connector_lifecycle,matrix_admin,+ discord_gateway,+ discord_gateway_task,)),)@@ -1254,11 +1329,23 @@ async def _shutdown(collab_lifecycle: CollaborationBridgeLifecycleService,connector_lifecycle: ServerSideConnectorLifecycleService,matrix_admin: Provisioning,+ discord_gateway: DiscordGatewayClient | None,+ discord_gateway_task: asyncio.Task[None] | None,) -> None:logger.info("Shutting down...")server.should_exit = Trueawait connector_lifecycle.stop_all()await collab_lifecycle.stop_all()+ # Cancel the supervised connect/retry loop before closing the socket, so a+ # retry in flight cannot re-open what stop() just closed.+ if discord_gateway_task is not None:+ discord_gateway_task.cancel()+ try:+ await discord_gateway_task+ except asyncio.CancelledError:+ pass+ if discord_gateway is not None:+ await discord_gateway.stop()await client_lifecycle.stop_all()await matrix_admin.close()diff --git a/core/switch_core/migrations/versions/4b8e2d61c9f7_tenants_inviting_email.py b/core/switch_core/migrations/versions/4b8e2d61c9f7_tenants_inviting_email.pynew file mode 100644index 000000000..e5bc1d98b--- /dev/null+++ b/core/switch_core/migrations/versions/4b8e2d61c9f7_tenants_inviting_email.py@@ -0,0 +1,48 @@+"""tenants_inviting_email: which workspaces have invited an address++A person signed in to Switch can be shown the invitations addressed to them+and accept one without the link. Listing those means reading `invitations`+across every tenant that might hold one, before any of them is bound — the+read row-level security refuses to a session with nothing bound. This adds the+tenth lookup to the exemption: it answers which tenants hold a live+invitation addressed to an e-mail, and the gateway then binds each tenant and+reads its invitations through the scoped store. See `db/tenant_lookup.py` for+what the exemption discloses and why this one is argued for.++The lookup DDL below is a verbatim copy of `switch_core/db/tenant_lookup.py`+as it stood when this migration was written, copied rather than imported so a+later edit to the module cannot change what this revision means.+`tests/switch_core/db/test_tenant_lookup.py` keeps the copy honest.++Revision ID: 4b8e2d61c9f7+Revises: 60b934c4c034+Create Date: 2026-09-28 00:00:00.000000++"""++from collections.abc import Sequence++from alembic import op++revision: str = "4b8e2d61c9f7"+down_revision: str | None = "60b934c4c034"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None++SECURE_SEARCH_PATH = "pg_catalog, public, pg_temp"++CREATE_TENANTS_INVITING_EMAIL = f"""CREATE OR REPLACE FUNCTION tenants_inviting_email(p_email text)+ RETURNS SETOF text+ LANGUAGE sql STABLE SECURITY DEFINER+ SET search_path = {SECURE_SEARCH_PATH}+AS $$SELECT DISTINCT tenant_id FROM invitations WHERE lower(email) = lower(p_email) AND revoked_at IS NULL AND expires_at > now() AND uses_remaining > 0 ORDER BY tenant_id$$"""++DROP_TENANTS_INVITING_EMAIL = "DROP FUNCTION IF EXISTS tenants_inviting_email(text)"+++def upgrade() -> None:+ op.execute(CREATE_TENANTS_INVITING_EMAIL)+++def downgrade() -> None:+ op.execute(DROP_TENANTS_INVITING_EMAIL)diff --git a/core/switch_core/migrations/versions/60b934c4c034_merge_agent_templates_and_usage_budgets_heads.py b/core/switch_core/migrations/versions/60b934c4c034_merge_agent_templates_and_usage_budgets_heads.pynew file mode 100644index 000000000..aa8b3d5c5--- /dev/null+++ b/core/switch_core/migrations/versions/60b934c4c034_merge_agent_templates_and_usage_budgets_heads.py@@ -0,0 +1,14 @@+"""Merge agent-saved templates and usage budgets migrations."""++revision = "60b934c4c034"+down_revision = ("d7a2e4c91b35", "e3b7c9d2a415")+branch_labels = None+depends_on = None+++def upgrade() -> None:+ pass+++def downgrade() -> None:+ passdiff --git a/core/switch_core/migrations/versions/7d3f5a19e2c8_tenant_join_domains.py b/core/switch_core/migrations/versions/7d3f5a19e2c8_tenant_join_domains.pynew file mode 100644index 000000000..d64406b5e--- /dev/null+++ b/core/switch_core/migrations/versions/7d3f5a19e2c8_tenant_join_domains.py@@ -0,0 +1,88 @@+"""tenant_join_domains, and the lookup that finds the workspaces open to a domain++A workspace can let anyone signed in with an address at a domain join it+without an invitation. `tenant_join_domains` records those domains, one row per+tenant and domain. It is tenant-scoped like every other table and brings its+own `tenant_isolation` policy, for the reason `5daaea6b674d` gives.++Offering those workspaces to someone means reading the table across every+tenant before any is bound, so this also adds the eleventh lookup to the+exemption from row-level security: `tenants_open_to_domain` answers which+tenants are open to a domain, and the gateway then binds each and reads it+through the scoped store. See `db/tenant_lookup.py` for what it discloses and+why it is argued for.++The DDL below is a verbatim copy of `switch_core/db/rls_ddl.py` and+`switch_core/db/tenant_lookup.py` as they stood when this migration was+written, copied rather than imported so a later edit to either module cannot+change what this revision means.++Revision ID: 7d3f5a19e2c8+Revises: 4b8e2d61c9f7+Create Date: 2026-09-28 00:00:00.000000++"""++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op++revision: str = "7d3f5a19e2c8"+down_revision: str | None = "4b8e2d61c9f7"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None++TABLE = "tenant_join_domains"+POLICY_NAME = "tenant_isolation"++ENABLE_RLS = f'ALTER TABLE "{TABLE}" ENABLE ROW LEVEL SECURITY'++CREATE_POLICY = f"""CREATE POLICY {POLICY_NAME} ON "{TABLE}"+ FOR ALL+ USING ("tenant_id" = (SELECT require_tenant_id()))+ WITH CHECK ("tenant_id" = (SELECT require_tenant_id()))"""++DROP_POLICY = f'DROP POLICY IF EXISTS {POLICY_NAME} ON "{TABLE}"'++SECURE_SEARCH_PATH = "pg_catalog, public, pg_temp"++CREATE_TENANTS_OPEN_TO_DOMAIN = f"""CREATE OR REPLACE FUNCTION tenants_open_to_domain(p_domain text)+ RETURNS SETOF text+ LANGUAGE sql STABLE SECURITY DEFINER+ SET search_path = {SECURE_SEARCH_PATH}+AS $$SELECT tenant_id FROM tenant_join_domains WHERE domain = lower(p_domain) ORDER BY tenant_id$$"""++DROP_TENANTS_OPEN_TO_DOMAIN = "DROP FUNCTION IF EXISTS tenants_open_to_domain(text)"+++def upgrade() -> None:+ op.create_table(+ TABLE,+ sa.Column("tenant_id", sa.Text(), nullable=False),+ sa.Column("domain", sa.Text(), nullable=False),+ sa.Column("created_by", sa.Text(), nullable=False),+ sa.Column(+ "created_at",+ sa.DateTime(timezone=True),+ server_default=sa.text("now()"),+ nullable=False,+ ),+ sa.CheckConstraint(+ "domain = lower(domain)", name="ck_tenant_join_domains_lower_case"+ ),+ sa.PrimaryKeyConstraint("tenant_id", "domain"),+ sa.ForeignKeyConstraint(+ ["tenant_id"], ["tenants.id"], name="fk_tenant_join_domains_tenant"+ ),+ sa.ForeignKeyConstraint(["created_by"], ["users.id"]),+ )+ op.execute(ENABLE_RLS)+ op.execute(CREATE_POLICY)+ op.execute(CREATE_TENANTS_OPEN_TO_DOMAIN)+++def downgrade() -> None:+ op.execute(DROP_TENANTS_OPEN_TO_DOMAIN)+ op.execute(DROP_POLICY)+ op.drop_table(TABLE)diff --git a/core/switch_core/migrations/versions/a9e1c3f75b20_merge_tenant_join_domains_and_preconfigured_bridges_heads.py b/core/switch_core/migrations/versions/a9e1c3f75b20_merge_tenant_join_domains_and_preconfigured_bridges_heads.pynew file mode 100644index 000000000..aef30c6cd--- /dev/null+++ b/core/switch_core/migrations/versions/a9e1c3f75b20_merge_tenant_join_domains_and_preconfigured_bridges_heads.py@@ -0,0 +1,14 @@+"""Merge tenant join domains and preconfigured collaboration bridges migrations."""++revision = "a9e1c3f75b20"+down_revision = ("7d3f5a19e2c8", "f4c8a2d61e93")+branch_labels = None+depends_on = None+++def upgrade() -> None:+ pass+++def downgrade() -> None:+ passdiff --git a/core/switch_core/migrations/versions/c7e4a91d3b20_tenant_usage.py b/core/switch_core/migrations/versions/c7e4a91d3b20_tenant_usage.pynew file mode 100644index 000000000..44573b964--- /dev/null+++ b/core/switch_core/migrations/versions/c7e4a91d3b20_tenant_usage.py@@ -0,0 +1,75 @@+"""per-tenant usage, counted as it happens++Revision ID: c7e4a91d3b20+Revises: c4e9a1f7b203++The metering record quotas are enforced against and billing will read: one row+per tenant, metric, hour, consumer and model, incremented in the same+transaction as the message or turn it counts (CHOO-2625).++It is a table of its own rather than a count over ``messages`` because usage+must outlive what it counts: deleting a room cascades to its messages, and a+tenant's spend cannot shrink when it tidies up. Nothing here can be backfilled+— counting starts when this migration runs.++Buckets are an hour wide so that a budget period can be any whole number of+hours; the key leads on the metric so the question a budget asks, "this+tenant's turns since a moment", is a range scan on the key itself.++``client_id`` carries no foreign key, so a count outlives the client it names.++The row-level-security DDL is a verbatim copy of ``switch_core/db/rls_ddl.py``+as it stood when this migration was written, copied rather than imported for+the reason ``265ed188ad6f`` gives.+"""++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op++revision: str = "c7e4a91d3b20"+down_revision: str | Sequence[str] | None = "c4e9a1f7b203"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None++REQUIRE_TENANT_FUNCTION_NAME = "require_tenant_id"+POLICY_NAME = "tenant_isolation"++_PREDICATE = f'"tenant_id" = (SELECT {REQUIRE_TENANT_FUNCTION_NAME}())'+_CREATE_POLICY = (+ f'CREATE POLICY {POLICY_NAME} ON "tenant_usage"\n'+ f" FOR ALL\n"+ f" USING ({_PREDICATE})\n"+ f" WITH CHECK ({_PREDICATE})"+)+++def upgrade() -> None:+ op.create_table(+ "tenant_usage",+ sa.Column("tenant_id", sa.Text(), nullable=False),+ sa.Column("metric", sa.Text(), nullable=False),+ sa.Column("bucket_start", sa.DateTime(timezone=True), nullable=False),+ sa.Column("client_id", sa.Text(), nullable=False),+ sa.Column("model", sa.Text(), nullable=False),+ sa.Column("amount", sa.BigInteger(), nullable=False),+ sa.ForeignKeyConstraint(+ ["tenant_id"], ["tenants.id"], name="fk_tenant_usage_tenant"+ ),+ sa.PrimaryKeyConstraint(+ "tenant_id", "metric", "bucket_start", "client_id", "model"+ ),+ sa.CheckConstraint(+ "metric IN ('messages', 'turns', 'input_tokens', 'output_tokens', 'cache_read_tokens', 'cache_write_tokens')",+ name="ck_tenant_usage_metric",+ ),+ sa.CheckConstraint("amount > 0", name="ck_tenant_usage_amount"),+ )+ op.execute('ALTER TABLE "tenant_usage" ENABLE ROW LEVEL SECURITY')+ op.execute(_CREATE_POLICY)+++def downgrade() -> None:+ op.execute(f'DROP POLICY IF EXISTS {POLICY_NAME} ON "tenant_usage"')+ op.drop_table("tenant_usage")diff --git a/core/switch_core/migrations/versions/e3b7c9d2a415_usage_budgets.py b/core/switch_core/migrations/versions/e3b7c9d2a415_usage_budgets.pynew file mode 100644index 000000000..2f56507eb--- /dev/null+++ b/core/switch_core/migrations/versions/e3b7c9d2a415_usage_budgets.py@@ -0,0 +1,112 @@+"""usage budgets: a ceiling on a metric over a repeating period++Revision ID: e3b7c9d2a415+Revises: c7e4a91d3b20++A budget caps one metric of ``tenant_usage`` for a whole tenant or for one+agent, optionally for one model, over a period of whole hours. An agent that+has reached a budget covering it is stopped until the period turns over. A+tenant with no budgets is unlimited, so nothing changes for existing tenants+when this runs.++Two partial unique indexes stand in for one unique constraint: ``agent_id`` is+null for a tenant-wide budget, and nulls never collide in a plain constraint.++The row-level-security DDL is a verbatim copy of ``switch_core/db/rls_ddl.py``+as it stood when this migration was written, copied rather than imported for+the reason ``265ed188ad6f`` gives.+"""++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op++revision: str = "e3b7c9d2a415"+down_revision: str | Sequence[str] | None = "c7e4a91d3b20"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None++REQUIRE_TENANT_FUNCTION_NAME = "require_tenant_id"+POLICY_NAME = "tenant_isolation"++_PREDICATE = f'"tenant_id" = (SELECT {REQUIRE_TENANT_FUNCTION_NAME}())'+_CREATE_POLICY = (+ f'CREATE POLICY {POLICY_NAME} ON "usage_budgets"\n'+ f" FOR ALL\n"+ f" USING ({_PREDICATE})\n"+ f" WITH CHECK ({_PREDICATE})"+)++_METRICS = (+ "messages",+ "turns",+ "input_tokens",+ "output_tokens",+ "cache_read_tokens",+ "cache_write_tokens",+)+++def upgrade() -> None:+ op.create_table(+ "usage_budgets",+ sa.Column("tenant_id", sa.Text(), nullable=False),+ sa.Column("id", sa.Text(), nullable=False),+ sa.Column("agent_id", sa.Text(), nullable=True),+ sa.Column("metric", sa.Text(), nullable=False),+ sa.Column("model", sa.Text(), nullable=False),+ sa.Column("amount_limit", sa.BigInteger(), nullable=False),+ sa.Column("period_hours", sa.Integer(), nullable=False),+ sa.Column(+ "created_at",+ sa.DateTime(timezone=True),+ server_default=sa.text("now()"),+ nullable=False,+ ),+ sa.ForeignKeyConstraint(+ ["tenant_id"], ["tenants.id"], name="fk_usage_budgets_tenant"+ ),+ sa.ForeignKeyConstraint(+ ["tenant_id", "agent_id"],+ ["agents.tenant_id", "agents.id"],+ name="fk_usage_budgets_agent",+ ondelete="CASCADE",+ ),+ sa.CheckConstraint(+ "metric IN ({})".format(", ".join(f"'{m}'" for m in _METRICS)),+ name="ck_usage_budgets_metric",+ ),+ sa.CheckConstraint(+ "amount_limit > 0 AND amount_limit <= 9007199254740991",+ name="ck_usage_budgets_amount_limit",+ ),+ sa.CheckConstraint(+ "period_hours > 0 AND period_hours <= 8784",+ name="ck_usage_budgets_period_hours",+ ),+ sa.PrimaryKeyConstraint("id"),+ )+ op.create_index(+ "uq_usage_budgets_tenant_wide",+ "usage_budgets",+ ["tenant_id", "metric", "model"],+ unique=True,+ postgresql_where=sa.text("agent_id IS NULL"),+ )+ op.create_index(+ "uq_usage_budgets_agent",+ "usage_budgets",+ ["tenant_id", "agent_id", "metric", "model"],+ unique=True,+ postgresql_where=sa.text("agent_id IS NOT NULL"),+ )+ op.execute('ALTER TABLE "usage_budgets" ENABLE ROW LEVEL SECURITY')+ op.execute(_CREATE_POLICY)+++def downgrade() -> None:+ op.execute(f'DROP POLICY IF EXISTS {POLICY_NAME} ON "usage_budgets"')+ op.drop_index("uq_usage_budgets_agent", table_name="usage_budgets")+ op.drop_index("uq_usage_budgets_tenant_wide", table_name="usage_budgets")+ op.drop_table("usage_budgets")diff --git a/core/switch_core/room_service.py b/core/switch_core/room_service.pyindex 199ae4d18..8523e5eaf 100644--- a/core/switch_core/room_service.py+++ b/core/switch_core/room_service.py@@ -127,7 +127,9 @@ class RoomCreateConfig(BaseModel):acting_user_id: str | None = Noneacting_is_admin: bool = False# Not derivable from `created_by`, which holds the *agent's owner* on the- # agent path. Stamped into the room's metadata so it survives.+ # agent path. Stamped into the room's metadata so it survives. `system` is+ # a channel the platform delivered to the bridge, so it is the one kind+ # whose `external_channel_id` the bridge is not asked to vouch for.created_by_kind: Literal["user", "agent", "system"] = "user"# Provisioned from a room template rather than created directly.from_template: bool = False@@ -373,6 +375,20 @@ class RoomService:)return default.id+ async def _require_tenant_bridge(self, bridge_id: str) -> None:+ """Refuse a bridge id that is not one of the bound tenant's bridges.++ The collaboration lifecycle's registry of running bridges is+ process-wide and holds every tenant's, so finding a bridge there says+ nothing about whether this caller may use it. The bridge's row, read+ under the tenant's row-level security, does. Checked before anything+ is provisioned on the platform behind it.+ """+ async with self._session_factory() as session:+ bridge = await self._collab_bridge_store.get(session, bridge_id)+ if bridge is None:+ raise ValueError(f"Bridge not found: {bridge_id}")+async def _require_channel_creation(self, bridge_id: str) -> None:"""Refuse to make a channel on a connection an operator has withheld itfrom, before anything is provisioned.@@ -384,7 +400,9 @@ class RoomService:"""async with self._session_factory() as session:bridge = await self._collab_bridge_store.get(session, bridge_id)- if bridge is None or bridge.channel_creation_enabled:+ if bridge is None:+ raise ValueError(f"Bridge not found: {bridge_id}")+ if bridge.channel_creation_enabled:returnraise ChannelCreationUnsupported(f"Creating channels is turned off for the '{bridge.display_name}' "@@ -471,10 +489,20 @@ class RoomService:bridge_id = await self._resolve_bridge_id(config)bridge_core = Noneif bridge_id:+ await self._require_tenant_bridge(bridge_id)bridge_core = self._collab_lifecycle.get(bridge_id)if bridge_core is None:raise ValueError(f"Bridge not running: {bridge_id}")+ # A channel the platform delivered to this bridge is its own by+ # construction; one named by the caller has to be shown to be.+ if (+ bridge_core+ and external_channel_id is not None+ and config.created_by_kind != "system"+ ):+ await bridge_core.adapter.require_bindable_channel(external_channel_id)+if bridge_core and external_channel_id is not None and channel_type is None:channel_type = await bridge_core.adapter.get_channel_type(external_channel_id@@ -1133,6 +1161,7 @@ class RoomService:if room is None:raise ValueError(f"Room not found: {room_id}")+ await self._require_tenant_bridge(bridge_id)bridge_core = self._collab_lifecycle.get(bridge_id)if external_channel_id is None and bridge_core is not None:@@ -1199,7 +1228,8 @@ class RoomService:back onto a channel it previously used (channels are left in place onbridge change, so the old one still exists). The caller is responsiblefor the id being a real channel on that bridge whose bridge bot is a- member; agents are still (re-)added to it.+ member, and the bridge refuses one that is not its own to bind+ (`require_bindable_channel`); agents are still (re-)added to it.Human users are **not** carried over. A user's identity isbridge-specific (a Mattermost account is not the same as a Slack@@ -1229,6 +1259,7 @@ class RoomService:if old_bridge_id == bridge_id:raise ValueError(f"Room {room_id} is already bound to bridge {bridge_id}")+ await self._require_tenant_bridge(bridge_id)new_bridge = self._collab_lifecycle.get(bridge_id)if new_bridge is None:raise ValueError(f"Bridge not running: {bridge_id}")@@ -1246,6 +1277,8 @@ class RoomService:room.description,channel_type=resolved_channel_type,)+ else:+ await new_bridge.adapter.require_bindable_channel(external_channel_id)# One binding for everything from here on: the bridge-column update,# and the invite/kick below, both write rows scoped to this room's@@ -1444,6 +1477,7 @@ class RoomService:Raises when the bridge is not running, since nothing can be looked upon it then."""+ await self._require_tenant_bridge(bridge_id)bridge_core = self._collab_lifecycle.get(bridge_id)if bridge_core is None:raise ValueError("the room's messaging app is not running")diff --git a/core/switch_core/session_activity/service.py b/core/switch_core/session_activity/service.pyindex 9c9793090..6d5362891 100644--- a/core/switch_core/session_activity/service.py+++ b/core/switch_core/session_activity/service.py@@ -16,6 +16,7 @@ from dataclasses import dataclassfrom datetime import UTC, datetime, timedeltafrom typing import Any, Literal+from sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.addressing import allows_on_behalf_of, parse_policy@@ -25,6 +26,7 @@ from switch_core.db.models import (Agent,ApprovalRequest,SessionActivityItem,+ UsageMetric,require_tenant_id,)from switch_core.db.session_scope import tenant_session@@ -38,8 +40,10 @@ from switch_core.db.stores.session_activity_store import (ApprovalRequestStore,SessionActivityStore,)+from switch_core.db.stores.usage_store import UsageStorefrom switch_core.delivery.addressing import AddressingResolverfrom switch_core.sessions.contract import (+ TURN_ENDED,ApprovalResult,QuestionsResult,RequestResult,@@ -53,6 +57,10 @@ MAX_OPTIONS = 10MAX_QUESTIONS = 50MAX_QUESTION_OPTIONS = 50MAX_CUSTOM_ANSWER_CHARS = 4000+MAX_MODEL_CHARS = 200+MAX_MODELS_PER_TURN = 50+# A host counts in JavaScript numbers, exact only up to 2**53 - 1.+MAX_TOKENS = 2**53 - 1# What the host sends inside a question is not truncated by the host, so it is# cut here to what any platform can show rather than refused._QUESTION_TITLE_CHARS = 500@@ -77,6 +85,18 @@ DECISIONS: tuple[Decision, ...] = ("accept", "acceptForSession", "decline", "canRequestKind = Literal["approval", "questions"]+@dataclass(frozen=True)+class TokenSpend:+ """Tokens one model spent in a turn. `model` is empty when the provider+ ran its default without naming it."""++ model: str+ input_tokens: int+ output_tokens: int+ cache_read_tokens: int+ cache_write_tokens: int++@dataclass(frozen=True)class ApprovalOption:id: str@@ -133,6 +153,7 @@ class SessionActivityService:self._sessions = session_factoryself._approvals = ApprovalRequestStore()self._activity = SessionActivityStore()+ self._usage = UsageStore()self._rooms = RoomStore()self._external_users = ExternalUserStore()self._addressing = AddressingResolver(@@ -164,8 +185,13 @@ class SessionActivityService:thread_id: str | None,message_id: str | None,occurred_at: datetime,+ usage: list[TokenSpend],) -> bool:- """Record one step of a turn. False when a revision at least as new is stored."""+ """Record one step of a turn. False when a revision at least as new is stored.++ `usage` is what the turn spent, and only a turn's own row, reported as+ ended, carries it.+ """if kind not in SESSION_ACTIVITY_KINDS:raise SessionError("INVALID_EVENT", f"Unknown activity kind: {kind}")if status not in ITEM_STATUSES[kind]:@@ -187,6 +213,10 @@ class SessionActivityService:)if revision < 0:raise SessionError("INVALID_EVENT", "A revision is never negative.")+ if usage and not (kind == "turn" and status in TURN_ENDED):+ raise SessionError(+ "INVALID_EVENT", "Only an ended turn's own row carries its usage."+ )if len(title) > MAX_TITLE_CHARS or len(text) > MAX_TEXT_CHARS:raise SessionError("INVALID_EVENT",@@ -197,7 +227,14 @@ class SessionActivityService:async with tenant_session(self._sessions, tenant_id) as db, db.begin():if room_id is not None:await self._require_member(db, agent_id, room_id)- return await self._activity.upsert(+ prior_status = (+ await self._activity.status_for_update(+ db, agent_id, session_id, turn_id, item_id+ )+ if kind == "turn"+ else None+ )+ moved = await self._activity.upsert(db,SessionActivityItem(tenant_id=tenant_id,@@ -217,6 +254,78 @@ class SessionActivityService:occurred_at=occurred_at,),)+ if moved and kind == "turn":+ if prior_status is None:+ await self._meter_turn(db, tenant_id, agent_id)+ if status in TURN_ENDED and prior_status not in TURN_ENDED:+ await self._meter_tokens(db, tenant_id, agent_id, usage)+ return moved++ async def _meter_turn(+ self, db: AsyncSession, tenant_id: str, agent_id: str+ ) -> None:+ """Count a turn the first time its host reports it, whatever its status.++ A turn has been paid for once it exists: one that errors or is+ interrupted still spent the model's time, so counting only the ones+ that complete would under-report exactly the runaway loops a budget is+ for.+ """+ await self._usage.record(+ db,+ tenant_id=tenant_id,+ metric=UsageMetric.TURNS,+ client_id=await self._agent_client_id(db, tenant_id, agent_id),+ model="",+ amount=1,+ )++ async def _meter_tokens(+ self,+ db: AsyncSession,+ tenant_id: str,+ agent_id: str,+ usage: list[TokenSpend],+ ) -> None:+ """Count what a turn spent, once: when its row first reports it ended.++ The counts are what the host says: a customer's own agent reports on+ itself, which is enough for a budget the customer sets for itself.+ """+ if not usage:+ return+ client_id = await self._agent_client_id(db, tenant_id, agent_id)+ # One agent's turns can end concurrently; upserting the counters in the+ # same order in each keeps two of them from deadlocking.+ for spend in sorted(usage, key=lambda s: s.model):+ for metric, amount in (+ (UsageMetric.INPUT_TOKENS, spend.input_tokens),+ (UsageMetric.OUTPUT_TOKENS, spend.output_tokens),+ (UsageMetric.CACHE_READ_TOKENS, spend.cache_read_tokens),+ (UsageMetric.CACHE_WRITE_TOKENS, spend.cache_write_tokens),+ ):+ if amount > 0:+ await self._usage.record(+ db,+ tenant_id=tenant_id,+ metric=metric,+ client_id=client_id,+ model=spend.model,+ amount=amount,+ )++ @staticmethod+ async def _agent_client_id(db: AsyncSession, tenant_id: str, agent_id: str) -> str:+ """The client an agent's usage is charged to, the identity every other+ metric is counted against."""+ client_id = await db.scalar(+ select(Agent.client_id).where(+ Agent.tenant_id == tenant_id, Agent.id == agent_id+ )+ )+ if client_id is None:+ raise SessionError("NOT_FOUND", f"Agent {agent_id} does not exist.")+ return client_idasync def turn_items(self, agent_id: str, session_id: str, turn_id: strdiff --git a/core/switch_core/telemetry/catalogue.py b/core/switch_core/telemetry/catalogue.pyindex 07d2126f7..579cbfe3a 100644--- a/core/switch_core/telemetry/catalogue.py+++ b/core/switch_core/telemetry/catalogue.py@@ -428,7 +428,9 @@ CATALOGUE: Mapping[str, Mapping[str, PropertyType]] = {"bridge_platform": BRIDGE_PLATFORM,"is_preconfigured": BOOLEAN,},- "invitation_sent": {},+ "invitation_sent": {+ "delivery": one_of("sent", "not_configured", "failed", "not_requested")+ },"invitation_accepted": {"age_hours": NUMBER},"bridge_disconnected": {"bridge_platform": BRIDGE_PLATFORM,diff --git a/core/switch_core/transport/port.py b/core/switch_core/transport/port.pyindex d2f5cb825..a1e5be81c 100644--- a/core/switch_core/transport/port.py+++ b/core/switch_core/transport/port.py@@ -77,12 +77,20 @@ class MessageTransport(Protocol):body: str,*,sender_name: str,+ metered: bool,format: MessageFormat = "text",mentions: list[str] | None = None,thread_root_id: str | None = None,extra_content: dict[str, object] | None = None,) -> SendResult:- """Post a text message. Raises `TransportError` if it is not accepted."""+ """Post a text message. Raises `TransportError` if it is not accepted.++ `metered` says whether the message counts toward the tenant's usage. It+ is false for what Switch posts on a participant's behalf — greetings,+ command replies, automatic refusals — which the participant never chose+ to say. It is an argument rather than something read from the content,+ because a sender controls the content.+ """...async def send_event(@@ -103,6 +111,7 @@ class MessageTransport(Protocol):size: int,*,sender_name: str,+ metered: bool,msgtype: str,caption: str | None = None,thread_root_id: str | None = None,@@ -112,7 +121,7 @@ class MessageTransport(Protocol):`group` marks this as one part of a multi-attachment message —`{"id": ..., "index": i, "total": n}` — for transports that cannot- carry several files on one event.+ carry several files on one event. `metered` is as for `send_message`."""...diff --git a/core/switch_core/transport/postgres.py b/core/switch_core/transport/postgres.pyindex 281134861..dbef6b843 100644--- a/core/switch_core/transport/postgres.py+++ b/core/switch_core/transport/postgres.py@@ -41,7 +41,13 @@ from datetime import UTC, datetimefrom typing import TYPE_CHECKING, Anyfrom switch_core.attachments import ATTACHMENT_GROUP_KEY-from switch_core.db.models import ClientRoom, MediaBlob, Message, MessageAttachment+from switch_core.db.models import (+ ClientRoom,+ MediaBlob,+ Message,+ MessageAttachment,+ UsageMetric,+)from switch_core.db.session_scope import tenant_sessionfrom switch_core.logging_context import log_contextfrom switch_core.messages.recorded_types import EPHEMERAL@@ -80,6 +86,7 @@ if TYPE_CHECKING:from switch_core.db.stores.media_store import MediaStorefrom switch_core.db.stores.message_store import MessageStorefrom switch_core.db.stores.room_store import RoomStore+ from switch_core.db.stores.usage_store import UsageStorefrom switch_core.messages.notify import MessageListenerlogger = logging.getLogger(__name__)@@ -93,6 +100,12 @@ _DELIVERY_PAGE = 200_MEDIA_MSGTYPES = frozenset({"m.image", "m.file", "m.video", "m.audio"})+# What a tenant is metered for: something a participant said. Custom events+# are the platform's own bookkeeping — reports, state, receipts — and charging+# a tenant for them would bill it for how Switch works.+_METERED_KINDS = frozenset({"message", "media"})++def _sent_kind(event_type: str, content: dict[str, object]) -> str:"""A bounded label for what was sent.@@ -161,6 +174,7 @@ class PostgresTransport:session_factory: async_sessionmaker[AsyncSession],room_store: RoomStore,message_store: MessageStore,+ usage_store: UsageStore,media_store: MediaStore,listener: MessageListener,invites: InviteBus,@@ -186,6 +200,7 @@ class PostgresTransport:self._session_factory = session_factoryself._room_store = room_storeself._message_store = message_store+ self._usage_store = usage_storeself._media_store = media_storeself._listener = listenerself._invites = invites@@ -579,6 +594,7 @@ class PostgresTransport:body: str,*,sender_name: str,+ metered: bool,format: MessageFormat = "text",mentions: list[str] | None = None,thread_root_id: str | None = None,@@ -592,7 +608,9 @@ class PostgresTransport:thread_root_id=thread_root_id,extra_content=extra_content,)- return await self._send(room_id, "m.room.message", content, sender_name)+ return await self._send(+ room_id, "m.room.message", content, sender_name, metered=metered+ )async def send_event(self,@@ -600,7 +618,9 @@ class PostgresTransport:event_type: str,content: dict[str, object],) -> SendResult:- return await self._send(room_id, event_type, content, self.display_name)+ return await self._send(+ room_id, event_type, content, self.display_name, metered=False+ )async def send_media(self,@@ -611,6 +631,7 @@ class PostgresTransport:size: int,*,sender_name: str,+ metered: bool,msgtype: str,caption: str | None = None,thread_root_id: str | None = None,@@ -627,7 +648,9 @@ class PostgresTransport:thread_root_id=thread_root_id,group=group,)- return await self._send(room_id, "m.room.message", content, sender_name)+ return await self._send(+ room_id, "m.room.message", content, sender_name, metered=metered+ )async def _send(self,@@ -635,6 +658,8 @@ class PostgresTransport:event_type: str,content: dict[str, object],sender_name: str,+ *,+ metered: bool,) -> SendResult:"""Write the event, which is what sending it means here.@@ -685,6 +710,15 @@ class PostgresTransport:await self._message_store.create(session, message, attachments_in(content))+ if metered and kind in _METERED_KINDS:+ await self._usage_store.record(+ session,+ tenant_id=tenant_id,+ metric=UsageMetric.MESSAGES,+ client_id=self.client_id,+ model="",+ amount=1,+ )await session.commit()except Exception:# `MESSAGES_SENT` is recorded only after the commit, so withoutdiff --git a/core/tests/integration/conftest.py b/core/tests/integration/conftest.pyindex 001c21e81..cc95737b2 100644--- a/core/tests/integration/conftest.py+++ b/core/tests/integration/conftest.py@@ -76,6 +76,7 @@ from switch_core.db.stores.room_role_store import RoomRoleStorefrom switch_core.db.stores.room_store import RoomStorefrom switch_core.db.stores.task_store import TaskStorefrom switch_core.db.stores.tenant_store import TenantStore+from switch_core.db.stores.usage_store import UsageStorefrom switch_core.db.stores.user_store import UserStorefrom switch_core.main import _seed_agent_registration_bootstrap_keyfrom switch_core.messages.notify import MessageListener@@ -557,6 +558,7 @@ async def harness(session_env: SessionEnv) -> AsyncIterator[Harness]:config=config,room_store=session_env.room_store,message_store=session_env.message_store,+ usage_store=UsageStore(),media_store=session_env.media_store,listener=message_listener,invites=invites,diff --git a/core/tests/integration/test_removal_stops_delivery_e2e.py b/core/tests/integration/test_removal_stops_delivery_e2e.pyindex 08915c1ce..14180b706 100644--- a/core/tests/integration/test_removal_stops_delivery_e2e.py+++ b/core/tests/integration/test_removal_stops_delivery_e2e.py@@ -93,7 +93,9 @@ async def test_removal_stops_every_reader_serving_the_room(harness: Harness) ->bodies = {}for label, room in rooms.items():bodies[label] = f"@e2e-removed-watcher please look at the {label} room"- await talker_client.send_message(room.matrix_room_id, bodies[label])+ await talker_client.send_message(+ room.matrix_room_id, bodies[label], metered=True+ )await _wait_buffered(harness, watcher.agent_id, room.id, bodies[label])# Both rooms are in the buffer and addressed, so every assertion after the@@ -163,7 +165,9 @@ async def test_a_room_the_agent_is_still_in_is_untouched(harness: Harness) -> Nobody = "@e2e-still-in-watcher this one still applies"await harness.client_for(talker.agent_id).send_message(- kept.room.matrix_room_id, body+ kept.room.matrix_room_id,+ body,+ metered=True,)await _wait_buffered(harness, watcher.agent_id, kept.room.id, body)diff --git a/core/tests/switch_core/bridges/agent/protocol/test_delegate_addressing.py b/core/tests/switch_core/bridges/agent/protocol/test_delegate_addressing.pyindex a85147746..422b4c44b 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_delegate_addressing.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_delegate_addressing.py@@ -6,10 +6,22 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.bridges.agent.protocol.connections import ConnectionRegistryfrom switch_core.bridges.agent.protocol.service import ProtocolServicefrom switch_core.bridges.agent.protocol.types import AgentStatus-from switch_core.db.models import Agent, ApiKey, Client, Room, User+from switch_core.budgets import BudgetExceeded, BudgetGuard+from switch_core.db.models import (+ Agent,+ ApiKey,+ Client,+ Room,+ UsageBudget,+ UsageMetric,+ User,+ require_tenant_id,+)from switch_core.db.stores.agent_store import AgentStore+from switch_core.db.stores.budget_store import BudgetStorefrom switch_core.db.stores.room_store import RoomStorefrom switch_core.db.stores.task_store import TaskStore+from switch_core.db.stores.usage_store import UsageStoredef _service(session_factory: async_sessionmaker[AsyncSession]) -> ProtocolService:@@ -21,6 +33,7 @@ def _service(session_factory: async_sessionmaker[AsyncSession]) -> ProtocolServisvc.agent_store = AgentStore() # type: ignore[attr-defined]svc.room_store = RoomStore() # type: ignore[attr-defined]svc.task_store = TaskStore() # type: ignore[attr-defined]+ svc.budget_guard = BudgetGuard(BudgetStore()) # type: ignore[attr-defined]# No live matrix client → delegate_task skips the custom-event send.svc.client_lifecycle = _NoClients() # type: ignore[attr-defined]@@ -218,3 +231,57 @@ class TestDelegateAddressingGate:result = await svc.delegate_task(req_id, room_id, perf_id, "do it", "details")assert result.task_id+++async def _spend_budget(session: AsyncSession, agent: Agent) -> None:+ session.add(+ UsageBudget(+ agent_id=agent.id,+ metric="turns",+ model="",+ amount_limit=1,+ period_hours=24,+ )+ )+ await UsageStore().record(+ session,+ tenant_id=require_tenant_id(),+ metric=UsageMetric.TURNS,+ client_id=agent.client_id,+ model="",+ amount=1,+ )+++class TestDelegateBudgetGate:+ @pytest.mark.parametrize("over_budget", ["requester", "performer"])+ async def test_an_agent_over_its_budget_takes_no_part_in_a_delegation(+ self, session_factory: async_sessionmaker[AsyncSession], over_budget: str+ ) -> None:+ svc = _service(session_factory)+ async with session_factory() as session:+ owner = await _make_user(session, "owner")+ requester = await _make_agent(session, "req", owner_id=owner.id)+ performer = await _make_agent(+ session,+ "perf",+ owner_id=owner.id,+ addressing_policy={+ "rules": [{"users": [], "agents": [], "owner_agents": True}]+ },+ )+ room = await _make_room(+ session, svc.room_store, [requester.id, performer.id]+ )+ await _spend_budget(+ session, requester if over_budget == "requester" else performer+ )+ await session.commit()+ req_id, perf_id, room_id = requester.id, performer.id, room.id++ with pytest.raises(BudgetExceeded, match="has reached its budget of 1 turns"):+ await svc.delegate_task(req_id, room_id, perf_id, "do it", "details")++ async with session_factory() as session:+ tasks = await svc.task_store.get_by_room(session, room_id)+ assert tasks == []diff --git a/core/tests/switch_core/bridges/agent/protocol/test_pool_checkouts.py b/core/tests/switch_core/bridges/agent/protocol/test_pool_checkouts.pynew file mode 100644index 000000000..891d8e0cb--- /dev/null+++ b/core/tests/switch_core/bridges/agent/protocol/test_pool_checkouts.py@@ -0,0 +1,407 @@+"""How many pool checkouts the hot paths cost.++These are performance assertions, and they are here because the failure they+guard against is not a slow page — it is fleet-wide agent loss. A request that+takes two slots where one would do halves the pool; a request that takes a+second slot *while holding the first* can wait the full pool timeout for it,+and every heartbeat queued behind that misses its TTL and reaps a live+connection. The numbers below are therefore contracts, not observations.+"""++from __future__ import annotations++from types import SimpleNamespace+from typing import Any++import pytest+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.bridges.agent.protocol.connections import ConnectionRegistry+from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.bridges.agent.protocol.types import RoomDescriptor+from switch_core.budgets import BudgetExceeded, BudgetGuard+from switch_core.db.models import (+ Agent,+ ApiKey,+ Client,+ Room,+ UsageBudget,+ UsageMetric,+ User,+)+from switch_core.db.stores.agent_session_store import AgentSessionStore+from switch_core.db.stores.agent_store import AgentStore+from switch_core.db.stores.budget_store import BudgetStore+from switch_core.db.stores.room_store import RoomStore+from switch_core.db.stores.usage_store import UsageStore+++class _CountingSessionFactory:+ """The real factory, counting the sessions opened through it.++ One session is one pool checkout, which is the quantity this whole change+ is about.+ """++ def __init__(self, inner: async_sessionmaker[AsyncSession]) -> None:+ self._inner = inner+ self.opened = 0++ def __call__(self) -> Any:+ self.opened += 1+ return self._inner()+++class _NoBridges:+ def get(self, _bridge_id: str) -> None:+ return None+++class _OneBridge:+ def __init__(self) -> None:+ self.typing: list[tuple[str, str, bool]] = []++ def get(self, _bridge_id: str) -> Any:+ return SimpleNamespace(handle_outbound_typing=self._record)++ async def _record(self, room_id: str, agent_name: str, is_typing: bool) -> None:+ self.typing.append((room_id, agent_name, is_typing))+++def _service(counting: _CountingSessionFactory) -> ProtocolService:+ svc = object.__new__(ProtocolService)+ svc.session_factory = counting # type: ignore[attr-defined]+ svc.agent_store = AgentStore() # type: ignore[attr-defined]+ svc.room_store = RoomStore() # type: ignore[attr-defined]+ svc.budget_guard = BudgetGuard(BudgetStore()) # type: ignore[attr-defined]+ svc.collab_lifecycle = _NoBridges() # type: ignore[attr-defined]+ svc.connections = ConnectionRegistry()+ return svc+++async def _seed(+ session_factory: async_sessionmaker[AsyncSession],+ *,+ policy: dict[str, Any] | None = None,+) -> tuple[str, str, str]:+ """One room with one member and one outsider. Returns (room, member, other).++ `policy` is applied to the member, which is the agent the addressing tests+ treat as the target.+ """+ async with session_factory() as session:+ user = User(name="o", email="o@test", role="user", password_hash="x")+ session.add(user)+ await session.flush()+ ids = []+ for name in ("member", "outsider"):+ key = ApiKey(+ user_id=user.id,+ key_hash=f"hash-{name}",+ encrypted_key="enc",+ label=name,+ type="agent",+ )+ client = Client(+ matrix_user_id=f"@{name}:test",+ display_name=name,+ type="agent",+ )+ session.add_all([key, client])+ await session.flush()+ agent = Agent(+ name=name,+ description="d",+ agent_type="session_addressable",+ connector_type="claude_code",+ integration_profile={},+ client_id=client.id,+ api_key_id=key.id,+ owner_id=user.id,+ addressing_policy=policy if name == "member" else None,+ )+ session.add(agent)+ await session.flush()+ ids.append(agent.id)+ room = Room(matrix_room_id="!r:test", name="room", description="d")+ session.add(room)+ await session.flush()+ await RoomStore().add_agents(session, room.id, [ids[0]])+ await session.commit()+ return room.id, ids[0], ids[1]+++class TestRequireRoomMember:+ async def test_membership_costs_one_checkout(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ room_id, member_id, _ = await _seed(session_factory)+ counting = _CountingSessionFactory(session_factory)+ svc = _service(counting)++ room = await svc.require_room_member(member_id, room_id)++ assert room.id == room_id+ assert counting.opened == 1, "one question, one slot"++ async def test_a_non_member_is_still_one_checkout(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ room_id, _, outsider_id = await _seed(session_factory)+ counting = _CountingSessionFactory(session_factory)+ svc = _service(counting)++ with pytest.raises(PermissionError):+ await svc.require_room_member(outsider_id, room_id)++ assert counting.opened == 1++ async def test_a_missing_room_still_raises_value_error(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ # "No such room" and "not your room" must stay distinguishable now that+ # the two reads have been folded into one statement.+ _, member_id, _ = await _seed(session_factory)+ svc = _service(_CountingSessionFactory(session_factory))++ with pytest.raises(ValueError, match="Room not found"):+ await svc.require_room_member(member_id, "no-such-room")++ async def test_the_resolved_room_carries_its_bridge(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ room_id, member_id, _ = await _seed(session_factory)+ svc = _service(_CountingSessionFactory(session_factory))++ room = await svc.require_room_member(member_id, room_id)++ assert room.bridge_id is None+++class TestCanAddress:+ async def test_a_restricted_target_reads_through_the_callers_session(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ # The nesting this replaces held one slot while blocking on a second,+ # which is how pool pressure turned into a pool timeout.+ _, member_id, outsider_id = await _seed(session_factory)+ async with session_factory() as session:+ await AgentStore().update(+ session,+ member_id,+ addressing_policy={"rules": [{"agents": [outsider_id], "users": []}]},+ )+ await session.commit()++ counting = _CountingSessionFactory(session_factory)+ svc = _service(counting)+ async with session_factory() as session:+ target = await svc.agent_store.get(session, member_id)+ assert target is not None+ counting.opened = 0++ allowed = await svc._can_address(+ session,+ target,+ room_id="room",+ group_id=None,+ sender_agent_id=outsider_id,+ )++ assert allowed is True+ assert counting.opened == 0, "_can_address must not open a session of its own"++ async def test_a_denied_sender_is_also_answered_in_the_callers_session(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ _, member_id, outsider_id = await _seed(session_factory)+ async with session_factory() as session:+ await AgentStore().update(+ session,+ member_id,+ addressing_policy={"rules": [{"agents": ["nobody"], "users": []}]},+ )+ await session.commit()++ counting = _CountingSessionFactory(session_factory)+ svc = _service(counting)+ async with session_factory() as session:+ target = await svc.agent_store.get(session, member_id)+ assert target is not None+ counting.opened = 0++ allowed = await svc._can_address(+ session,+ target,+ room_id="room",+ group_id=None,+ sender_agent_id=outsider_id,+ )++ assert allowed is False+ assert counting.opened == 0++ async def test_an_open_policy_reads_nothing_at_all(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ _, member_id, outsider_id = await _seed(session_factory)+ counting = _CountingSessionFactory(session_factory)+ svc = _service(counting)++ async with session_factory() as session:+ target = await svc.agent_store.get(session, member_id)+ assert target is not None+ counting.opened = 0++ allowed = await svc._can_address(+ session,+ target,+ room_id="room",+ group_id=None,+ sender_agent_id=outsider_id,+ )++ assert allowed is True+ assert counting.opened == 0+++class TestTyping:+ async def test_an_internal_room_costs_nothing_beyond_membership(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ # Was three checkouts: membership took two of its own, then a third+ # re-read the agent and the room the caller had already resolved.+ room_id, member_id, _ = await _seed(session_factory)+ counting = _CountingSessionFactory(session_factory)+ svc = _service(counting)++ await svc.set_typing(member_id, room_id, True)++ assert counting.opened == 1++ async def test_a_bridged_room_costs_one_read_for_the_agent_name(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ _, member_id, _ = await _seed(session_factory)+ counting = _CountingSessionFactory(session_factory)+ svc = _service(counting)+ bridge = _OneBridge()+ svc.collab_lifecycle = bridge # type: ignore[assignment]+ room = RoomDescriptor(+ id="room-1",+ name="room",+ description="d",+ transport_room_id="!r:test",+ matrix_room_id="!r:test",+ bridge_id="bridge-1",+ )++ await svc._set_typing(member_id, room, True)++ assert bridge.typing == [("room-1", "member", True)]+ assert counting.opened == 1+++class TestSendMessage:+ async def test_posting_to_an_internal_room_costs_one_checkout(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ # One to authorize. A bridged room adds exactly one more, to name the+ # agent for the typing indicator — and no more than that, because the+ # room the caller already resolved is passed along instead of re-read.+ room_id, member_id, _ = await _seed(session_factory)+ counting = _CountingSessionFactory(session_factory)+ svc = _service(counting)+ sent: list[tuple[str, str]] = []++ class _Client:+ async def send_message(+ self, matrix_room_id: str, content: str, **_kwargs: Any+ ) -> str:+ sent.append((matrix_room_id, content))+ return "$event"++ svc.client_lifecycle = SimpleNamespace( # type: ignore[assignment]+ get_by_agent_id=lambda _agent_id: _Client()+ )++ event_id = await svc.send_message(member_id, room_id, "hello")++ assert event_id == "$event"+ assert sent == [("!r:test", "hello")]+ assert counting.opened == 1++ async def test_a_non_member_cannot_post(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ room_id, _, outsider_id = await _seed(session_factory)+ svc = _service(_CountingSessionFactory(session_factory))++ with pytest.raises(PermissionError):+ await svc.send_message(outsider_id, room_id, "hello")++ async def test_an_agent_over_its_budget_cannot_post_and_it_costs_one_checkout(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ room_id, member_id, _ = await _seed(session_factory)+ async with session_factory() as session:+ agent = await AgentStore().get(session, member_id)+ assert agent is not None+ session.add(+ UsageBudget(+ agent_id=member_id,+ metric="messages",+ model="",+ amount_limit=2,+ period_hours=24,+ )+ )+ await UsageStore().record(+ session,+ tenant_id=agent.tenant_id,+ metric=UsageMetric.MESSAGES,+ client_id=agent.client_id,+ model="",+ amount=2,+ )+ await session.commit()+ counting = _CountingSessionFactory(session_factory)+ svc = _service(counting)++ with pytest.raises(BudgetExceeded, match="member has reached its budget"):+ await svc.send_message(member_id, room_id, "hello")++ assert counting.opened == 1+++class TestAgentStatuses:+ async def test_a_request_handler_can_reuse_its_own_session(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ # The gateway builds a room's detail inside its request transaction.+ # Resolving statuses used to open a second one from underneath it.+ room_id, member_id, _ = await _seed(session_factory)+ counting = _CountingSessionFactory(session_factory)+ svc = _service(counting)+ svc.agent_session_store = AgentSessionStore() # type: ignore[attr-defined]++ async with session_factory() as session:+ counting.opened = 0+ statuses = await svc.get_agent_statuses_by_ids_in_session(+ session, room_id, [member_id]+ )++ assert member_id in statuses+ assert counting.opened == 0++ async def test_the_session_less_form_still_takes_exactly_one(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ room_id, member_id, _ = await _seed(session_factory)+ counting = _CountingSessionFactory(session_factory)+ svc = _service(counting)+ svc.agent_session_store = AgentSessionStore() # type: ignore[attr-defined]++ await svc.get_agent_statuses_by_ids(room_id, [member_id])++ assert counting.opened == 1diff --git a/core/tests/switch_core/bridges/agent/protocol/test_send_media.py b/core/tests/switch_core/bridges/agent/protocol/test_send_media.pyindex f522a9e73..1eff08346 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_send_media.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_send_media.py@@ -26,6 +26,7 @@ class _FakeClient:mimetype: str,size: int,*,+ metered: bool,msgtype: str,caption: str | None = None,thread_root_id: str | None = None,@@ -38,6 +39,7 @@ class _FakeClient:"filename": filename,"mimetype": mimetype,"size": size,+ "metered": metered,"msgtype": msgtype,"caption": caption,"thread_root_id": thread_root_id,@@ -58,7 +60,7 @@ def _build_service(client: _FakeClient, *, max_bytes: int = 100) -> ProtocolServ# Presence unions the heartbeat rows with the live connections# (CHOO-1857); an empty registry means "rows only".svc.connections = ConnectionRegistry()- svc.require_room_member = _require # type: ignore[assignment]+ svc.require_room_poster = _require # type: ignore[assignment]svc.client_lifecycle = SimpleNamespace( # type: ignore[assignment]get_by_agent_id=lambda agent_id: client)@@ -88,6 +90,7 @@ async def test_send_media_uploads_and_posts_image() -> None:sent = client.sends[0]assert sent["room_id"] == "!room"assert sent["msgtype"] == "m.image"+ assert sent["metered"] is Trueassert sent["caption"] is Noneassert sent["thread_root_id"] is None# A lone attachment carries no group marker.diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_agent_display_names.py b/core/tests/switch_core/bridges/collaboration/test_bridge_agent_display_names.pyindex c950d1fa3..5b5bb4d48 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_agent_display_names.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_agent_display_names.py@@ -640,10 +640,12 @@ def _discord_adapter(adapter = DiscordAdapter(config=DiscordConnectionConfig(bot_token="token", guild_id=str(GUILD_ID)))- adapter._bot_user_id = BOT_USER_ID+ adapter._connection._bot_user_id = BOT_USER_IDchannel = _FakeChannel()dm = _FakeChannel(DM_CHANNEL_ID, dm=True)- adapter._client = _FakeDiscordClient({CHANNEL_ID: channel, DM_CHANNEL_ID: dm}) # type: ignore[assignment]+ adapter._connection._client = _FakeDiscordClient(+ {CHANNEL_ID: channel, DM_CHANNEL_ID: dm}+ ) # type: ignore[assignment]if bridge is not None:adapter.set_agent_presentation_resolver(bridge._agent_presentation)return adapter, channel, dmdiff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_identity_backfill.py b/core/tests/switch_core/bridges/collaboration/test_bridge_identity_backfill.pyindex a3ce2b1da..fb6e2b32a 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_identity_backfill.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_identity_backfill.py@@ -157,3 +157,50 @@ async def test_stop_stops_the_activity_publisher() -> None:await core.start()await core.stop()assert events == ["started", "stopped"]+++async def test_attach_reprovision_does_not_overwrite_a_running_task() -> None:+ """A shared bridge re-provisions when its connection attaches, but must not+ replace a start-time run still in flight: the run spends most of its life in+ the agent read before the per-agent loop, so an attach then would otherwise+ spawn a second provisioner (two concurrent create_agent_identity calls can+ double a role) and orphan the handle stop() cancels."""+ started = asyncio.Event()+ release = asyncio.Event()++ async def _slow_provision() -> None:+ started.set()+ await release.wait()++ core, _ = _core(_slow_provision)+ core._identity_task = asyncio.create_task(core._run_agent_identities())+ await asyncio.wait_for(started.wait(), timeout=1)+ running = core._identity_task++ core._provision_identities_on_attach()++ assert core._identity_task is running # not overwritten while live+ release.set()+ await core.stop()+++async def test_attach_reprovision_runs_when_no_task_is_live() -> None:+ """The usual case: the start-time run has finished (it fails fast while the+ bridge is unattached), so attaching spawns a fresh provisioning run."""+ runs = 0+ done = asyncio.Event()++ async def _provision() -> None:+ nonlocal runs+ runs += 1+ done.set()++ core, _ = _core(_provision)+ core._identity_task = None++ core._provision_identities_on_attach()+ await asyncio.wait_for(done.wait(), timeout=1)++ assert runs == 1+ assert core._identity_task is not None+ await core.stop()diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_media.py b/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_media.pyindex 65fed94ca..4b49d8d47 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_media.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_media.py@@ -30,6 +30,8 @@ class _FakePuppet:filename,mimetype,size,+ *,+ metered,msgtype,caption=None,thread_root_id=None,@@ -51,7 +53,7 @@ class _FakePuppet:return f"$evt-{len(self.media) - 1}"async def send_message(- self, matrix_room_id, content, format=None, thread_root_id=None+ self, matrix_room_id, content, *, metered, format=None, thread_root_id=None): # noqa: ANN001, ANN201, A002self.messages.append({"content": content, "thread_root_id": thread_root_id})return "$evt-text"diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_type_registry.py b/core/tests/switch_core/bridges/collaboration/test_bridge_type_registry.pyindex 83010183f..ec8ff2e25 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_type_registry.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_type_registry.py@@ -79,8 +79,14 @@ def test_discord_adapter_registers_with_expected_required_fields() -> None:schema = service.get_config_schema("discord")# agent_roles is offered but not required: it needs Manage Roles and room# under Discord's 250-role cap, so a connection stays valid without it.+ # event_delivery is hidden (SkipJsonSchema): it is written by the install+ # flow, not chosen on the form.assert set(schema["properties"]) == {"bot_token", "guild_id", "agent_roles"}- assert set(schema["required"]) == {"bot_token", "guild_id"}+ # bot_token is offered but not required by the schema: a shared-connection+ # bridge (the distributed app) has none. What enforces it for a self-+ # registered bridge — which opens its own connection and receives nothing+ # without one — is the model validator, not this form.+ assert set(schema["required"]) == {"guild_id"}def test_telegram_adapter_registers_with_expected_required_fields() -> None:diff --git a/core/tests/switch_core/bridges/collaboration/test_discord_activity_view.py b/core/tests/switch_core/bridges/collaboration/test_discord_activity_view.pyindex e09b78eab..6ddf0a78e 100644--- a/core/tests/switch_core/bridges/collaboration/test_discord_activity_view.py+++ b/core/tests/switch_core/bridges/collaboration/test_discord_activity_view.py@@ -528,7 +528,7 @@ async def test_a_conversation_discord_will_not_resolve_is_not_a_turn_that_is_gonhas established nothing about the turn, which is still exactly where itwas, so the reader is told to try again instead."""adapter, channel = _guild_with({READER_ID})- client: Any = adapter._client+ client: Any = adapter._connection._clientclient._channels.pop(CHANNEL_ID)response = _HTTPResponse()response.status = 500 # type: ignore[misc]@@ -551,7 +551,7 @@ async def test_a_conversation_discord_says_is_not_there_is_gone() -> None:one answer again. A 404 is Discord saying the channel does not exist, andthat really is a turn nothing can be read from."""adapter, channel = _guild_with({READER_ID})- client: Any = adapter._client+ client: Any = adapter._connection._clientclient._channels.pop(CHANNEL_ID)client.fetch_errors[CHANNEL_ID] = discord.NotFound( # type: ignore[arg-type]_HTTPResponse(), {"code": 10003, "message": "Unknown Channel"}diff --git a/core/tests/switch_core/bridges/collaboration/test_discord_adapter.py b/core/tests/switch_core/bridges/collaboration/test_discord_adapter.pyindex 5cac95b50..d60a98b1a 100644--- a/core/tests/switch_core/bridges/collaboration/test_discord_adapter.py+++ b/core/tests/switch_core/bridges/collaboration/test_discord_adapter.py@@ -9,6 +9,7 @@ import pytestfrom switch_core.bridges.agent.commands import COMMANDSfrom switch_core.bridges.collaboration.discord import adapter as adapter_module+from switch_core.bridges.collaboration.discord import connection as connection_modulefrom switch_core.bridges.collaboration.discord.adapter import (_WEBHOOK_NAME,DiscordAdapter,@@ -26,7 +27,7 @@ def _adapter() -> DiscordAdapter:adapter = DiscordAdapter(config=DiscordConnectionConfig(bot_token="token", guild_id=str(GUILD_ID)))- adapter._bot_user_id = BOT_USER_ID+ adapter._connection._bot_user_id = BOT_USER_IDreturn adapter@@ -316,12 +317,10 @@ def test_own_webhook_message_dropped_but_foreign_webhook_bridged() -> None:assert captured[0].message_ref == f"{CHANNEL_ID}:2"-def test_other_guild_and_system_messages_skipped() -> None:+def test_system_messages_skipped() -> None:adapter = _adapter()captured = _capture_messages(adapter)- other_guild_channel = _FakeChannel(guild=_FakeGuild(guild_id=999))- _run(adapter._handle_message(_gateway_message(channel=other_guild_channel)))_run(adapter._handle_message(_gateway_message(@@ -333,6 +332,54 @@ def test_other_guild_and_system_messages_skipped() -> None:assert captured == []+def _connection() -> Any:+ return connection_module.DiscordConnection(+ bot_token="token",+ intents=discord.Intents.none(),+ command_guild_id=GUILD_ID,+ )+++def test_connection_routes_messages_to_the_matching_guild_handler() -> None:+ # The guild filter that used to live in _handle_message now lives in the+ # connection: a message reaches only the handler registered for its guild.+ conn = _connection()+ delivered: list[Any] = []++ async def handler(message: Any) -> None:+ delivered.append(message)++ conn.register_message_handler(GUILD_ID, handler)+ on_message = conn._make_on_message()++ _run(on_message(_gateway_message(channel=_FakeChannel())))+ _run(+ on_message(+ _gateway_message(channel=_FakeChannel(guild=_FakeGuild(guild_id=999)))+ )+ )++ assert len(delivered) == 1+++def test_connection_drops_dms_unless_a_dm_handler_is_set() -> None:+ conn = _connection()+ delivered: list[Any] = []++ async def handler(message: Any) -> None:+ delivered.append(message)++ conn.register_message_handler(GUILD_ID, handler)+ on_message = conn._make_on_message()++ _run(on_message(_gateway_message(channel=_FakeDMChannel())))+ assert delivered == []++ conn.set_dm_handler(handler)+ _run(on_message(_gateway_message(channel=_FakeDMChannel())))+ assert len(delivered) == 1++def test_duplicate_message_ids_deduplicated() -> None:adapter = _adapter()captured = _capture_messages(adapter)@@ -445,7 +492,7 @@ def test_a_command_argument_picked_from_the_at_menu_arrives_as_a_name() -> None:return _Guild() if guild_id == GUILD_ID else Noneadapter = _adapter()- adapter._client = _Client() # type: ignore[assignment]+ adapter._connection._client = _Client() # type: ignore[assignment]commands = _capture_commands(adapter)_run(@@ -559,7 +606,7 @@ def test_oversize_attachment_reported_as_failure() -> None:def test_send_message_posts_via_webhook_with_agent_identity() -> None:adapter = _adapter()channel = _FakeChannel()- adapter._client = _FakeClient({CHANNEL_ID: channel})+ adapter._connection._client = _FakeClient({CHANNEL_ID: channel})webhook = _FakeWebhook()adapter._webhooks[(CHANNEL_ID, _WEBHOOK_NAME)] = webhook@@ -579,7 +626,7 @@ def test_send_message_posts_via_webhook_with_agent_identity() -> None:def test_long_message_is_split_across_posts_not_dropped() -> None:adapter = _adapter()channel = _FakeChannel()- adapter._client = _FakeClient({CHANNEL_ID: channel})+ adapter._connection._client = _FakeClient({CHANNEL_ID: channel})webhook = _FakeWebhook()adapter._webhooks[(CHANNEL_ID, _WEBHOOK_NAME)] = webhookbody = "\n".join(f"line {i}" for i in range(1000))@@ -600,7 +647,7 @@ def test_long_message_is_split_across_posts_not_dropped() -> None:def test_long_admin_message_is_split_across_posts() -> None:adapter = _adapter()channel = _FakeChannel()- adapter._client = _FakeClient({CHANNEL_ID: channel})+ adapter._connection._client = _FakeClient({CHANNEL_ID: channel})body = "\n".join(f"- `!cmd-{i}` — does a thing" for i in range(200))ref = _run(adapter.admin_message(str(CHANNEL_ID), body))@@ -614,7 +661,7 @@ def test_long_admin_message_is_split_across_posts() -> None:def test_failed_part_leaves_a_visible_truncation_notice() -> None:adapter = _adapter()channel = _FakeChannel()- adapter._client = _FakeClient({CHANNEL_ID: channel})+ adapter._connection._client = _FakeClient({CHANNEL_ID: channel})webhook = _FakeWebhook()adapter._webhooks[(CHANNEL_ID, _WEBHOOK_NAME)] = webhookbody = "\n".join(f"line {i}" for i in range(1000))@@ -643,7 +690,7 @@ def test_send_message_with_thread_root_posts_into_thread() -> None:root = _FakeMessage(channel, message_id=4000)root.content = "the root message"channel.messages[4000] = root- adapter._client = _FakeClient({CHANNEL_ID: channel})+ adapter._connection._client = _FakeClient({CHANNEL_ID: channel})webhook = _FakeWebhook()adapter._webhooks[(CHANNEL_ID, _WEBHOOK_NAME)] = webhook@@ -663,7 +710,7 @@ def test_send_message_reuses_existing_thread() -> None:adapter = _adapter()channel = _FakeChannel()thread = _FakeThread(parent=channel, thread_id=4000)- adapter._client = _FakeClient({CHANNEL_ID: channel, 4000: thread})+ adapter._connection._client = _FakeClient({CHANNEL_ID: channel, 4000: thread})webhook = _FakeWebhook()adapter._webhooks[(CHANNEL_ID, _WEBHOOK_NAME)] = webhook@@ -679,7 +726,7 @@ def test_send_message_reuses_existing_thread() -> None:def test_send_message_to_dm_falls_back_to_bot_post() -> None:adapter = _adapter()dm = _FakeDMChannel()- adapter._client = _FakeClient({dm.id: dm})+ adapter._connection._client = _FakeClient({dm.id: dm})ref = _run(adapter.send_message(str(dm.id), "my-agent", "hi"))@@ -693,7 +740,7 @@ def test_send_message_to_dm_falls_back_to_bot_post() -> None:def test_send_attachment_posts_via_webhook_with_agent_identity() -> None:adapter = _adapter()channel = _FakeChannel()- adapter._client = _FakeClient({CHANNEL_ID: channel})+ adapter._connection._client = _FakeClient({CHANNEL_ID: channel})webhook = _FakeWebhook()adapter._webhooks[(CHANNEL_ID, _WEBHOOK_NAME)] = webhook@@ -724,7 +771,7 @@ def test_send_attachment_posts_via_webhook_with_agent_identity() -> None:def test_send_attachment_without_caption_sends_empty_content() -> None:adapter = _adapter()channel = _FakeChannel()- adapter._client = _FakeClient({CHANNEL_ID: channel})+ adapter._connection._client = _FakeClient({CHANNEL_ID: channel})webhook = _FakeWebhook()adapter._webhooks[(CHANNEL_ID, _WEBHOOK_NAME)] = webhook@@ -742,7 +789,7 @@ def test_send_attachment_into_thread() -> None:adapter = _adapter()channel = _FakeChannel()thread = _FakeThread(parent=channel, thread_id=4000)- adapter._client = _FakeClient({CHANNEL_ID: channel, 4000: thread})+ adapter._connection._client = _FakeClient({CHANNEL_ID: channel, 4000: thread})webhook = _FakeWebhook()adapter._webhooks[(CHANNEL_ID, _WEBHOOK_NAME)] = webhook@@ -764,7 +811,7 @@ def test_send_attachment_into_thread() -> None:def test_send_attachment_to_dm_posts_file_as_bot() -> None:adapter = _adapter()dm = _FakeDMChannel()- adapter._client = _FakeClient({dm.id: dm})+ adapter._connection._client = _FakeClient({dm.id: dm})ref = _run(adapter.send_attachment(@@ -786,7 +833,7 @@ def test_send_attachment_falls_back_to_text_note_on_http_error() -> None:adapter = _adapter()channel = _FakeChannel()- adapter._client = _FakeClient({CHANNEL_ID: channel})+ adapter._connection._client = _FakeClient({CHANNEL_ID: channel})webhook = _FileRejectingWebhook()adapter._webhooks[(CHANNEL_ID, _WEBHOOK_NAME)] = webhook@@ -812,7 +859,7 @@ def test_send_attachment_falls_back_to_text_note_on_http_error() -> None:def test_admin_message_posts_as_bot_not_webhook() -> None:adapter = _adapter()channel = _FakeChannel()- adapter._client = _FakeClient({CHANNEL_ID: channel})+ adapter._connection._client = _FakeClient({CHANNEL_ID: channel})ref = _run(adapter.admin_message(str(CHANNEL_ID), "system notice"))@@ -824,7 +871,7 @@ def test_admin_message_posts_as_bot_not_webhook() -> None:def test_update_message_edits_via_webhook_with_thread() -> None:adapter = _adapter()channel = _FakeChannel()- adapter._client = _FakeClient({CHANNEL_ID: channel})+ adapter._connection._client = _FakeClient({CHANNEL_ID: channel})webhook = _FakeWebhook()adapter._webhooks[(CHANNEL_ID, _WEBHOOK_NAME)] = webhook@@ -841,7 +888,7 @@ def test_update_message_falls_back_to_bot_message_edit() -> None:channel = _FakeChannel()bot_msg = _FakeMessage(channel, message_id=502)channel.messages[502] = bot_msg- adapter._client = _FakeClient({CHANNEL_ID: channel})+ adapter._connection._client = _FakeClient({CHANNEL_ID: channel})webhook = _FakeWebhook()webhook.edit_raises_not_found = Trueadapter._webhooks[(CHANNEL_ID, _WEBHOOK_NAME)] = webhook@@ -859,7 +906,7 @@ def test_delete_message_goes_through_the_webhook_that_sent_it() -> None:channel = _FakeChannel()webhook = _FakeWebhook()channel.existing_webhooks = [webhook]- adapter._client = _FakeClient({CHANNEL_ID: channel})+ adapter._connection._client = _FakeClient({CHANNEL_ID: channel})_run(adapter.delete_message(str(CHANNEL_ID), f"{CHANNEL_ID}:901"))@@ -873,7 +920,7 @@ def test_delete_message_in_a_thread_passes_the_thread_through() -> None:webhook = _FakeWebhook()channel.existing_webhooks = [webhook]thread = _FakeThread(parent=channel, thread_id=4000)- adapter._client = _FakeClient({CHANNEL_ID: channel, 4000: thread})+ adapter._connection._client = _FakeClient({CHANNEL_ID: channel, 4000: thread})_run(adapter.delete_message(str(CHANNEL_ID), "4000:901"))@@ -892,7 +939,7 @@ def test_delete_message_falls_back_to_the_bot_for_its_own_posts() -> None:thread = _FakeThread(parent=channel, thread_id=4000)thread.deleted_ids = [] # type: ignore[attr-defined]thread.get_partial_message = lambda mid: _FakePartialMessage(thread, mid) # type: ignore[attr-defined]- adapter._client = _FakeClient({CHANNEL_ID: channel, 4000: thread})+ adapter._connection._client = _FakeClient({CHANNEL_ID: channel, 4000: thread})_run(adapter.delete_message(str(CHANNEL_ID), "4000:901"))@@ -903,7 +950,7 @@ def test_delete_message_falls_back_to_the_bot_for_its_own_posts() -> None:def test_send_typing_triggers_once_and_off_is_noop() -> None:adapter = _adapter()channel = _FakeChannel()- adapter._client = _FakeClient({CHANNEL_ID: channel})+ adapter._connection._client = _FakeClient({CHANNEL_ID: channel})_run(adapter.send_typing(str(CHANNEL_ID), "my-agent", True))_run(adapter.send_typing(str(CHANNEL_ID), "my-agent", False))@@ -919,7 +966,7 @@ def test_get_webhook_adopts_existing_bridge_webhook() -> None:channel = _FakeChannel()existing = _FakeWebhook(name="Switch Bridge", webhook_id=555)channel.existing_webhooks = [_FakeWebhook(name="other", webhook_id=1), existing]- adapter._client = _FakeClient({CHANNEL_ID: channel})+ adapter._connection._client = _FakeClient({CHANNEL_ID: channel})webhook = _run(adapter._get_webhook(CHANNEL_ID))@@ -931,7 +978,7 @@ def test_get_webhook_adopts_existing_bridge_webhook() -> None:def test_get_webhook_creates_when_missing() -> None:adapter = _adapter()channel = _FakeChannel()- adapter._client = _FakeClient({CHANNEL_ID: channel})+ adapter._connection._client = _FakeClient({CHANNEL_ID: channel})webhook = _run(adapter._get_webhook(CHANNEL_ID))@@ -949,7 +996,9 @@ def test_get_webhook_creates_when_missing() -> None:def test_translate_inbound_converts_user_and_channel_mentions() -> None:adapter = _adapter()adapter._user_names[7] = "louis"- adapter._client = _FakeClient({CHANNEL_ID: _FakeChannel(name="general")})+ adapter._connection._client = _FakeClient(+ {CHANNEL_ID: _FakeChannel(name="general")}+ )out = adapter.translate_inbound(f"hi <@7> and <@!7>, see <#{CHANNEL_ID}> or <@99>")@@ -1060,10 +1109,10 @@ def test_start_becomes_ready_then_stop_closes_client() -> None:async def scenario() -> None:with patch.object(adapter_module.discord, "Client", lambda **kw: fake):await adapter.start(*_noop_callbacks())- assert adapter._client is fake+ assert adapter._connection._client is fakeassert fake.logged_inassert fake.registered_events # on_message handler registered- assert adapter._bot_user_id == BOT_USER_ID+ assert adapter._connection._bot_user_id == BOT_USER_ID# Slash commands are published to the configured GUILD, never# globally: the adapter is single-guild by construction, guild@@ -1079,8 +1128,8 @@ def test_start_becomes_ready_then_stop_closes_client() -> None:await adapter.stop()assert fake.closed- assert adapter._client is None- assert adapter._tree is None+ assert adapter._connection._client is None+ assert adapter._connection._tree is None_run(scenario())@@ -1113,12 +1162,12 @@ def test_start_times_out_when_never_ready_and_stops() -> None:async def scenario() -> None:with (patch.object(adapter_module.discord, "Client", lambda **kw: fake),- patch.object(adapter_module, "_READY_TIMEOUT", 0.05),+ patch.object(connection_module, "_READY_TIMEOUT", 0.05),):with pytest.raises(RuntimeError, match="not ready"):await adapter.start(*_noop_callbacks())# Timeout path tears the half-open client down.assert fake.closed- assert adapter._client is None+ assert adapter._connection._client is None_run(scenario())diff --git a/core/tests/switch_core/bridges/collaboration/test_discord_agent_roles.py b/core/tests/switch_core/bridges/collaboration/test_discord_agent_roles.pyindex 30f193d3a..7c2cf62ac 100644--- a/core/tests/switch_core/bridges/collaboration/test_discord_agent_roles.py+++ b/core/tests/switch_core/bridges/collaboration/test_discord_agent_roles.py@@ -102,7 +102,7 @@ def _adapter(guild: _FakeGuild, *, agent_roles: bool = True) -> DiscordAdapter:bot_token="token", guild_id=str(GUILD_ID), agent_roles=agent_roles))- made._client = _FakeClient(guild) # type: ignore[assignment]+ made._connection._client = _FakeClient(guild) # type: ignore[assignment]return madediff --git a/core/tests/switch_core/bridges/collaboration/test_discord_card_removal.py b/core/tests/switch_core/bridges/collaboration/test_discord_card_removal.pyindex 6659c6868..9fd140180 100644--- a/core/tests/switch_core/bridges/collaboration/test_discord_card_removal.py+++ b/core/tests/switch_core/bridges/collaboration/test_discord_card_removal.py@@ -262,8 +262,8 @@ async def test_a_channel_that_cannot_be_resolved_is_not_a_card_that_is_gone() ->nothing about the card. Reading it as success would retire a card still onthe screen."""adapter, _channel, _thread, _publication = _guild_setup()- adapter._client.fetch_errors[CHANNEL_ID] = _unknown_message() # type: ignore[union-attr]- adapter._client._channels.pop(CHANNEL_ID) # type: ignore[union-attr]+ adapter._connection._client.fetch_errors[CHANNEL_ID] = _unknown_message() # type: ignore[union-attr]+ adapter._connection._client._channels.pop(CHANNEL_ID) # type: ignore[union-attr]with pytest.raises(RemovalFailed):await adapter.remove_publication(str(CHANNEL_ID), CARD)@@ -275,7 +275,7 @@ async def test_an_unparseable_reference_never_reaches_discord() -> None:resolved, by an `int()` that happens to raise."""adapter, channel, _thread, publication = _guild_setup()looked_up: list[int] = []- client = adapter._client+ client = adapter._connection._clientclient.get_channel = _recording(client.get_channel, looked_up) # type: ignore[union-attr]for reference in ("nonsense", f"{CHANNEL_ID}:", ":999", "abc:def"):diff --git a/core/tests/switch_core/bridges/collaboration/test_discord_distributed_app.py b/core/tests/switch_core/bridges/collaboration/test_discord_distributed_app.pynew file mode 100644index 000000000..0410130ed--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_discord_distributed_app.py@@ -0,0 +1,61 @@+"""The registration walkthrough and the code have to agree, so this compares them.++`docs/old/bridges/DISCORD_DISTRIBUTED_APP.md` carries a pinned contract block:+the OAuth scopes the *Add to Server* URL asks for, the least-privilege+permission integer it requests, and the redirect it registers. Each is a+promise the running system keeps — Discord refuses a redirect that does not+match, and a permission the code needs but the URL never requested surfaces as a+customer's bot silently unable to do its job, with nothing in our logs.++The contract is parsed out of the markdown rather than kept in a fixture,+because a fixture would be a third copy of a value that already lives in the+code and the doc.+"""++from __future__ import annotations++import json+import re+from pathlib import Path++from switch_core.bridges.collaboration.discord.install import PERMISSIONS, SCOPES+from switch_core.bridges.collaboration.install import (+ oauth_callback_path,+ public_url,+)++_DOC = (+ Path(__file__).resolve().parents[5]+ / "docs"+ / "old"+ / "bridges"+ / "DISCORD_DISTRIBUTED_APP.md"+)++_HOST = "HOST"+++def _contract() -> dict:+ text = _DOC.read_text()+ blocks = re.findall(r"```json\n(.*?)\n```", text, re.DOTALL)+ assert len(blocks) == 1, (+ f"expected exactly one json block in {_DOC.name}, found {len(blocks)}"+ )+ return json.loads(blocks[0])+++def test_the_doc_requests_the_scopes_the_code_asks_for() -> None:+ """Same scopes, same order — the order the authorize URL builds them in."""+ assert tuple(_contract()["scopes"]) == SCOPES+++def test_the_doc_pins_the_permission_integer_the_code_pins() -> None:+ """A decimal bitfield, exact. A drift here is a permission granted-and-unused+ or needed-and-missing, and only the second is visible, late."""+ assert int(_contract()["permissions"]) == PERMISSIONS+++def test_the_doc_registers_the_redirect_the_callback_is_served_at() -> None:+ """The one mismatch Discord refuses outright, byte for byte."""+ expected = public_url(f"https://{_HOST}", oauth_callback_path("discord"))+ assert _contract()["redirect_uri"] == expecteddiff --git a/core/tests/switch_core/bridges/collaboration/test_discord_eager_attach.py b/core/tests/switch_core/bridges/collaboration/test_discord_eager_attach.pynew file mode 100644index 000000000..b741cd2aa--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_discord_eager_attach.py@@ -0,0 +1,147 @@+"""A Discord bridge on the shared connection is attached as it starts.++It used to be attached at boot, if it existed then, and otherwise only when its+guild's first message arrived. Until that message a new install could not reach+Discord at all: searching its members to link an account failed, and so did+anything else that needed the socket. The lifecycle now hands each bridge to+the gateway client as it starts, before anything in it runs, and the client+attaches it if the connection is up.+"""++from __future__ import annotations++import uuid+from typing import Any++import pytest+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.bridges.collaboration.adapter import CollaborationAdapter+from switch_core.bridges.collaboration.discord.adapter import (+ DiscordAdapter,+ DiscordConnectionConfig,+)+from switch_core.bridges.collaboration.discord.connection import DiscordConnection+from switch_core.bridges.collaboration.discord.gateway import DiscordGatewayClient++from .test_lifecycle_tenant_binding import (+ _make_bridge,+ _make_tenant,+ _service,+ _StubAdapter,+ _StubConfig,+)+++def _shared_adapter() -> DiscordAdapter:+ return DiscordAdapter(+ config=DiscordConnectionConfig(guild_id="900", event_delivery="shared")+ )+++async def _noop_on_connected(_connection: DiscordConnection) -> None: ...+++def _gateway() -> DiscordGatewayClient:+ install_service: Any = object()+ return DiscordGatewayClient(+ bot_token="bot-token",+ message_content=False,+ members=False,+ install_service=install_service,+ on_connected=_noop_on_connected,+ )+++async def _connect(+ gateway: DiscordGatewayClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ async def _start() -> None: ...++ monkeypatch.setattr(gateway, "start", _start)+ await gateway.start_with_retry()+++class TestTheGatewayClient:+ async def test_a_bridge_starting_while_the_connection_is_up_is_attached(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ gateway = _gateway()+ await _connect(gateway, monkeypatch)+ adapter = _shared_adapter()++ gateway.attach_if_live(adapter)++ assert adapter._connection is gateway.connection++ async def test_one_starting_before_the_connection_is_up_is_left_for_later(+ self,+ ) -> None:+ # Attached now it would provision against a client that is not there,+ # and the attach on connect would be a no-op that never redoes it.+ gateway = _gateway()+ adapter = _shared_adapter()++ gateway.attach_if_live(adapter)++ assert adapter._connection is None++ async def test_the_walk_on_connect_sees_the_connection_as_up(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ # So a bridge starting during the walk is attached by one or the other.+ seen: list[DiscordConnection | None] = []+ gateway = _gateway()+ adapter = _shared_adapter()++ async def on_connected(_connection: DiscordConnection) -> None:+ gateway.attach_if_live(adapter)+ seen.append(adapter._connection)++ gateway._on_connected = on_connected+ await _connect(gateway, monkeypatch)++ assert seen == [gateway.connection]++ async def test_another_platforms_adapter_is_left_alone(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ gateway = _gateway()+ await _connect(gateway, monkeypatch)+ other = _StubAdapter(config=_StubConfig())++ gateway.attach_if_live(other) # type: ignore[arg-type]++ assert not hasattr(other, "_connection")+++class TestTheLifecycle:+ async def test_a_listener_is_handed_the_adapter_before_the_bridge_runs(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ tenant = f"tenant-{uuid.uuid4().hex[:8]}"+ async with session_factory() as session:+ await _make_tenant(session, tenant)+ bridge_id, _ = await _make_bridge(session, tenant_id=tenant)+ await session.commit()++ service = _service(session_factory)+ service.register_adapter("mattermost", _StubAdapter, _StubConfig)+ events: list[str] = []+ handed: list[CollaborationAdapter] = []++ def listener(adapter: CollaborationAdapter) -> None:+ events.append("listener")+ handed.append(adapter)++ async def _run(*_: object) -> None:+ events.append("run")++ service._run_bridge = _run # type: ignore[method-assign]+ service.add_bridge_starting_listener(listener)++ await service.start(bridge_id)++ assert events[0] == "listener"+ assert handed == [service.get_adapter(bridge_id)]+ await service.stop_all()diff --git a/core/tests/switch_core/bridges/collaboration/test_discord_gateway.py b/core/tests/switch_core/bridges/collaboration/test_discord_gateway.pynew file mode 100644index 000000000..5e72a90d0--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_discord_gateway.py@@ -0,0 +1,112 @@+"""The shared, deployment-level Discord Gateway connection.++Stage 4a: the connection exists with the right intents and command scope, binds+no tenant, and never opens the door to a direct message (guard G4 begins here —+no DM intent and no DM handler). Attaching bridges, routing and removal come+later; this pins the foundation.+"""++from __future__ import annotations++from collections.abc import Awaitable, Callable+from typing import Any++import pytest++from switch_core.bridges.collaboration.discord.connection import DiscordConnection+from switch_core.bridges.collaboration.discord.gateway import DiscordGatewayClient+++async def _noop_on_connected(_connection: DiscordConnection) -> None: ...+++def _gateway(+ *,+ message_content: bool = False,+ members: bool = False,+ on_connected: Callable[[DiscordConnection], Awaitable[None]] = _noop_on_connected,+) -> DiscordGatewayClient:+ # These tests only inspect the connection the client builds, so a bare+ # stand-in for the install service (never called here) is enough.+ install_service: Any = object()+ return DiscordGatewayClient(+ bot_token="bot-token",+ message_content=message_content,+ members=members,+ install_service=install_service,+ on_connected=on_connected,+ )+++def test_it_requests_no_dm_intent_and_privileged_intents_default_off() -> None:+ """G4 starts here (no DM intent). message_content and members are both+ privileged and off by default so the connection opens unapproved."""+ intents = _gateway().connection._intents+ assert intents.guilds is True+ assert intents.guild_messages is True+ assert intents.dm_messages is False+ assert intents.message_content is False+ assert intents.members is False+++def test_message_content_can_be_turned_on() -> None:+ assert _gateway(message_content=True).connection._intents.message_content is True+++def test_members_can_be_turned_on_independently() -> None:+ """Its own flag, approved separately from message content."""+ intents = _gateway(members=True).connection._intents+ assert intents.members is True+ assert intents.message_content is False+++def test_commands_register_globally_not_per_guild() -> None:+ """Decision #7: one application-wide command set, not one per guild."""+ assert _gateway().connection._command_guild_id is None+++def test_no_dm_handler_is_wired() -> None:+ """A DM carries no guild, so it cannot be attributed to a tenant; the slot+ is left empty so any that arrive are dropped (G4)."""+ assert _gateway().connection._dm_handler is None+++async def test_start_with_retry_retries_the_initial_connect_then_attaches(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A failed initial connect is not terminal: it retries with backoff, and+ on the first success fires on_connected (which attaches the running bridges)+ exactly once."""+ attached: list[DiscordConnection] = []++ async def on_connected(conn: DiscordConnection) -> None:+ attached.append(conn)++ gateway = _gateway(on_connected=on_connected)++ attempts = 0++ async def flaky_start() -> None:+ nonlocal attempts+ attempts += 1+ if attempts < 3:+ raise RuntimeError("gateway unreachable")++ async def _noop_close() -> None: ...++ slept: list[float] = []++ async def fake_sleep(delay: float) -> None:+ slept.append(delay)++ monkeypatch.setattr(gateway, "start", flaky_start)+ monkeypatch.setattr(gateway._connection, "close", _noop_close)+ monkeypatch.setattr(+ "switch_core.bridges.collaboration.discord.gateway.asyncio.sleep", fake_sleep+ )++ await gateway.start_with_retry()++ assert attempts == 3 # failed twice, succeeded on the third+ assert slept == [5.0, 10.0] # backoff doubled after each failure+ assert attached == [gateway.connection] # fired once, after the successdiff --git a/core/tests/switch_core/bridges/collaboration/test_discord_gateway_routing.py b/core/tests/switch_core/bridges/collaboration/test_discord_gateway_routing.pynew file mode 100644index 000000000..634dc4c2e--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_discord_gateway_routing.py@@ -0,0 +1,363 @@+"""The shared connection routes each guild message by resolving it fresh.++This is where the isolation guards on the multi-tenant socket are pinned:+- G1: the dispatch runs with no tenant bound, and the tenant is resolved fresh+ per event (nothing about a guild's tenant is cached on the connection).+- G3: a guild with no active install resolves to nothing and is dropped, never+ routed to a default or first tenant.+"""++from __future__ import annotations++from typing import Any++import discord++from switch_core.bridges.collaboration.discord.adapter import (+ DiscordAdapter,+ DiscordConnectionConfig,+)+from switch_core.bridges.collaboration.discord.connection import DiscordConnection+from switch_core.bridges.collaboration.discord.gateway import DiscordGatewayClient+from switch_core.bridges.collaboration.install_service import (+ WebhookBridgeUnavailable,+ WebhookTarget,+ WebhookWorkspaceUnknown,+)+from switch_core.tenant_context import current_tenant_id, tenant_scope++GUILD_ID = 42+++class _FakeInstallService:+ def __init__(+ self, *, target: WebhookTarget | None = None, error: Exception | None = None+ ) -> None:+ self._target = target+ self._error = error+ self.calls: list[tuple[str, str]] = []+ self.revoked_calls: list[tuple[str, str, str]] = []++ async def resolve_by_workspace(+ self, *, platform: str, workspace_id: str+ ) -> WebhookTarget:+ self.calls.append((platform, workspace_id))+ if self._error is not None:+ raise self._error+ assert self._target is not None+ return self._target++ async def revoked(self, *, platform: str, workspace_id: str, reason: str) -> None:+ self.revoked_calls.append((platform, workspace_id, reason))+++def _gateway(install_service: Any) -> DiscordGatewayClient:+ async def _noop_on_connected(connection: DiscordConnection) -> None:+ # These tests drive the event handlers directly; the connect/attach+ # path is exercised in test_discord_gateway.+ ...++ return DiscordGatewayClient(+ bot_token="bot-token",+ message_content=False,+ members=False,+ install_service=install_service,+ on_connected=_noop_on_connected,+ )+++def _shared_adapter() -> DiscordAdapter:+ return DiscordAdapter(+ config=DiscordConnectionConfig(guild_id=str(GUILD_ID), event_delivery="shared")+ )+++def _message(guild_id: int | None) -> discord.Message:+ guild = None if guild_id is None else type("_G", (), {"id": guild_id})()+ # A human author (id 1, not the unconnected gateway's bot id 0) and a plain+ # post type, so the gateway's cheap pre-filter passes it through to routing.+ author = type("_A", (), {"id": 1})()+ return type(+ "_M",+ (),+ {"guild": guild, "author": author, "type": discord.MessageType.default},+ )() # type: ignore[return-value]+++def _target(adapter: Any) -> WebhookTarget:+ return WebhookTarget(+ tenant_id="tenant-a", platform="discord", bridge_id="bridge-1", adapter=adapter+ )+++async def test_a_resolved_message_is_dispatched_to_its_bridge() -> None:+ adapter = _shared_adapter()+ seen: dict[str, Any] = {}++ async def fake_dispatch(message: discord.Message) -> None:+ seen["message"] = message++ adapter.dispatch_inbound = fake_dispatch # type: ignore[method-assign]+ service = _FakeInstallService(target=_target(adapter))+ gateway = _gateway(service)++ message = _message(GUILD_ID)+ await gateway._on_guild_message(message)++ assert service.calls == [("discord", str(GUILD_ID))]+ assert seen["message"] is message+ # The inert bridge was handed the shared connection on first use.+ assert adapter._connection is gateway.connection+++async def test_dispatch_runs_with_no_tenant_bound() -> None:+ """G1: even if the caller had a tenant bound, the dispatch does not — each+ handler below binds the tenant of the room it acts on."""+ adapter = _shared_adapter()+ seen: dict[str, Any] = {}++ async def fake_dispatch(message: discord.Message) -> None:+ seen["tenant_during"] = current_tenant_id()++ adapter.dispatch_inbound = fake_dispatch # type: ignore[method-assign]+ gateway = _gateway(_FakeInstallService(target=_target(adapter)))++ with tenant_scope("tenant-somebody-else"):+ await gateway._on_guild_message(_message(GUILD_ID))+ # The binding is restored for the caller after the event (G1).+ assert current_tenant_id() == "tenant-somebody-else"++ assert seen["tenant_during"] is None+++async def test_a_guild_with_no_active_install_is_dropped() -> None:+ """G3: fails closed — no default or first tenant."""+ adapter = _shared_adapter()+ dispatched = False++ async def fake_dispatch(message: discord.Message) -> None:+ nonlocal dispatched+ dispatched = True++ adapter.dispatch_inbound = fake_dispatch # type: ignore[method-assign]+ gateway = _gateway(+ _FakeInstallService(error=WebhookWorkspaceUnknown("no tenant holds it"))+ )++ await gateway._on_guild_message(_message(GUILD_ID))++ assert dispatched is False+++async def test_a_bridge_not_yet_running_is_dropped() -> None:+ gateway = _gateway(+ _FakeInstallService(error=WebhookBridgeUnavailable("no bridge yet"))+ )+ # No adapter to dispatch to; the point is it does not raise.+ await gateway._on_guild_message(_message(GUILD_ID))+++async def test_a_dm_shaped_event_is_ignored() -> None:+ """Defensive: the connection routes DMs to the (unset) DM handler, but a+ guild-less event reaching here is dropped before any resolution (G4)."""+ service = _FakeInstallService()+ gateway = _gateway(service)++ await gateway._on_guild_message(_message(None))++ assert service.calls == []+++async def test_the_bots_own_post_is_dropped_before_any_resolution() -> None:+ """Perf: an own post needs no tenant and no DB, so the shared socket spends+ no resolution on it (it would be dropped again in the adapter regardless)."""+ service = _FakeInstallService()+ gateway = _gateway(service) # unconnected → bot_user_id 0++ message = _message(GUILD_ID)+ message.author.id = gateway.connection.bot_user_id # type: ignore[misc]+ await gateway._on_guild_message(message)++ assert service.calls == []+++async def test_a_non_post_message_type_is_dropped_before_any_resolution() -> None:+ service = _FakeInstallService()+ gateway = _gateway(service)++ message = _message(GUILD_ID)+ message.type = discord.MessageType.pins_add # type: ignore[misc]+ await gateway._on_guild_message(message)++ assert service.calls == []+++async def test_a_non_discord_bridge_is_dropped_not_dispatched() -> None:+ """A guild resolving to a non-Discord bridge is a wiring fault, not a+ message to force through."""++ class _NotDiscord:+ pass++ gateway = _gateway(_FakeInstallService(target=_target(_NotDiscord())))+ await gateway._on_guild_message(_message(GUILD_ID)) # logs and returns+++class _FakeResponse:+ def __init__(self) -> None:+ self.refusals: list[tuple[str, bool]] = []++ async def send_message(self, content: str, *, ephemeral: bool = False) -> None:+ self.refusals.append((content, ephemeral))+++def _interaction(+ guild_id: int | None,+ kind: discord.InteractionType = discord.InteractionType.application_command,+) -> Any:+ return type(+ "_I", (), {"guild_id": guild_id, "type": kind, "response": _FakeResponse()}+ )()+++def _press(guild_id: int | None) -> Any:+ return _interaction(guild_id, discord.InteractionType.component)+++def _command() -> Any:+ return type("_C", (), {"name": "help"})()+++async def test_a_slash_command_is_routed_to_its_guilds_bridge() -> None:+ adapter = _shared_adapter()+ seen: dict[str, Any] = {}++ async def fake_slash(interaction: Any, command: Any, values: Any) -> None:+ seen["tenant_during"] = current_tenant_id()+ seen["command"] = command++ adapter.dispatch_slash = fake_slash # type: ignore[method-assign]+ gateway = _gateway(_FakeInstallService(target=_target(adapter)))++ interaction = _interaction(GUILD_ID)+ command = _command()+ with tenant_scope("tenant-somebody-else"):+ await gateway._on_slash(interaction, command, {})++ assert seen["command"] is command+ assert seen["tenant_during"] is None # G1+ assert interaction.response.refusals == []+ assert adapter._connection is gateway.connection+++async def test_a_slash_from_an_uninstalled_guild_is_refused_ephemerally() -> None:+ """Global commands appear everywhere; an unmapped guild gets an ephemeral+ refusal rather than an unacknowledged 'interaction failed' (and G3)."""+ gateway = _gateway(+ _FakeInstallService(error=WebhookWorkspaceUnknown("no tenant holds it"))+ )+ interaction = _interaction(GUILD_ID)++ await gateway._on_slash(interaction, _command(), {})++ assert len(interaction.response.refusals) == 1+ assert interaction.response.refusals[0][1] is True # ephemeral+++async def test_a_slash_with_no_guild_is_refused() -> None:+ gateway = _gateway(_FakeInstallService())+ interaction = _interaction(None)++ await gateway._on_slash(interaction, _command(), {})++ assert len(interaction.response.refusals) == 1+++async def test_the_shared_connection_takes_presses_on_cards() -> None:+ """Without a handler the connection drops every press, and Discord tells+ the presser it failed."""+ gateway = _gateway(_FakeInstallService())++ async def _connect(**_: Any) -> None: ...++ gateway.connection.connect = _connect # type: ignore[method-assign]+ await gateway.start()++ assert gateway.connection._interaction_handler == gateway._on_interaction+++async def test_a_press_is_routed_to_its_guilds_bridge() -> None:+ adapter = _shared_adapter()+ seen: dict[str, Any] = {}++ async def fake_press(interaction: Any) -> None:+ seen["tenant_during"] = current_tenant_id()+ seen["interaction"] = interaction++ adapter.dispatch_interaction = fake_press # type: ignore[method-assign]+ service = _FakeInstallService(target=_target(adapter))+ gateway = _gateway(service)++ press = _press(GUILD_ID)+ with tenant_scope("tenant-somebody-else"):+ await gateway._on_interaction(press)++ assert seen["interaction"] is press+ assert seen["tenant_during"] is None # G1+ assert service.calls == [("discord", str(GUILD_ID))]+ assert press.response.refusals == []+ assert adapter._connection is gateway.connection+++async def test_a_press_from_an_uninstalled_guild_is_refused_ephemerally() -> None:+ """A card left behind after a disconnect is still pressable; the presser is+ told why nothing happened (and G3)."""+ gateway = _gateway(+ _FakeInstallService(error=WebhookWorkspaceUnknown("no tenant holds it"))+ )+ press = _press(GUILD_ID)++ await gateway._on_interaction(press)++ assert press.response.refusals == [+ ("Switch is not connected to this server.", True)+ ]+++async def test_a_slash_invocation_is_left_to_the_command_tree() -> None:+ service = _FakeInstallService()+ gateway = _gateway(service)+ interaction = _interaction(GUILD_ID)++ await gateway._on_interaction(interaction)++ assert service.calls == []+ assert interaction.response.refusals == []+++def _guild(guild_id: int) -> Any:+ return type("_G", (), {"id": guild_id, "name": "Acme"})()+++async def test_being_removed_from_a_guild_ends_its_install() -> None:+ """Decision #8: the platform-initiated end path, which revokes no token."""+ service = _FakeInstallService()+ gateway = _gateway(service)++ await gateway._on_guild_remove(_guild(GUILD_ID))++ assert service.revoked_calls == [+ ("discord", str(GUILD_ID), "the bot was removed from the Discord server")+ ]+++async def test_joining_a_guild_provisions_nothing() -> None:+ """An out-of-band join is logged and ignored — nothing is resolved or ended;+ only a recorded install makes a guild route anywhere (G3)."""+ service = _FakeInstallService()+ gateway = _gateway(service)++ await gateway._on_guild_join(_guild(GUILD_ID))++ assert service.calls == []+ assert service.revoked_calls == []diff --git a/core/tests/switch_core/bridges/collaboration/test_discord_installer.py b/core/tests/switch_core/bridges/collaboration/test_discord_installer.pynew file mode 100644index 000000000..d1cc44b31--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_discord_installer.py@@ -0,0 +1,212 @@+"""The distributed Discord installer: the authorize URL, the tokenless grant,+and the two half-states its connection config refuses.++Discord has no webhook, so the inbound half of the ABC is stubbed to raise;+those stubs are tested only to prove they fail loud rather than silently doing+nothing, because nothing reaches them in normal operation.+"""++from __future__ import annotations++from urllib.parse import parse_qs, urlparse++import httpx+import pytest++from switch_core.bridges.collaboration.discord.adapter import DiscordConnectionConfig+from switch_core.bridges.collaboration.discord.install import (+ PERMISSIONS,+ SCOPES,+ DiscordAppInstaller,+)+from switch_core.bridges.collaboration.install import MessagingInstallError+++def installer() -> DiscordAppInstaller:+ return DiscordAppInstaller(+ client_id="123456789012345678",+ client_secret="secret",+ application_id="123456789012345678",+ )+++class TestTheAuthorizeUrl:+ def test_it_carries_the_state_and_redirect_unchanged(+ self, installer: DiscordAppInstaller+ ) -> None:+ redirect = "https://switch.example/messaging/discord/oauth/callback"+ url = installer.authorize_url(state="opaque-state", redirect_uri=redirect)+ query = parse_qs(urlparse(url).query)+ assert query["state"] == ["opaque-state"]+ assert query["redirect_uri"] == [redirect]+ assert query["response_type"] == ["code"]++ def test_it_asks_for_the_pinned_scopes_and_permissions(+ self, installer: DiscordAppInstaller+ ) -> None:+ """Decision #11: the scopes and permission integer are fixed in code,+ and this is where the authorize URL is held to them."""+ url = installer.authorize_url(state="s", redirect_uri="https://x.example/cb")+ query = parse_qs(urlparse(url).query)+ assert query["scope"] == [" ".join(SCOPES)]+ assert query["permissions"] == [str(PERMISSIONS)]+++class TestRedeem:+ async def _grant(+ self,+ installer: DiscordAppInstaller,+ monkeypatch: pytest.MonkeyPatch,+ response: httpx.Response,+ ):+ async def fake_post(self, url, **kwargs): # type: ignore[no-untyped-def]+ return response++ monkeypatch.setattr(httpx.AsyncClient, "post", fake_post)+ return await installer.redeem(code="the-code", redirect_uri="https://x/cb")++ async def test_a_good_exchange_becomes_a_tokenless_grant(+ self, installer: DiscordAppInstaller, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ grant = await self._grant(+ installer,+ monkeypatch,+ httpx.Response(+ 200,+ json={+ "access_token": "user-token-we-drop",+ "scope": "bot applications.commands",+ "guild": {"id": "42", "name": "Acme"},+ },+ ),+ )+ assert grant.external_workspace_id == "42"+ assert grant.workspace_name == "Acme"+ assert grant.bot_token is None+ assert grant.scopes == "bot applications.commands"++ async def test_a_guild_with_no_name_falls_back_to_its_id(+ self, installer: DiscordAppInstaller, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ grant = await self._grant(+ installer,+ monkeypatch,+ httpx.Response(200, json={"guild": {"id": "42"}}),+ )+ assert grant.workspace_name == "42"++ async def test_a_non_2xx_is_refused(+ self, installer: DiscordAppInstaller, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ with pytest.raises(MessagingInstallError, match="Discord refused"):+ await self._grant(+ installer, monkeypatch, httpx.Response(400, text="invalid_grant")+ )++ async def test_no_guild_means_the_bot_was_not_added(+ self, installer: DiscordAppInstaller, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """No `guild` in the response is the bot scope dropped or a cancel; there+ is nothing to attribute the install to."""+ with pytest.raises(MessagingInstallError, match="no guild"):+ await self._grant(+ installer,+ monkeypatch,+ httpx.Response(200, json={"access_token": "t"}),+ )+++class TestConnectionConfig:+ def test_it_renders_a_shared_tokenless_config(+ self, installer: DiscordAppInstaller+ ) -> None:+ from switch_core.bridges.collaboration.install import InstallGrant++ config = installer.connection_config(+ InstallGrant(+ external_workspace_id="42",+ workspace_name="Acme",+ bot_token=None,+ scopes="bot applications.commands",+ )+ )+ assert config == {"guild_id": "42", "event_delivery": "shared"}+++class TestTheWorkspaceABridgeServes:+ def test_a_shared_bridge_serves_its_guild(+ self, installer: DiscordAppInstaller+ ) -> None:+ assert (+ installer.workspace_of_bridge(+ {"guild_id": "42", "event_delivery": "shared"}+ )+ == "42"+ )++ def test_a_self_registered_bridge_is_not_checked(+ self, installer: DiscordAppInstaller+ ) -> None:+ """Its own token reaches only what its owner added it to."""+ assert (+ installer.workspace_of_bridge(+ {"guild_id": "42", "event_delivery": "own_connection"}+ )+ is None+ )+++class TestTheWebhookHalfIsStubbed:+ """Discord delivers over the Gateway; these raise so a mistaken caller sees+ it rather than silently getting nothing.++ `verify_webhook` is the exception: it is the one an unauthenticated stranger+ can reach (it runs first for any POST to `/messaging/discord/*`), so it+ raises `MessagingInstallError`, which the route turns into a 404 rather than+ a repeatable 500."""++ async def test_revoke_raises(self, installer: DiscordAppInstaller) -> None:+ with pytest.raises(NotImplementedError):+ await installer.revoke(bot_token="whatever")++ def test_verify_webhook_raises_not_found(+ self, installer: DiscordAppInstaller+ ) -> None:+ with pytest.raises(MessagingInstallError):+ installer.verify_webhook(headers={}, body=b"")++ def test_parse_webhook_raises(self, installer: DiscordAppInstaller) -> None:+ with pytest.raises(NotImplementedError):+ installer.parse_webhook(endpoint="events", headers={}, body=b"")++ def test_workspace_of_event_raises(self, installer: DiscordAppInstaller) -> None:+ with pytest.raises(NotImplementedError):+ installer.workspace_of_event({})++ def test_revocation_of_event_raises(self, installer: DiscordAppInstaller) -> None:+ with pytest.raises(NotImplementedError):+ installer.revocation_of_event({})+++class TestConnectionConfigHalfStates:+ """The two shapes that look configured and cannot work."""++ def test_own_connection_needs_a_token(self) -> None:+ with pytest.raises(ValueError, match="bot_token is required"):+ DiscordConnectionConfig(guild_id="42", event_delivery="own_connection")++ def test_shared_must_not_carry_a_token(self) -> None:+ with pytest.raises(ValueError, match="bot_token must be empty"):+ DiscordConnectionConfig(+ guild_id="42", event_delivery="shared", bot_token="a-token"+ )++ def test_a_self_registered_config_still_validates(self) -> None:+ """The default path is unchanged: own_connection with a token."""+ config = DiscordConnectionConfig(guild_id="42", bot_token="a-token")+ assert config.event_delivery == "own_connection"++ def test_a_shared_config_validates_without_a_token(self) -> None:+ config = DiscordConnectionConfig(guild_id="42", event_delivery="shared")+ assert config.bot_token is Nonediff --git a/core/tests/switch_core/bridges/collaboration/test_discord_isolation_guards.py b/core/tests/switch_core/bridges/collaboration/test_discord_isolation_guards.pynew file mode 100644index 000000000..db374f8f0--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_discord_isolation_guards.py@@ -0,0 +1,168 @@+"""The four isolation guards on the shared, multi-tenant Discord connection.++Each guard has a test that fails without it. G1 (per-event scoping, no tenant+cached, resolved fresh) and G3 (no default tenant, unmapped guild dropped) live+in `test_discord_gateway_routing.py`, where the routing they guard is. G4's+intent half is in `test_discord_gateway.py`. This file pins the two remaining+faces: G4's drop-before-routing and G2's tenant-scoped identity.+"""++from __future__ import annotations++from typing import Any++import discord+import pytest++from switch_core.bridges.collaboration.adapter import ChannelNotBindable+from switch_core.bridges.collaboration.discord.adapter import (+ DiscordAdapter,+ DiscordConnectionConfig,+)+from switch_core.bridges.collaboration.discord.connection import DiscordConnection+++def _connection() -> DiscordConnection:+ return DiscordConnection(+ bot_token="bot-token",+ intents=discord.Intents.none(),+ command_guild_id=None,+ )+++def _message(guild_id: int | None) -> Any:+ guild = None if guild_id is None else type("_G", (), {"id": guild_id})()+ return type("_M", (), {"guild": guild})()+++# ── G4 — no guild-less routing ───────────────────────────────────────────────+++async def test_a_dm_is_dropped_before_routing() -> None:+ """A guild-less message reaches no handler when the DM slot is empty, which+ is how the shared connection is wired — a DM carries no guild to attribute+ to a tenant."""+ conn = _connection()+ routed: list[Any] = []++ async def catch_all(message: Any) -> None:+ routed.append(message)++ conn.set_guild_message_handler(catch_all)+ # No DM handler set (the shared connection leaves it unset).+ on_message = conn._make_on_message()++ await on_message(_message(None)) # a DM+ assert routed == []++ await on_message(_message(42)) # a guild message still routes+ assert len(routed) == 1+++# ── G2 — tenant-scoped identity ──────────────────────────────────────────────+++async def test_each_guilds_bridge_has_its_own_identity_caches() -> None:+ """The same Discord user in two tenants' guilds yields two independent+ records: each guild is served by its own adapter (one install = one tenant,+ decision D2), so a user-id-keyed cache on one is not shared with the other.+ The database side is scoped the same way — puppet and external-user rows are+ written under each bridge's tenant through row-level security."""+ tenant_a = DiscordAdapter(+ config=DiscordConnectionConfig(guild_id="1", event_delivery="shared")+ )+ tenant_b = DiscordAdapter(+ config=DiscordConnectionConfig(guild_id="2", event_delivery="shared")+ )++ tenant_a._user_names[999] = "alice-in-a"++ assert tenant_a._user_names is not tenant_b._user_names+ assert 999 not in tenant_b._user_names+++# ── A bridge reaches only its own guild's channels ───────────────────────────+++class _Webhook:+ id = 7001+ name = "Switch"+ token = "placeholder-webhook-token"++ def __init__(self, sent: list[dict[str, Any]]) -> None:+ self._sent = sent++ async def send(self, content: str = "", **kwargs: Any) -> Any:+ self._sent.append({"content": content, **kwargs})+ channel = type("_Ch", (), {"id": 555})()+ return type("_Sent", (), {"id": 8001, "channel": channel})()+++class _Channel:+ """A text channel in `guild_id`, or a DM when that is None. The shared bot+ can see every tenant's channels, because it is in every tenant's guild."""++ id = 555+ parent_id = None++ def __init__(self, guild_id: int | None) -> None:+ self.guild = (+ None+ if guild_id is None+ else type("_G", (), {"id": guild_id, "default_role": None})()+ )+ self.sent: list[dict[str, Any]] = []++ async def webhooks(self) -> list[Any]:+ return []++ async def create_webhook(self, *, name: str) -> _Webhook:+ return _Webhook(self.sent)+++def _guild_1_bridge_seeing(channel: _Channel, delivery: str) -> DiscordAdapter:+ config = (+ DiscordConnectionConfig(guild_id="1", event_delivery="shared")+ if delivery == "shared"+ else DiscordConnectionConfig(guild_id="1", bot_token="placeholder-token")+ )+ adapter = DiscordAdapter(config=config)+ client = type("_C", (), {"get_channel": lambda self, _id: channel})()+ adapter._connection = type("_Conn", (), {"client": client})() # type: ignore[assignment]+ return adapter++[email protected]("delivery", ["shared", "own_connection"])+async def test_a_channel_in_another_guild_cannot_be_bound(delivery: str) -> None:+ """Binding a room to a channel by id asks the bridge first. Being able to+ see the channel proves nothing on the shared bot, and even a tenant's own+ bot serves one guild per bridge."""+ adapter = _guild_1_bridge_seeing(_Channel(guild_id=2), delivery)++ with pytest.raises(ChannelNotBindable):+ await adapter.require_bindable_channel("555")+++async def test_a_channel_in_its_own_guild_can_be_bound() -> None:+ adapter = _guild_1_bridge_seeing(_Channel(guild_id=1), "shared")++ await adapter.require_bindable_channel("555")+++async def test_a_dm_cannot_be_bound_on_the_shared_connection() -> None:+ """Shared delivery carries no DMs, so a DM is not this bridge's."""+ adapter = _guild_1_bridge_seeing(_Channel(guild_id=None), "shared")++ with pytest.raises(ChannelNotBindable):+ await adapter.require_bindable_channel("555")+++async def test_a_bridge_does_not_post_into_another_guild() -> None:+ """The backstop under binding: every lookup refuses another guild's+ channel, so nothing reaches one even if a room names it."""+ channel = _Channel(guild_id=2)+ adapter = _guild_1_bridge_seeing(channel, "shared")++ await adapter.send_message("555", "OrgA-agent", "hello from org A")++ assert channel.sent == []diff --git a/core/tests/switch_core/bridges/collaboration/test_discord_member_search_budget.py b/core/tests/switch_core/bridges/collaboration/test_discord_member_search_budget.pynew file mode 100644index 000000000..3e890a786--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_discord_member_search_budget.py@@ -0,0 +1,95 @@+"""Member searches have a budget on each Discord socket.++A search is a Gateway send, and discord.py holds every send past 110 a minute+until the minute is up. On the shared connection that is every organisation's+budget at once, so searches are capped below it and refused outright once the+cap is spent: the person searching is told to try again, instead of waiting on+a search that times out.+"""++from __future__ import annotations++from typing import Any++import discord+import pytest++from switch_core.bridges.collaboration.adapter import DirectorySearchBusy+from switch_core.bridges.collaboration.discord import connection as connection_module+from switch_core.bridges.collaboration.discord.adapter import (+ DiscordAdapter,+ DiscordConnectionConfig,+)+from switch_core.bridges.collaboration.discord.connection import (+ _MEMBER_SEARCHES_PER_WINDOW,+ DiscordConnection,+)+++class _Clock:+ def __init__(self) -> None:+ self.now = 1000.0++ def __call__(self) -> float:+ return self.now+++def clock(monkeypatch: pytest.MonkeyPatch) -> _Clock:+ fake = _Clock()+ monkeypatch.setattr(connection_module, "_clock", fake)+ return fake+++def _connection() -> DiscordConnection:+ return DiscordConnection(+ bot_token="t", intents=discord.Intents.none(), command_guild_id=None+ )+++def _spend(connection: DiscordConnection) -> None:+ for _ in range(_MEMBER_SEARCHES_PER_WINDOW):+ connection.take_member_search()+++def test_searches_within_the_budget_go_through(clock: _Clock) -> None:+ _spend(_connection())+++def test_the_next_one_is_refused_and_says_when_to_retry(clock: _Clock) -> None:+ connection = _connection()+ _spend(connection)+ clock.now += 20++ with pytest.raises(DirectorySearchBusy) as refused:+ connection.take_member_search()++ assert refused.value.retry_after == pytest.approx(40)+ assert "try again in 40 seconds" in str(refused.value)+++def test_the_budget_comes_back_as_the_window_moves(clock: _Clock) -> None:+ connection = _connection()+ _spend(connection)+ clock.now += 60++ connection.take_member_search()+++async def test_a_spent_budget_stops_the_search_before_it_reaches_discord(+ clock: _Clock,+) -> None:+ connection = _connection()+ _spend(connection)+ adapter = DiscordAdapter(+ config=DiscordConnectionConfig(guild_id="900", event_delivery="shared")+ )+ adapter.attach_shared_connection(connection)++ async def _no_guild() -> Any:+ raise AssertionError("searched Discord with the budget spent")++ adapter._get_guild = _no_guild # type: ignore[method-assign]++ with pytest.raises(DirectorySearchBusy):+ await adapter.search_directory_users("lou")diff --git a/core/tests/switch_core/bridges/collaboration/test_discord_provisioning.py b/core/tests/switch_core/bridges/collaboration/test_discord_provisioning.pyindex 49cdfd039..19f9ba940 100644--- a/core/tests/switch_core/bridges/collaboration/test_discord_provisioning.py+++ b/core/tests/switch_core/bridges/collaboration/test_discord_provisioning.py@@ -122,7 +122,7 @@ class _FakePrivateChannel:def _wire(adapter: DiscordAdapter, guild: _FakeGuild, channels: dict[int, Any] | None = None) -> None:- adapter._client = _FakeClient(guild, channels) # type: ignore[assignment]+ adapter._connection._client = _FakeClient(guild, channels) # type: ignore[assignment]# ── create_channel ───────────────────────────────────────────────────────────diff --git a/core/tests/switch_core/bridges/collaboration/test_discord_sdk_only.py b/core/tests/switch_core/bridges/collaboration/test_discord_sdk_only.pyindex 39f3f2ff7..feb1e3f11 100644--- a/core/tests/switch_core/bridges/collaboration/test_discord_sdk_only.py+++ b/core/tests/switch_core/bridges/collaboration/test_discord_sdk_only.py@@ -309,8 +309,8 @@ def _adapter(channels: dict[int, Any]) -> DiscordAdapter:adapter = DiscordAdapter(config=DiscordConnectionConfig(bot_token="token", guild_id=str(GUILD_ID)))- adapter._bot_user_id = BOT_USER_ID- adapter._client = _Client(channels) # type: ignore[assignment]+ adapter._connection._bot_user_id = BOT_USER_ID+ adapter._connection._client = _Client(channels) # type: ignore[assignment]return adapter@@ -508,7 +508,7 @@ async def test_a_thread_the_bot_cannot_open_never_becomes_the_whole_channel() ->a private conversation an audience, and nothing takes it back."""adapter, channel, webhook = _no_thread_yet()- client: Any = adapter._client+ client: Any = adapter._connection._clientclient.fetch_errors[ROOT_MESSAGE_ID] = discord.Forbidden( # type: ignore[arg-type]_Response(), "not a member of this thread")diff --git a/core/tests/switch_core/bridges/collaboration/test_discord_shared_bridge.py b/core/tests/switch_core/bridges/collaboration/test_discord_shared_bridge.pynew file mode 100644index 000000000..48925b70b--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_discord_shared_bridge.py@@ -0,0 +1,146 @@+"""A shared-delivery Discord bridge is constructible and inert.++The distributed app's per-guild bridge (decision #3) opens no Gateway connection+of its own — it will register its guild with the one shared connection once that+is built. Until then it exists as a bridge but neither sends nor receives, and+any outbound path fails loud rather than pretending. This pins that state so a+completing install can produce such a bridge without it crashing on start and+without it silently swallowing sends.+"""++from __future__ import annotations++import pytest++from switch_core.bridges.collaboration.discord.adapter import (+ DiscordAdapter,+ DiscordConnectionConfig,+)+from switch_core.bridges.collaboration.models import (+ InboundAgentJoin,+ InboundAppJoin,+ InboundCommand,+ InboundMessage,+ InboundUserJoin,+)++GUILD_ID = "900"+++def _shared_adapter() -> DiscordAdapter:+ return DiscordAdapter(+ config=DiscordConnectionConfig(guild_id=GUILD_ID, event_delivery="shared")+ )+++async def _noop_message(_: InboundMessage) -> None: ...+async def _noop_command(_: InboundCommand) -> None: ...+async def _noop_agent(_: InboundAgentJoin) -> None: ...+async def _noop_user(_: InboundUserJoin) -> None: ...+async def _noop_app(_: InboundAppJoin) -> None: ...+++async def _start(adapter: DiscordAdapter) -> None:+ await adapter.start(+ _noop_message, _noop_command, _noop_agent, _noop_user, _noop_app+ )+++def test_a_shared_config_builds_an_adapter_with_no_connection() -> None:+ adapter = _shared_adapter()+ assert adapter._connection is None+++def test_an_own_connection_config_still_builds_its_connection() -> None:+ adapter = DiscordAdapter(+ config=DiscordConnectionConfig(guild_id=GUILD_ID, bot_token="token")+ )+ assert adapter._connection is not None+++async def test_inert_start_opens_no_connection() -> None:+ """start() returns without dialling Discord and stores the callbacks for the+ moment the shared connection attaches; nothing is opened."""+ adapter = _shared_adapter()+ await _start(adapter)+ assert adapter._connection is None+ assert adapter._on_message is _noop_message+++async def test_stopping_an_inert_bridge_is_safe() -> None:+ adapter = _shared_adapter()+ await _start(adapter)+ await adapter.stop() # no connection to close+++async def test_an_outbound_path_fails_loud_while_inert() -> None:+ """It does not silently no-op: reaching the client before the shared+ connection is attached is a bug, and it surfaces as one."""+ adapter = _shared_adapter()+ with pytest.raises(RuntimeError, match="shared delivery"):+ adapter._require_client()+++class _StubConnection:+ def __init__(self) -> None:+ self.closed = False++ async def close(self) -> None:+ self.closed = True+++async def test_stopping_a_shared_bridge_detaches_but_does_not_close_the_socket() -> (+ None+):+ """The shared socket is the deployment's, not this bridge's: closing it on a+ disconnect would drop every other tenant's Discord traffic. stop() detaches+ instead, and a restarted bridge re-attaches to the live socket on its next+ event rather than holding a stale one."""+ adapter = _shared_adapter()+ await _start(adapter)+ shared = _StubConnection()+ adapter.attach_shared_connection(shared) # type: ignore[arg-type]+ assert adapter._connection is shared++ await adapter.stop()++ assert shared.closed is False+ assert adapter._connection is None+++async def test_stopping_an_own_connection_bridge_closes_its_socket() -> None:+ """An own-connection bridge does own its socket, so stopping it closes it."""+ adapter = DiscordAdapter(+ config=DiscordConnectionConfig(guild_id=GUILD_ID, bot_token="token")+ )+ stub = _StubConnection()+ adapter._connection = stub # type: ignore[assignment]++ await adapter.stop()++ assert stub.closed is True+++async def test_attach_sets_the_connection_and_fires_on_attached_once() -> None:+ """Attaching wakes the inert bridge and re-runs the work that needed the+ connection (via _on_attached). It is set-once: a second attach is a no-op and+ does not fire again."""+ adapter = _shared_adapter()+ await _start(adapter)+ fired: list[int] = []+ adapter.set_on_attached(lambda: fired.append(1))++ first = _StubConnection()+ adapter.attach_shared_connection(first) # type: ignore[arg-type]+ adapter.attach_shared_connection(_StubConnection()) # type: ignore[arg-type]++ assert adapter._connection is first+ assert fired == [1]+++def test_a_shared_adapter_satisfies_the_shared_connection_protocol() -> None:+ """The lifecycle/gateway/boot narrow to this Protocol; an own-connection or+ non-Discord adapter is not meant to, so its capability is opt-in by shape."""+ from switch_core.bridges.collaboration.adapter import SupportsSharedConnection++ assert isinstance(_shared_adapter(), SupportsSharedConnection)diff --git a/core/tests/switch_core/bridges/collaboration/test_discord_slash_commands.py b/core/tests/switch_core/bridges/collaboration/test_discord_slash_commands.pyindex 15873ff7d..b2572b5b6 100644--- a/core/tests/switch_core/bridges/collaboration/test_discord_slash_commands.py+++ b/core/tests/switch_core/bridges/collaboration/test_discord_slash_commands.py@@ -36,7 +36,7 @@ def _adapter() -> DiscordAdapter:adapter = DiscordAdapter(config=DiscordConnectionConfig(bot_token="token", guild_id=str(GUILD_ID)))- adapter._bot_user_id = BOT_USER_ID+ adapter._connection._bot_user_id = BOT_USER_IDreturn adapter@@ -493,7 +493,7 @@ def _adapter_with_roles(roles: dict[int, str] | None = None, members: dict[int, str] | None = None) -> DiscordAdapter:adapter = _adapter()- adapter._client = _RoleClient(_RoleGuild(roles or {}, members or {})) # type: ignore[assignment]+ adapter._connection._client = _RoleClient(_RoleGuild(roles or {}, members or {})) # type: ignore[assignment]return adapterdiff --git a/core/tests/switch_core/bridges/collaboration/test_install_service.py b/core/tests/switch_core/bridges/collaboration/test_install_service.pyindex ee1abf287..32757ba9d 100644--- a/core/tests/switch_core/bridges/collaboration/test_install_service.py+++ b/core/tests/switch_core/bridges/collaboration/test_install_service.py@@ -70,8 +70,9 @@ class _FakeInstaller(MessagingAppInstaller):platform: ClassVar[str] = "slack"- def __init__(self, workspace_id: str) -> None:+ def __init__(self, workspace_id: str, *, tokenless: bool = False) -> None:self.workspace_id = workspace_id+ self.tokenless = tokenlessself.redeem_calls: list[str] = []self.revoked_tokens: list[str] = []self.revoke_error: Exception | None = None@@ -84,7 +85,10 @@ class _FakeInstaller(MessagingAppInstaller):return InstallGrant(external_workspace_id=self.workspace_id,workspace_name="Acme",- bot_token="xoxb-granted",+ # `None` stands in for a platform whose credential is+ # deployment-level, not per-install (Discord). The service must+ # store no token for it and revoke nothing on disconnect.+ bot_token=None if self.tokenless else "xoxb-granted",scopes="chat:write",)@@ -188,7 +192,7 @@ class _Fixture:self.service: MessagingInstallService-async def _fixture(harness: RLSHarness) -> _Fixture:+async def _fixture(harness: RLSHarness, *, tokenless: bool = False) -> _Fixture:fixture = _Fixture()suffix = uuid.uuid4().hex[:8]fixture.tenant_a = f"tenant-a-{suffix}"@@ -204,7 +208,7 @@ async def _fixture(harness: RLSHarness) -> _Fixture:fixture.user_id = user.idawait session.commit()- fixture.installer = _FakeInstaller(fixture.workspace)+ fixture.installer = _FakeInstaller(fixture.workspace, tokenless=tokenless)fixture.lifecycle = _FakeLifecycle(harness.restricted, fixture.tenant_a, suffix)installers = MessagingInstallerRegistry()installers.register(fixture.installer)@@ -631,3 +635,43 @@ class TestWhatTheOperatorSees:listed = await MessagingInstallStore().list_for_tenant(session)assert listed == []+++class TestATokenlessGrant:+ """A platform whose credential is deployment-level, not per-install (Discord).++ The grant carries no token, so there is nothing to encrypt at record time+ and nothing to revoke at the platform on disconnect — the app-level bot+ token is not this install's to end. The rest of the flow is unchanged.+ """++ async def test_complete_stores_no_token_and_still_builds_a_bridge(+ self, rls_harness: RLSHarness+ ) -> None:+ fixture = await _fixture(rls_harness, tokenless=True)+ state = await _begin(rls_harness.restricted, fixture, fixture.tenant_a)++ install = await fixture.service.complete(+ platform="slack", code="the-code", state_token=state+ )++ assert install.encrypted_bot_token is None+ assert install.bridge_id is not None+ assert len(fixture.lifecycle.registered) == 1++ async def test_disconnect_revokes_nothing_and_ends_cleanly(+ self, rls_harness: RLSHarness+ ) -> None:+ fixture = await _fixture(rls_harness, tokenless=True)+ install = await _installed(rls_harness.restricted, fixture, fixture.tenant_a)+ bridge_id = install.bridge_id++ ended = await fixture.service.disconnect(+ tenant_id=fixture.tenant_a, install_id=install.id+ )++ assert fixture.installer.revoked_tokens == []+ assert ended.status == INSTALL_DISCONNECTED+ assert ended.ended_at is not None+ assert ended.bridge_id is None+ assert fixture.lifecycle.removed == [bridge_id]diff --git a/core/tests/switch_core/bridges/collaboration/test_lifecycle_start_guards.py b/core/tests/switch_core/bridges/collaboration/test_lifecycle_start_guards.pynew file mode 100644index 000000000..d8f1dd5e9--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_lifecycle_start_guards.py@@ -0,0 +1,108 @@+"""A start guard can stop a bridge before any of it runs.++Guards answer what a bridge's own config cannot: whether the workspace it+names is its tenant's. A refusal has to come before the adapter is built, so a+refused bridge never reaches its platform and nothing is handed to the+starting listeners.+"""++from __future__ import annotations++import uuid+from collections.abc import Mapping++import pytest+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.bridges.collaboration.adapter import CollaborationAdapter+from switch_core.bridges.collaboration.models import BridgeStartRefused++from .test_lifecycle_tenant_binding import (+ _make_bridge,+ _make_tenant,+ _service,+ _StubAdapter,+ _StubConfig,+)+++async def _bridge(session_factory: async_sessionmaker[AsyncSession]) -> tuple[str, str]:+ tenant = f"tenant-{uuid.uuid4().hex[:8]}"+ async with session_factory() as session:+ await _make_tenant(session, tenant)+ bridge_id, _ = await _make_bridge(session, tenant_id=tenant)+ await session.commit()+ return tenant, bridge_id+++async def test_a_refused_bridge_runs_nothing(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ tenant, bridge_id = await _bridge(session_factory)+ service = _service(session_factory)+ service.register_adapter("mattermost", _StubAdapter, _StubConfig)+ asked: list[dict[str, object]] = []+ handed: list[CollaborationAdapter] = []++ async def refuse(**kwargs: object) -> None:+ asked.append(kwargs)+ raise BridgeStartRefused("not this tenant's")++ service.add_bridge_start_guard(refuse)+ service.add_bridge_starting_listener(handed.append)++ with pytest.raises(BridgeStartRefused):+ await service.start(bridge_id)++ assert asked == [+ {+ "bridge_id": bridge_id,+ "tenant_id": tenant,+ "bridge_type": "mattermost",+ "connection_config": {},+ }+ ]+ assert handed == []+ assert service.get_adapter(bridge_id) is None+++async def test_a_bridge_every_guard_allows_starts(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ _, bridge_id = await _bridge(session_factory)+ service = _service(session_factory)+ service.register_adapter("mattermost", _StubAdapter, _StubConfig)++ async def allow(**_: object) -> None: ...++ async def _run(*_: object) -> None: ...++ service._run_bridge = _run # type: ignore[method-assign]+ service.add_bridge_start_guard(allow)++ await service.start(bridge_id)++ assert service.get_adapter(bridge_id) is not None+ await service.stop_all()+++async def test_an_edit_can_be_checked_before_it_is_stored(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ """The edit route asks with the config it would store, not the old one."""+ service = _service(session_factory)+ seen: list[Mapping[str, object]] = []++ async def record(*, connection_config: Mapping[str, object], **_: object) -> None:+ seen.append(connection_config)++ service.add_bridge_start_guard(record)++ await service.check_start_guards(+ bridge_id="b",+ tenant_id="t",+ bridge_type="discord",+ connection_config={"guild_id": "2"},+ )++ assert seen == [{"guild_id": "2"}]diff --git a/core/tests/switch_core/bridges/collaboration/test_lifecycle_tenant_binding.py b/core/tests/switch_core/bridges/collaboration/test_lifecycle_tenant_binding.pyindex 86a998977..f0cf04f2e 100644--- a/core/tests/switch_core/bridges/collaboration/test_lifecycle_tenant_binding.py+++ b/core/tests/switch_core/bridges/collaboration/test_lifecycle_tenant_binding.py@@ -578,3 +578,24 @@ async def test_a_conflict_with_nothing_bound_fails_closed_to_the_non_disclosing_assert "Their Secret Teams" not in messageassert incumbent_tenant not in messageassert "already claimed" in message+++class _RunningBridge:+ def __init__(self, tenant_id: str) -> None:+ self.tenant_id = tenant_id++[email protected]_ambient_tenant+def test_get_hands_a_running_bridge_only_to_its_own_tenant(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ svc = _service(session_factory)+ bridge = _RunningBridge("tenant-a")+ svc._bridges["bridge-a"] = bridge # type: ignore[assignment]++ with tenant_scope("tenant-a"):+ assert svc.get("bridge-a") is bridge+ with tenant_scope("tenant-b"):+ assert svc.get("bridge-a") is None+ assert svc.get("bridge-a") is bridge+ assert svc.get("bridge-missing") is Nonediff --git a/core/tests/switch_core/bridges/collaboration/test_shared_bridge_install_guard.py b/core/tests/switch_core/bridges/collaboration/test_shared_bridge_install_guard.pynew file mode 100644index 000000000..790b027f9--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_shared_bridge_install_guard.py@@ -0,0 +1,189 @@+"""A bridge on the deployment's own app may only start for the tenant that+installed it.++Such a bridge reaches whatever workspace its config names through the one+credential every tenant shares, so a config naming another tenant's workspace+would put this tenant's rooms in it. The guard asks for the tenant's live+install of that workspace before the bridge runs.++Postgres is real because the install is read under row-level security, and+that read is what keeps one tenant's install from vouching for another's+bridge.+"""++from __future__ import annotations++import uuid+from collections.abc import Mapping+from dataclasses import dataclass++import pytest++from switch_core.bridges.collaboration.install import MessagingInstallerRegistry+from switch_core.bridges.collaboration.install_service import MessagingInstallService+from switch_core.bridges.collaboration.models import BridgeStartRefused+from switch_core.db.models import CollaborationBridge+from switch_core.db.stores.messaging_event_store import MessagingEventReceiptStore+from switch_core.db.stores.messaging_install_store import MessagingInstallStore+from tests.conftest import RLSHarness++from .test_install_service import (+ _ORIGIN,+ _SECRET,+ _begin,+ _FakeInstaller,+ _FakeLifecycle,+ _fixture,+)++pytestmark = pytest.mark.no_ambient_tenant+++class _SharedAppInstaller(_FakeInstaller):+ """A platform whose installed bridges all run on the deployment's credential."""++ def workspace_of_bridge(+ self, connection_config: Mapping[str, object]+ ) -> str | None:+ if connection_config.get("event_delivery") != "shared":+ return None+ return str(connection_config["workspace_id"])+++class _StartingLifecycle(_FakeLifecycle):+ """Asks the guard as the real lifecycle does when it starts the bridge+ the install flow registers, while the install's pointer is still empty."""++ service: MessagingInstallService+ workspace_id: str++ async def register(self, **kwargs: object) -> CollaborationBridge:+ bridge = await super().register(**kwargs)+ await self.service.refuse_uninstalled_bridge(+ bridge_id=bridge.id,+ tenant_id=self._tenant_id,+ bridge_type=str(kwargs["bridge_type"]),+ connection_config=_shared(self.workspace_id),+ )+ return bridge+++@dataclass(frozen=True)+class _Ids:+ tenant_a: str+ tenant_b: str+ workspace: str+ bridge_id: str+++def _shared(workspace_id: str) -> dict[str, object]:+ return {"workspace_id": workspace_id, "event_delivery": "shared"}+++async def _shared_app(harness: RLSHarness) -> tuple[MessagingInstallService, _Ids]:+ base = await _fixture(harness)+ suffix = uuid.uuid4().hex[:8]+ lifecycle = _StartingLifecycle(harness.restricted, base.tenant_a, suffix)+ installers = MessagingInstallerRegistry()+ installers.register(_SharedAppInstaller(base.workspace))+ service = MessagingInstallService(+ session_factory=harness.restricted,+ store=MessagingInstallStore(),+ receipts=MessagingEventReceiptStore(),+ installers=installers,+ lifecycle=lifecycle, # type: ignore[arg-type]+ public_origin=_ORIGIN,+ secret=_SECRET,+ )+ lifecycle.service = service+ lifecycle.workspace_id = base.workspace+ base.service = service+ state = await _begin(harness.restricted, base, base.tenant_a)+ install = await service.complete(platform="slack", code="c", state_token=state)+ assert install.bridge_id is not None+ return service, _Ids(+ tenant_a=base.tenant_a,+ tenant_b=base.tenant_b,+ workspace=base.workspace,+ bridge_id=install.bridge_id,+ )+++class TestWhatMayStart:+ async def test_the_bridge_the_install_built(self, rls_harness: RLSHarness) -> None:+ # Getting here at all is the install flow passing the guard while the+ # install's pointer was still empty.+ service, ids = await _shared_app(rls_harness)++ await service.refuse_uninstalled_bridge(+ bridge_id=ids.bridge_id,+ tenant_id=ids.tenant_a,+ bridge_type="slack",+ connection_config=_shared(ids.workspace),+ )++ async def test_a_bridge_that_is_not_on_the_shared_app(+ self, rls_harness: RLSHarness+ ) -> None:+ """Its own credential reaches only what its owner added it to."""+ service, ids = await _shared_app(rls_harness)++ await service.refuse_uninstalled_bridge(+ bridge_id="someone-elses",+ tenant_id=ids.tenant_b,+ bridge_type="slack",+ connection_config={"workspace_id": ids.workspace},+ )++ async def test_a_platform_this_deployment_has_no_app_for(+ self, rls_harness: RLSHarness+ ) -> None:+ service, ids = await _shared_app(rls_harness)++ await service.refuse_uninstalled_bridge(+ bridge_id="any",+ tenant_id=ids.tenant_b,+ bridge_type="mattermost",+ connection_config=_shared(ids.workspace),+ )+++class TestWhatIsRefused:+ async def test_another_tenants_bridge_naming_the_workspace(+ self, rls_harness: RLSHarness+ ) -> None:+ """The takeover: tenant B registers a shared bridge for A's workspace."""+ service, ids = await _shared_app(rls_harness)++ with pytest.raises(BridgeStartRefused, match=ids.workspace):+ await service.refuse_uninstalled_bridge(+ bridge_id="tenant-b-bridge",+ tenant_id=ids.tenant_b,+ bridge_type="slack",+ connection_config=_shared(ids.workspace),+ )++ async def test_a_second_bridge_of_the_same_tenant_on_the_workspace(+ self, rls_harness: RLSHarness+ ) -> None:+ """One install, one bridge: a bridge it did not build is not vouched for."""+ service, ids = await _shared_app(rls_harness)++ with pytest.raises(BridgeStartRefused):+ await service.refuse_uninstalled_bridge(+ bridge_id="another-bridge",+ tenant_id=ids.tenant_a,+ bridge_type="slack",+ connection_config=_shared(ids.workspace),+ )++ async def test_a_workspace_nobody_installed(self, rls_harness: RLSHarness) -> None:+ service, ids = await _shared_app(rls_harness)++ with pytest.raises(BridgeStartRefused):+ await service.refuse_uninstalled_bridge(+ bridge_id=ids.bridge_id,+ tenant_id=ids.tenant_a,+ bridge_type="slack",+ connection_config=_shared("T-never-installed"),+ )diff --git a/core/tests/switch_core/clients/test_addressing_enforcement.py b/core/tests/switch_core/clients/test_addressing_enforcement.pyindex 05d3d76a8..f8ad6be17 100644--- a/core/tests/switch_core/clients/test_addressing_enforcement.py+++ b/core/tests/switch_core/clients/test_addressing_enforcement.py@@ -1,11 +1,14 @@from __future__ import annotationsfrom contextlib import asynccontextmanager+from datetime import UTC, datetimefrom types import SimpleNamespace+from switch_core.budgets import BudgetGuardfrom switch_core.clients.admin_messages import AUTO_REPLY_FLAGfrom switch_core.clients.admin_messages import PLATFORM_MARKER as _PLATFORM_MARKERfrom switch_core.clients.agent_client import AgentClient+from switch_core.db.stores.budget_store import BudgetStandingfrom switch_core.delivery.addressing import (ADDRESSING_DENIED_MESSAGE as _ADDRESSING_DENIED_MESSAGE,)@@ -509,7 +512,34 @@ class TestOwnerAgentsAddressing:assert (await _decide(client)).refusal == _ADDRESSING_DENIED_MESSAGE-def _gate_client(*, allowed: bool, refusal: str = _ADDRESSING_DENIED_MESSAGE): # type: ignore[no-untyped-def]+def _standing(*, spent: int) -> BudgetStanding:+ return BudgetStanding(+ id="budget-1",+ agent_id="agent-1",+ agent_name="fixer",+ metric="turns",+ model="",+ amount_limit=10,+ period_hours=24,+ spent=spent,+ resets_at=datetime(2026, 1, 2, tzinfo=UTC),+ )+++class _FakeBudgetStore:+ def __init__(self, standings: list[BudgetStanding]) -> None:+ self._standings = standings++ async def standings(self, _session, *, tenant_id, agent_id): # type: ignore[no-untyped-def]+ return self._standings+++def _gate_client( # type: ignore[no-untyped-def]+ *,+ allowed: bool,+ refusal: str = _ADDRESSING_DENIED_MESSAGE,+ budgets: list[BudgetStanding] | None = None,+):"""Fake client for _gate_addressed and the auto-reply it hands back."""sent: list[dict] = []@@ -525,7 +555,9 @@ def _gate_client(*, allowed: bool, refusal: str = _ADDRESSING_DENIED_MESSAGE):return "human"client = SimpleNamespace(- agent=SimpleNamespace(name="fixer"),+ agent=SimpleNamespace(id="agent-1", name="fixer"),+ tenant_id="tenant-1",+ _budget_guard=BudgetGuard(_FakeBudgetStore(budgets or [])), # type: ignore[arg-type]_addressing_allowed=_addressing_allowed,send_message=_send_message,_sender_handle=_sender_handle,@@ -600,6 +632,32 @@ class TestGateAddressed:assert outcome.refusal == _ADDRESSING_DENIED_MESSAGEassert client.sent == []+ async def test_an_agent_within_its_budget_stays_addressed(self) -> None:+ client = _gate_client(allowed=True, budgets=[_standing(spent=9)])+ outcome = await _gate(client, _event())+ assert outcome.addressed is True+ assert client.sent == []++ async def test_an_agent_over_budget_is_demoted_and_says_so(self) -> None:+ client = _gate_client(allowed=True, budgets=[_standing(spent=10)])+ outcome = await _gate(client, _event())+ assert outcome.addressed is False+ reply = client.sent[0]+ assert "Agent fixer has reached its budget of 10 turns per 24h" in reply["body"]+ assert "2026-01-02 00:00 UTC" in reply["body"]+ assert reply["extra_content"] == {AUTO_REPLY_FLAG: True}++ async def test_an_over_budget_agent_does_not_answer_an_auto_reply(self) -> None:+ client = _gate_client(allowed=True, budgets=[_standing(spent=10)])+ outcome = await _gate(client, _event(auto_reply=True))+ assert outcome.addressed is False+ assert client.sent == []++ async def test_a_denied_sender_hears_the_policy_not_the_budget(self) -> None:+ client = _gate_client(allowed=False, budgets=[_standing(spent=10)])+ await _gate(client, _event())+ assert _ADDRESSING_DENIED_MESSAGE in client.sent[0]["body"]+def _command(args: str = "", user_id: str = "@u:switch.local", command: str = "reset"diff --git a/core/tests/switch_core/clients/test_admin_client.py b/core/tests/switch_core/clients/test_admin_client.pyindex 6127ceb09..a345d12f9 100644--- a/core/tests/switch_core/clients/test_admin_client.py+++ b/core/tests/switch_core/clients/test_admin_client.py@@ -89,6 +89,7 @@ def _admin_client(room_id,body,*,+ metered,format="markdown",mentions=None,thread_root_id=None,@@ -97,6 +98,7 @@ def _admin_client(sent.append({"body": body,+ "metered": metered,"thread_root_id": thread_root_id,"mentions": mentions,"extra_content": extra_content,@@ -366,6 +368,7 @@ class TestAdminCommandDispatch:await client.reply_command("!m", "the result")assert sent[0]["body"] == "the result"assert _marker_type(sent[0]) == AdminMessageType.COMMAND_RESULT.value+ assert sent[0]["metered"] is Falseasync def test_admin_owned_command_is_handled(self) -> None:host, sent = _command_host()diff --git a/core/tests/switch_core/clients/test_agent_client_pool_checkouts.py b/core/tests/switch_core/clients/test_agent_client_pool_checkouts.pynew file mode 100644index 000000000..f300d3e66--- /dev/null+++ b/core/tests/switch_core/clients/test_agent_client_pool_checkouts.py@@ -0,0 +1,287 @@+"""How many pool checkouts one inbound room message costs an agent client.++A room fans every Matrix message out to *all* of its agent clients at once, in+a single event-loop tick. So this number is multiplied by the size of the room+before it ever reaches the pool: at two checkouts per client, a ten-agent room+turned one Slack message into twenty concurrent checkouts out of forty, and the+addressed client alone took up to nine more. That is the burst that pushed the+pool to its ceiling and started failing heartbeats.++The contract is one checkout per client per message, and none at all for a+message that needs no lookup — plus, as with the room service, no session held+open while the client posts to Matrix.+"""++from __future__ import annotations++from types import SimpleNamespace+from typing import Any++from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.bridges.agent.protocol.connections import ConnectionRegistry+from switch_core.budgets import BudgetGuard+from switch_core.clients.agent_client import AgentClient+from switch_core.clients.room_meta import RoomMeta+from switch_core.db.models import Agent, ApiKey, Client, Room, User+from switch_core.db.stores.agent_session_store import AgentSessionStore+from switch_core.db.stores.agent_store import AgentStore+from switch_core.db.stores.budget_store import BudgetStore+from switch_core.db.stores.client_store import ClientStore+from switch_core.db.stores.external_user_store import ExternalUserStore+from switch_core.db.stores.room_role_store import RoomRoleStore+from switch_core.db.stores.room_store import RoomStore+from switch_core.delivery.addressing import AddressingResolver+from switch_core.transport import InboundMessage, RoomRef++MATRIX_ROOM_ID = "!r:test"+++class _CountingSessionFactory:+ """The real factory, counting sessions opened and tracking how many are+ open right now. One session is one pool checkout."""++ def __init__(self, inner: async_sessionmaker[AsyncSession]) -> None:+ self._inner = inner+ self.opened = 0+ self.live = 0++ def __call__(self) -> Any:+ self.opened += 1+ return _Tracked(self, self._inner())+++class _Tracked:+ def __init__(self, tracker: _CountingSessionFactory, inner: Any) -> None:+ self._tracker = tracker+ self._inner = inner++ async def __aenter__(self) -> AsyncSession:+ self._tracker.live += 1+ return await self._inner.__aenter__() # type: ignore[no-any-return]++ async def __aexit__(self, *exc: object) -> bool:+ self._tracker.live -= 1+ return await self._inner.__aexit__(*exc) # type: ignore[no-any-return]+++async def _seed(+ session_factory: async_sessionmaker[AsyncSession], *, names: list[str]+) -> tuple[str, dict[str, Agent]]:+ async with session_factory() as session:+ user = User(name="o", email="o@test", role="user", password_hash="x")+ session.add(user)+ await session.flush()+ agents: dict[str, Agent] = {}+ for name in names:+ key = ApiKey(+ user_id=user.id,+ key_hash=f"hash-{name}",+ encrypted_key="enc",+ label=name,+ type="agent",+ )+ client = Client(+ matrix_user_id=f"@{name}:test",+ display_name=name,+ type="agent",+ )+ session.add_all([key, client])+ await session.flush()+ agent = Agent(+ name=name,+ description="d",+ agent_type="session_addressable",+ connector_type="claude_code",+ integration_profile={"connection_model": "session_addressable"},+ client_id=client.id,+ api_key_id=key.id,+ owner_id=user.id,+ )+ session.add(agent)+ await session.flush()+ agents[name] = agent+ room = Room(matrix_room_id=MATRIX_ROOM_ID, name="room", description="d")+ session.add(room)+ await session.flush()+ await RoomStore().add_agents(session, room.id, [a.id for a in agents.values()])+ await session.commit()+ return room.id, agents+++def _client(+ counting: _CountingSessionFactory, agent: Agent, room_id: str+) -> AgentClient:+ """An AgentClient wired to the real stores, with its room-meta cache warm.++ The cache is warm because that is the steady state: a client resolves a+ room once and then answers every later message in it from memory.+ """+ client = object.__new__(AgentClient)+ client.session_factory = counting # type: ignore[assignment]+ client.client_store = ClientStore()+ client.matrix_user_id = f"@{agent.name}:test"+ client.client_id = agent.client_id+ client.tenant_id = agent.tenant_id+ client._agent = agent+ client._agent_store = AgentStore()+ client._room_store = RoomStore()+ client._room_role_store = RoomRoleStore()+ client._agent_session_store = AgentSessionStore()+ client._external_user_store = ExternalUserStore()+ client._connections = ConnectionRegistry()+ client._addressing = AddressingResolver(+ room_store=client._room_store,+ room_role_store=client._room_role_store,+ client_store=client.client_store,+ agent_store=client._agent_store,+ external_user_store=client._external_user_store,+ live_connection_ids=client._connections.live_connection_ids,+ )+ client._budget_guard = BudgetGuard(BudgetStore())+ client._frontend_base_url = None+ client._room_meta = {+ MATRIX_ROOM_ID: RoomMeta(+ room_id=room_id,+ name="room",+ bridge_id=None,+ channel_type="channel_public",+ )+ }+ client._attachment_groups = {}+ client._attachment_group_timers = {}+ client.sent = [] # type: ignore[attr-defined]++ async def _send_message(matrix_room_id: str, body: str, **kwargs: Any) -> str:+ client.sent.append((body, counting.live)) # type: ignore[attr-defined]+ return "$sent"++ client.send_message = _send_message # type: ignore[assignment, method-assign]+ client._event_buffer = SimpleNamespace( # type: ignore[assignment]+ enqueue=lambda *_a, **_k: None+ )+ return client+++def _message(body: str, sender: str = "@switch-slack-louisa:test") -> InboundMessage:+ return InboundMessage(+ room_id=MATRIX_ROOM_ID,+ event_id="$trigger",+ sender=sender,+ timestamp=0,+ content={"body": body, "sender_name": "louisa"},+ body=body,+ sender_name="louisa",+ )+++def _room() -> RoomRef:+ return RoomRef(room_id=MATRIX_ROOM_ID)+++class TestInboundMessageCheckouts:+ async def test_chatter_with_no_at_costs_nothing(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ # The common case in a busy room, and the one multiplied by every agent+ # in it: no `@`, so there is nothing an alias or a role lease could+ # match and no reason to touch the database at all.+ room_id, agents = await _seed(session_factory, names=["member"])+ counting = _CountingSessionFactory(session_factory)+ client = _client(counting, agents["member"], room_id)++ await client.on_message(_room(), _message("just talking amongst ourselves"))++ assert counting.opened == 0++ async def test_an_at_message_for_somebody_else_costs_one(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ # Was two: the room alias and the role lease each took a session.+ room_id, agents = await _seed(session_factory, names=["member", "other"])+ counting = _CountingSessionFactory(session_factory)+ client = _client(counting, agents["member"], room_id)++ await client.on_message(_room(), _message("@other can you look at this"))++ assert counting.opened == 1++ async def test_being_addressed_and_offline_still_costs_one(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ # The expensive path: addressing policy, liveness, and the whole+ # offline-reply derivation. Was up to nine checkouts.+ room_id, agents = await _seed(session_factory, names=["member"])+ counting = _CountingSessionFactory(session_factory)+ client = _client(counting, agents["member"], room_id)++ await client.on_message(_room(), _message("@member can you look at this"))++ assert counting.opened == 1+ assert len(client.sent) == 1 # type: ignore[attr-defined]++ async def test_no_session_is_open_while_the_auto_reply_is_posted(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ # Posting to Matrix is an unbounded wait as far as the pool is+ # concerned; doing it inside the transaction is how a slot ends up+ # idle-in-transaction for seconds.+ room_id, agents = await _seed(session_factory, names=["member"])+ counting = _CountingSessionFactory(session_factory)+ client = _client(counting, agents["member"], room_id)++ await client.on_message(_room(), _message("@member you there?"))++ assert [live for _body, live in client.sent] == [0] # type: ignore[attr-defined]++ async def test_a_restricted_agent_refusing_a_sender_costs_one(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ room_id, agents = await _seed(session_factory, names=["member"])+ async with session_factory() as session:+ await AgentStore().update(+ session,+ agents["member"].id,+ addressing_policy={"rules": [{"agents": ["nobody"], "users": []}]},+ )+ await session.commit()+ counting = _CountingSessionFactory(session_factory)+ client = _client(counting, agents["member"], room_id)++ await client.on_message(_room(), _message("@member you there?"))++ assert counting.opened == 1+ assert [live for _body, live in client.sent] == [0] # type: ignore[attr-defined]++ async def test_an_alias_tag_costs_one(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ # Reached only after the alias lookup misses on name, so this is the+ # path where alias and role used to be two separate checkouts.+ room_id, agents = await _seed(session_factory, names=["member"])+ async with session_factory() as session:+ await RoomStore().set_alias(session, room_id, agents["member"].id, "fixer")+ await session.commit()+ counting = _CountingSessionFactory(session_factory)+ client = _client(counting, agents["member"], room_id)++ await client.on_message(_room(), _message("@fixer please look"))++ assert counting.opened == 1+ assert len(client.sent) == 1 # type: ignore[attr-defined]++ async def test_a_ten_agent_room_costs_ten(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ # The burst, end to end. One message, every client in the room handling+ # it at once: ten slots out of forty, where it used to be twenty plus+ # the addressed client's own handful.+ names = [f"a{i}" for i in range(10)]+ room_id, agents = await _seed(session_factory, names=names)+ counting = _CountingSessionFactory(session_factory)+ clients = [_client(counting, agents[name], room_id) for name in names]++ for client in clients:+ await client.on_message(_room(), _message("@a3 can you take this"))++ assert counting.opened == 10diff --git a/core/tests/switch_core/clients/test_client_tenant_plumbing.py b/core/tests/switch_core/clients/test_client_tenant_plumbing.pyindex 09d217977..f14b7969a 100644--- a/core/tests/switch_core/clients/test_client_tenant_plumbing.py+++ b/core/tests/switch_core/clients/test_client_tenant_plumbing.py@@ -47,6 +47,7 @@ from switch_core.db.stores.media_store import MediaStorefrom switch_core.db.stores.message_store import MessageStorefrom switch_core.db.stores.room_store import RoomStorefrom switch_core.db.stores.tenant_store import TenantStore+from switch_core.db.stores.usage_store import UsageStorefrom switch_core.tenant_context import tenant_scopefrom switch_core.transport.ephemeral import EphemeralBusfrom switch_core.transport.invites import InviteBus@@ -59,6 +60,7 @@ def _factory(session_factory: async_sessionmaker[AsyncSession]) -> ClientFactoryconfig=SimpleNamespace(matrix_server_name="test"), # type: ignore[arg-type]room_store=RoomStore(),message_store=MessageStore(),+ usage_store=UsageStore(),media_store=MediaStore(),listener=MagicMock(),invites=InviteBus(),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.pyindex 99467989b..1f67a9c74 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@@ -127,6 +127,20 @@ async def test_no_session_reply_threads_under_triggering_mention() -> None:]# The reply is stamped as an auto-reply so it can't re-trigger another one.assert send_message.calls[0]["extra_content"] == {AUTO_REPLY_FLAG: True}+ # Switch said it, not the agent, so the tenant is not charged for it.+ assert send_message.calls[0]["metered"] is False+++async def test_a_command_reply_is_not_metered() -> None:+ send_message = _Recorder()+ await AgentClient.reply_command(+ SimpleNamespace(send_message=send_message), # type: ignore[arg-type]+ "!matrix:server",+ "the result",+ )++ assert send_message.calls[0]["metered"] is False@pytest.mark.asynciodiff --git a/core/tests/switch_core/clients/test_send_media.py b/core/tests/switch_core/clients/test_send_media.pyindex c5d72a44d..2dc94eed8 100644--- a/core/tests/switch_core/clients/test_send_media.py+++ b/core/tests/switch_core/clients/test_send_media.py@@ -54,6 +54,7 @@ async def test_send_media_with_caption_passes_caption_and_filename_through() ->1234,msgtype="m.image",caption="look at this",+ metered=True,)assert event_id == "$fake1"@@ -75,7 +76,13 @@ async def test_send_media_without_caption_sends_no_caption() -> None:client = _client(transport)await client.send_media(- "!room", "mxc://s/abc", "cat.png", "image/png", 1234, msgtype="m.image"+ "!room",+ "mxc://s/abc",+ "cat.png",+ "image/png",+ 1234,+ msgtype="m.image",+ metered=True,)sent = transport.sent_media[0]@@ -87,7 +94,13 @@ async def test_send_media_returns_none_when_the_transport_rejects_it() -> None:client = _client(FakeTransport(fail_send="nope"))result = await client.send_media(- "!room", "mxc://s/abc", "cat.png", "image/png", 1234, msgtype="m.image"+ "!room",+ "mxc://s/abc",+ "cat.png",+ "image/png",+ 1234,+ msgtype="m.image",+ metered=True,)assert result is Nonediff --git a/core/tests/switch_core/db/stores/test_budget_store.py b/core/tests/switch_core/db/stores/test_budget_store.pynew file mode 100644index 000000000..d29460674--- /dev/null+++ b/core/tests/switch_core/db/stores/test_budget_store.py@@ -0,0 +1,333 @@+"""Budgets and what has been spent against them, against a real database.++The period arithmetic and the spend sum are SQL, so none of this is mocked.+"""++from __future__ import annotations++from datetime import UTC, datetime, timedelta++import pytest+from sqlalchemy.exc import IntegrityError+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.budgets import BudgetExceeded, BudgetGuard+from switch_core.db.models import (+ MAX_BUDGET_AMOUNT,+ MAX_BUDGET_PERIOD_HOURS,+ TENANT_ZERO_ID,+ Agent,+ ApiKey,+ Client,+ TenantUsage,+ UsageMetric,+ User,+)+from switch_core.db.stores.budget_store import BudgetNotFound, BudgetStore+++async def _agent(session: AsyncSession, name: str) -> Agent:+ owner = User(+ id=f"owner-{name}", name=name, email=f"{name}@example.test", role="user"+ )+ session.add(owner)+ await session.flush()+ client = Client(matrix_user_id=f"@{name}:test", display_name=name, type="agent")+ key = ApiKey(+ user_id=owner.id,+ key_hash=f"hash-{name}",+ encrypted_key="",+ label="unused fixture",+ type="agent",+ )+ session.add_all([client, key])+ await session.flush()+ agent = Agent(+ name=name,+ description="test agent",+ agent_type="session_addressable",+ connector_type="codex",+ integration_profile={},+ client_id=client.id,+ api_key_id=key.id,+ )+ session.add(agent)+ await session.flush()+ return agent+++def _hour(offset: int) -> datetime:+ now = datetime.now(UTC).replace(minute=0, second=0, microsecond=0)+ return now + timedelta(hours=offset)+++def _spent(client_id: str, amount: int, *, metric="turns", model="", hour=0):+ return TenantUsage(+ metric=metric,+ bucket_start=_hour(hour),+ client_id=client_id,+ model=model,+ amount=amount,+ )+++async def _budget(+ session: AsyncSession,+ *,+ agent_id: str | None,+ metric: UsageMetric = UsageMetric.TURNS,+ model: str = "",+ amount_limit: int = 10,+ period_hours: int = 1,+):+ return await BudgetStore().create(+ session,+ tenant_id=TENANT_ZERO_ID,+ agent_id=agent_id,+ metric=metric,+ model=model,+ amount_limit=amount_limit,+ period_hours=period_hours,+ )+++async def _standings(session: AsyncSession, agent_id: str | None):+ return await BudgetStore().standings(+ session, tenant_id=TENANT_ZERO_ID, agent_id=agent_id+ )+++class TestSpend:+ async def test_an_agent_budget_counts_only_that_agent_this_period(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ mine = await _agent(session, "mine")+ other = await _agent(session, "other")+ await _budget(session, agent_id=mine.id)+ session.add_all(+ [+ _spent(mine.client_id, 3),+ _spent(mine.client_id, 100, hour=-1),+ _spent(other.client_id, 50),+ ]+ )+ await session.commit()++ async with session_factory() as session:+ [standing] = await _standings(session, None)++ assert standing.agent_name == "mine"+ assert standing.spent == 3+ assert standing.resets_at == _hour(1)+ assert not standing.exhausted++ async def test_a_daily_budget_turns_over_at_midnight_utc(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ await _budget(session, agent_id=None, period_hours=24)+ await session.commit()++ async with session_factory() as session:+ [standing] = await _standings(session, None)++ midnight = datetime.now(UTC).replace(hour=0, minute=0, second=0, microsecond=0)+ assert standing.resets_at == midnight + timedelta(days=1)++ async def test_a_tenant_wide_budget_counts_every_agent_and_no_one_else(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ one = await _agent(session, "one")+ two = await _agent(session, "two")+ await _budget(session, agent_id=None, metric=UsageMetric.MESSAGES)+ session.add_all(+ [+ _spent("a-person", 40, metric="messages"),+ _spent("a-bridge", 40, metric="messages"),+ _spent(one.client_id, 4, metric="messages"),+ _spent(two.client_id, 6, metric="messages"),+ ]+ )+ await session.commit()++ async with session_factory() as session:+ [standing] = await _standings(session, None)++ assert standing.agent_id is None+ assert standing.spent == 10+ assert standing.exhausted++ async def test_a_model_budget_counts_only_that_model(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ agent = await _agent(session, "modelled")+ await _budget(+ session,+ agent_id=agent.id,+ metric=UsageMetric.OUTPUT_TOKENS,+ model="big",+ amount_limit=1000,+ )+ session.add_all(+ [+ _spent(agent.client_id, 300, metric="output_tokens", model="big"),+ _spent(agent.client_id, 900, metric="output_tokens", model="small"),+ ]+ )+ await session.commit()++ async with session_factory() as session:+ [standing] = await _standings(session, None)++ assert standing.spent == 300++ async def test_an_agent_is_covered_by_its_own_and_tenant_wide_budgets(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ mine = await _agent(session, "covered")+ other = await _agent(session, "elsewhere")+ await _budget(session, agent_id=None)+ await _budget(session, agent_id=mine.id)+ await _budget(session, agent_id=other.id)+ await session.commit()++ async with session_factory() as session:+ covering = await _standings(session, mine.id)++ assert [s.agent_id for s in covering] == [None, mine.id]+++class TestChanges:+ async def test_a_second_budget_on_the_same_thing_is_refused(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ await _budget(session, agent_id=None)+ with pytest.raises(IntegrityError, match="uq_usage_budgets_tenant_wide"):+ await _budget(session, agent_id=None, amount_limit=99)++ @pytest.mark.parametrize(+ ("amount_limit", "period_hours", "constraint"),+ [+ (MAX_BUDGET_AMOUNT + 1, 24, "ck_usage_budgets_amount_limit"),+ (10, MAX_BUDGET_PERIOD_HOURS + 1, "ck_usage_budgets_period_hours"),+ ],+ )+ async def test_a_budget_past_the_bounds_is_refused(+ self,+ session_factory: async_sessionmaker[AsyncSession],+ amount_limit: int,+ period_hours: int,+ constraint: str,+ ) -> None:+ async with session_factory() as session:+ with pytest.raises(IntegrityError, match=constraint):+ await _budget(+ session,+ agent_id=None,+ amount_limit=amount_limit,+ period_hours=period_hours,+ )++ async def test_the_longest_budget_reads_its_standing(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ agent = await _agent(session, "yearly")+ session.add(_spent(agent.client_id, 4))+ await _budget(+ session,+ agent_id=agent.id,+ amount_limit=MAX_BUDGET_AMOUNT,+ period_hours=MAX_BUDGET_PERIOD_HOURS,+ )+ [standing] = await _standings(session, agent.id)++ assert standing.spent == 4+ assert standing.resets_at > datetime.now(UTC)++ async def test_update_and_delete_name_a_budget_that_exists(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ store = BudgetStore()+ async with session_factory() as session:+ budget = await _budget(session, agent_id=None)+ await store.update(+ session,+ tenant_id=TENANT_ZERO_ID,+ budget_id=budget.id,+ amount_limit=5,+ period_hours=48,+ )+ [standing] = await _standings(session, None)+ assert (standing.amount_limit, standing.period_hours) == (5, 48)++ await store.delete(session, tenant_id=TENANT_ZERO_ID, budget_id=budget.id)+ assert await _standings(session, None) == []+ with pytest.raises(BudgetNotFound):+ await store.delete(+ session, tenant_id=TENANT_ZERO_ID, budget_id=budget.id+ )++ async def test_deleting_an_agent_deletes_its_budgets(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ agent = await _agent(session, "deleted")+ await _budget(session, agent_id=agent.id)+ await session.commit()+ await session.delete(agent)+ await session.commit()++ async with session_factory() as session:+ assert await _standings(session, None) == []+++class TestGuard:+ async def test_an_agent_within_its_budgets_passes(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ agent = await _agent(session, "within")+ await _budget(session, agent_id=agent.id)+ session.add(_spent(agent.client_id, 9))+ await session.flush()++ await BudgetGuard(BudgetStore()).require_within(+ session, tenant_id=TENANT_ZERO_ID, agent_id=agent.id+ )++ async def test_the_budget_that_stops_the_agent_longest_is_reported(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ agent = await _agent(session, "stopped")+ await _budget(session, agent_id=agent.id, period_hours=1)+ await _budget(+ session,+ agent_id=None,+ metric=UsageMetric.MESSAGES,+ amount_limit=2,+ period_hours=24,+ )+ session.add_all(+ [+ _spent(agent.client_id, 10),+ _spent(agent.client_id, 2, metric="messages"),+ ]+ )+ await session.flush()++ with pytest.raises(BudgetExceeded) as stopped:+ await BudgetGuard(BudgetStore()).require_within(+ session, tenant_id=TENANT_ZERO_ID, agent_id=agent.id+ )++ assert stopped.value.standing.metric == "messages"+ assert str(stopped.value).startswith(+ "This workspace has reached its budget of 2 messages per 24h."+ )diff --git a/core/tests/switch_core/db/stores/test_messaging_install_store.py b/core/tests/switch_core/db/stores/test_messaging_install_store.pyindex 5b1304417..1d37a378b 100644--- a/core/tests/switch_core/db/stores/test_messaging_install_store.py+++ b/core/tests/switch_core/db/stores/test_messaging_install_store.py@@ -269,3 +269,31 @@ class TestRecordingAnInstall:session, platform="slack", external_workspace_id=fixture.workspace)assert theirs is None++ async def test_a_tokenless_install_records_and_reads_back(+ self, rls_harness: RLSHarness+ ) -> None:+ """A platform whose credential is deployment-level (Discord) stores no+ token: the row goes in with `encrypted_bot_token = NULL` and reads back+ through the scoped path unchanged."""+ fixture = await _two_tenants(rls_harness.owner)+ store = MessagingInstallStore()++ async with tenant_session(rls_harness.restricted, fixture.tenant_a) as session:+ recorded = await store.record_install(+ session,+ platform="discord",+ external_workspace_id=fixture.workspace,+ encrypted_bot_token=None,+ scopes="bot applications.commands",+ user_id=fixture.user_id,+ )+ assert recorded.encrypted_bot_token is None+ await session.commit()++ async with tenant_session(rls_harness.restricted, fixture.tenant_a) as session:+ mine = await store.get_for_workspace(+ session, platform="discord", external_workspace_id=fixture.workspace+ )+ assert mine is not None+ assert mine.encrypted_bot_token is Nonediff --git a/core/tests/switch_core/db/stores/test_tenant_store.py b/core/tests/switch_core/db/stores/test_tenant_store.pynew file mode 100644index 000000000..bd5f51098--- /dev/null+++ b/core/tests/switch_core/db/stores/test_tenant_store.py@@ -0,0 +1,47 @@+"""`TenantStore.create` names the one failure a caller can recover from.++A taken slug can be answered by picking another; any other integrity error+cannot, and must not be mistaken for one — the workspace route retries on the+first and would otherwise retry on everything.+"""++from __future__ import annotations++import uuid++import pytest+from sqlalchemy.exc import IntegrityError+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.db.models import Tenant+from switch_core.db.session_scope import tenant_session+from switch_core.db.stores.tenant_store import TenantSlugTaken, TenantStore+++async def _create(+ session_factory: async_sessionmaker[AsyncSession], tenant_id: str, slug: str+) -> None:+ async with tenant_session(session_factory, tenant_id) as session:+ await TenantStore().create(session, Tenant(id=tenant_id, slug=slug, name=slug))+ await session.commit()+++class TestCreatingATenant:+ async def test_a_taken_slug_raises_tenant_slug_taken(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await _create(session_factory, str(uuid.uuid4()), "taken-slug")++ with pytest.raises(TenantSlugTaken) as raised:+ await _create(session_factory, str(uuid.uuid4()), "taken-slug")++ assert raised.value.slug == "taken-slug"++ async def test_any_other_conflict_is_left_as_it_is(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ tenant_id = str(uuid.uuid4())+ await _create(session_factory, tenant_id, "first-slug")++ with pytest.raises(IntegrityError):+ await _create(session_factory, tenant_id, "second-slug")diff --git a/core/tests/switch_core/db/stores/test_usage_store.py b/core/tests/switch_core/db/stores/test_usage_store.pynew file mode 100644index 000000000..ecdf9c8f5--- /dev/null+++ b/core/tests/switch_core/db/stores/test_usage_store.py@@ -0,0 +1,194 @@+"""Per-tenant usage counters, against a real database.++The upsert, the hour bucket and the check constraints are the behaviour, so+none of this is mocked.+"""++from __future__ import annotations++from datetime import UTC, datetime, timedelta++import pytest+from sqlalchemy import func, select+from sqlalchemy.exc import IntegrityError+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.db.models import (+ TENANT_ZERO_ID,+ Client,+ Tenant,+ TenantUsage,+ UsageMetric,+)+from switch_core.db.session_scope import tenant_session+from switch_core.db.stores.usage_store import UsageStore++OTHER_TENANT = "11111111-1111-1111-1111-111111111111"+++async def _client(session: AsyncSession, name: str) -> str:+ client = Client(matrix_user_id=f"@{name}:test", display_name=name, type="agent")+ session.add(client)+ await session.flush()+ return client.id+++async def _record(+ session: AsyncSession,+ client_id: str,+ *,+ metric: UsageMetric = UsageMetric.MESSAGES,+ model: str = "",+ amount: int = 1,+ tenant_id: str = TENANT_ZERO_ID,+) -> None:+ await UsageStore().record(+ session,+ tenant_id=tenant_id,+ metric=metric,+ client_id=client_id,+ model=model,+ amount=amount,+ )+++def _hour(offset: int) -> datetime:+ now = datetime.now(UTC).replace(minute=0, second=0, microsecond=0)+ return now + timedelta(hours=offset)+++class TestRecording:+ async def test_counts_in_the_same_hour_add_up(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ client_id = await _client(session, "counted")+ await _record(session, client_id)+ await _record(session, client_id, amount=4)+ await session.commit()++ async with session_factory() as session:+ rows = (await session.scalars(select(TenantUsage))).all()++ assert len(rows) == 1+ assert rows[0].amount == 5+ assert rows[0].bucket_start == _hour(0)++ async def test_metrics_and_models_are_counted_apart(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ client_id = await _client(session, "several")+ await _record(session, client_id)+ await _record(session, client_id, metric=UsageMetric.TURNS)+ await _record(+ session, client_id, metric=UsageMetric.INPUT_TOKENS, model="a"+ )+ await _record(+ session, client_id, metric=UsageMetric.INPUT_TOKENS, model="b"+ )+ await session.commit()++ async with session_factory() as session:+ count = await session.scalar(select(func.count()).select_from(TenantUsage))++ assert count == 4++ async def test_a_count_that_is_not_positive_is_refused(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ # A zero or negative amount would let a caller spend usage back, so it+ # is an error at the door rather than an adjustment.+ async with session_factory() as session:+ client_id = await _client(session, "refused")+ with pytest.raises(ValueError, match="positive"):+ await _record(session, client_id, amount=0)++ async def test_the_database_refuses_an_unknown_metric(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ session.add(+ TenantUsage(+ metric="vibes",+ bucket_start=_hour(0),+ client_id="c",+ model="",+ amount=1,+ )+ )+ with pytest.raises(IntegrityError, match="ck_tenant_usage_metric"):+ await session.flush()+++class TestTotals:+ async def test_totals_cover_the_hours_in_the_window(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ client_id = await _client(session, "windowed")+ for offset, amount in ((-3, 100), (-2, 10), (-1, 1), (0, 1000)):+ session.add(+ TenantUsage(+ metric="messages",+ bucket_start=_hour(offset),+ client_id=client_id,+ model="",+ amount=amount,+ )+ )+ await session.commit()++ async with session_factory() as session:+ # `since` mid-hour still takes that whole hour; `until` excludes+ # the bucket that starts on it.+ totals = await UsageStore().totals(+ session,+ tenant_id=TENANT_ZERO_ID,+ since=_hour(-2) + timedelta(minutes=30),+ until=_hour(0),+ )++ assert [(t.metric, t.client_name, t.amount) for t in totals] == [+ ("messages", "windowed", 11)+ ]++ async def test_usage_outlives_the_client_it_names(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ # What a deleted client spent is still the tenant's spend.+ async with session_factory() as session:+ await _record(session, "gone-client")+ await session.commit()++ async with session_factory() as session:+ totals = await UsageStore().totals(+ session, tenant_id=TENANT_ZERO_ID, since=_hour(-1), until=_hour(1)+ )++ assert len(totals) == 1+ assert totals[0].client_id == "gone-client"+ assert totals[0].client_name is None+ assert totals[0].amount == 1++ async def test_another_tenants_usage_is_not_counted(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ # The owner connection ignores the policy, so this is the explicit+ # tenant filter doing the work — the one a fan-out relies on.+ async with session_factory() as session:+ session.add(Tenant(id=OTHER_TENANT, slug="other", name="Other"))+ await session.commit()+ async with tenant_session(session_factory, OTHER_TENANT) as session:+ await _record(session, "theirs", amount=50, tenant_id=OTHER_TENANT)+ await session.commit()+ async with session_factory() as session:+ await _record(session, "ours", amount=2)+ await session.commit()++ async with session_factory() as session:+ totals = await UsageStore().totals(+ session, tenant_id=TENANT_ZERO_ID, since=_hour(-1), until=_hour(1)+ )++ assert [(t.client_id, t.amount) for t in totals] == [("ours", 2)]diff --git a/core/tests/switch_core/db/stores/test_user_store_oidc.py b/core/tests/switch_core/db/stores/test_user_store_oidc.pyindex 4b7ad6bcf..d8e970ead 100644--- a/core/tests/switch_core/db/stores/test_user_store_oidc.py+++ b/core/tests/switch_core/db/stores/test_user_store_oidc.py@@ -7,7 +7,7 @@ from sqlalchemy import selectfrom sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.db.models import OidcIdentity, User+from switch_core.db.models import TENANT_ZERO_ID, OidcIdentity, TenantMember, Userfrom switch_core.db.stores.user_store import (OidcIdentityConflictError,OidcIdentityRaceError,@@ -30,6 +30,7 @@ class TestGetOrCreateOidcUser:name="New",sub="okta|9",email_verified=True,+ join_tenant=True,)await session.commit()assert user.role == "user"@@ -54,6 +55,7 @@ class TestGetOrCreateOidcUser:name="New",sub="okta|10",email_verified=True,+ join_tenant=True,)await session.commit()assert user.email == "[email protected]"@@ -70,6 +72,7 @@ class TestGetOrCreateOidcUser:name="A",sub="okta|1",email_verified=True,+ join_tenant=True,)await session.commit()first.role = "admin"@@ -82,6 +85,7 @@ class TestGetOrCreateOidcUser:name="A",sub="okta|1",email_verified=True,+ join_tenant=True,)assert again.id == first.idassert again.role == "admin"@@ -110,6 +114,7 @@ class TestGetOrCreateOidcUser:name="Pat",sub="okta|42",email_verified=True,+ join_tenant=True,)await session.commit()@@ -145,6 +150,7 @@ class TestGetOrCreateOidcUser:name="Pat",sub="okta|43",email_verified=True,+ join_tenant=True,)await session.commit()@@ -204,6 +210,7 @@ class TestGetOrCreateOidcUser:name="Shared",sub="okta|1",email_verified=True,+ join_tenant=True,)await session.commit()@@ -214,6 +221,7 @@ class TestGetOrCreateOidcUser:name="Shared",sub="okta|2",email_verified=True,+ join_tenant=True,)await session.commit()@@ -249,6 +257,7 @@ class TestGetOrCreateOidcUser:name="Different",sub="okta|1",email_verified=False,+ join_tenant=True,)async def test_identity_already_bound_elsewhere_is_never_relinked(@@ -266,6 +275,7 @@ class TestGetOrCreateOidcUser:name="Owner",sub="okta|owned",email_verified=True,+ join_tenant=True,)await session.commit()@@ -285,6 +295,7 @@ class TestGetOrCreateOidcUser:name="Owner",sub="okta|owned",email_verified=True,+ join_tenant=True,)assert again.id == owner.id@@ -313,6 +324,7 @@ class TestGetOrCreateOidcUser:name="Legacy",sub="okta|7",email_verified=True,+ join_tenant=True,)assert got.id == legacy_user.id@@ -350,6 +362,7 @@ class TestGetOrCreateOidcUser:name="Admin",sub="okta|8",email_verified=False,+ join_tenant=True,)assert got.id == legacy_admin.idassert got.role == "admin"@@ -372,6 +385,7 @@ class TestGetOrCreateOidcUser:name="Logged",sub="okta|logged",email_verified=True,+ join_tenant=True,)await session.commit()@@ -437,6 +451,7 @@ class TestGetOrCreateOidcUser:name="Winner",sub="okta|always-races",email_verified=True,+ join_tenant=True,)await winner_session.commit()@@ -455,6 +470,7 @@ class TestGetOrCreateOidcUser:name="Loser",sub="okta|always-races",email_verified=True,+ join_tenant=True,)async def test_concurrent_creation_of_the_same_identity_resolves_to_the_winner(@@ -474,6 +490,7 @@ class TestGetOrCreateOidcUser:name="Race",sub="okta|race",email_verified=True,+ join_tenant=True,)await winner_session.commit()@@ -498,6 +515,7 @@ class TestGetOrCreateOidcUser:name="Other",sub="okta|race",email_verified=True,+ join_tenant=True,)assert resolved.id == winner.id@@ -518,6 +536,7 @@ class TestGetOrCreateOidcUser:name="First",sub="okta|first",email_verified=True,+ join_tenant=True,)await winner_session.commit()@@ -540,9 +559,107 @@ class TestGetOrCreateOidcUser:name="Second",sub="okta|second",email_verified=True,+ join_tenant=True,)assert resolved.id == winner.idfor sub in ("okta|first", "okta|second"):identity = await store.get_by_oidc_identity(session, iss=_ISS, sub=sub)assert identity is not None and identity.id == winner.id+++async def _membership_count(session: AsyncSession, user_id: str) -> int:+ result = await session.execute(+ select(TenantMember).where(TenantMember.user_id == user_id)+ )+ return len(result.scalars().all())+++class TestProvisioningWithoutJoiningATenant:+ """`join_tenant=False` is how an `open` or `invite_only` server signs+ people up: the account and its identity are made, and nothing places them+ in a workspace. It must hold with no tenant bound at all, since that is+ how the callback runs in those modes."""++ async def test_a_new_account_gets_its_identity_and_no_membership(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ store = UserStore()+ async with session_factory() as session:+ user = await store.get_or_create_oidc_user(+ session,+ iss=_ISS,+ email="[email protected]",+ name="Loose",+ sub="okta|loose",+ email_verified=True,+ join_tenant=False,+ )+ await session.commit()++ again = await store.get_by_oidc_identity(+ session, iss=_ISS, sub="okta|loose"+ )+ assert again is not None and again.id == user.id+ assert await _membership_count(session, user.id) == 0++ async def test_linking_an_existing_account_adds_no_membership(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ store = UserStore()+ async with session_factory() as session:+ existing = User(name="Prior", email="[email protected]", role="user")+ session.add(existing)+ await session.commit()++ user = await store.get_or_create_oidc_user(+ session,+ iss=_ISS,+ email="[email protected]",+ name="Prior",+ sub="okta|prior",+ email_verified=True,+ join_tenant=False,+ )+ await session.commit()++ assert user.id == existing.id+ assert await _membership_count(session, user.id) == 0+++class TestLastTenant:+ async def test_an_account_with_no_history_has_none(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ user = User(name="Fresh", email="[email protected]", role="user")+ session.add(user)+ await session.commit()+ assert UserStore().last_tenant_id(user) is None++ async def test_recording_keeps_the_rest_of_the_metadata(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ store = UserStore()+ async with session_factory() as session:+ user = User(+ name="Noted",+ email="[email protected]",+ role="user",+ metadata_={"theme": "dark"},+ )+ session.add(user)+ await session.commit()+ user_id = user.id++ await store.record_last_tenant(session, user, TENANT_ZERO_ID)+ await session.commit()++ async with session_factory() as session:+ reloaded = await session.get(User, user_id)+ assert reloaded is not None+ assert store.last_tenant_id(reloaded) == TENANT_ZERO_ID+ assert reloaded.metadata_ == {+ "theme": "dark",+ "last_tenant_id": TENANT_ZERO_ID,+ }diff --git a/core/tests/switch_core/db/test_tenant_lookup.py b/core/tests/switch_core/db/test_tenant_lookup.pyindex a68e939ef..503b43572 100644--- a/core/tests/switch_core/db/test_tenant_lookup.py+++ b/core/tests/switch_core/db/test_tenant_lookup.py@@ -56,6 +56,7 @@ from switch_core.db.models import (Room,ServerConnector,Tenant,+ TenantJoinDomain,TenantMember,User,)@@ -73,7 +74,9 @@ from switch_core.db.tenant_lookup import (tenant_of_messaging_install,tenant_of_room,tenant_of_server_connector,+ tenants_inviting_email,tenants_of_user,+ tenants_open_to_domain,)from switch_core.tenant_context import tenant_scopefrom tests.conftest import RLSHarness@@ -101,6 +104,8 @@ _DROPPED_SINCE = {"tenant_of_client": "b1d7c4f0a92e"}_ADDED_SINCE = {"tenant_of_invitation": "5daaea6b674d","tenant_of_messaging_install": "c8a4e21f6d30",+ "tenants_inviting_email": "4b8e2d61c9f7",+ "tenants_open_to_domain": "7d3f5a19e2c8",}# A third kind of change, and the quietest: a lookup whose body a later@@ -482,6 +487,85 @@ class TestWhatTheyAnswer:await tenant_of_invitation(rls_harness.restricted, "no-such-hash") is None)+ async def test_an_address_resolves_to_the_tenants_with_live_invitations_for_it(+ self, rls_harness: RLSHarness+ ) -> None:+ """Only live invitations count, the address matches in any case, and+ a tenant with several answers once. Tenant B's invitations to the+ address are all dead in a different way, so it must not appear."""+ fixture = await _two_populated_tenants(rls_harness)+ address = f"invitee-{uuid.uuid4().hex[:8]}@example.test"+ now = datetime.now(UTC)+ live: dict[str, object] = {+ "expires_at": now + timedelta(days=1),+ "uses_remaining": 1,+ }+ rows = [+ (fixture.tenant_a, address.upper(), live),+ (fixture.tenant_a, address, live),+ (fixture.tenant_b, address, {**live, "revoked_at": now}),+ (+ fixture.tenant_b,+ address,+ {**live, "expires_at": now - timedelta(minutes=1)},+ ),+ (fixture.tenant_b, address, {**live, "uses_remaining": 0}),+ (fixture.tenant_b, f"other-{address}", live),+ ]+ async with rls_harness.owner() as session:+ for tenant_id, email, state in rows:+ session.add(+ Invitation(+ tenant_id=tenant_id,+ role="member",+ email=email,+ token_hash=uuid.uuid4().hex,+ created_by=fixture.user_in_both,+ **state,+ )+ )+ await session.commit()++ assert await tenants_inviting_email(rls_harness.restricted, address) == [+ fixture.tenant_a+ ]+ assert (+ await tenants_inviting_email(rls_harness.restricted, "[email protected]")+ == []+ )++ async def test_a_domain_resolves_to_the_tenants_open_to_it(+ self, rls_harness: RLSHarness+ ) -> None:+ """The domain matches in any case, and only the tenants open to it+ answer."""+ fixture = await _two_populated_tenants(rls_harness)+ domain = f"open-{uuid.uuid4().hex[:8]}.example.test"+ async with rls_harness.owner() as session:+ session.add(+ TenantJoinDomain(+ tenant_id=fixture.tenant_a,+ domain=domain,+ created_by=fixture.user_in_both,+ )+ )+ session.add(+ TenantJoinDomain(+ tenant_id=fixture.tenant_b,+ domain=f"other-{domain}",+ created_by=fixture.user_in_both,+ )+ )+ await session.commit()++ assert await tenants_open_to_domain(rls_harness.restricted, domain.upper()) == [+ fixture.tenant_a+ ]+ assert (+ await tenants_open_to_domain(rls_harness.restricted, "nobody.example.test")+ == []+ )+async def test_an_installed_workspace_resolves_to_the_tenant_that_installed_it(self, rls_harness: RLSHarness) -> None:diff --git a/core/tests/switch_core/gateway/test_directory_fallback.py b/core/tests/switch_core/gateway/test_directory_fallback.pyindex d4cd15109..13a973dc3 100644--- a/core/tests/switch_core/gateway/test_directory_fallback.py+++ b/core/tests/switch_core/gateway/test_directory_fallback.py@@ -20,10 +20,12 @@ from types import SimpleNamespaceimport pytestfrom fastapi import HTTPException+from switch_core.bridges.collaboration.adapter import DirectorySearchBusyfrom switch_core.bridges.collaboration.models import DirectoryUserfrom switch_core.bridges.collaboration.telegram.adapter import TelegramAdapterfrom switch_core.gateway.collaborations import (_known_as_directory_users,+ _require_directory_account,search_bridge_directory,)@@ -211,3 +213,27 @@ async def test_the_platform_names_itself_in_the_refusal() -> None:assert str(excinfo.value).startswith("Telegram has no searchable user directory")assert "Adapter" not in str(excinfo.value)+++class TestABusyDirectory:+ """A directory refusing more searches is a 429 with when to retry, not the+ 502 every other platform failure is, so the dialog can say try again."""++ async def test_a_search_is_told_when_to_retry(self) -> None:+ with pytest.raises(HTTPException) as refused:+ await _search(adapter_result=DirectorySearchBusy(12.2), known=[])++ assert refused.value.status_code == 429+ assert refused.value.headers == {"Retry-After": "13"}+ assert "try again in 13 seconds" in refused.value.detail++ async def test_so_is_the_check_behind_a_claim(self) -> None:+ with pytest.raises(HTTPException) as refused:+ await _require_directory_account(+ _StubLifecycle(DirectorySearchBusy(5)), # type: ignore[arg-type]+ bridge_id="b1",+ external_user_id="11",+ username="louis",+ )++ assert refused.value.status_code == 429diff --git a/core/tests/switch_core/gateway/test_email_domains.py b/core/tests/switch_core/gateway/test_email_domains.pynew file mode 100644index 000000000..80b04872f--- /dev/null+++ b/core/tests/switch_core/gateway/test_email_domains.py@@ -0,0 +1,41 @@+import re+from importlib.resources import files++import pytest++from switch_core.gateway.email_domains import join_domain_refusal++DOMAIN = re.compile(+ r"^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$"+)+++ "domain",+ [+ "gmail.com", # free-mail list+ "mailinator.com", # disposable list+ "proton.me", # in neither list, added by hand+ ],+)+def test_a_public_provider_is_refused(domain: str) -> None:+ refusal = join_domain_refusal(domain)+ assert refusal is not None+ assert domain in refusal++[email protected]("domain", ["acme.example", "switch.local"])+def test_an_organisation_domain_is_allowed(domain: str) -> None:+ assert join_domain_refusal(domain) is None++[email protected]("name", ["free.txt", "disposable.txt"])+def test_every_listed_entry_is_a_lower_case_domain(name: str) -> None:+ text = (+ files("switch_core.gateway")+ .joinpath("email_domain_lists", name)+ .read_text(encoding="utf-8")+ )+ entries = [line for line in text.splitlines() if not line.startswith("#")]+ assert entries+ assert [e for e in entries if not DOMAIN.match(e)] == []diff --git a/core/tests/switch_core/gateway/test_invite_mail.py b/core/tests/switch_core/gateway/test_invite_mail.pynew file mode 100644index 000000000..d5873bbfb--- /dev/null+++ b/core/tests/switch_core/gateway/test_invite_mail.py@@ -0,0 +1,170 @@+from __future__ import annotations++import smtplib+from datetime import UTC, datetime+from email.message import EmailMessage+from typing import Any++import pytest++from switch_core.gateway import invite_mail+from switch_core.gateway.invite_mail import (+ InviteEmail,+ InviteEmailFailed,+ SmtpInviteMailer,+ build_invite_message,+ invite_link,+)++_INVITE = InviteEmail(+ to="[email protected]",+ link="https://switch.example.com/invite#token=abc",+ workspace_name="<b>Acme & co</b>",+ inviter_name="Ada",+ role="member",+ expires_at=datetime(2030, 1, 2, 3, 4, tzinfo=UTC),+)+++def _parts(message: EmailMessage) -> tuple[str, str]:+ plain = message.get_body(preferencelist=("plain",))+ rich = message.get_body(preferencelist=("html",))+ assert plain is not None and rich is not None+ return plain.get_content(), rich.get_content()+++def test_the_link_carries_the_token_in_the_fragment() -> None:+ assert (+ invite_link("https://switch.example.com/", "tok")+ == "https://switch.example.com/invite#token=tok"+ )+++def test_the_message_names_the_workspace_the_inviter_and_the_link() -> None:+ message = build_invite_message(_INVITE, "[email protected]")++ assert message["To"] == "[email protected]"+ assert message["From"] == "[email protected]"+ assert message["Subject"] == "Ada invited you to <b>Acme & co</b> on Switch"+ plain, rich = _parts(message)+ assert _INVITE.link in plain+ assert "[email protected]" in plain+ assert "2030-01-02 03:04 UTC" in plain+ assert f'href="{_INVITE.link}"' in rich+++def test_names_are_escaped_in_the_html_part() -> None:+ _plain, rich = _parts(build_invite_message(_INVITE, "[email protected]"))++ assert "<b>Acme" not in rich+ assert "<b>Acme & co</b>" in rich+++def test_a_line_break_in_a_name_cannot_reach_the_headers() -> None:+ invite = InviteEmail(**{**_INVITE.__dict__, "workspace_name": "Acme\r\nBcc: x@y"})++ message = build_invite_message(invite, "[email protected]")++ assert message["Bcc"] is None+ assert message["Subject"] == "Ada invited you to Acme Bcc: x@y on Switch"+++class _RecordingSmtp:+ instances: list[_RecordingSmtp] = []++ def __init__(self, host: str, port: int, **kwargs: Any) -> None:+ self.host, self.port, self.kwargs = host, port, kwargs+ self.calls: list[str] = []+ self.sent: list[EmailMessage] = []+ _RecordingSmtp.instances.append(self)++ def __enter__(self) -> _RecordingSmtp:+ return self++ def __exit__(self, *exc: object) -> None:+ self.calls.append("quit")++ def starttls(self, **kwargs: Any) -> None:+ self.calls.append("starttls")++ def login(self, username: str, password: str) -> None:+ self.calls.append(f"login:{username}")++ def send_message(self, message: EmailMessage) -> None:+ self.calls.append("send")+ self.sent.append(message)+++class _RecordingSmtpSsl(_RecordingSmtp):+ pass+++def smtp(monkeypatch: pytest.MonkeyPatch) -> type[_RecordingSmtp]:+ _RecordingSmtp.instances = []+ monkeypatch.setattr(invite_mail.smtplib, "SMTP", _RecordingSmtp)+ monkeypatch.setattr(invite_mail.smtplib, "SMTP_SSL", _RecordingSmtpSsl)+ return _RecordingSmtp+++def _mailer(tls: str, *, username: str | None = None) -> SmtpInviteMailer:+ return SmtpInviteMailer(+ host="smtp.example.com",+ port=587,+ tls=tls,+ username=username,+ password="placeholder" if username else None,+ sender="[email protected]",+ )+++async def test_starttls_upgrades_then_logs_in_then_sends(+ smtp: type[_RecordingSmtp],+) -> None:+ await _mailer("starttls", username="relay-user").send_invitation(_INVITE)++ [conn] = smtp.instances+ assert type(conn) is _RecordingSmtp+ assert conn.calls == ["starttls", "login:relay-user", "send", "quit"]+ assert conn.sent[0]["To"] == "[email protected]"+++async def test_implicit_tls_connects_over_tls_and_skips_login_without_credentials(+ smtp: type[_RecordingSmtp],+) -> None:+ await _mailer("tls").send_invitation(_INVITE)++ [conn] = smtp.instances+ assert type(conn) is _RecordingSmtpSsl+ assert conn.calls == ["send", "quit"]+++async def test_no_tls_is_plain(smtp: type[_RecordingSmtp]) -> None:+ await _mailer("none").send_invitation(_INVITE)++ [conn] = smtp.instances+ assert conn.calls == ["send", "quit"]+++async def test_a_relay_refusal_is_reported_as_a_failed_send(+ monkeypatch: pytest.MonkeyPatch, smtp: type[_RecordingSmtp]+) -> None:+ def refuse(self: _RecordingSmtp, message: EmailMessage) -> None:+ raise smtplib.SMTPRecipientsRefused({message["To"]: (550, b"no")})++ monkeypatch.setattr(_RecordingSmtp, "send_message", refuse)++ with pytest.raises(InviteEmailFailed, match="smtp.example.com:587"):+ await _mailer("none").send_invitation(_INVITE)+++async def test_an_unreachable_relay_is_reported_as_a_failed_send(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def unreachable(*args: object, **kwargs: object) -> None:+ raise ConnectionRefusedError("connection refused")++ monkeypatch.setattr(invite_mail.smtplib, "SMTP", unreachable)++ with pytest.raises(InviteEmailFailed):+ await _mailer("starttls").send_invitation(_INVITE)diff --git a/core/tests/switch_core/gateway/test_messaging_installs_authz.py b/core/tests/switch_core/gateway/test_messaging_installs_authz.pynew file mode 100644index 000000000..a3261181c--- /dev/null+++ b/core/tests/switch_core/gateway/test_messaging_installs_authz.py@@ -0,0 +1,110 @@+"""Installing a messaging app is workspace administration.++An install lands a bridge in one tenant and nowhere else, so the person who+may do it is that workspace's owner or admin — not only the deployment+operator. On a server where people sign themselves up, the operator bit is+held by nobody who runs a workspace, so gating these routes on it would leave+the Slack button unreachable to exactly the people it is for.+"""++from __future__ import annotations++from types import SimpleNamespace++import httpx+from fastapi import FastAPI+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.db.models import Tenant, TenantMember, User+from switch_core.db.stores.user_store import UserStore+from switch_core.gateway import dependencies as gw_deps+from switch_core.gateway.auth import create_jwt, require_admin, require_tenant_admin+from switch_core.gateway.messaging_installs import router++_SECRET = "unit-test-jwt-key-unit-test-jwt-key-unit-test" # gitleaks:allow+_TENANT = "messaging-installs-authz"+++def _dependency_calls(dependant: object) -> list[object]:+ """All dependency callables reachable from a route, recursively."""+ calls = [dependant.call] # type: ignore[attr-defined]+ for sub in dependant.dependencies: # type: ignore[attr-defined]+ calls.extend(_dependency_calls(sub))+ return calls+++def test_every_route_requires_a_tenant_admin_and_not_the_operator() -> None:+ routes = [route for route in router.routes if hasattr(route, "dependant")]+ assert len(routes) == 4+ for route in routes:+ calls = _dependency_calls(route.dependant) # type: ignore[attr-defined]+ assert require_tenant_admin in calls, route.path # type: ignore[attr-defined]+ assert require_admin not in calls, route.path # type: ignore[attr-defined]+++def _app(session_factory: async_sessionmaker[AsyncSession]) -> FastAPI:+ async def _session_dep():+ async with session_factory() as session:+ yield session++ app = FastAPI()+ app.include_router(router, prefix="/messaging-apps")+ app.dependency_overrides[gw_deps.get_session] = _session_dep+ app.dependency_overrides[gw_deps.get_session_factory] = lambda: session_factory+ app.dependency_overrides[gw_deps.get_user_store] = lambda: UserStore()+ app.dependency_overrides[gw_deps.get_install_service] = lambda: None+ app.dependency_overrides[gw_deps.get_config] = lambda: SimpleNamespace(+ jwt_secret_key=_SECRET, gateway_tenant_choice_enabled=False+ )+ return app+++async def _member(+ session_factory: async_sessionmaker[AsyncSession], *, name: str, role: str+) -> str:+ async with session_factory() as session:+ if await session.get(Tenant, _TENANT) is None:+ session.add(Tenant(id=_TENANT, slug=_TENANT, name=_TENANT))+ await session.flush()+ user = User(name=name, email=f"{name}@example.invalid", role="user")+ session.add(user)+ await session.flush()+ session.add(TenantMember(tenant_id=_TENANT, user_id=user.id, role=role))+ await session.commit()+ return user.id+++async def _list_installs(+ session_factory: async_sessionmaker[AsyncSession], user_id: str, name: str+) -> httpx.Response:+ token = create_jwt(user_id, f"{name}@example.invalid", "user", _SECRET, _TENANT)+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=_app(session_factory)),+ base_url="http://test",+ cookies={"switch_auth": token},+ ) as client:+ return await client.get("/messaging-apps/installs")+++class TestWhoMayManageInstalls:+ async def test_a_workspace_owner_who_is_not_an_operator_may(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ user_id = await _member(session_factory, name="owner", role="owner")+ response = await _list_installs(session_factory, user_id, "owner")+ assert response.status_code == 200, response.text+ assert response.json() == {"installs": []}++ async def test_a_workspace_admin_may(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ user_id = await _member(session_factory, name="wsadmin", role="admin")+ response = await _list_installs(session_factory, user_id, "wsadmin")+ assert response.status_code == 200, response.text++ async def test_a_plain_member_may_not(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ user_id = await _member(session_factory, name="plain", role="member")+ response = await _list_installs(session_factory, user_id, "plain")+ assert response.status_code == 403diff --git a/core/tests/switch_core/gateway/test_oidc_routes.py b/core/tests/switch_core/gateway/test_oidc_routes.pyindex 59e87a806..1ff98a73b 100644--- a/core/tests/switch_core/gateway/test_oidc_routes.py+++ b/core/tests/switch_core/gateway/test_oidc_routes.py@@ -11,7 +11,13 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerimport switch_core.gateway.oidc_routes as oidc_routesfrom switch_core.config import SwitchConfig-from switch_core.db.models import TENANT_ZERO_ID, OidcIdentity, TenantMember, User+from switch_core.db.models import (+ TENANT_ZERO_ID,+ OidcIdentity,+ Tenant,+ TenantMember,+ User,+)from switch_core.db.stores.user_store import OidcIdentityRaceError, UserStorefrom switch_core.gateway.auth import decode_jwt, hash_passwordfrom switch_core.gateway.auth_routes import auth_config@@ -88,18 +94,20 @@ class TestOidcCallback:request=SimpleNamespace(), # type: ignore[arg-type]config=_config(),session=session,+ session_factory=session_factory,user_store=UserStore(),)assert response.status_code == 303set_cookie = response.headers.get("set-cookie")assert set_cookie is not None and "switch_auth=" in set_cookie- # Signing in selects no workspace. That null claim is the recovery- # path out of a selection that has gone stale — a removed member is- # 403'd on every request until something mints one without it — so- # a later change carrying the previous tenant forward here would- # strand them until their cookie expired (CHOO-2723).- assert _tenant_claim(set_cookie) is None+ # Signing in selects a workspace only from the user's *current*+ # memberships — here, the one just created. Signing in is the+ # recovery path out of a selection that has gone stale (a removed+ # member is 403'd on every request until something mints a claim+ # they can use), so it must never carry a previous claim forward+ # unchecked (CHOO-2723).+ assert _tenant_claim(set_cookie) == TENANT_ZERO_IDuser = await UserStore().get_by_email(session, "[email protected]")assert user is not None@@ -135,6 +143,7 @@ class TestOidcCallback:request=SimpleNamespace(), # type: ignore[arg-type]config=_config(),session=session,+ session_factory=session_factory,user_store=UserStore(),)assert exc.value.status_code == 401@@ -165,6 +174,7 @@ class TestOidcCallback:request=SimpleNamespace(), # type: ignore[arg-type]config=_config(gateway_oidc_require_email_verified=False),session=session,+ session_factory=session_factory,user_store=UserStore(),)@@ -191,6 +201,7 @@ class TestOidcCallback:request=SimpleNamespace(), # type: ignore[arg-type]config=_config(gateway_oidc_require_email_verified=False),session=session,+ session_factory=session_factory,user_store=UserStore(),)assert exc.value.status_code == 401@@ -229,6 +240,7 @@ class TestOidcCallback:request=SimpleNamespace(), # type: ignore[arg-type]config=_config(gateway_oidc_require_email_verified=False),session=session,+ session_factory=session_factory,user_store=UserStore(),)assert exc.value.status_code == 409@@ -268,6 +280,7 @@ class TestOidcCallback:request=SimpleNamespace(), # type: ignore[arg-type]config=_config(),session=session,+ session_factory=session_factory,user_store=UserStore(),)assert response.status_code == 303@@ -306,6 +319,7 @@ class TestOidcCallback:request=SimpleNamespace(), # type: ignore[arg-type]config=_config(),session=session,+ session_factory=session_factory,user_store=UserStore(),)assert first.status_code == 303@@ -330,6 +344,7 @@ class TestOidcCallback:request=SimpleNamespace(), # type: ignore[arg-type]config=_config(),session=session,+ session_factory=session_factory,user_store=UserStore(),)assert response.status_code == 303@@ -378,6 +393,7 @@ class TestOidcCallback:request=SimpleNamespace(), # type: ignore[arg-type]config=_config(gateway_oidc_require_email_verified=False),session=session,+ session_factory=session_factory,user_store=UserStore(),)assert response.status_code == 303@@ -416,6 +432,7 @@ class TestOidcCallback:request=SimpleNamespace(), # type: ignore[arg-type]config=_config(),session=session,+ session_factory=session_factory,user_store=_AlwaysRacingStore(), # type: ignore[arg-type])assert exc.value.status_code == 503@@ -436,6 +453,7 @@ class TestOidcCallback:request=SimpleNamespace(), # type: ignore[arg-type]config=_config(),session=session,+ session_factory=session_factory,user_store=UserStore(),)assert exc.value.status_code == 401@@ -462,6 +480,7 @@ class TestOidcCallback:request=SimpleNamespace(), # type: ignore[arg-type]config=_config(),session=session,+ session_factory=session_factory,user_store=UserStore(),)assert exc.value.status_code == 502@@ -489,6 +508,7 @@ class TestOidcCallback:request=SimpleNamespace(), # type: ignore[arg-type]config=_config(),session=session,+ session_factory=session_factory,user_store=UserStore(),)assert exc.value.status_code == 502@@ -518,6 +538,7 @@ class TestOidcCallback:request=SimpleNamespace(), # type: ignore[arg-type]config=_config(),session=session,+ session_factory=session_factory,user_store=UserStore(),)assert exc.value.status_code == 503@@ -531,8 +552,9 @@ class TestTheCallbackPlacesTheUserInATenant:"""Sign-in provisions accounts, and an account with no membership cannever sign in again (`gateway/auth.py` refuses to guess one). The callbackbinds tenant zero explicitly rather than letting `TenantScoped`'s fallback- supply it — the same row today, but a decision rather than an accident,- and the line a later sign-up phase changes.+ supply it — the same row today, but a decision rather than an accident.+ That is the `default_tenant` sign-up mode; `TestSignUpWithoutADefaultTenant`+ covers the others."""async def _memberships(@@ -563,6 +585,7 @@ class TestTheCallbackPlacesTheUserInATenant:request=SimpleNamespace(), # type: ignore[arg-type]config=_config(),session=session,+ session_factory=session_factory,user_store=UserStore(),)user = await UserStore().get_by_email(session, "[email protected]")@@ -606,6 +629,7 @@ class TestTheCallbackPlacesTheUserInATenant:request=SimpleNamespace(), # type: ignore[arg-type]config=_config(),session=session,+ session_factory=session_factory,user_store=UserStore(),)memberships = await self._memberships(session, user_id)@@ -644,6 +668,7 @@ class TestTheCallbackPlacesTheUserInATenant:request=SimpleNamespace(), # type: ignore[arg-type]config=_config(),session=session,+ session_factory=session_factory,user_store=UserStore(),)memberships = await self._memberships(session, user_id)@@ -651,6 +676,137 @@ class TestTheCallbackPlacesTheUserInATenant:assert [m.tenant_id for m in memberships] == [TENANT_ZERO_ID]+def _verified_token(email: str, sub: str) -> dict:+ return {+ "userinfo": {+ "email": email,+ "email_verified": True,+ "sub": sub,+ "name": email.split("@", 1)[0],+ }+ }+++async def _memberships(session: AsyncSession, user_id: str) -> list[TenantMember]:+ result = await session.execute(+ select(TenantMember).where(TenantMember.user_id == user_id)+ )+ return list(result.scalars().all())+++class TestSignUpWithoutADefaultTenant:+ """In `open` and `invite_only` the callback places nobody: a new account+ arrives with no workspace and makes or accepts one itself. Tenant zero is+ an operator's workspace on such a server, not a lobby."""++ @pytest.mark.parametrize("mode", ["open", "invite_only"])+ async def test_a_new_account_has_no_membership_and_no_claim(+ self,+ mode: str,+ session_factory: async_sessionmaker[AsyncSession],+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ email = f"new-{mode.replace('_', '-')}@example.com"+ token = _verified_token(email, f"okta|new-{mode}")+ monkeypatch.setattr(oidc_routes, "_client", lambda: _FakeClient(token))++ async with session_factory() as session:+ response = await oidc_routes.oidc_callback(+ request=SimpleNamespace(), # type: ignore[arg-type]+ config=_config(gateway_signup_mode=mode),+ session=session,+ session_factory=session_factory,+ user_store=UserStore(),+ )+ user = await UserStore().get_by_email(session, email)+ assert user is not None+ memberships = await _memberships(session, user.id)++ assert response.status_code == 303+ assert memberships == []+ set_cookie = response.headers.get("set-cookie")+ assert set_cookie is not None+ assert _tenant_claim(set_cookie) is None++ async def test_linking_a_verified_email_adds_no_membership(+ self,+ session_factory: async_sessionmaker[AsyncSession],+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ async with session_factory() as session:+ existing = User(+ name="Unplaced",+ email="[email protected]",+ role="user",+ password_hash=hash_password("pw"),+ )+ session.add(existing)+ await session.commit()+ user_id = existing.id++ token = _verified_token("[email protected]", "okta|unplaced")+ monkeypatch.setattr(oidc_routes, "_client", lambda: _FakeClient(token))++ async with session_factory() as session:+ await oidc_routes.oidc_callback(+ request=SimpleNamespace(), # type: ignore[arg-type]+ config=_config(gateway_signup_mode="open"),+ session=session,+ session_factory=session_factory,+ user_store=UserStore(),+ )+ identity = (+ await session.execute(+ select(OidcIdentity).where(OidcIdentity.sub == "okta|unplaced")+ )+ ).scalar_one()+ memberships = await _memberships(session, user_id)++ assert identity.user_id == user_id+ assert memberships == []++ async def test_a_returning_account_lands_in_its_last_workspace(+ self,+ session_factory: async_sessionmaker[AsyncSession],+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ other = "oidc-returning-other"+ async with session_factory() as session:+ session.add(Tenant(id=other, slug=other, name=other))+ await session.flush()+ existing = User(+ name="Back",+ email="[email protected]",+ role="user",+ metadata_={"last_tenant_id": other},+ )+ session.add(existing)+ await session.flush()+ for tenant_id in (TENANT_ZERO_ID, other):+ session.add(+ TenantMember(+ tenant_id=tenant_id, user_id=existing.id, role="member"+ )+ )+ await session.commit()++ token = _verified_token("[email protected]", "okta|back")+ monkeypatch.setattr(oidc_routes, "_client", lambda: _FakeClient(token))++ async with session_factory() as session:+ response = await oidc_routes.oidc_callback(+ request=SimpleNamespace(), # type: ignore[arg-type]+ config=_config(gateway_signup_mode="open"),+ session=session,+ session_factory=session_factory,+ user_store=UserStore(),+ )++ set_cookie = response.headers.get("set-cookie")+ assert set_cookie is not None+ assert _tenant_claim(set_cookie) == other++class TestAuthConfigEndpoint:async def test_reports_enabled_oidc_and_label(self) -> None:config = _config(gateway_oidc_provider_label="Okta")@@ -670,3 +826,7 @@ class TestAuthConfigEndpoint:result = await auth_config(config=config)assert result.oidc_enabled is Falseassert result.password_login_enabled is False++ async def test_reports_the_signup_mode(self) -> None:+ result = await auth_config(config=_config(gateway_signup_mode="invite_only"))+ assert result.signup_mode == "invite_only"diff --git a/core/tests/switch_core/gateway/test_session_requires_authentication.py b/core/tests/switch_core/gateway/test_session_requires_authentication.pyindex 2c8b36c3d..7067cde12 100644--- a/core/tests/switch_core/gateway/test_session_requires_authentication.py+++ b/core/tests/switch_core/gateway/test_session_requires_authentication.py@@ -40,14 +40,17 @@ from switch_core.gateway.dependencies import get_session, get_system_session# The only routes that may open a session with no tenant bound. `get_session`# is unavailable to them because there is no `get_current_user` to bind one:-# for login and the OIDC callback there is no caller yet at all; for switching-# tenants the caller is authenticated (`get_authenticated_user_id`) but has,-# by construction, not yet selected the tenant this session opens for — see-# `get_system_session`'s docstring. All three take `get_system_session`-# instead, which says so in the signature.+# for login and the OIDC callback there is no caller yet at all; for the rest+# the caller is authenticated but has, by construction, no selected tenant to+# bind — switching is choosing one, creating a workspace makes one, and the+# session state is how a caller without one learns so. See+# `get_system_session`'s docstring. They take `get_system_session` instead,+# which says so in the signature._ROUTES_WITH_NO_TENANT_BOUND = {("POST", "/auth/login"),("GET", "/auth/oidc/callback"),+ ("GET", "/auth/session"),+ ("POST", "/tenants"),("POST", "/tenants/{tenant_id}/switch"),# Locks the caller's `users` row, which has no tenant, while it creates a# workspace that has none yet either.@@ -74,6 +77,9 @@ _ROUTES_THAT_NEVER_BIND_A_TENANT = {("GET", "/auth/oidc/callback"),("POST", "/auth/login"),("POST", "/auth/logout"),+ # What a signed-in caller's session resolves to — including that it+ # resolves to no workspace, which is the answer a caller with none needs.+ ("GET", "/auth/session"),# A deployment-wide constant — the agent types this build knows about.# Nothing tenant-specific to scope it to.("GET", "/known-types"),@@ -87,6 +93,21 @@ _ROUTES_THAT_NEVER_BIND_A_TENANT = {# neither the one on the caller's session nor one they belong to yet. It# opens its own `tenant_session` around that id — see `accept_invitation`.("POST", "/invitations/accept"),+ # Invitations addressed to the caller are in workspaces they are not in, so+ # no session of theirs is bound to one. Listing opens a `tenant_session`+ # per tenant `tenants_with_invitations_for` names; accepting opens one+ # around the tenant the request names, and finds nothing if the+ # invitation is not there — see `list_my_invitations` and+ # `accept_my_invitation`.+ ("GET", "/invitations/mine"),+ ("POST", "/invitations/mine/accept"),+ # Workspaces open to the caller's e-mail domain are ones they are not in+ # yet, for the same reason. Listing opens a `tenant_session` per tenant+ # `tenants_open_to` names; joining opens one around the tenant in the path+ # and finds nothing unless it is open to the caller's domain — see+ # `list_joinable_tenants` and `join_tenant_by_domain`.+ ("GET", "/joinable-tenants"),+ ("POST", "/joinable-tenants/{tenant_id}/join"),}diff --git a/core/tests/switch_core/gateway/test_shared_bridge_registration.py b/core/tests/switch_core/gateway/test_shared_bridge_registration.pynew file mode 100644index 000000000..ed89800b8--- /dev/null+++ b/core/tests/switch_core/gateway/test_shared_bridge_registration.py@@ -0,0 +1,160 @@+"""A shared bridge is made by installing the app, and stays on what it was+installed into.++The deployment's own app is in every tenant's workspaces, so a shared bridge+reaches whatever its config names. Registering one by hand, or editing one to+name another workspace, would let a tenant admin put their rooms in somebody+else's. Both are refused before anything is stored.+"""++from __future__ import annotations++import uuid+from typing import Any++import pytest+from fastapi import HTTPException+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.bridges.collaboration.models import BridgeStartRefused+from switch_core.db.models import Client, CollaborationBridge, User+from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore+from switch_core.db.stores.room_store import RoomStore+from switch_core.gateway.collaborations import create_bridge, update_bridge+from switch_core.gateway.schemas import BridgeCreateRequest, BridgeUpdateRequest++_BRIDGE_STORE = CollaborationBridgeStore()+++class _Lifecycle:+ """Records what reached it; refuses any start when told to."""++ def __init__(self, *, refuse: bool = False) -> None:+ self.refuse = refuse+ self.registered: list[dict[str, object]] = []+ self.checked: list[dict[str, Any]] = []++ async def register(self, **kwargs: object) -> None:+ self.registered.append(kwargs)++ def validate_connection_config(+ self, bridge_type: str, connection_config: dict[str, object]+ ) -> None: ...++ def supports_channel_creation(self, bridge_type: str) -> bool:+ return False++ async def check_start_guards(self, **kwargs: Any) -> None:+ self.checked.append(kwargs)+ if self.refuse:+ raise BridgeStartRefused("not installed for this tenant")+++def _admin() -> User:+ return User(id="admin", name="admin", email="[email protected]", role="admin")+++async def _shared_bridge(session: AsyncSession) -> str:+ client = Client(+ matrix_user_id=f"@bridge-{uuid.uuid4().hex[:12]}:test",+ display_name="bridge client",+ type="bridge",+ )+ session.add(client)+ await session.flush()+ bridge = CollaborationBridge(+ type="discord",+ display_name="Acme",+ client_id=client.id,+ status="active",+ connection_config={"guild_id": "111", "event_delivery": "shared"},+ )+ session.add(bridge)+ await session.flush()+ return bridge.id+++async def _update(+ session_factory: async_sessionmaker[AsyncSession],+ bridge_id: str,+ lifecycle: _Lifecycle,+ connection_config: dict[str, object],+) -> HTTPException:+ async with session_factory() as session:+ with pytest.raises(HTTPException) as refused:+ await update_bridge(+ bridge_id=bridge_id,+ payload=BridgeUpdateRequest(connection_config=connection_config),+ session=session,+ bridge_store=_BRIDGE_STORE,+ room_store=RoomStore(),+ collab_lifecycle=lifecycle, # type: ignore[arg-type]+ _user=_admin(),+ )+ return refused.value+++async def _stored_config(+ session_factory: async_sessionmaker[AsyncSession], bridge_id: str+) -> dict[str, object]:+ async with session_factory() as session:+ bridge = await _BRIDGE_STORE.get(session, bridge_id)+ assert bridge is not None+ return dict(bridge.connection_config or {})+++async def test_a_shared_bridge_cannot_be_registered_by_hand() -> None:+ lifecycle = _Lifecycle()++ with pytest.raises(HTTPException) as refused:+ await create_bridge(+ req=BridgeCreateRequest(+ bridge_type="discord",+ display_name="Not mine",+ connection_config={"guild_id": "999", "event_delivery": "shared"},+ ),+ session=None, # type: ignore[arg-type]+ bridge_store=_BRIDGE_STORE,+ collab_lifecycle=lifecycle, # type: ignore[arg-type]+ _user=_admin(),+ )++ assert refused.value.status_code == 422+ assert lifecycle.registered == []+++async def test_a_shared_bridge_cannot_be_pointed_at_another_workspace(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ async with session_factory() as session:+ bridge_id = await _shared_bridge(session)+ await session.commit()+ lifecycle = _Lifecycle(refuse=True)++ refused = await _update(session_factory, bridge_id, lifecycle, {"guild_id": "999"})++ assert refused.status_code == 422+ # Asked with the config it would have stored, and nothing was stored.+ assert lifecycle.checked[0]["connection_config"]["guild_id"] == "999"+ assert (await _stored_config(session_factory, bridge_id))["guild_id"] == "111"+++async def test_how_a_bridge_receives_events_cannot_be_changed(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ async with session_factory() as session:+ bridge_id = await _shared_bridge(session)+ await session.commit()+ lifecycle = _Lifecycle()++ refused = await _update(+ session_factory,+ bridge_id,+ lifecycle,+ {"event_delivery": "own_connection", "bot_token": "pasted-token"},+ )++ assert refused.status_code == 422+ assert (await _stored_config(session_factory, bridge_id))[+ "event_delivery"+ ] == "shared"diff --git a/core/tests/switch_core/gateway/test_tenant_api_routes.py b/core/tests/switch_core/gateway/test_tenant_api_routes.pynew file mode 100644index 000000000..6c3155848--- /dev/null+++ b/core/tests/switch_core/gateway/test_tenant_api_routes.py@@ -0,0 +1,2236 @@+"""The route half of CHOO-2722: `gateway/tenants.py`'s workspace, invitation+and member routes.++Builds route-scoped apps the same way `test_tenant_resolution.py` does —+`switch_core.gateway.dependencies`' functions overridden individually rather+than through `init_dependencies` — so nothing here leaks into another test and+nothing but `switch_core.gateway.tenants` itself is exercised for real.++`_FakeClientLifecycle.create_tenant` mirrors+`ClientLifecycleService.create_tenant`'s DB half (insert the tenant row inside+a `tenant_session` bound to its own id) without the Matrix admin-client+provisioning, which needs a running homeserver these tests have no business+depending on. The unique-slug behaviour under test comes from the same+`tenants.slug` column either way.+"""++from __future__ import annotations++import asyncio+import uuid+from datetime import UTC, datetime, timedelta+from types import SimpleNamespace++import httpx+import pytest+from fastapi import FastAPI+from sqlalchemy import select+from sqlalchemy.exc import IntegrityError+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.db.models import (+ Agent,+ ApiKey,+ Client,+ Invitation,+ Tenant,+ TenantMember,+ UsageMetric,+ User,+)+from switch_core.db.session_scope import tenant_session+from switch_core.db.stores.agent_store import AgentStore+from switch_core.db.stores.api_key_store import ApiKeyStore+from switch_core.db.stores.budget_store import BudgetStore+from switch_core.db.stores.invitation_store import InvitationStore+from switch_core.db.stores.join_domain_store import JoinDomainStore+from switch_core.db.stores.tenant_store import TenantStore+from switch_core.db.stores.usage_store import UsageStore+from switch_core.db.stores.user_store import UserStore+from switch_core.gateway import dependencies as gw_deps+from switch_core.gateway.auth import create_jwt, decode_jwt+from switch_core.gateway.invite_mail import (+ InviteEmail,+ InviteEmailFailed,+ InviteMailer,+)+from switch_core.gateway.tenants import router as tenants_router++_SECRET = "unit-test-jwt-key-unit-test-jwt-key-unit-test" # gitleaks:allow+TENANT_A = "tenant-api-routes-a"+TENANT_B = "tenant-api-routes-b"+++class _FakeClientLifecycle:+ def __init__(self, session_factory: async_sessionmaker[AsyncSession]) -> None:+ self._session_factory = session_factory++ async def create_tenant(self, name: str, slug: str) -> Tenant:+ tenant = Tenant(id=str(uuid.uuid4()), name=name, slug=slug)+ async with tenant_session(self._session_factory, tenant.id) as session:+ await TenantStore().create(session, tenant)+ await session.commit()+ return tenant+++class _ProvisioningFailsLifecycle(_FakeClientLifecycle):+ """Commits the tenant, then fails the way a concurrent admin-client insert+ does — an integrity error that has nothing to do with the slug."""++ def __init__(self, session_factory: async_sessionmaker[AsyncSession]) -> None:+ super().__init__(session_factory)+ self.calls = 0++ async def create_tenant(self, name: str, slug: str) -> Tenant:+ self.calls += 1+ await super().create_tenant(name, slug)+ raise IntegrityError("INSERT INTO clients ...", None, Exception("duplicate"))+++class _RecordingMailer:+ def __init__(self) -> None:+ self.sent: list[InviteEmail] = []++ async def send_invitation(self, invite: InviteEmail) -> None:+ self.sent.append(invite)+++class _FailingMailer:+ async def send_invitation(self, invite: InviteEmail) -> None:+ raise InviteEmailFailed("relay refused the message")+++def _fake_protocol() -> SimpleNamespace:+ return SimpleNamespace(+ api_key_cache=SimpleNamespace(+ invalidate=lambda key_hash: None,+ invalidate_agent=lambda agent_id: None,+ )+ )+++def _app(+ session_factory: async_sessionmaker[AsyncSession],+ *,+ client_lifecycle: object | None = None,+ max_workspaces_per_user: int = 3,+ signup_mode: str = "default_tenant",+ mailer: InviteMailer | None = None,+ invite_emails_per_day: int = 50,+) -> FastAPI:+ async def _session_dep():+ async with session_factory() as session:+ yield session++ app = FastAPI()+ app.include_router(tenants_router)+ app.dependency_overrides[gw_deps.get_session] = _session_dep+ app.dependency_overrides[gw_deps.get_system_session] = _session_dep+ app.dependency_overrides[gw_deps.get_session_factory] = lambda: session_factory+ app.dependency_overrides[gw_deps.get_user_store] = lambda: UserStore()+ app.dependency_overrides[gw_deps.get_agent_store] = lambda: AgentStore()+ app.dependency_overrides[gw_deps.get_api_key_store] = lambda: ApiKeyStore()+ app.dependency_overrides[gw_deps.get_invitation_store] = lambda: InvitationStore()+ app.dependency_overrides[gw_deps.get_join_domain_store] = lambda: JoinDomainStore()+ app.dependency_overrides[gw_deps.get_usage_store] = lambda: UsageStore()+ app.dependency_overrides[gw_deps.get_budget_store] = lambda: BudgetStore()+ app.dependency_overrides[gw_deps.get_protocol] = lambda: _fake_protocol()+ app.dependency_overrides[gw_deps.get_invite_mailer] = lambda: mailer+ app.dependency_overrides[gw_deps.get_client_lifecycle] = lambda: (+ client_lifecycle or _FakeClientLifecycle(session_factory)+ )+ app.dependency_overrides[gw_deps.get_config] = lambda: SimpleNamespace(+ jwt_secret_key=_SECRET,+ gateway_cookie_secure=False,+ gateway_tenant_choice_enabled=False,+ gateway_max_workspaces_per_user=max_workspaces_per_user,+ gateway_signup_mode=signup_mode,+ gateway_invite_emails_per_day=invite_emails_per_day,+ frontend_base_url="https://switch.example.com/",+ )+ return app+++def _client(app: FastAPI, token: str) -> httpx.AsyncClient:+ return httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app),+ base_url="http://test",+ cookies={"switch_auth": token},+ )+++async def _make_tenant(+ session_factory: async_sessionmaker[AsyncSession], tenant_id: str+) -> None:+ async with session_factory() as session:+ session.add(Tenant(id=tenant_id, slug=tenant_id, name=tenant_id))+ await session.commit()+++async def _make_member(+ session_factory: async_sessionmaker[AsyncSession],+ *,+ name: str,+ tenant_id: str,+ role: str,+ email: str | None = None,+ user_role: str = "user",+) -> str:+ """A user with a membership in `tenant_id`.++ `role` is the per-tenant membership role; `user_role` is the global+ `users.role`, which is a different axis entirely — `"admin"` there is the+ deployment operator bit, granted by nothing self-service.+ """+ async with session_factory() as session:+ user = User(name=name, email=email or f"{name}@example.invalid", role=user_role)+ session.add(user)+ await session.flush()+ session.add(TenantMember(tenant_id=tenant_id, user_id=user.id, role=role))+ await session.commit()+ return user.id+++def _token(user_id: str, email: str, tenant_id: str | None) -> str:+ return create_jwt(user_id, email, "user", _SECRET, tenant_id)+++def _tenant_claim(response: httpx.Response) -> str | None:+ token = response.cookies.get("switch_auth")+ assert token is not None, "no session cookie was minted"+ claim: str | None = decode_jwt(token, _SECRET).get("tenant_id")+ return claim+++async def _make_unaffiliated_user(+ session_factory: async_sessionmaker[AsyncSession], *, name: str, role: str+) -> str:+ async with session_factory() as session:+ user = User(name=name, email=f"{name}@example.invalid", role=role)+ session.add(user)+ await session.commit()+ return user.id+++async def _last_tenant_id(+ session_factory: async_sessionmaker[AsyncSession], user_id: str+) -> str | None:+ async with session_factory() as session:+ user = await session.get(User, user_id)+ assert user is not None+ return UserStore().last_tenant_id(user)+++async def _make_api_key(+ session_factory: async_sessionmaker[AsyncSession],+ *,+ tenant_id: str,+ user_id: str,+ key_type: str = "registration",+) -> str:+ """A personal (non-agent) API key for `user_id` in `tenant_id`. Returns+ its `key_hash`."""+ key_hash = uuid.uuid4().hex+ async with session_factory() as session:+ session.add(+ ApiKey(+ tenant_id=tenant_id,+ user_id=user_id,+ key_hash=key_hash,+ encrypted_key="unused-in-tests",+ label="test-key",+ type=key_type,+ )+ )+ await session.commit()+ return key_hash+++async def _make_agent_with_key(+ session_factory: async_sessionmaker[AsyncSession],+ *,+ tenant_id: str,+ owner_id: str,+) -> tuple[str, str, str]:+ """An agent owned by `owner_id`, plus the `agents`-type key backing it.++ Returns `(agent_id, agent_name, key_hash)`. The agent's own client and+ api_key rows are constructed first — `agents.client_id` and+ `agents.api_key_id` are both foreign keys, not free-form strings.+ """+ key_hash = uuid.uuid4().hex+ name = f"agent-{uuid.uuid4().hex[:8]}"+ async with session_factory() as session:+ client = Client(+ tenant_id=tenant_id,+ matrix_user_id=f"@bot-{uuid.uuid4().hex[:8]}:test",+ display_name="test-agent-bot",+ type="agent",+ )+ session.add(client)+ await session.flush()++ api_key = ApiKey(+ tenant_id=tenant_id,+ user_id=owner_id,+ key_hash=key_hash,+ encrypted_key="unused-in-tests",+ label="agent-key",+ type="agent",+ )+ session.add(api_key)+ await session.flush()++ agent = Agent(+ tenant_id=tenant_id,+ name=name,+ description="test agent",+ agent_type="other",+ connector_type="claude-code",+ integration_profile={},+ client_id=client.id,+ api_key_id=api_key.id,+ owner_id=owner_id,+ )+ session.add(agent)+ await session.commit()+ return agent.id, name, key_hash+++class TestCreateTenant:+ async def test_creating_a_tenant_makes_the_caller_its_owner(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await _make_tenant(session_factory, TENANT_A)+ user_id = await _make_member(+ session_factory, name="founder", tenant_id=TENANT_A, role="member"+ )+ token = _token(user_id, "[email protected]", TENANT_A)++ async with _client(_app(session_factory), token) as client:+ response = await client.post("/tenants", json={"name": "Acme Corp"})++ assert response.status_code == 201, response.text+ body = response.json()+ assert body["slug"] == "acme-corp"+ assert body["role"] == "owner"++ async with session_factory() as session:+ membership = await session.get(TenantMember, (body["id"], user_id))+ assert membership is not None+ assert membership.role == "owner"++ async def test_creating_a_tenant_switches_the_caller_into_it(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await _make_tenant(session_factory, TENANT_A)+ user_id = await _make_member(+ session_factory, name="mover", tenant_id=TENANT_A, role="member"+ )+ token = _token(user_id, "[email protected]", TENANT_A)++ async with _client(_app(session_factory), token) as client:+ response = await client.post("/tenants", json={"name": "Moving Co"})++ assert response.status_code == 201, response.text+ new_id = response.json()["id"]+ assert _tenant_claim(response) == new_id+ assert await _last_tenant_id(session_factory, user_id) == new_id++ async def test_a_caller_with_no_workspace_can_create_their_first(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ user_id = await _make_unaffiliated_user(+ session_factory, name="newcomer", role="user"+ )+ token = _token(user_id, "[email protected]", None)++ async with _client(_app(session_factory, signup_mode="open"), token) as client:+ response = await client.post("/tenants", json={"name": "First Light"})++ assert response.status_code == 201, response.text+ assert response.json()["role"] == "owner"+ assert _tenant_claim(response) == response.json()["id"]++ async def test_a_taken_slug_gets_a_suffix_rather_than_a_409(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """A 409 would tell the caller that a workspace of that name exists+ somewhere on the server. Nobody types the slug, so a suffixed one costs+ them nothing."""+ await _make_tenant(session_factory, TENANT_A)+ user_id = await _make_member(+ session_factory, name="second-founder", tenant_id=TENANT_A, role="member"+ )+ token = _token(user_id, "[email protected]", TENANT_A)++ async with _client(_app(session_factory), token) as client:+ first = await client.post("/tenants", json={"name": "Widgets Inc"})+ assert first.status_code == 201, first.text+ second = await client.post("/tenants", json={"name": "Widgets Inc"})++ assert second.status_code == 201, second.text+ assert first.json()["slug"] == "widgets-inc"+ assert second.json()["slug"].startswith("widgets-inc-")+ assert second.json()["id"] != first.json()["id"]++ async def test_invite_only_refuses_a_non_operator(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ user_id = await _make_unaffiliated_user(+ session_factory, name="hopeful", role="user"+ )+ token = _token(user_id, "[email protected]", None)++ app = _app(session_factory, signup_mode="invite_only")+ async with _client(app, token) as client:+ response = await client.post("/tenants", json={"name": "Hopeful Ltd"})++ assert response.status_code == 403+ assert "invitation" in response.json()["detail"]+ async with session_factory() as session:+ assert (+ await session.execute(+ select(Tenant).where(Tenant.name == "Hopeful Ltd")+ )+ ).first() is None++ async def test_invite_only_still_lets_an_operator_create(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ user_id = await _make_unaffiliated_user(+ session_factory, name="operator", role="admin"+ )+ token = create_jwt(user_id, "[email protected]", "admin", _SECRET, None)++ app = _app(session_factory, signup_mode="invite_only")+ async with _client(app, token) as client:+ response = await client.post("/tenants", json={"name": "Ops Co"})++ assert response.status_code == 201, response.text++ async def test_a_failure_other_than_a_taken_slug_is_not_retried(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """Retrying would leave the committed workspace behind, ownerless, and+ make another one."""+ user_id = await _make_unaffiliated_user(+ session_factory, name="unlucky", role="user"+ )+ token = _token(user_id, "[email protected]", None)+ lifecycle = _ProvisioningFailsLifecycle(session_factory)++ app = _app(session_factory, client_lifecycle=lifecycle, signup_mode="open")+ async with _client(app, token) as client:+ with pytest.raises(IntegrityError):+ await client.post("/tenants", json={"name": "Unlucky Co"})++ assert lifecycle.calls == 1++ async def test_a_name_with_no_slug_characters_is_400(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await _make_tenant(session_factory, TENANT_A)+ user_id = await _make_member(+ session_factory, name="emoji-fan", tenant_id=TENANT_A, role="member"+ )+ token = _token(user_id, "[email protected]", TENANT_A)++ async with _client(_app(session_factory), token) as client:+ response = await client.post("/tenants", json={"name": "!!!"})++ assert response.status_code == 400+++class TestWorkspaceCreationLimit:+ """`POST /tenants` is the one route here with no tenant to authorize+ against, so what stands in for its neighbours' role check is a bound on how+ many workspaces one person may own. It exists because a workspace is not+ just a row: `all_tenant_ids()` drives a fan-out per tenant at boot and a+ sweep every few seconds (`docs/old/multi-tenancy-phase2-tenants.md`, §5).+ """++ async def test_a_caller_at_the_limit_is_refused(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await _make_tenant(session_factory, TENANT_A)+ user_id = await _make_member(+ session_factory, name="serial-founder", tenant_id=TENANT_A, role="member"+ )+ token = _token(user_id, "[email protected]", TENANT_A)++ app = _app(session_factory, max_workspaces_per_user=2)+ async with _client(app, token) as client:+ assert (+ await client.post("/tenants", json={"name": "First"})+ ).status_code == 201+ assert (+ await client.post("/tenants", json={"name": "Second"})+ ).status_code == 201+ third = await client.post("/tenants", json={"name": "Third"})++ assert third.status_code == 403+ assert "created 2 workspaces" in third.json()["detail"]++ async def test_nothing_is_provisioned_for_a_refused_caller(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ # The bound is checked before `create_tenant`, so a refusal must not+ # leave the orphan workspace the handler's own docstring warns about.+ await _make_tenant(session_factory, TENANT_A)+ user_id = await _make_member(+ session_factory, name="blocked-founder", tenant_id=TENANT_A, role="member"+ )+ token = _token(user_id, "[email protected]", TENANT_A)++ app = _app(session_factory, max_workspaces_per_user=0)+ async with _client(app, token) as client:+ response = await client.post("/tenants", json={"name": "Never Made"})++ assert response.status_code == 403+ async with session_factory() as session:+ found = await session.scalars(+ select(Tenant).where(Tenant.slug == "never-made")+ )+ assert found.first() is None++ async def test_handing_a_workspace_over_does_not_free_the_allowance(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ # What is bounded is creation. Were it ownership, creating, promoting a+ # second account and stepping down would reset the count every time.+ await _make_tenant(session_factory, TENANT_A)+ user_id = await _make_member(+ session_factory, name="hand-off", tenant_id=TENANT_A, role="member"+ )+ token = _token(user_id, "[email protected]", TENANT_A)++ app = _app(session_factory, max_workspaces_per_user=1)+ async with _client(app, token) as client:+ first = await client.post("/tenants", json={"name": "Handed Over"})+ async with session_factory() as session:+ member = await session.get(TenantMember, (first.json()["id"], user_id))+ assert member is not None+ member.role = "member"+ await session.commit()+ second = await client.post("/tenants", json={"name": "One Too Many"})++ assert first.status_code == 201+ assert second.status_code == 403++ async def test_concurrent_requests_cannot_all_pass_the_check(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await _make_tenant(session_factory, TENANT_A)+ user_id = await _make_member(+ session_factory, name="burst", tenant_id=TENANT_A, role="member"+ )+ token = _token(user_id, "[email protected]", TENANT_A)++ app = _app(session_factory, max_workspaces_per_user=1)+ async with _client(app, token) as client:+ responses = await asyncio.gather(+ *(+ client.post("/tenants", json={"name": f"Burst {i}"})+ for i in range(5)+ )+ )++ codes = sorted(r.status_code for r in responses)+ assert codes.count(201) == 1+ assert set(codes) - {201} <= {403, 409}+ async with session_factory() as session:+ owned = await session.scalars(+ select(TenantMember).where(+ TenantMember.user_id == user_id, TenantMember.role == "owner"+ )+ )+ assert len(owned.all()) == 1++ async def test_a_request_during_another_creation_is_refused_not_queued(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ # Waiting would hold a pool connection for as long as the other+ # creation takes; refusing at once holds none.+ await _make_tenant(session_factory, TENANT_A)+ user_id = await _make_member(+ session_factory, name="in-flight", tenant_id=TENANT_A, role="member"+ )+ token = _token(user_id, "[email protected]", TENANT_A)++ app = _app(session_factory, max_workspaces_per_user=3)+ async with session_factory() as holder:+ await holder.scalar(+ select(User).where(User.id == user_id).with_for_update(key_share=True)+ )+ async with _client(app, token) as client:+ response = await client.post("/tenants", json={"name": "Queued"})++ assert response.status_code == 409+ assert "being created" in response.json()["detail"]++ async def test_a_limit_of_zero_says_creation_is_disabled(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ # Zero is how a deployment closes the route, and it must not be+ # reported as though the caller had used up an allowance.+ await _make_tenant(session_factory, TENANT_A)+ user_id = await _make_member(+ session_factory, name="early-bird", tenant_id=TENANT_A, role="member"+ )+ token = _token(user_id, "[email protected]", TENANT_A)++ app = _app(session_factory, max_workspaces_per_user=0)+ async with _client(app, token) as client:+ response = await client.post("/tenants", json={"name": "Too Early"})++ assert response.status_code == 403+ assert response.json()["detail"] == (+ "Workspace creation is disabled on this deployment"+ )++ async def test_memberships_the_caller_does_not_own_are_free(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ # Being invited into someone else's workspace must not spend an+ # allowance: the invitee cannot get it back without being removed.+ await _make_tenant(session_factory, TENANT_A)+ await _make_tenant(session_factory, TENANT_B)+ user_id = await _make_member(+ session_factory, name="joiner", tenant_id=TENANT_A, role="admin"+ )+ async with session_factory() as session:+ session.add(+ TenantMember(tenant_id=TENANT_B, user_id=user_id, role="member")+ )+ await session.commit()+ token = _token(user_id, "[email protected]", TENANT_A)++ app = _app(session_factory, max_workspaces_per_user=1)+ async with _client(app, token) as client:+ response = await client.post("/tenants", json={"name": "Mine At Last"})++ assert response.status_code == 201, response.text++ async def test_an_operator_is_exempt(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ # `users.role == "admin"` is the deployment operator bit, and this+ # bound is about self-service. An operator provisioning workspaces for+ # other people is exactly who it must not stop — the same bypass+ # `authz.administers_tenant` and `authz.owns_tenant` already give them.+ await _make_tenant(session_factory, TENANT_A)+ user_id = await _make_member(+ session_factory,+ name="the-operator",+ tenant_id=TENANT_A,+ role="member",+ user_role="admin",+ )+ token = _token(user_id, "[email protected]", TENANT_A)++ app = _app(session_factory, max_workspaces_per_user=0)+ async with _client(app, token) as client:+ first = await client.post("/tenants", json={"name": "Customer One"})+ second = await client.post("/tenants", json={"name": "Customer Two"})++ assert first.status_code == 201, first.text+ assert second.status_code == 201, second.text++ async def test_the_operator_bit_is_read_fresh_not_from_the_token(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ # The JWT carries a role claim from login. Trusting it would keep a+ # revoked operator exempt for the life of their cookie, so the bit+ # comes from the `users` row on every request.+ await _make_tenant(session_factory, TENANT_A)+ user_id = await _make_member(+ session_factory, name="demoted", tenant_id=TENANT_A, role="member"+ )+ stale_operator_token = create_jwt(+ user_id, "[email protected]", "admin", _SECRET, TENANT_A+ )++ async with _client(+ _app(session_factory, max_workspaces_per_user=0), stale_operator_token+ ) as client:+ response = await client.post("/tenants", json={"name": "Not Allowed"})++ assert response.status_code == 403+++class TestInvitationAuthorisation:+ """A member of workspace A cannot mint an invitation to workspace B —+ each request is bound to exactly one tenant, and the path segment cannot+ override that."""++ async def test_a_plain_member_cannot_mint_an_invitation(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await _make_tenant(session_factory, TENANT_A)+ user_id = await _make_member(+ session_factory, name="rank-and-file", tenant_id=TENANT_A, role="member"+ )+ token = _token(user_id, "[email protected]", TENANT_A)++ async with _client(_app(session_factory), token) as client:+ response = await client.post(+ f"/tenants/{TENANT_A}/invitations", json={"role": "member"}+ )++ assert response.status_code == 403++ async def test_an_admin_of_a_cannot_mint_an_invitation_naming_b(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await _make_tenant(session_factory, TENANT_A)+ await _make_tenant(session_factory, TENANT_B)+ user_id = await _make_member(+ session_factory, name="a-admin", tenant_id=TENANT_A, role="admin"+ )+ token = _token(user_id, "[email protected]", TENANT_A)++ async with _client(_app(session_factory), token) as client:+ response = await client.post(+ f"/tenants/{TENANT_B}/invitations", json={"role": "member"}+ )++ assert response.status_code == 403++ async with tenant_session(session_factory, TENANT_B) as scoped:+ assert await InvitationStore().list_for_tenant(scoped) == []++ async def test_an_owner_can_mint_an_invitation_to_their_own_tenant(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await _make_tenant(session_factory, TENANT_A)+ user_id = await _make_member(+ session_factory, name="a-owner", tenant_id=TENANT_A, role="owner"+ )+ token = _token(user_id, "[email protected]", TENANT_A)++ async with _client(_app(session_factory), token) as client:+ response = await client.post(+ f"/tenants/{TENANT_A}/invitations",+ json={"role": "member", "uses_remaining": 3},+ )++ assert response.status_code == 201, response.text+ body = response.json()+ assert body["role"] == "member"+ assert body["uses_remaining"] == 3+ assert "token" in body and body["token"]++ async def test_an_absurd_expiry_is_refused_rather_than_crashing(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """`timedelta` raises `OverflowError` well before `int` runs out, so an+ expiry bounded only from below turns a bad request into a 500. The+ bound belongs on the schema, where it is a 422 with a field name."""+ await _make_tenant(session_factory, TENANT_A)+ user_id = await _make_member(+ session_factory, name="time-lord", tenant_id=TENANT_A, role="owner"+ )+ token = _token(user_id, "[email protected]", TENANT_A)++ async with _client(_app(session_factory), token) as client:+ response = await client.post(+ f"/tenants/{TENANT_A}/invitations",+ json={"role": "member", "expires_in_hours": 1000000000},+ )++ assert response.status_code == 422, response.text+++class TestOwnershipIsOwnerOnly:+ """Who owns a workspace is decided by its owners, not by its admins.++ An `admin` runs the workspace; only an `owner` moves the ownership set.+ The distinction exists because a last-owner guard cannot see a sequence:+ each request below is individually safe — two owners stand at every+ step — and together they hand the workspace to someone the founder never+ promoted.+ """++ async def test_an_admin_cannot_take_the_workspace_from_its_owner(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await _make_tenant(session_factory, TENANT_A)+ founder_id = await _make_member(+ session_factory, name="founder-owner", tenant_id=TENANT_A, role="owner"+ )+ admin_id = await _make_member(+ session_factory, name="ambitious-admin", tenant_id=TENANT_A, role="admin"+ )+ token = _token(admin_id, "[email protected]", TENANT_A)++ async with _client(_app(session_factory), token) as client:+ promote_self = await client.patch(+ f"/tenants/{TENANT_A}/members/{admin_id}", json={"role": "owner"}+ )+ demote_founder = await client.patch(+ f"/tenants/{TENANT_A}/members/{founder_id}", json={"role": "member"}+ )+ remove_founder = await client.delete(+ f"/tenants/{TENANT_A}/members/{founder_id}"+ )++ assert promote_self.status_code == 403, promote_self.text+ assert demote_founder.status_code == 403, demote_founder.text+ assert remove_founder.status_code == 403, remove_founder.text++ async with session_factory() as session:+ founder = await session.get(TenantMember, (TENANT_A, founder_id))+ admin = await session.get(TenantMember, (TENANT_A, admin_id))+ assert founder is not None and founder.role == "owner"+ assert admin is not None and admin.role == "admin"++ async def test_an_admin_cannot_mint_an_owner_invitation(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """Otherwise the escalation above is the same three steps with a link+ in the middle: invite an accomplice as owner, then let them do it."""+ await _make_tenant(session_factory, TENANT_A)+ await _make_member(+ session_factory, name="quiet-owner", tenant_id=TENANT_A, role="owner"+ )+ admin_id = await _make_member(+ session_factory, name="inviting-admin", tenant_id=TENANT_A, role="admin"+ )+ token = _token(admin_id, "[email protected]", TENANT_A)++ async with _client(_app(session_factory), token) as client:+ refused = await client.post(+ f"/tenants/{TENANT_A}/invitations", json={"role": "owner"}+ )+ allowed = await client.post(+ f"/tenants/{TENANT_A}/invitations", json={"role": "admin"}+ )++ assert refused.status_code == 403, refused.text+ assert allowed.status_code == 201, allowed.text++ async with tenant_session(session_factory, TENANT_A) as scoped:+ roles = [i.role for i in await InvitationStore().list_for_tenant(scoped)]+ assert roles == ["admin"]++ async def test_an_owner_can_do_all_of_it(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """The guard is narrower authority, not a locked door: everything the+ admin was refused above succeeds for an owner."""+ await _make_tenant(session_factory, TENANT_A)+ owner_id = await _make_member(+ session_factory, name="real-owner", tenant_id=TENANT_A, role="owner"+ )+ member_id = await _make_member(+ session_factory, name="promoted", tenant_id=TENANT_A, role="member"+ )+ token = _token(owner_id, "[email protected]", TENANT_A)++ async with _client(_app(session_factory), token) as client:+ promote = await client.patch(+ f"/tenants/{TENANT_A}/members/{member_id}", json={"role": "owner"}+ )+ demote = await client.patch(+ f"/tenants/{TENANT_A}/members/{member_id}", json={"role": "member"}+ )+ invite = await client.post(+ f"/tenants/{TENANT_A}/invitations", json={"role": "owner"}+ )+ remove = await client.delete(f"/tenants/{TENANT_A}/members/{member_id}")++ assert promote.status_code == 200, promote.text+ assert promote.json()["role"] == "owner"+ assert demote.status_code == 200, demote.text+ assert invite.status_code == 201, invite.text+ assert remove.status_code == 200, remove.text+++class TestInvitationLifecycle:+ async def _mint(+ self,+ session_factory: async_sessionmaker[AsyncSession],+ *,+ tenant_id: str,+ admin_id: str,+ role: str = "member",+ email: str | None = None,+ uses_remaining: int = 1,+ expires_in_hours: int = 168,+ ) -> tuple[str, str]:+ """Mint directly through the store (not the route) so a lifecycle+ test does not depend on `TestInvitationAuthorisation` passing first.+ Returns `(invitation_id, token)`."""+ async with tenant_session(session_factory, tenant_id) as session:+ invitation, token = await InvitationStore().create(+ session,+ role=role,+ email=email,+ expires_at=datetime.now(UTC) + timedelta(hours=expires_in_hours),+ uses_remaining=uses_remaining,+ created_by=admin_id,+ )+ await session.commit()+ return invitation.id, token++ async def test_accepting_grants_membership_in_the_invited_role(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await _make_tenant(session_factory, TENANT_A)+ admin_id = await _make_member(+ session_factory, name="inviter", tenant_id=TENANT_A, role="owner"+ )+ _id, token = await self._mint(+ session_factory, tenant_id=TENANT_A, admin_id=admin_id, role="admin"+ )+ await _make_tenant(session_factory, TENANT_B)+ invitee_id = await _make_member(+ session_factory, name="invitee", tenant_id=TENANT_B, role="member"+ )+ caller_token = _token(invitee_id, "[email protected]", TENANT_B)++ async with _client(_app(session_factory), caller_token) as client:+ response = await client.post("/invitations/accept", json={"token": token})++ assert response.status_code == 200, response.text+ body = response.json()+ assert body["id"] == TENANT_A+ assert body["role"] == "admin"+ assert _tenant_claim(response) == TENANT_A+ assert await _last_tenant_id(session_factory, invitee_id) == TENANT_A++ async with session_factory() as session:+ membership = await session.get(TenantMember, (TENANT_A, invitee_id))+ assert membership is not None+ assert membership.role == "admin"++ async def test_re_accepting_an_invitation_you_already_hold_costs_nothing(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """A shared link is double-clicked, or reloaded, or opened on a phone+ as well. The second acceptance grants nothing new, so it must spend+ nothing either — otherwise one careless refresh burns a seat that was+ meant for somebody else, and the invitation dies with nobody's+ membership to show for it.+ """+ await _make_tenant(session_factory, TENANT_A)+ admin_id = await _make_member(+ session_factory, name="link-sharer", tenant_id=TENANT_A, role="owner"+ )+ invitation_id, token = await self._mint(+ session_factory, tenant_id=TENANT_A, admin_id=admin_id, uses_remaining=2+ )+ await _make_tenant(session_factory, TENANT_B)+ invitee_id = await _make_member(+ session_factory, name="double-clicker", tenant_id=TENANT_B, role="member"+ )++ app = _app(session_factory)+ async with _client(+ app, _token(invitee_id, "[email protected]", TENANT_B)+ ) as client:+ first = await client.post("/invitations/accept", json={"token": token})+ second = await client.post("/invitations/accept", json={"token": token})++ assert first.status_code == 200, first.text+ assert second.status_code == 200, second.text+ assert second.json()["role"] == first.json()["role"]++ async with tenant_session(session_factory, TENANT_A) as session:+ invitation = await session.get(Invitation, invitation_id)+ assert invitation is not None+ assert invitation.uses_remaining == 1++ async def test_accepting_twice_fails_the_second_time(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await _make_tenant(session_factory, TENANT_A)+ admin_id = await _make_member(+ session_factory, name="inviter2", tenant_id=TENANT_A, role="owner"+ )+ _id, token = await self._mint(+ session_factory, tenant_id=TENANT_A, admin_id=admin_id, uses_remaining=1+ )+ await _make_tenant(session_factory, TENANT_B)+ first_invitee = await _make_member(+ session_factory, name="first-invitee", tenant_id=TENANT_B, role="member"+ )+ second_invitee = await _make_member(+ session_factory, name="second-invitee", tenant_id=TENANT_B, role="member"+ )++ app = _app(session_factory)+ async with _client(+ app, _token(first_invitee, "[email protected]", TENANT_B)+ ) as client:+ first = await client.post("/invitations/accept", json={"token": token})+ assert first.status_code == 200, first.text++ async with _client(+ app, _token(second_invitee, "[email protected]", TENANT_B)+ ) as client:+ second = await client.post("/invitations/accept", json={"token": token})++ assert second.status_code == 403+ assert "used" in second.json()["detail"].lower()++ async with session_factory() as session:+ assert await session.get(TenantMember, (TENANT_A, second_invitee)) is None++ async def test_a_revoked_invitation_is_refused(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await _make_tenant(session_factory, TENANT_A)+ admin_id = await _make_member(+ session_factory, name="revoker", tenant_id=TENANT_A, role="owner"+ )+ invitation_id, token = await self._mint(+ session_factory, tenant_id=TENANT_A, admin_id=admin_id+ )+ async with tenant_session(session_factory, TENANT_A) as session:+ await InvitationStore().revoke(session, invitation_id)+ await session.commit()++ await _make_tenant(session_factory, TENANT_B)+ invitee_id = await _make_member(+ session_factory, name="too-late", tenant_id=TENANT_B, role="member"+ )++ async with _client(+ _app(session_factory),+ _token(invitee_id, "[email protected]", TENANT_B),+ ) as client:+ response = await client.post("/invitations/accept", json={"token": token})++ assert response.status_code == 403+ assert "revoked" in response.json()["detail"].lower()++ async def test_an_expired_invitation_is_refused(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await _make_tenant(session_factory, TENANT_A)+ admin_id = await _make_member(+ session_factory, name="expiry-setter", tenant_id=TENANT_A, role="owner"+ )+ _id, token = await self._mint(+ session_factory,+ tenant_id=TENANT_A,+ admin_id=admin_id,+ expires_in_hours=1,+ )+ # Force it into the past directly — the store only accepts a future+ # `expires_at` implicitly by convention, not by constraint, so this is+ # the straightforward way to get an already-expired row.+ async with session_factory() as session:+ result = await session.execute(select(Invitation))+ invitation = result.scalars().one()+ invitation.expires_at = datetime.now(UTC) - timedelta(hours=1) # type: ignore[assignment]+ await session.commit()++ await _make_tenant(session_factory, TENANT_B)+ invitee_id = await _make_member(+ session_factory, name="too-slow", tenant_id=TENANT_B, role="member"+ )++ async with _client(+ _app(session_factory),+ _token(invitee_id, "[email protected]", TENANT_B),+ ) as client:+ response = await client.post("/invitations/accept", json={"token": token})++ assert response.status_code == 403+ assert "expired" in response.json()["detail"].lower()++ async def test_an_email_bound_invitation_refuses_a_different_address(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await _make_tenant(session_factory, TENANT_A)+ admin_id = await _make_member(+ session_factory, name="picky-inviter", tenant_id=TENANT_A, role="owner"+ )+ _id, token = await self._mint(+ session_factory,+ tenant_id=TENANT_A,+ admin_id=admin_id,+ email="[email protected]",+ )+ await _make_tenant(session_factory, TENANT_B)+ wrong_person = await _make_member(+ session_factory,+ name="wrong-person",+ tenant_id=TENANT_B,+ role="member",+ email="[email protected]",+ )++ async with _client(+ _app(session_factory),+ _token(wrong_person, "[email protected]", TENANT_B),+ ) as client:+ response = await client.post("/invitations/accept", json={"token": token})++ assert response.status_code == 403+ assert "email" in response.json()["detail"].lower()++ async def test_an_email_bound_invitation_accepts_the_addressed_email(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await _make_tenant(session_factory, TENANT_A)+ admin_id = await _make_member(+ session_factory, name="picky-inviter2", tenant_id=TENANT_A, role="owner"+ )+ _id, token = await self._mint(+ session_factory,+ tenant_id=TENANT_A,+ admin_id=admin_id,+ email="[email protected]",+ )+ await _make_tenant(session_factory, TENANT_B)+ right_person = await _make_member(+ session_factory,+ name="right-person",+ tenant_id=TENANT_B,+ role="member",+ email="[email protected]",+ )++ async with _client(+ _app(session_factory),+ _token(right_person, "[email protected]", TENANT_B),+ ) as client:+ response = await client.post("/invitations/accept", json={"token": token})++ assert response.status_code == 200, response.text+++TENANT_C = "tenant-api-routes-c"+++class TestInvitationsAddressedToMe:+ _mint = TestInvitationLifecycle._mint++ async def _invitee(+ self, session_factory: async_sessionmaker[AsyncSession], name: str+ ) -> tuple[str, str]:+ """A signed-in person with a workspace of their own, and their cookie."""+ await _make_tenant(session_factory, TENANT_B)+ email = f"{name}@example.invalid"+ user_id = await _make_member(+ session_factory, name=name, tenant_id=TENANT_B, role="member", email=email+ )+ return user_id, _token(user_id, email, TENANT_B)++ async def test_lists_live_invitations_to_my_address_in_workspaces_i_am_not_in(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ invitee_id, cookie = await self._invitee(session_factory, "sought-after")+ for tenant_id in (TENANT_A, TENANT_C):+ await _make_tenant(session_factory, tenant_id)+ inviter_a = await _make_member(+ session_factory, name="Ada", tenant_id=TENANT_A, role="owner"+ )+ inviter_c = await _make_member(+ session_factory, name="Cy", tenant_id=TENANT_C, role="owner"+ )+ wanted_a, _ = await self._mint(+ session_factory,+ tenant_id=TENANT_A,+ admin_id=inviter_a,+ role="admin",+ email="[email protected]",+ )+ wanted_c, _ = await self._mint(+ session_factory,+ tenant_id=TENANT_C,+ admin_id=inviter_c,+ email="[email protected]",+ )+ await self._mint(session_factory, tenant_id=TENANT_A, admin_id=inviter_a)+ await self._mint(+ session_factory,+ tenant_id=TENANT_A,+ admin_id=inviter_a,+ email="[email protected]",+ )+ inviter_b = await _make_member(+ session_factory, name="Bo", tenant_id=TENANT_B, role="owner"+ )+ await self._mint(+ session_factory,+ tenant_id=TENANT_B,+ admin_id=inviter_b,+ email="[email protected]",+ )++ async with _client(_app(session_factory), cookie) as client:+ response = await client.get("/invitations/mine")++ assert response.status_code == 200, response.text+ found = {i["id"]: i for i in response.json()}+ assert set(found) == {wanted_a, wanted_c}+ assert found[wanted_a]["tenant_id"] == TENANT_A+ assert found[wanted_a]["tenant_name"] == TENANT_A+ assert found[wanted_a]["role"] == "admin"+ assert found[wanted_a]["invited_by"] == "Ada"+ assert "token" not in found[wanted_a]++ async def test_accepting_by_id_joins_switches_and_spends_a_use(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ invitee_id, cookie = await self._invitee(session_factory, "joiner")+ await _make_tenant(session_factory, TENANT_A)+ inviter = await _make_member(+ session_factory, name="inviter", tenant_id=TENANT_A, role="owner"+ )+ invitation_id, _ = await self._mint(+ session_factory,+ tenant_id=TENANT_A,+ admin_id=inviter,+ email="[email protected]",+ )++ async with _client(_app(session_factory), cookie) as client:+ response = await client.post(+ "/invitations/mine/accept",+ json={"tenant_id": TENANT_A, "invitation_id": invitation_id},+ )+ after = await client.get("/invitations/mine")++ assert response.status_code == 200, response.text+ assert response.json()["id"] == TENANT_A+ assert response.json()["role"] == "member"+ assert _tenant_claim(response) == TENANT_A+ assert await _last_tenant_id(session_factory, invitee_id) == TENANT_A+ assert after.json() == []+ async with tenant_session(session_factory, TENANT_A) as session:+ invitation = await session.get(Invitation, invitation_id)+ assert invitation is not None+ assert invitation.uses_remaining == 0+ assert await session.get(TenantMember, (TENANT_A, invitee_id)) is not None++ async def test_a_shareable_link_is_not_accepted_by_its_id(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """Without an address the token is the only credential; its id is+ not one."""+ _invitee_id, cookie = await self._invitee(session_factory, "id-guesser")+ await _make_tenant(session_factory, TENANT_A)+ inviter = await _make_member(+ session_factory, name="inviter", tenant_id=TENANT_A, role="owner"+ )+ invitation_id, _ = await self._mint(+ session_factory, tenant_id=TENANT_A, admin_id=inviter+ )++ async with _client(_app(session_factory), cookie) as client:+ response = await client.post(+ "/invitations/mine/accept",+ json={"tenant_id": TENANT_A, "invitation_id": invitation_id},+ )++ assert response.status_code == 404+ async with tenant_session(session_factory, TENANT_A) as session:+ invitation = await session.get(Invitation, invitation_id)+ assert invitation is not None+ assert invitation.uses_remaining == 1++ async def test_someone_elses_invitation_is_not_found(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ _invitee_id, cookie = await self._invitee(session_factory, "not-them")+ await _make_tenant(session_factory, TENANT_A)+ inviter = await _make_member(+ session_factory, name="inviter", tenant_id=TENANT_A, role="owner"+ )+ invitation_id, _ = await self._mint(+ session_factory,+ tenant_id=TENANT_A,+ admin_id=inviter,+ email="[email protected]",+ )++ async with _client(_app(session_factory), cookie) as client:+ response = await client.post(+ "/invitations/mine/accept",+ json={"tenant_id": TENANT_A, "invitation_id": invitation_id},+ )++ assert response.status_code == 404++ async def test_an_invitation_named_under_the_wrong_workspace_is_not_found(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ _invitee_id, cookie = await self._invitee(session_factory, "misdirected")+ for tenant_id in (TENANT_A, TENANT_C):+ await _make_tenant(session_factory, tenant_id)+ inviter = await _make_member(+ session_factory, name="inviter", tenant_id=TENANT_A, role="owner"+ )+ invitation_id, _ = await self._mint(+ session_factory,+ tenant_id=TENANT_A,+ admin_id=inviter,+ email="[email protected]",+ )++ async with _client(_app(session_factory), cookie) as client:+ response = await client.post(+ "/invitations/mine/accept",+ json={"tenant_id": TENANT_C, "invitation_id": invitation_id},+ )++ assert response.status_code == 404+ async with session_factory() as session:+ assert await session.get(TenantMember, (TENANT_C, _invitee_id)) is None++ async def test_a_revoked_invitation_says_so(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ _invitee_id, cookie = await self._invitee(session_factory, "too-late")+ await _make_tenant(session_factory, TENANT_A)+ inviter = await _make_member(+ session_factory, name="inviter", tenant_id=TENANT_A, role="owner"+ )+ invitation_id, _ = await self._mint(+ session_factory,+ tenant_id=TENANT_A,+ admin_id=inviter,+ email="[email protected]",+ )+ async with tenant_session(session_factory, TENANT_A) as session:+ await InvitationStore().revoke(session, invitation_id)+ await session.commit()++ async with _client(_app(session_factory), cookie) as client:+ response = await client.post(+ "/invitations/mine/accept",+ json={"tenant_id": TENANT_A, "invitation_id": invitation_id},+ )++ assert response.status_code == 403+ assert "revoked" in response.json()["detail"]+++class TestMemberRoutes:+ async def test_listing_shows_every_member_and_their_role(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await _make_tenant(session_factory, TENANT_A)+ owner_id = await _make_member(+ session_factory, name="list-owner", tenant_id=TENANT_A, role="owner"+ )+ await _make_member(+ session_factory, name="list-member", tenant_id=TENANT_A, role="member"+ )+ token = _token(owner_id, "[email protected]", TENANT_A)++ async with _client(_app(session_factory), token) as client:+ response = await client.get(f"/tenants/{TENANT_A}/members")++ assert response.status_code == 200, response.text+ roles = {row["name"]: row["role"] for row in response.json()}+ assert roles == {"list-owner": "owner", "list-member": "member"}++ async def test_the_last_owner_cannot_be_demoted(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await _make_tenant(session_factory, TENANT_A)+ owner_id = await _make_member(+ session_factory, name="sole-owner", tenant_id=TENANT_A, role="owner"+ )+ token = _token(owner_id, "[email protected]", TENANT_A)++ async with _client(_app(session_factory), token) as client:+ response = await client.patch(+ f"/tenants/{TENANT_A}/members/{owner_id}", json={"role": "member"}+ )++ assert response.status_code == 409++ async with session_factory() as session:+ membership = await session.get(TenantMember, (TENANT_A, owner_id))+ assert membership is not None+ assert membership.role == "owner"++ async def test_an_owner_can_be_demoted_when_another_owner_remains(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await _make_tenant(session_factory, TENANT_A)+ owner_id = await _make_member(+ session_factory, name="owner-one", tenant_id=TENANT_A, role="owner"+ )+ other_owner_id = await _make_member(+ session_factory, name="owner-two", tenant_id=TENANT_A, role="owner"+ )+ token = _token(owner_id, "[email protected]", TENANT_A)++ async with _client(_app(session_factory), token) as client:+ response = await client.patch(+ f"/tenants/{TENANT_A}/members/{other_owner_id}",+ json={"role": "member"},+ )++ assert response.status_code == 200, response.text+ assert response.json()["role"] == "member"++ async def test_the_last_owner_cannot_be_removed(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await _make_tenant(session_factory, TENANT_A)+ owner_id = await _make_member(+ session_factory, name="undeletable-owner", tenant_id=TENANT_A, role="owner"+ )+ token = _token(owner_id, "[email protected]", TENANT_A)++ async with _client(_app(session_factory), token) as client:+ response = await client.delete(f"/tenants/{TENANT_A}/members/{owner_id}")++ assert response.status_code == 409++ async with session_factory() as session:+ assert await session.get(TenantMember, (TENANT_A, owner_id)) is not None++ async def test_removing_a_member_deletes_their_membership(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await _make_tenant(session_factory, TENANT_A)+ owner_id = await _make_member(+ session_factory, name="remover", tenant_id=TENANT_A, role="owner"+ )+ target_id = await _make_member(+ session_factory, name="removed", tenant_id=TENANT_A, role="member"+ )+ token = _token(owner_id, "[email protected]", TENANT_A)++ async with _client(_app(session_factory), token) as client:+ response = await client.delete(f"/tenants/{TENANT_A}/members/{target_id}")++ assert response.status_code == 200, response.text++ async with session_factory() as session:+ assert await session.get(TenantMember, (TENANT_A, target_id)) is None++ async def test_removing_a_member_stops_their_api_key_working(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """The bite test: after removal, the credential the member minted in+ this tenant no longer resolves to anything — not merely hidden, gone.+ A live bearer-auth attempt with the same hash would fail at the very+ first lookup `ApiKeyStore.get_by_hash` performs.+ """+ await _make_tenant(session_factory, TENANT_A)+ owner_id = await _make_member(+ session_factory, name="key-remover", tenant_id=TENANT_A, role="owner"+ )+ target_id = await _make_member(+ session_factory, name="key-holder", tenant_id=TENANT_A, role="member"+ )+ key_hash = await _make_api_key(+ session_factory, tenant_id=TENANT_A, user_id=target_id+ )+ token = _token(owner_id, "[email protected]", TENANT_A)++ async with session_factory() as session:+ assert await ApiKeyStore().get_by_hash(session, key_hash) is not None++ async with _client(_app(session_factory), token) as client:+ response = await client.delete(f"/tenants/{TENANT_A}/members/{target_id}")+ assert response.status_code == 200, response.text++ async with session_factory() as session:+ assert await ApiKeyStore().get_by_hash(session, key_hash) is None++ async def test_a_member_who_owns_an_agent_here_cannot_be_removed(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """An agent is not the member's private property to lose along with+ their membership — it sits in rooms with other people, and deleting it+ is not recoverable the way reminting a key is. Removal must refuse,+ naming the agent, and this must not be a partial write: not the+ membership, not the member's unrelated personal key, not the agent's+ own key may be touched when the route 409s.+ """+ await _make_tenant(session_factory, TENANT_A)+ owner_id = await _make_member(+ session_factory, name="agent-remover", tenant_id=TENANT_A, role="owner"+ )+ target_id = await _make_member(+ session_factory, name="agent-owner", tenant_id=TENANT_A, role="member"+ )+ agent_id, agent_name, agent_key_hash = await _make_agent_with_key(+ session_factory, tenant_id=TENANT_A, owner_id=target_id+ )+ personal_key_hash = await _make_api_key(+ session_factory, tenant_id=TENANT_A, user_id=target_id+ )+ token = _token(owner_id, "[email protected]", TENANT_A)++ async with _client(_app(session_factory), token) as client:+ response = await client.delete(f"/tenants/{TENANT_A}/members/{target_id}")++ assert response.status_code == 409, response.text+ assert agent_name in response.json()["detail"]++ async with session_factory() as session:+ assert await session.get(TenantMember, (TENANT_A, target_id)) is not None+ assert await AgentStore().get(session, agent_id) is not None+ assert await ApiKeyStore().get_by_hash(session, agent_key_hash) is not None+ assert (+ await ApiKeyStore().get_by_hash(session, personal_key_hash) is not None+ )++ async def test_a_plain_member_cannot_remove_anyone(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await _make_tenant(session_factory, TENANT_A)+ member_id = await _make_member(+ session_factory, name="powerless", tenant_id=TENANT_A, role="member"+ )+ target_id = await _make_member(+ session_factory, name="untouchable", tenant_id=TENANT_A, role="member"+ )+ token = _token(member_id, "[email protected]", TENANT_A)++ async with _client(_app(session_factory), token) as client:+ response = await client.delete(f"/tenants/{TENANT_A}/members/{target_id}")++ assert response.status_code == 403+++def _window() -> dict[str, str]:+ now = datetime.now(UTC)+ return {+ "since": (now - timedelta(hours=1)).isoformat(),+ "until": (now + timedelta(hours=1)).isoformat(),+ }+++class TestCurrentTenantRoute:+ async def test_a_member_is_told_the_workspace_they_are_bound_to(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await _make_tenant(session_factory, TENANT_A)+ await _make_tenant(session_factory, TENANT_B)+ user_id = await _make_member(+ session_factory, name="current-member", tenant_id=TENANT_A, role="member"+ )+ async with session_factory() as session:+ session.add(TenantMember(tenant_id=TENANT_B, user_id=user_id, role="owner"))+ await session.commit()+ token = _token(user_id, "[email protected]", TENANT_A)++ async with _client(_app(session_factory), token) as client:+ response = await client.get("/tenants/current")++ assert response.status_code == 200+ assert response.json() == {+ "id": TENANT_A,+ "slug": TENANT_A,+ "name": TENANT_A,+ "role": "member",+ "administers": False,+ }++ @pytest.mark.parametrize(+ ("role", "user_role"),+ [("admin", "user"), ("owner", "user"), ("member", "admin")],+ )+ async def test_an_admin_owner_or_operator_is_told_they_administer_it(+ self,+ session_factory: async_sessionmaker[AsyncSession],+ role: str,+ user_role: str,+ ) -> None:+ await _make_tenant(session_factory, TENANT_A)+ user_id = await _make_member(+ session_factory,+ name="current-admin",+ tenant_id=TENANT_A,+ role=role,+ user_role=user_role,+ )+ token = _token(user_id, "[email protected]", TENANT_A)++ async with _client(_app(session_factory), token) as client:+ response = await client.get("/tenants/current")++ assert response.status_code == 200+ assert response.json()["administers"] is True+++class TestUsageRoute:+ async def _spend(+ self,+ session_factory: async_sessionmaker[AsyncSession],+ tenant_id: str,+ amount: int,+ ) -> None:+ async with tenant_session(session_factory, tenant_id) as session:+ await UsageStore().record(+ session,+ tenant_id=tenant_id,+ metric=UsageMetric.MESSAGES,+ client_id=f"client-of-{tenant_id}",+ model="",+ amount=amount,+ )+ await session.commit()++ async def test_an_admin_sees_their_workspaces_usage_only(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await _make_tenant(session_factory, TENANT_A)+ await _make_tenant(session_factory, TENANT_B)+ await self._spend(session_factory, TENANT_A, 3)+ await self._spend(session_factory, TENANT_B, 40)+ user_id = await _make_member(+ session_factory, name="usage-admin", tenant_id=TENANT_A, role="admin"+ )+ token = _token(user_id, "[email protected]", TENANT_A)++ async with _client(_app(session_factory), token) as client:+ response = await client.get(f"/tenants/{TENANT_A}/usage", params=_window())++ assert response.status_code == 200+ assert response.json() == [+ {+ "metric": "messages",+ "client_id": f"client-of-{TENANT_A}",+ "client_name": None,+ "client_type": None,+ "model": "",+ "amount": 3,+ }+ ]++ async def test_a_plain_member_cannot_read_usage(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await _make_tenant(session_factory, TENANT_A)+ user_id = await _make_member(+ session_factory, name="usage-member", tenant_id=TENANT_A, role="member"+ )+ token = _token(user_id, "[email protected]", TENANT_A)++ async with _client(_app(session_factory), token) as client:+ response = await client.get(f"/tenants/{TENANT_A}/usage", params=_window())++ assert response.status_code == 403++ async def test_an_admin_of_a_cannot_read_bs_usage(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await _make_tenant(session_factory, TENANT_A)+ await _make_tenant(session_factory, TENANT_B)+ user_id = await _make_member(+ session_factory, name="usage-snoop", tenant_id=TENANT_A, role="admin"+ )+ token = _token(user_id, "[email protected]", TENANT_A)++ async with _client(_app(session_factory), token) as client:+ response = await client.get(f"/tenants/{TENANT_B}/usage", params=_window())++ assert response.status_code == 403++ async def test_a_window_without_a_timezone_is_refused(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await _make_tenant(session_factory, TENANT_A)+ user_id = await _make_member(+ session_factory, name="usage-naive", tenant_id=TENANT_A, role="owner"+ )+ token = _token(user_id, "[email protected]", TENANT_A)++ async with _client(_app(session_factory), token) as client:+ response = await client.get(+ f"/tenants/{TENANT_A}/usage",+ params={"since": "2026-01-01T00:00:00", "until": "2026-01-02T00:00:00"},+ )++ assert response.status_code == 400+ assert "timezone" in response.json()["detail"]++ async def test_an_empty_window_is_refused(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await _make_tenant(session_factory, TENANT_A)+ user_id = await _make_member(+ session_factory, name="usage-empty", tenant_id=TENANT_A, role="owner"+ )+ token = _token(user_id, "[email protected]", TENANT_A)+ window = _window()++ async with _client(_app(session_factory), token) as client:+ response = await client.get(+ f"/tenants/{TENANT_A}/usage",+ params={"since": window["until"], "until": window["since"]},+ )++ assert response.status_code == 400+++class TestBudgetRoutes:+ async def _admin(+ self, session_factory: async_sessionmaker[AsyncSession], name: str+ ) -> tuple[str, str]:+ await _make_tenant(session_factory, TENANT_A)+ user_id = await _make_member(+ session_factory, name=name, tenant_id=TENANT_A, role="admin"+ )+ return user_id, _token(user_id, f"{name}@example.invalid", TENANT_A)++ async def test_an_admin_sets_a_budget_and_sees_its_spend(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ user_id, token = await self._admin(session_factory, "budget-admin")+ agent_id, agent_name, _ = await _make_agent_with_key(+ session_factory, tenant_id=TENANT_A, owner_id=user_id+ )+ async with session_factory() as session:+ agent = await AgentStore().get(session, agent_id)+ assert agent is not None+ await UsageStore().record(+ session,+ tenant_id=TENANT_A,+ metric=UsageMetric.TURNS,+ client_id=agent.client_id,+ model="",+ amount=3,+ )+ await session.commit()++ async with _client(_app(session_factory), token) as client:+ created = await client.post(+ f"/tenants/{TENANT_A}/budgets",+ json={+ "agent_id": agent_id,+ "metric": "turns",+ "model": "",+ "amount_limit": 3,+ "period_hours": 24,+ },+ )+ listed = await client.get(f"/tenants/{TENANT_A}/budgets")++ assert created.status_code == 201+ body = created.json()+ assert body["agent_name"] == agent_name+ assert (body["spent"], body["exhausted"]) == (3, True)+ assert listed.json() == [body]++ async def test_a_second_budget_on_the_same_thing_is_a_conflict(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ _, token = await self._admin(session_factory, "budget-twice")+ budget = {+ "agent_id": None,+ "metric": "messages",+ "model": "",+ "amount_limit": 100,+ "period_hours": 24,+ }++ async with _client(_app(session_factory), token) as client:+ first = await client.post(f"/tenants/{TENANT_A}/budgets", json=budget)+ second = await client.post(f"/tenants/{TENANT_A}/budgets", json=budget)++ assert first.status_code == 201+ assert second.status_code == 409++ @pytest.mark.parametrize("metric", ["messages", "turns"])+ async def test_a_budget_on_a_metric_counted_without_a_model_cannot_name_one(+ self, session_factory: async_sessionmaker[AsyncSession], metric: str+ ) -> None:+ _, token = await self._admin(session_factory, f"budget-model-{metric}")++ async with _client(_app(session_factory), token) as client:+ response = await client.post(+ f"/tenants/{TENANT_A}/budgets",+ json={+ "agent_id": None,+ "metric": metric,+ "model": "some-model",+ "amount_limit": 100,+ "period_hours": 24,+ },+ )++ assert response.status_code == 422+ assert "not counted per model" in response.text++ @pytest.mark.parametrize(+ ("amount_limit", "period_hours"),+ [(2**53, 24), (100, 8785), (0, 24), (100, 0)],+ )+ async def test_a_budget_past_the_bounds_is_refused(+ self,+ session_factory: async_sessionmaker[AsyncSession],+ amount_limit: int,+ period_hours: int,+ ) -> None:+ _, token = await self._admin(session_factory, "budget-bounds")+ limits = {"amount_limit": amount_limit, "period_hours": period_hours}++ async with _client(_app(session_factory), token) as client:+ created = await client.post(+ f"/tenants/{TENANT_A}/budgets",+ json={"agent_id": None, "metric": "turns", "model": "", **limits},+ )+ within = await client.post(+ f"/tenants/{TENANT_A}/budgets",+ json={+ "agent_id": None,+ "metric": "turns",+ "model": "",+ "amount_limit": 100,+ "period_hours": 24,+ },+ )+ updated = await client.put(+ f"/tenants/{TENANT_A}/budgets/{within.json()['id']}", json=limits+ )++ assert created.status_code == 422+ assert within.status_code == 201+ assert updated.status_code == 422++ async def test_a_budget_for_another_workspaces_agent_is_not_found(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ _, token = await self._admin(session_factory, "budget-foreign")+ await _make_tenant(session_factory, TENANT_B)+ their_owner = await _make_member(+ session_factory, name="budget-theirs", tenant_id=TENANT_B, role="owner"+ )+ their_agent, _, _ = await _make_agent_with_key(+ session_factory, tenant_id=TENANT_B, owner_id=their_owner+ )++ async with _client(_app(session_factory), token) as client:+ response = await client.post(+ f"/tenants/{TENANT_A}/budgets",+ json={+ "agent_id": their_agent,+ "metric": "turns",+ "model": "",+ "amount_limit": 1,+ "period_hours": 24,+ },+ )++ assert response.status_code == 404++ async def test_a_limit_that_is_not_positive_is_refused(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ _, token = await self._admin(session_factory, "budget-zero")++ async with _client(_app(session_factory), token) as client:+ response = await client.post(+ f"/tenants/{TENANT_A}/budgets",+ json={+ "agent_id": None,+ "metric": "turns",+ "model": "",+ "amount_limit": 0,+ "period_hours": 24,+ },+ )++ assert response.status_code == 422++ async def test_an_admin_changes_and_removes_a_budget(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ _, token = await self._admin(session_factory, "budget-edit")++ async with _client(_app(session_factory), token) as client:+ created = await client.post(+ f"/tenants/{TENANT_A}/budgets",+ json={+ "agent_id": None,+ "metric": "output_tokens",+ "model": "some-model",+ "amount_limit": 1000,+ "period_hours": 24,+ },+ )+ budget_id = created.json()["id"]+ updated = await client.put(+ f"/tenants/{TENANT_A}/budgets/{budget_id}",+ json={"amount_limit": 5000, "period_hours": 168},+ )+ deleted = await client.delete(f"/tenants/{TENANT_A}/budgets/{budget_id}")+ again = await client.delete(f"/tenants/{TENANT_A}/budgets/{budget_id}")+ listed = await client.get(f"/tenants/{TENANT_A}/budgets")++ assert updated.status_code == 200+ assert (updated.json()["amount_limit"], updated.json()["period_hours"]) == (+ 5000,+ 168,+ )+ assert deleted.status_code == 204+ assert again.status_code == 404+ assert listed.json() == []++ async def test_a_plain_member_cannot_see_budgets(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await _make_tenant(session_factory, TENANT_A)+ user_id = await _make_member(+ session_factory, name="budget-member", tenant_id=TENANT_A, role="member"+ )+ token = _token(user_id, "[email protected]", TENANT_A)++ async with _client(_app(session_factory), token) as client:+ response = await client.get(f"/tenants/{TENANT_A}/budgets")++ assert response.status_code == 403++ async def test_an_admin_of_a_cannot_touch_bs_budgets(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ _, token = await self._admin(session_factory, "budget-snoop")+ await _make_tenant(session_factory, TENANT_B)++ async with _client(_app(session_factory), token) as client:+ response = await client.get(f"/tenants/{TENANT_B}/budgets")++ assert response.status_code == 403+++class TestInvitationEmail:+ """An invitation naming an address is e-mailed there when a relay is+ configured, and stands whether or not the e-mail goes out — the response+ says which, so the admin knows when to share the link themselves."""++ async def _owner(+ self, session_factory: async_sessionmaker[AsyncSession], name: str+ ) -> str:+ await _make_tenant(session_factory, TENANT_A)+ user_id = await _make_member(+ session_factory, name=name, tenant_id=TENANT_A, role="owner"+ )+ return _token(user_id, f"{name}@example.invalid", TENANT_A)++ async def _invite(self, app: FastAPI, token: str, body: dict) -> httpx.Response:+ async with _client(app, token) as client:+ return await client.post(f"/tenants/{TENANT_A}/invitations", json=body)++ async def test_an_addressed_invitation_is_e_mailed_with_its_link(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ token = await self._owner(session_factory, "sender")+ mailer = _RecordingMailer()++ response = await self._invite(+ _app(session_factory, mailer=mailer),+ token,+ {"role": "admin", "email": " [email protected] "},+ )++ assert response.status_code == 201, response.text+ body = response.json()+ assert body["email_delivery"] == "sent"+ assert body["email"] == "[email protected]"+ [sent] = mailer.sent+ assert sent.to == "[email protected]"+ assert sent.link == f"https://switch.example.com/invite#token={body['token']}"+ assert sent.workspace_name == TENANT_A+ assert sent.inviter_name == "sender"+ assert sent.role == "admin"++ async def test_without_a_relay_the_invitation_stands_and_says_so(+ self,+ session_factory: async_sessionmaker[AsyncSession],+ caplog: pytest.LogCaptureFixture,+ ) -> None:+ token = await self._owner(session_factory, "no-relay")++ with caplog.at_level("WARNING", logger="switch_core.gateway.tenants"):+ response = await self._invite(+ _app(session_factory), token, {"email": "[email protected]"}+ )++ assert response.status_code == 201, response.text+ assert response.json()["email_delivery"] == "not_configured"+ assert "no SMTP relay is configured" in caplog.text+ async with tenant_session(session_factory, TENANT_A) as scoped:+ [invitation] = await InvitationStore().list_for_tenant(scoped)+ assert invitation.email == "[email protected]"++ async def test_a_failed_send_still_leaves_a_usable_invitation(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ token = await self._owner(session_factory, "unlucky")+ app = _app(session_factory, mailer=_FailingMailer())++ response = await self._invite(app, token, {"email": "[email protected]"})++ assert response.status_code == 201, response.text+ assert response.json()["email_delivery"] == "failed"++ await _make_tenant(session_factory, TENANT_B)+ invitee_id = await _make_member(+ session_factory, name="invitee", tenant_id=TENANT_B, role="member"+ )+ async with _client(+ app, _token(invitee_id, "[email protected]", TENANT_B)+ ) as client:+ accepted = await client.post(+ "/invitations/accept", json={"token": response.json()["token"]}+ )+ assert accepted.status_code == 200, accepted.text++ async def test_a_link_invitation_sends_nothing(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ token = await self._owner(session_factory, "linker")+ mailer = _RecordingMailer()++ response = await self._invite(+ _app(session_factory, mailer=mailer), token, {"role": "member"}+ )++ assert response.status_code == 201, response.text+ assert response.json()["email_delivery"] == "not_requested"+ assert mailer.sent == []++ @pytest.mark.parametrize(+ "email", ["not-an-address", "a@b", "two@@example.com", "sp [email protected]"]+ )+ async def test_something_that_is_not_an_address_is_refused(+ self, session_factory: async_sessionmaker[AsyncSession], email: str+ ) -> None:+ token = await self._owner(session_factory, "typist")++ response = await self._invite(+ _app(session_factory, mailer=_RecordingMailer()), token, {"email": email}+ )++ assert response.status_code == 422++ async def test_the_daily_cap_refuses_before_minting_anything(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ token = await self._owner(session_factory, "prolific")+ mailer = _RecordingMailer()+ app = _app(session_factory, mailer=mailer, invite_emails_per_day=2)++ for n in range(2):+ ok = await self._invite(app, token, {"email": f"p{n}@example.com"})+ assert ok.status_code == 201, ok.text+ link = await self._invite(app, token, {"role": "member"})+ over = await self._invite(app, token, {"email": "[email protected]"})++ assert link.status_code == 201, "link invitations are not capped"+ assert over.status_code == 429+ assert "daily limit" in over.json()["detail"]+ assert len(mailer.sent) == 2+ async with tenant_session(session_factory, TENANT_A) as scoped:+ assert len(await InvitationStore().list_for_tenant(scoped)) == 3++ async def test_an_operator_is_not_capped(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await _make_tenant(session_factory, TENANT_A)+ async with session_factory() as session:+ operator = User(+ name="operator", email="[email protected]", role="admin"+ )+ session.add(operator)+ await session.flush()+ session.add(+ TenantMember(tenant_id=TENANT_A, user_id=operator.id, role="owner")+ )+ await session.commit()+ operator_id = operator.id+ token = _token(operator_id, "[email protected]", TENANT_A)+ app = _app(session_factory, mailer=_RecordingMailer(), invite_emails_per_day=1)++ for n in range(2):+ response = await self._invite(app, token, {"email": f"o{n}@example.com"})+ assert response.status_code == 201, response.text+++class TestJoiningByDomain:+ async def _admin(+ self, session_factory: async_sessionmaker[AsyncSession], email: str+ ) -> tuple[str, str]:+ """An admin of workspace A, and their cookie."""+ await _make_tenant(session_factory, TENANT_A)+ user_id = await _make_member(+ session_factory, name=email, tenant_id=TENANT_A, role="admin", email=email+ )+ return user_id, _token(user_id, email, TENANT_A)++ async def _outsider(+ self, session_factory: async_sessionmaker[AsyncSession], email: str+ ) -> tuple[str, str]:+ """A signed-in person in workspace B, and their cookie."""+ async with session_factory() as session:+ if await session.get(Tenant, TENANT_B) is None:+ session.add(Tenant(id=TENANT_B, slug=TENANT_B, name=TENANT_B))+ await session.commit()+ user_id = await _make_member(+ session_factory, name=email, tenant_id=TENANT_B, role="member", email=email+ )+ return user_id, _token(user_id, email, TENANT_B)++ async def test_an_admin_opens_the_workspace_to_their_own_domain(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ admin_id, cookie = await self._admin(session_factory, "[email protected]")++ async with _client(_app(session_factory), cookie) as client:+ before = await client.get(f"/tenants/{TENANT_A}/join-domains")+ added = await client.post(+ f"/tenants/{TENANT_A}/join-domains", json={"domain": " ACME.example "}+ )+ again = await client.post(+ f"/tenants/{TENANT_A}/join-domains", json={"domain": "acme.example"}+ )+ after = await client.get(f"/tenants/{TENANT_A}/join-domains")++ assert before.status_code == 200, before.text+ assert before.json() == {+ "domains": [],+ "own_domain": "acme.example",+ "own_domain_refusal": None,+ }+ assert added.status_code == 201, added.text+ assert added.json()["domain"] == "acme.example"+ assert added.json()["created_by"] == admin_id+ assert again.status_code == 409+ assert [d["domain"] for d in after.json()["domains"]] == ["acme.example"]++ async def test_another_domain_is_refused(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ _admin_id, cookie = await self._admin(session_factory, "[email protected]")++ async with _client(_app(session_factory), cookie) as client:+ response = await client.post(+ f"/tenants/{TENANT_A}/join-domains", json={"domain": "rival.example"}+ )++ assert response.status_code == 400+ assert "your own address, acme.example" in response.json()["detail"]++ async def test_a_public_e_mail_provider_is_refused_even_as_your_own(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ _admin_id, cookie = await self._admin(session_factory, "[email protected]")++ async with _client(_app(session_factory), cookie) as client:+ listed = await client.get(f"/tenants/{TENANT_A}/join-domains")+ response = await client.post(+ f"/tenants/{TENANT_A}/join-domains", json={"domain": "gmail.com"}+ )++ assert "public e-mail provider" in listed.json()["own_domain_refusal"]+ assert response.status_code == 400+ assert "public e-mail provider" in response.json()["detail"]++ async def test_a_member_cannot_open_the_workspace(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await _make_tenant(session_factory, TENANT_A)+ member_id = await _make_member(+ session_factory,+ name="mo",+ tenant_id=TENANT_A,+ role="member",+ email="[email protected]",+ )++ async with _client(+ _app(session_factory), _token(member_id, "[email protected]", TENANT_A)+ ) as client:+ response = await client.post(+ f"/tenants/{TENANT_A}/join-domains", json={"domain": "acme.example"}+ )++ assert response.status_code == 403++ async def test_someone_at_the_domain_sees_and_joins_it_as_a_member(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ _admin_id, admin_cookie = await self._admin(session_factory, "[email protected]")+ joiner_id, cookie = await self._outsider(session_factory, "[email protected]")+ _other_id, other_cookie = await self._outsider(+ session_factory, "[email protected]"+ )++ async with _client(_app(session_factory), admin_cookie) as client:+ await client.post(+ f"/tenants/{TENANT_A}/join-domains", json={"domain": "acme.example"}+ )+ async with _client(_app(session_factory), other_cookie) as client:+ not_offered = await client.get("/joinable-tenants")+ not_joined = await client.post(f"/joinable-tenants/{TENANT_A}/join")+ async with _client(_app(session_factory), cookie) as client:+ offered = await client.get("/joinable-tenants")+ joined = await client.post(f"/joinable-tenants/{TENANT_A}/join")+ afterwards = await client.get("/joinable-tenants")++ assert not_offered.json() == []+ assert not_joined.status_code == 404+ assert offered.status_code == 200, offered.text+ assert offered.json() == [+ {+ "tenant_id": TENANT_A,+ "tenant_slug": TENANT_A,+ "tenant_name": TENANT_A,+ "domain": "acme.example",+ }+ ]+ assert joined.status_code == 200, joined.text+ assert joined.json()["role"] == "member"+ assert _tenant_claim(joined) == TENANT_A+ assert await _last_tenant_id(session_factory, joiner_id) == TENANT_A+ assert afterwards.json() == []+ async with tenant_session(session_factory, TENANT_A) as session:+ membership = await session.get(TenantMember, (TENANT_A, joiner_id))+ assert membership is not None+ assert membership.role == "member"++ async def test_joining_again_keeps_the_role_you_have(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ admin_id, cookie = await self._admin(session_factory, "[email protected]")++ async with _client(_app(session_factory), cookie) as client:+ await client.post(+ f"/tenants/{TENANT_A}/join-domains", json={"domain": "acme.example"}+ )+ response = await client.post(f"/joinable-tenants/{TENANT_A}/join")++ assert response.status_code == 200, response.text+ assert response.json()["role"] == "admin"++ async def test_closing_the_domain_stops_new_joins(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ _admin_id, admin_cookie = await self._admin(session_factory, "[email protected]")+ _joiner_id, cookie = await self._outsider(session_factory, "[email protected]")++ async with _client(_app(session_factory), admin_cookie) as client:+ await client.post(+ f"/tenants/{TENANT_A}/join-domains", json={"domain": "acme.example"}+ )+ removed = await client.delete(+ f"/tenants/{TENANT_A}/join-domains/acme.example"+ )+ missing = await client.delete(+ f"/tenants/{TENANT_A}/join-domains/acme.example"+ )+ async with _client(_app(session_factory), cookie) as client:+ offered = await client.get("/joinable-tenants")+ joined = await client.post(f"/joinable-tenants/{TENANT_A}/join")++ assert removed.status_code == 204+ assert missing.status_code == 404+ assert offered.json() == []+ assert joined.status_code == 404diff --git a/core/tests/switch_core/gateway/test_tenant_resolution.py b/core/tests/switch_core/gateway/test_tenant_resolution.pyindex 049cc489a..8666dcc48 100644--- a/core/tests/switch_core/gateway/test_tenant_resolution.py+++ b/core/tests/switch_core/gateway/test_tenant_resolution.py@@ -63,6 +63,7 @@ from switch_core.gateway.auth import (hash_password,)from switch_core.gateway.auth_routes import login+from switch_core.gateway.auth_routes import router as auth_routerfrom switch_core.gateway.schemas import LoginRequestfrom switch_core.gateway.tenants import router as tenants_routerfrom tests.conftest import empty_the_database@@ -132,6 +133,32 @@ def _tenants_app(session_factory: async_sessionmaker[AsyncSession]) -> FastAPI:return app+def _session_app(+ session_factory: async_sessionmaker[AsyncSession],+ *,+ signup_mode: str,+ invite_email_enabled: bool = False,+) -> FastAPI:+ """A route-scoped app for `GET /auth/session`, stubbed as `_app` is."""++ async def _session_dep():+ async with session_factory() as session:+ yield session++ app = FastAPI()+ app.include_router(auth_router)+ app.dependency_overrides[gw_deps.get_session_factory] = lambda: session_factory+ app.dependency_overrides[gw_deps.get_system_session] = _session_dep+ app.dependency_overrides[gw_deps.get_user_store] = lambda: UserStore()+ app.dependency_overrides[gw_deps.get_config] = lambda: SimpleNamespace(+ jwt_secret_key=_SECRET,+ gateway_signup_mode=signup_mode,+ gateway_max_workspaces_per_user=3,+ invite_email_enabled=invite_email_enabled,+ )+ return app++async def _session_tenant(session: AsyncSession) -> str | None:row = await session.execute(text("SELECT current_setting('app.tenant_id', true)"))return row.scalar_one() or None@@ -154,7 +181,7 @@ def _login_config() -> SimpleNamespace:)-def _tenant_claim(response: Response) -> str | None:+def _tenant_claim(response: Response | httpx.Response) -> str | None:raw = response.headers.get("set-cookie")assert raw is not None, "no session cookie was minted"token = raw.split("switch_auth=", 1)[1].split(";", 1)[0]@@ -205,51 +232,287 @@ async def _make_user_with_memberships(return user.id-class TestSigningInSelectsNoWorkspace:- """Both interactive mint sites pass a null tenant claim, and that is load- bearing rather than incidental.+class TestSigningInSelectsFromCurrentMemberships:+ """Both interactive mint sites choose the claim from the user's memberships+ *as they are now*: the workspace they last used if they still belong to+ it, else their only one, else none.- It is the way out of a selection that has gone stale: a member removed- from the workspace their cookie names is 403'd- (`TENANT_SELECTION_INVALID`) on every request until something mints a- cookie without it. If either of these were later made to "helpfully"- carry the previous tenant forward, that person would be stranded until- their cookie expired — and the rest of the suite would stay green, since- only `/auth/refresh`'s claim is asserted anywhere else (CHOO-2723).+ Checking against current memberships is load bearing. Signing in is the+ way out of a selection that has gone stale: a member removed from the+ workspace their cookie names is 403'd (`TENANT_SELECTION_INVALID`) on every+ request until something mints a cookie they can use. Carrying a previous+ tenant forward unchecked would strand them until their cookie expired+ (CHOO-2723)."""- async def test_password_login_mints_no_tenant_claim(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:+ async def _login(+ self, session_factory: async_sessionmaker[AsyncSession], email: str+ ) -> Response:+ response = Response()+ async with session_factory() as session:+ await login(+ LoginRequest(email=email, password="correct horse battery staple"),+ response,+ session,+ session_factory,+ UserStore(),+ _login_config(),+ )+ return response++ async def _password_user(+ self,+ session_factory: async_sessionmaker[AsyncSession],+ *,+ name: str,+ tenant_ids: list[str],+ last_tenant_id: str | None,+ ) -> str:async with session_factory() as session:+ for tenant_id in tenant_ids:+ if tenant_id != TENANT_ZERO_ID:+ session.add(Tenant(id=tenant_id, slug=tenant_id, name=tenant_id))+ await session.flush()user = User(- name="signer",- email="[email protected]",+ name=name,+ email=f"{name}@example.invalid",role="user",password_hash=hash_password("correct horse battery staple"),+ metadata_=(+ {"last_tenant_id": last_tenant_id} if last_tenant_id else None+ ),)session.add(user)await session.flush()- session.add(- TenantMember(tenant_id=TENANT_ZERO_ID, user_id=user.id, role="member")- )+ for tenant_id in tenant_ids:+ session.add(+ TenantMember(tenant_id=tenant_id, user_id=user.id, role="member")+ )await session.commit()+ return user.id- response = Response()- await login(- LoginRequest(- email="[email protected]",- password="correct horse battery staple",- ),- response,- session,- UserStore(),- _login_config(),- )+ async def test_a_sole_membership_is_selected(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await self._password_user(+ session_factory,+ name="solo",+ tenant_ids=[TENANT_ZERO_ID],+ last_tenant_id=None,+ )+ response = await self._login(session_factory, "[email protected]")+ assert _tenant_claim(response) == TENANT_ZERO_ID++ async def test_the_last_workspace_is_selected_among_several(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await self._password_user(+ session_factory,+ name="returning",+ tenant_ids=[TENANT_ZERO_ID, TENANT_B],+ last_tenant_id=TENANT_B,+ )+ response = await self._login(session_factory, "[email protected]")+ assert _tenant_claim(response) == TENANT_B++ async def test_a_last_workspace_they_have_left_is_not_selected(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await self._password_user(+ session_factory,+ name="removed",+ tenant_ids=[TENANT_ZERO_ID, TENANT_B],+ last_tenant_id=NOT_A_MEMBER_TENANT,+ )+ response = await self._login(session_factory, "[email protected]")+ assert _tenant_claim(response) is None++ async def test_a_stale_last_workspace_falls_back_to_the_sole_membership(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await self._password_user(+ session_factory,+ name="removed-solo",+ tenant_ids=[TENANT_ZERO_ID],+ last_tenant_id=NOT_A_MEMBER_TENANT,+ )+ response = await self._login(session_factory, "[email protected]")+ assert _tenant_claim(response) == TENANT_ZERO_ID++ async def test_several_with_no_history_select_none(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await self._password_user(+ session_factory,+ name="undecided-login",+ tenant_ids=[TENANT_ZERO_ID, TENANT_B],+ last_tenant_id=None,+ )+ response = await self._login(session_factory, "[email protected]")+ assert _tenant_claim(response) is None+ async def test_no_membership_selects_none(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await self._password_user(+ session_factory, name="homeless", tenant_ids=[], last_tenant_id=None+ )+ response = await self._login(session_factory, "[email protected]")assert _tenant_claim(response) is None+class TestSessionStateEndpoint:+ """`GET /auth/session` answers for every signed-in caller, including the+ ones `get_current_user` refuses, and its `state` agrees with what tenant+ resolution would do to the next request."""++ async def _get(+ self,+ session_factory: async_sessionmaker[AsyncSession],+ token: str,+ *,+ signup_mode: str,+ invite_email_enabled: bool = False,+ ) -> httpx.Response:+ async with _client(+ _session_app(+ session_factory,+ signup_mode=signup_mode,+ invite_email_enabled=invite_email_enabled,+ ),+ token,+ ) as client:+ return await client.get("/auth/session")++ async def test_a_valid_claim_is_ready(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ user_id = await _make_user_with_memberships(+ session_factory, name="ready", tenant_ids=[TENANT_ZERO_ID, TENANT_B]+ )+ token = create_jwt(user_id, "[email protected]", "user", _SECRET, TENANT_B)++ response = await self._get(session_factory, token, signup_mode="default_tenant")++ assert response.status_code == 200, response.text+ body = response.json()+ assert body["state"] == "ready"+ assert body["tenant"]["id"] == TENANT_B+ assert body["tenant"]["role"] == "member"+ assert {t["id"] for t in body["tenants"]} == {TENANT_ZERO_ID, TENANT_B}+ assert body["user"] == {+ "id": user_id,+ "name": "ready",+ "email": "[email protected]",+ "is_operator": False,+ }++ async def test_no_claim_and_one_membership_is_ready(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ user_id = await _make_user(session_factory, name="single", tenant_id=TENANT_B)+ token = create_jwt(user_id, "[email protected]", "user", _SECRET, None)++ body = (+ await self._get(session_factory, token, signup_mode="default_tenant")+ ).json()++ assert body["state"] == "ready"+ assert body["tenant"]["id"] == TENANT_B++ async def test_no_claim_and_several_memberships_needs_selection(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ user_id = await _make_user_with_memberships(+ session_factory, name="chooser", tenant_ids=[TENANT_ZERO_ID, TENANT_B]+ )+ token = create_jwt(user_id, "[email protected]", "user", _SECRET, None)++ body = (+ await self._get(session_factory, token, signup_mode="default_tenant")+ ).json()++ assert body["state"] == "needs_selection"+ assert body["tenant"] is None+ assert len(body["tenants"]) == 2++ async def test_a_stale_claim_needs_selection_even_with_one_membership(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """Tenant resolution refuses a claim naming no membership rather than+ falling back to the sole one, so reporting "ready" here would be+ contradicted by the very next request."""+ user_id = await _make_user(session_factory, name="stale", tenant_id=TENANT_B)+ token = create_jwt(+ user_id, "[email protected]", "user", _SECRET, NOT_A_MEMBER_TENANT+ )++ body = (+ await self._get(session_factory, token, signup_mode="default_tenant")+ ).json()++ assert body["state"] == "needs_selection"+ assert body["tenant"] is None++ async def test_no_membership_needs_a_workspace(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ user_id = await _make_user_with_memberships(+ session_factory, name="nowhere", tenant_ids=[]+ )+ token = create_jwt(user_id, "[email protected]", "user", _SECRET, None)++ body = (await self._get(session_factory, token, signup_mode="open")).json()++ assert body["state"] == "needs_workspace"+ assert body["tenants"] == []+ assert body["can_create_workspace"] is True++ async def test_invite_only_offers_no_workspace_creation(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ user_id = await _make_user_with_memberships(+ session_factory, name="waiting", tenant_ids=[]+ )+ token = create_jwt(user_id, "[email protected]", "user", _SECRET, None)++ body = (+ await self._get(session_factory, token, signup_mode="invite_only")+ ).json()++ assert body["state"] == "needs_workspace"+ assert body["can_create_workspace"] is False++ async def test_it_says_whether_invitations_are_e_mailed(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ user_id = await _make_user_with_memberships(+ session_factory, name="mailer", tenant_ids=[TENANT_B]+ )+ token = create_jwt(user_id, "[email protected]", "user", _SECRET, None)++ off = await self._get(session_factory, token, signup_mode="open")+ on = await self._get(+ session_factory, token, signup_mode="open", invite_email_enabled=True+ )++ assert off.json()["invite_email_enabled"] is False+ assert on.json()["invite_email_enabled"] is True++ async def test_an_unauthenticated_caller_is_401(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(+ app=_session_app(session_factory, signup_mode="open")+ ),+ base_url="http://test",+ ) as client:+ response = await client.get("/auth/session")++ assert response.status_code == 401++class TestAGatewayRequestBindsTheCallersTenant:async def test_the_sessions_tenant_matches_the_users_membership(self, session_factory: async_sessionmaker[AsyncSession]@@ -521,8 +784,11 @@ class TestSwitchTenantEndpoint:assert response.status_code == 200, response.textassert response.json()["id"] == user_id- set_cookie = response.headers.get("set-cookie")- assert set_cookie is not None and "switch_auth=" in set_cookie+ assert _tenant_claim(response) == TENANT_B+ async with session_factory() as session:+ user = await session.get(User, user_id)+ assert user is not None+ assert UserStore().last_tenant_id(user) == TENANT_Basync def test_switching_to_a_tenant_you_do_not_belong_to_is_refused(self, session_factory: async_sessionmaker[AsyncSession]@@ -643,3 +909,63 @@ class TestTenantListingHoldsOneConnectionAtATime:assert response.status_code == 200, response.textassert {row["id"] for row in response.json()} == {TENANT_ZERO_ID, TENANT_B}+++class TestSigningInHoldsOneConnectionAtATime:+ """The sign-in surface reads the user on the system session and then+ looks up memberships on sessions of its own. Doing both at once would+ need two pooled connections per request — deadlocking on a pool of one,+ and quietly halving capacity on a real one. Each route below has to end+ its read before the lookup starts."""++ async def test_password_login_completes_on_a_pool_of_one(+ self, one_connection_session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ factory = one_connection_session_factory+ async with factory() as session:+ user = User(+ name="poollogin",+ email="[email protected]",+ role="user",+ password_hash=hash_password("correct horse battery staple"),+ )+ session.add(user)+ await session.flush()+ session.add(+ TenantMember(tenant_id=TENANT_ZERO_ID, user_id=user.id, role="member")+ )+ await session.commit()++ response = Response()+ async with factory() as session:+ await login(+ LoginRequest(+ email="[email protected]",+ password="correct horse battery staple",+ ),+ response,+ session,+ factory,+ UserStore(),+ _login_config(),+ )++ assert _tenant_claim(response) == TENANT_ZERO_ID++ async def test_session_state_completes_on_a_pool_of_one(+ self, one_connection_session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ user_id = await _make_user_with_memberships(+ one_connection_session_factory,+ name="poolstate",+ tenant_ids=[TENANT_ZERO_ID, TENANT_B],+ )+ token = create_jwt(user_id, "[email protected]", "user", _SECRET, None)++ async with _client(+ _session_app(one_connection_session_factory, signup_mode="open"), token+ ) as client:+ response = await client.get("/auth/session")++ assert response.status_code == 200, response.text+ assert response.json()["state"] == "needs_selection"diff --git a/core/tests/switch_core/session_activity/test_bridge_publisher.py b/core/tests/switch_core/session_activity/test_bridge_publisher.pyindex edef651f9..c0bf3f5fb 100644--- a/core/tests/switch_core/session_activity/test_bridge_publisher.py+++ b/core/tests/switch_core/session_activity/test_bridge_publisher.py@@ -177,6 +177,7 @@ async def _step(thread_id=ASKED,message_id=ASKED,occurred_at=datetime.now(UTC),+ usage=[],)diff --git a/core/tests/switch_core/session_activity/test_isolation.py b/core/tests/switch_core/session_activity/test_isolation.pyindex c1b8e08ed..71c486d13 100644--- a/core/tests/switch_core/session_activity/test_isolation.py+++ b/core/tests/switch_core/session_activity/test_isolation.py@@ -83,6 +83,7 @@ async def test_each_tenant_sees_only_its_own_activity_and_requests(rls_harness):thread_id=None,message_id=None,occurred_at=datetime.now(UTC),+ usage=[],)await service.open_approval(tenant,diff --git a/core/tests/switch_core/session_activity/test_maintenance.py b/core/tests/switch_core/session_activity/test_maintenance.pyindex ba67175fb..40c5c09a9 100644--- a/core/tests/switch_core/session_activity/test_maintenance.py+++ b/core/tests/switch_core/session_activity/test_maintenance.py@@ -50,6 +50,7 @@ async def test_a_pass_expires_overdue_requests_and_prunes_only_when_asked(thread_id=None,message_id=None,occurred_at=datetime.now(UTC),+ usage=[],)past = datetime.now(UTC) - timedelta(days=30)await _backdate(session_factory, ApprovalRequest, expires_at=past)diff --git a/core/tests/switch_core/session_activity/test_routes.py b/core/tests/switch_core/session_activity/test_routes.pyindex ad33f217e..e07e0bf35 100644--- a/core/tests/switch_core/session_activity/test_routes.py+++ b/core/tests/switch_core/session_activity/test_routes.py@@ -10,7 +10,7 @@ from sqlalchemy import selectfrom switch_core.bridges.agent.api.activity_routes import routerfrom switch_core.bridges.agent.auth import get_agent_from_scopefrom switch_core.bridges.agent.dependencies import get_session_factory-from switch_core.db.models import Agent, ApprovalRequest+from switch_core.db.models import Agent, ApprovalRequest, TenantUsagefrom switch_core.session_activity.service import ApprovalOption, PlatformPersonfrom switch_core.sessions.contract import Answer, QuestionsResultfrom switch_core.sessions.errors import SessionError@@ -110,6 +110,58 @@ async def test_malformed_activity_is_a_422(client, overrides):assert response.status_code == 422+_USAGE = {+ "model": "big",+ "input_tokens": 10,+ "output_tokens": 2,+ "cache_read_tokens": 300,+ "cache_write_tokens": 0,+}+++def _ended_turn(**overrides):+ return _activity(+ **{+ "item_id": "turn",+ "kind": "turn",+ "status": "completed",+ "title": "",+ "text": "",+ **overrides,+ }+ )+++async def test_an_ended_turn_row_carries_what_the_turn_spent(client, session_factory):+ response = await client.post(+ f"/agent-sessions/{SESSION}/activity", json=_ended_turn(usage=[_USAGE])+ )+ assert response.json() == {"recorded": True}+ async with session_factory() as db:+ rows = (await db.execute(select(TenantUsage.metric, TenantUsage.amount))).all()+ assert sorted(rows) == [+ ("cache_read_tokens", 300),+ ("input_tokens", 10),+ ("output_tokens", 2),+ ("turns", 1),+ ]+++ "body",+ [+ _activity(usage=[_USAGE]),+ _ended_turn(status="running", usage=[_USAGE]),+ _ended_turn(usage=[{**_USAGE, "input_tokens": -1}]),+ _ended_turn(usage=[{**_USAGE, "input_tokens": 2**53}]),+ _ended_turn(usage=[{**_USAGE, "reasoning_tokens": 1}]),+ ],+)+async def test_usage_anywhere_but_an_ended_turn_or_malformed_is_a_422(client, body):+ response = await client.post(f"/agent-sessions/{SESSION}/activity", json=body)+ assert response.status_code == 422++async def test_a_questions_request_over_http(client, service, people):opened = await client.post(f"/agent-sessions/{SESSION}/approvals",diff --git a/core/tests/switch_core/session_activity/test_service.py b/core/tests/switch_core/session_activity/test_service.pyindex 2ae265892..7085888b7 100644--- a/core/tests/switch_core/session_activity/test_service.py+++ b/core/tests/switch_core/session_activity/test_service.py@@ -3,16 +3,17 @@ from __future__ import annotationsfrom datetime import UTC, datetime, timedeltaimport pytest-from sqlalchemy import update+from sqlalchemy import select, updatefrom switch_core.addressing import owner_only_policy-from switch_core.db.models import ApprovalRequest+from switch_core.db.models import ApprovalRequest, TenantUsagefrom switch_core.session_activity.service import (ApprovalOption,PlatformPerson,Question,QuestionOption,SwitchUser,+ TokenSpend,)from switch_core.sessions.contract import Answer, QuestionsResultfrom switch_core.sessions.errors import SessionError@@ -64,6 +65,7 @@ def _step(**overrides):thread_id=None,message_id=None,occurred_at=datetime(2026, 9, 23, 12, 0, tzinfo=UTC),+ usage=[],)values.update(overrides)return values@@ -118,6 +120,86 @@ async def test_a_step_is_upserted_by_revision_and_announced_by_turn(service, chaassert all(change.row is None for change in announced)+def _turn(turn_id: str, revision: int, status: str, usage=()):+ return _step(+ turn_id=turn_id,+ item_id="turn",+ kind="turn",+ revision=revision,+ status=status,+ title="",+ text="",+ usage=list(usage),+ )+++async def _turns_counted(session_factory) -> int:+ async with session_factory() as db:+ rows = await db.scalars(+ select(TenantUsage.amount).where(TenantUsage.metric == "turns")+ )+ return sum(rows)+++async def test_a_turn_is_counted_once_when_first_reported(service, session_factory):+ # A turn is spent once it exists: its later statuses, a retried report and+ # its steps are the same turn, and one that errors still cost model time.+ await service.report_item(AGENT, SESSION, **_turn("turn-1", 1, "running"))+ await service.report_item(AGENT, SESSION, **_turn("turn-1", 1, "running"))+ await service.report_item(AGENT, SESSION, **_step(revision=2))+ await service.report_item(AGENT, SESSION, **_turn("turn-1", 3, "error"))+ assert await _turns_counted(session_factory) == 1++ await service.report_item(AGENT, SESSION, **_turn("turn-2", 4, "completed"))+ assert await _turns_counted(session_factory) == 2+++def _spend(model: str, input_tokens: int) -> TokenSpend:+ return TokenSpend(+ model=model,+ input_tokens=input_tokens,+ output_tokens=1,+ cache_read_tokens=0,+ cache_write_tokens=0,+ )+++async def _tokens_counted(session_factory) -> list[tuple[str, str, int]]:+ async with session_factory() as db:+ rows = await db.execute(+ select(TenantUsage.metric, TenantUsage.model, TenantUsage.amount).where(+ TenantUsage.metric != "turns"+ )+ )+ return sorted(tuple(row) for row in rows)+++async def test_a_turns_tokens_are_counted_once_when_it_first_ends(+ service, session_factory+):+ spent = [_spend("small", 7), _spend("big", 10)]+ await service.report_item(AGENT, SESSION, **_turn("turn-1", 1, "running"))+ await service.report_item(AGENT, SESSION, **_turn("turn-1", 2, "completed", spent))+ # A retried report, and a later revision of an ended turn, spend nothing new.+ await service.report_item(AGENT, SESSION, **_turn("turn-1", 2, "completed", spent))+ await service.report_item(+ AGENT, SESSION, **_turn("turn-1", 3, "interrupted", spent)+ )+ assert await _tokens_counted(session_factory) == [+ ("input_tokens", "big", 10),+ ("input_tokens", "small", 7),+ ("output_tokens", "big", 1),+ ("output_tokens", "small", 1),+ ]+++async def test_usage_on_a_turn_that_has_not_ended_is_refused(service):+ with pytest.raises(SessionError, match="ended turn"):+ await service.report_item(+ AGENT, SESSION, **_turn("turn-1", 1, "running", [_spend("big", 1)])+ )++async def test_a_turns_steps_are_read_in_the_order_first_reported(service):for item_id, kind, status in [("turn", "turn", "running"),diff --git a/core/tests/switch_core/test_config_discord_app.py b/core/tests/switch_core/test_config_discord_app.pynew file mode 100644index 000000000..c3b4d77a1--- /dev/null+++ b/core/tests/switch_core/test_config_discord_app.py@@ -0,0 +1,65 @@+"""Half-configuring the distributed Discord app has to be a startup error.++The four credentials are useless apart: without the client id and secret the+code exchange is refused, without the application id there is no app to speak+for, and without the bot token the shared Gateway connection has nothing to open+with. A deployment that sets three of four looks configured, offers the button,+and breaks — so it does not start. And an app with no public origin builds its+redirect against nothing, which Discord refuses with nothing in our logs.+"""++import pytest++from switch_core.config import SwitchConfig++_BASE_KWARGS = dict(+ db_host="db",+ db_port="5432",+ db_user="postgres",+ db_password="pw",+ db_name="switch",+ matrix_server_name="switch.local",+ agent_registration_token="token",+ jwt_secret_key="jwt",+ gateway_admin_email="[email protected]",+ gateway_admin_password="pw",+)++_APP = dict(+ discord_app_client_id="123456789012345678",+ discord_app_client_secret="secret",+ discord_app_bot_token="bot-token",+ discord_app_application_id="123456789012345678",+)+++def _config(**overrides: object) -> SwitchConfig:+ return SwitchConfig(**{**_BASE_KWARGS, **overrides}) # type: ignore[arg-type]+++def test_setting_none_of_them_is_the_ordinary_case() -> None:+ assert _config().discord_app_client_id is None+++def test_setting_all_four_with_a_public_origin_is_accepted() -> None:+ config = _config(**_APP, messaging_public_url="https://switch.example")+ assert config.discord_app_bot_token == "bot-token"++[email protected]("missing", sorted(_APP))+def test_setting_some_of_them_raises(missing: str) -> None:+ partial = {key: value for key, value in _APP.items() if key != missing}+ with pytest.raises(ValueError, match="Partial distributed Discord app config"):+ _config(**partial, messaging_public_url="https://switch.example")+++def test_an_app_with_no_public_origin_raises() -> None:+ """The redirect is built from it, and Discord compares it byte for byte."""+ with pytest.raises(ValueError, match="MESSAGING_PUBLIC_URL"):+ _config(**_APP)+++def test_the_gateway_url_does_not_stand_in_for_it() -> None:+ """They name different hosts and only one is a valid OAuth redirect origin."""+ with pytest.raises(ValueError, match="MESSAGING_PUBLIC_URL"):+ _config(**_APP, gateway_public_url="https://gateway.example")diff --git a/core/tests/switch_core/test_config_smtp.py b/core/tests/switch_core/test_config_smtp.pynew file mode 100644index 000000000..5494f7480--- /dev/null+++ b/core/tests/switch_core/test_config_smtp.py@@ -0,0 +1,70 @@+import pytest++from switch_core.config import SwitchConfig++_BASE_KWARGS = dict(+ db_host="db",+ db_port="5432",+ db_user="postgres",+ db_password="pw",+ db_name="switch",+ matrix_server_name="switch.local",+ agent_registration_token="token",+ jwt_secret_key="jwt",+ gateway_admin_email="[email protected]",+ gateway_admin_password="pw",+)++_SMTP = dict(+ gateway_smtp_host="smtp.example.com",+ gateway_smtp_from="[email protected]",+ frontend_base_url="https://switch.example.com",+)+++def _config(**overrides: object) -> SwitchConfig:+ return SwitchConfig(**{**_BASE_KWARGS, **overrides}) # type: ignore[arg-type]+++def test_mail_is_off_by_default() -> None:+ assert _config().invite_email_enabled is False+++def test_a_host_with_a_sender_and_a_link_origin_turns_it_on() -> None:+ assert _config(**_SMTP).invite_email_enabled is True+++ ("missing", "named"),+ [+ ("gateway_smtp_from", "GATEWAY_SMTP_FROM"),+ ("frontend_base_url", "FRONTEND_BASE_URL"),+ ],+)+def test_a_host_without_what_the_e_mail_needs_refuses_to_start(+ missing: str, named: str+) -> None:+ with pytest.raises(ValueError, match=named):+ _config(**{**_SMTP, missing: None})+++ "credentials",+ [{"gateway_smtp_username": "relay-user"}, {"gateway_smtp_password": "placeholder"}],+)+def test_half_a_credential_refuses_to_start(credentials: dict[str, str]) -> None:+ with pytest.raises(ValueError, match="set together"):+ _config(**_SMTP, **credentials)+++def test_the_daily_cap_must_allow_at_least_one() -> None:+ with pytest.raises(ValueError, match="GATEWAY_INVITE_EMAILS_PER_DAY"):+ _config(gateway_invite_emails_per_day=0)+++def test_empty_values_from_an_uncommented_env_file_mean_unset() -> None:+ config = _config(+ gateway_smtp_host="", gateway_smtp_username="", gateway_smtp_password=""+ )++ assert config.invite_email_enabled is Falsediff --git a/core/tests/switch_core/test_config_standalone_compose.py b/core/tests/switch_core/test_config_standalone_compose.pynew file mode 100644index 000000000..e86cfbfa8--- /dev/null+++ b/core/tests/switch_core/test_config_standalone_compose.py@@ -0,0 +1,49 @@+"""Every variable the standalone compose file defaults to empty must boot empty.++`KEY: ${KEY:-}` hands the container an empty string whenever `.env` does not+set the key, which is most deployments for most keys. An empty string is not+unset to a settings class that validates: a boolean or a checked string refuses+it and the container never starts. So a key forwarded that way has to be one+the config accepts empty, and any other is forwarded as a bare key instead.+"""++import re+from pathlib import Path++import pytest++from switch_core.config import SwitchConfig++_COMPOSE = (+ Path(__file__).resolve().parents[3] / "deploy/local/standalone-docker-compose.yml"+)++_EMPTY_DEFAULT = re.compile(r"^\s+([A-Z][A-Z0-9_]*): \$\{\1:-\}\s*$", re.MULTILINE)++_BASE_KWARGS = dict(+ db_host="db",+ db_port="5432",+ db_user="postgres",+ db_password="pw",+ db_name="switch",+ matrix_server_name="switch.local",+ agent_registration_token="token",+ jwt_secret_key="jwt",+ gateway_admin_email="[email protected]",+ gateway_admin_password="pw",+)+++def _defaulted_to_empty() -> list[str]:+ return sorted(set(_EMPTY_DEFAULT.findall(_COMPOSE.read_text())))+++def test_the_compose_file_has_such_keys() -> None:+ assert _defaulted_to_empty()++[email protected]("key", _defaulted_to_empty())+def test_the_config_accepts_it_empty(key: str, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv(key, "")++ SwitchConfig(**_BASE_KWARGS) # type: ignore[arg-type]diff --git a/core/tests/switch_core/test_room_service_change_bridge.py b/core/tests/switch_core/test_room_service_change_bridge.pyindex 7e077fee4..f2733f8c9 100644--- a/core/tests/switch_core/test_room_service_change_bridge.py+++ b/core/tests/switch_core/test_room_service_change_bridge.py@@ -5,6 +5,7 @@ from typing import Anyimport pytest+from switch_core.bridges.collaboration.adapter import ChannelNotBindablefrom switch_core.bridges.collaboration.models import ChannelCreationUnsupportedfrom switch_core.room_service import RoomService@@ -69,6 +70,12 @@ class _FakeAdapter:def __init__(self, events: list[Any], new_channel_id: str) -> None:self._events = eventsself._new_channel_id = new_channel_id+ self.not_bindable: set[str] = set()++ async def require_bindable_channel(self, channel_id: str) -> None:+ self._events.append(("require_bindable", channel_id))+ if channel_id in self.not_bindable:+ raise ChannelNotBindable(f"{channel_id} is not this bridge's")async def create_channel(self, name: str, topic: str, *, channel_type: str = "channel_public"@@ -324,8 +331,10 @@ class TestChangeBridge:external_channel_id="chan-reused",)- # No new channel provisioned; the provided id is bound and mapped.+ # No new channel provisioned; the provided id is vouched for, then+ # bound and mapped.assert not any(e[0] == "create_channel" for e in events)+ assert events[0] == ("require_bindable", "chan-reused")assert room_store.update_bridge_calls[0]["external_channel_id"] == "chan-reused"assert ("add_room_mapping", "room-1", "chan-reused") in eventsassert ("add_agents", "chan-reused", ["agent.one"]) in events@@ -334,6 +343,42 @@ class TestChangeBridge:# established explicitly or the room only ever hears @mentions.assert ("ensure_capture", [("chan-reused", "channel_public")]) in events+ async def test_a_channel_the_bridge_refuses_is_not_bound(self) -> None:+ """The id is the caller's, and binding decides where the room's+ messages are posted: a bridge on a shared connection can see other+ organisations' channels, so it is asked first and nothing moves."""+ events: list[Any] = []+ room = SimpleNamespace(+ id="room-1",+ tenant_id="room-tenant",+ name="Work",+ description="A room",+ matrix_room_id="!mx:switch.local",+ bridge_id="bridge-old",+ channel_type="channel_public",+ external_channel_id="chan-old",+ )+ new_bridge = _FakeBridgeCore(events, matrix_user_id="@bot-new:switch.local")+ new_bridge.adapter.not_bindable.add("chan-elsewhere")+ old_bridge = _FakeBridgeCore(events, matrix_user_id="@bot-old:switch.local")+ svc, room_store = _build_service(+ room=room,+ agent_ids=["a1"],+ agent_names={"a1": "agent.one"},+ bridges={"bridge-new": new_bridge, "bridge-old": old_bridge},+ events=events,+ )++ with pytest.raises(ChannelNotBindable):+ await svc.change_bridge(+ "room-1",+ bridge_id="bridge-new",+ external_channel_id="chan-elsewhere",+ )++ assert events == [("require_bindable", "chan-elsewhere")]+ assert room_store.update_bridge_calls == []+async def test_capture_is_established_for_a_freshly_created_channel(self) -> None:# Idempotent by design: the adapter skips a channel it is already# subscribed to, so asking again after provisioning costs nothing anddiff --git a/core/tests/switch_core/test_room_service_channel_binding.py b/core/tests/switch_core/test_room_service_channel_binding.pynew file mode 100644index 000000000..14a8872ef--- /dev/null+++ b/core/tests/switch_core/test_room_service_channel_binding.py@@ -0,0 +1,78 @@+"""A room bound to an existing channel by id binds only a channel the bridge+calls its own.++Binding decides where a room's messages are posted, and on a connection shared+between organisations the bot can see every organisation's channels. So a+caller-supplied id is put to the bridge before anything is created; a channel+the platform delivered to the bridge is not, because it reached this bridge by+being its own. The move path (`change_bridge`) is covered beside its other+tests.+"""++from __future__ import annotations++from types import SimpleNamespace+from typing import Any++import pytest++from switch_core.bridges.collaboration.adapter import ChannelNotBindable+from switch_core.room_service import RoomCreateConfig+from tests.switch_core.test_room_service_change_bridge import (+ _build_service,+ _FakeBridgeCore,+)+++class _Reached(Exception):+ """Raised by the first step after the check, to show it was passed."""+++def _service(events: list[Any]) -> tuple[Any, _FakeBridgeCore]:+ bridge = _FakeBridgeCore(events, matrix_user_id="@bot:switch.local")+ bridge.adapter.not_bindable.add("chan-elsewhere")+ svc, _ = _build_service(+ room=SimpleNamespace(),+ agent_ids=[],+ agent_names={},+ bridges={"bridge-1": bridge},+ events=events,+ )++ async def create_matrix_room(*_: Any, **__: Any) -> str:+ raise _Reached++ svc._matrix_admin.create_room = create_matrix_room+ return svc, bridge+++def _config(created_by_kind: str) -> RoomCreateConfig:+ return RoomCreateConfig(+ name="Work",+ description="",+ bridge_id="bridge-1",+ external_channel_id="chan-elsewhere",+ channel_type="channel_public",+ created_by_kind=created_by_kind, # type: ignore[arg-type]+ )++[email protected]("kind", ["user", "agent"])+async def test_a_channel_the_bridge_refuses_is_not_bound(kind: str) -> None:+ events: list[Any] = []+ svc, _ = _service(events)++ with pytest.raises(ChannelNotBindable):+ await svc.create_room(_config(kind))++ assert events == [("require_bindable", "chan-elsewhere")]+++async def test_a_channel_the_platform_delivered_is_not_asked_about() -> None:+ events: list[Any] = []+ svc, _ = _service(events)++ with pytest.raises(_Reached):+ await svc.create_room(_config("system"))++ assert ("require_bindable", "chan-elsewhere") not in eventsdiff --git a/core/tests/switch_core/test_room_service_foreign_bridge.py b/core/tests/switch_core/test_room_service_foreign_bridge.pynew file mode 100644index 000000000..853e33f25--- /dev/null+++ b/core/tests/switch_core/test_room_service_foreign_bridge.py@@ -0,0 +1,237 @@+"""A tenant cannot reach another tenant's collaboration bridge by naming its id.++The running bridges live in one process-wide registry, so a `bridge_id` taken+from a caller has to be checked against the bound tenant's own bridges before+anything happens on the platform behind it. Otherwise a channel (or a DM, or a+directory lookup) runs on the other tenant's Slack or Mattermost, and only the+database insert that follows fails on the composite foreign key — after the+side effect.++Real Postgres, with the service connected as a role row-level security+applies to (`rls_harness.restricted`), because that is what makes the other+tenant's bridge row invisible in production. The running bridge is faked, and+records every platform call so a test can assert none was made.+"""++from __future__ import annotations++import uuid+from typing import Any++import pytest+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.db.models import Client, CollaborationBridge, Tenant+from switch_core.db.session_scope import tenant_session+from switch_core.db.stores.agent_store import AgentStore+from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore+from switch_core.db.stores.room_store import RoomStore+from switch_core.room_service import RoomCreateConfig, RoomService+from switch_core.tenant_context import tenant_scope+from tests.conftest import RLSHarness++pytestmark = pytest.mark.no_ambient_tenant+++class _FakeMatrix:+ def __init__(self) -> None:+ self._n = 0++ async def create_room(self, name: str, topic: str) -> str:+ self._n += 1+ return f"!room-{self._n}:switch.local"++ async def invite_to_room(self, room_id: str, user_id: str) -> None:+ return None++ async def kick_user(self, room_id: str, user_id: str) -> None:+ return None+++class _RecordingAdapter:+ def __init__(self, calls: list[str]) -> None:+ self._calls = calls++ async def create_channel(+ self, name: str, topic: str, *, channel_type: str = "channel_public"+ ) -> str:+ self._calls.append("create_channel")+ return "chan-foreign"++ async def create_dm_channel(self, **kwargs: Any) -> str:+ self._calls.append("create_dm_channel")+ return "dm-foreign"++ async def get_channel_type(self, external_channel_id: str) -> str:+ self._calls.append("get_channel_type")+ return "channel_public"++ async def add_agents_to_channel(+ self, channel_id: str, agent_names: list[str]+ ) -> None:+ self._calls.append("add_agents_to_channel")++ async def ensure_channel_subscriptions(+ self, channels: list[tuple[str, str]]+ ) -> None:+ self._calls.append("ensure_channel_subscriptions")+++class _RecordingBridgeCore:+ def __init__(self, tenant_id: str) -> None:+ self.calls: list[str] = []+ self.tenant_id = tenant_id+ self._bridge_client_matrix_user_id = "@bot:switch.local"+ self.adapter = _RecordingAdapter(self.calls)++ async def resolve_external_user_id_map(self, names: list[str]) -> dict[str, str]:+ self.calls.append("resolve_external_user_id_map")+ return {name: f"ext-{name}" for name in names}++ def begin_provisioning(self, external_channel_id: str) -> None:+ return None++ def end_provisioning(self, external_channel_id: str) -> None:+ return None++ def add_room_mapping(self, *args: Any) -> None:+ self.calls.append("add_room_mapping")++ def remove_room_mapping(self, *args: Any) -> None:+ return None+++class _FakeLifecycle:+ def __init__(self, bridges: dict[str, _RecordingBridgeCore]) -> None:+ self._bridges = bridges++ def get(self, bridge_id: str) -> Any:+ return self._bridges.get(bridge_id)+++class _NoRunningClients:+ def get_by_agent_id(self, agent_id: str) -> Any:+ return None++ def get_by_type(self, client_type: str, tenant_id: str) -> list[Any]:+ return []++ def get(self, client_id: str) -> Any:+ return None+++async def _make_tenant(session_factory: async_sessionmaker[AsyncSession]) -> str:+ tenant_id = f"tenant-{uuid.uuid4().hex[:8]}"+ async with session_factory() as session:+ session.add(Tenant(id=tenant_id, slug=tenant_id, name=tenant_id))+ await session.commit()+ return tenant_id+++async def _make_bridge(+ session_factory: async_sessionmaker[AsyncSession], *, tenant_id: str+) -> str:+ async with tenant_session(session_factory, tenant_id) as session:+ client = Client(+ matrix_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:switch.local",+ display_name="bridge client",+ type="bridge",+ )+ session.add(client)+ await session.flush()+ bridge = CollaborationBridge(+ type="mattermost",+ display_name="MM",+ client_id=client.id,+ status="active",+ channel_creation_enabled=True,+ )+ session.add(bridge)+ await session.flush()+ await session.commit()+ return bridge.id+++def _service(+ session_factory: async_sessionmaker[AsyncSession],+ bridges: dict[str, _RecordingBridgeCore],+) -> RoomService:+ svc = object.__new__(RoomService)+ svc._session_factory = session_factory # type: ignore[assignment]+ svc._room_store = RoomStore() # type: ignore[assignment]+ svc._agent_store = AgentStore() # type: ignore[assignment]+ svc._client_lifecycle = _NoRunningClients() # type: ignore[assignment]+ svc._collab_lifecycle = _FakeLifecycle(bridges) # type: ignore[assignment]+ svc._collab_bridge_store = CollaborationBridgeStore() # type: ignore[assignment]+ svc._matrix_admin = _FakeMatrix() # type: ignore[assignment]+ return svc+++async def setup(+ rls_harness: RLSHarness,+) -> tuple[RoomService, str, str, _RecordingBridgeCore]:+ """Tenant A owns a running bridge; returns a service, tenant B, A's bridge+ id, and A's bridge so a test can check nothing ran on it."""+ tenant_a = await _make_tenant(rls_harness.owner)+ tenant_b = await _make_tenant(rls_harness.owner)+ bridge_a = await _make_bridge(rls_harness.owner, tenant_id=tenant_a)+ core_a = _RecordingBridgeCore(tenant_a)+ svc = _service(rls_harness.restricted, {bridge_a: core_a})+ return svc, tenant_b, bridge_a, core_a+++async def test_create_room_refuses_another_tenants_bridge(setup: Any) -> None:+ svc, tenant_b, bridge_a, core_a = setup+ with tenant_scope(tenant_b), pytest.raises(ValueError, match="Bridge not found"):+ await svc.create_room(+ RoomCreateConfig(name="r", description="d", bridge_id=bridge_a)+ )+ assert core_a.calls == []+++async def test_create_room_refuses_another_tenants_bridge_for_an_existing_channel(+ setup: Any,+) -> None:+ svc, tenant_b, bridge_a, core_a = setup+ with tenant_scope(tenant_b), pytest.raises(ValueError, match="Bridge not found"):+ await svc.create_room(+ RoomCreateConfig(+ name="r",+ description="d",+ bridge_id=bridge_a,+ external_channel_id="chan-existing",+ )+ )+ assert core_a.calls == []+++async def test_link_bridge_refuses_another_tenants_bridge(setup: Any) -> None:+ svc, tenant_b, bridge_a, core_a = setup+ with tenant_scope(tenant_b):+ own = await svc.create_room(+ RoomCreateConfig(name="r", description="d", internal_only=True)+ )+ with pytest.raises(ValueError, match="Bridge not found"):+ await svc.link_bridge_to_room(own.room.id, bridge_a, "channel_public")+ assert core_a.calls == []+++async def test_change_bridge_refuses_another_tenants_bridge(setup: Any) -> None:+ svc, tenant_b, bridge_a, core_a = setup+ with tenant_scope(tenant_b):+ own = await svc.create_room(+ RoomCreateConfig(name="r", description="d", internal_only=True)+ )+ with pytest.raises(ValueError, match="Bridge not found"):+ await svc.change_bridge(own.room.id, bridge_id=bridge_a)+ assert core_a.calls == []+++async def test_resolve_bridge_users_refuses_another_tenants_bridge(+ setup: Any,+) -> None:+ svc, tenant_b, bridge_a, core_a = setup+ with tenant_scope(tenant_b), pytest.raises(ValueError, match="Bridge not found"):+ await svc.resolve_bridge_users(bridge_a, ["someone"])+ assert core_a.calls == []diff --git a/core/tests/switch_core/transport/fake.py b/core/tests/switch_core/transport/fake.pyindex 34d313b6d..d385e09df 100644--- a/core/tests/switch_core/transport/fake.py+++ b/core/tests/switch_core/transport/fake.py@@ -85,6 +85,7 @@ class FakeTransport:body: str,*,sender_name: str,+ metered: bool,format: MessageFormat = "text",mentions: list[str] | None = None,thread_root_id: str | None = None,@@ -97,6 +98,7 @@ class FakeTransport:"room_id": room_id,"body": body,"sender_name": sender_name,+ "metered": metered,"format": format,"mentions": mentions,"thread_root_id": thread_root_id,@@ -140,6 +142,7 @@ class FakeTransport:size: int,*,sender_name: str,+ metered: bool,msgtype: str,caption: str | None = None,thread_root_id: str | None = None,@@ -155,6 +158,7 @@ class FakeTransport:"mimetype": mimetype,"size": size,"sender_name": sender_name,+ "metered": metered,"msgtype": msgtype,"caption": caption,"thread_root_id": thread_root_id,diff --git a/core/tests/switch_core/transport/test_postgres_transport.py b/core/tests/switch_core/transport/test_postgres_transport.pyindex a69c36a5d..5bdea7b80 100644--- a/core/tests/switch_core/transport/test_postgres_transport.py+++ b/core/tests/switch_core/transport/test_postgres_transport.py@@ -17,15 +17,25 @@ import uuidfrom collections.abc import Iteratorimport pytest+from sqlalchemy import delete, selectfrom sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.db.models import TENANT_ZERO_ID, Client, ClientRoom, Room, Tenant+from switch_core.db.models import (+ TENANT_ZERO_ID,+ Client,+ ClientRoom,+ Message,+ Room,+ Tenant,+ TenantUsage,+)from switch_core.db.session_scope import tenant_sessionfrom switch_core.db.stores.client_store import ClientStorefrom switch_core.db.stores.media_store import MediaStorefrom switch_core.db.stores.message_store import MessageStorefrom switch_core.db.stores.room_store import RoomStore+from switch_core.db.stores.usage_store import UsageStorefrom switch_core.observability.metrics import MetricsRegistry, install, uninstallfrom switch_core.provisioning.postgres import PostgresProvisioningfrom switch_core.tenant_context import current_tenant_id, tenant_scope@@ -185,6 +195,7 @@ def _transport(session_factory=session_factory,room_store=RoomStore(),message_store=MessageStore(),+ usage_store=UsageStore(),media_store=MediaStore(),listener=listener or _FakeListener(),invites=invites or InviteBus(),@@ -200,6 +211,110 @@ class TestConformsToThePort:assert isinstance(transport, MessageTransport)+class TestMetering:+ """Every message a participant sends is counted against its tenant, in the+ same write as the message, so the two cannot disagree."""++ async def _usage(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> list[tuple[str, str, int]]:+ async with session_factory() as session:+ rows = await session.scalars(select(TenantUsage))+ return [(r.metric, r.client_id, r.amount) for r in rows]++ async def test_messages_and_media_are_counted_for_the_sender(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ _, transport_room_id, client_id, user_id = await _make_room(session)+ await session.commit()++ transport = _transport(session_factory, client_id=client_id, user_id=user_id)+ await transport.send_message(+ transport_room_id, "one", sender_name="a", metered=True+ )+ await transport.send_message(+ transport_room_id, "two", sender_name="a", metered=True+ )+ await transport.send_media(+ transport_room_id,+ "blob://1",+ "report.pdf",+ "application/pdf",+ 2048,+ sender_name="a",+ msgtype="m.file",+ metered=True,+ )++ assert await self._usage(session_factory) == [("messages", client_id, 3)]++ async def test_platform_events_are_not_counted(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ # Reports, runtime state and receipts are how Switch works, not+ # something the tenant said, so they are not billed as messages.+ async with session_factory() as session:+ _, transport_room_id, client_id, user_id = await _make_room(session)+ await session.commit()++ transport = _transport(session_factory, client_id=client_id, user_id=user_id)+ await transport.send_event(+ transport_room_id, "com.switch.report.tool_call", {"tool": "Bash"}+ )++ assert await self._usage(session_factory) == []++ async def test_an_unmetered_send_is_stored_but_not_counted(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ # What Switch posts on a participant's behalf — a greeting, a command+ # reply, an automatic refusal — is not something it chose to say.+ async with session_factory() as session:+ room_id, transport_room_id, client_id, user_id = await _make_room(session)+ await session.commit()++ transport = _transport(session_factory, client_id=client_id, user_id=user_id)+ await transport.send_message(+ transport_room_id, "unavailable", sender_name="a", metered=False+ )+ await transport.send_media(+ transport_room_id,+ "blob://1",+ "report.pdf",+ "application/pdf",+ 2048,+ sender_name="a",+ msgtype="m.file",+ metered=False,+ )++ assert await self._usage(session_factory) == []+ async with session_factory() as session:+ stored = await session.scalars(+ select(Message).where(Message.room_id == room_id)+ )+ assert len(list(stored)) == 2++ async def test_the_count_survives_the_room(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ # Deleting a room cascades to its messages; it must not refund them.+ async with session_factory() as session:+ room_id, transport_room_id, client_id, user_id = await _make_room(session)+ await session.commit()++ transport = _transport(session_factory, client_id=client_id, user_id=user_id)+ await transport.send_message(+ transport_room_id, "spent", sender_name="a", metered=True+ )+ async with session_factory() as session:+ await session.execute(delete(Room).where(Room.id == room_id))+ await session.commit()++ assert await self._usage(session_factory) == [("messages", client_id, 1)]++class TestSending:async def test_a_message_becomes_a_row(self, session_factory: async_sessionmaker[AsyncSession]@@ -210,7 +325,10 @@ class TestSending:transport = _transport(session_factory, client_id=client_id, user_id=user_id)result = await transport.send_message(- transport_room_id, "hello", sender_name="agent one"+ transport_room_id,+ "hello",+ sender_name="agent one",+ metered=True,)async with session_factory() as session:@@ -239,10 +357,16 @@ class TestSending:transport = _transport(session_factory, client_id=client_id, user_id=user_id)first = await transport.send_message(- transport_room_id, "one", sender_name="agent one"+ transport_room_id,+ "one",+ sender_name="agent one",+ metered=True,)second = await transport.send_message(- transport_room_id, "two", sender_name="agent one"+ transport_room_id,+ "two",+ sender_name="agent one",+ metered=True,)async with session_factory() as session:@@ -266,6 +390,7 @@ class TestSending:"in the thread",sender_name="agent one",thread_root_id="root-1",+ metered=True,)async with session_factory() as session:@@ -293,6 +418,7 @@ class TestSending:sender_name="agent one",msgtype="m.file",caption="the report",+ metered=True,)async with session_factory() as session:@@ -362,7 +488,10 @@ class TestSending:transport = _transport(session_factory, client_id="c", user_id="@a:test")with pytest.raises(TransportError):await transport.send_message(- "!nowhere:test", "hello", sender_name="agent one"+ "!nowhere:test",+ "hello",+ sender_name="agent one",+ metered=True,)@@ -455,6 +584,7 @@ class TestMedia:session_factory=session_factory,room_store=RoomStore(),message_store=MessageStore(),+ usage_store=UsageStore(),media_store=MediaStore(),listener=_FakeListener(),invites=InviteBus(),@@ -513,7 +643,9 @@ class TestReceiving:) -> None:transport, listener, received, room, _ = await self._receiving(session_factory)- sent = await transport.send_message(room, "hello", sender_name="agent one")+ sent = await transport.send_message(+ room, "hello", sender_name="agent one", metered=True+ )await listener.announce(await _watched_room(transport))assert len(received.events) == 1@@ -540,7 +672,9 @@ class TestReceiving:listener = _FakeListener()writer = _transport(session_factory, client_id=client_id, user_id=user_id)- await writer.send_message(room, "said before anyone listened", sender_name="a")+ await writer.send_message(+ room, "said before anyone listened", sender_name="a", metered=True+ )received = _Received()reader = _transport(@@ -554,7 +688,7 @@ class TestReceiving:await listener.announce(switch_room_id)assert received.events == []- await writer.send_message(room, "said after", sender_name="a")+ await writer.send_message(room, "said after", sender_name="a", metered=True)await listener.announce(switch_room_id)await listener.announce(switch_room_id)@@ -574,6 +708,7 @@ class TestReceiving:12,sender_name="agent one",msgtype="m.file",+ metered=True,)await listener.announce(await _watched_room(transport))@@ -768,7 +903,9 @@ class TestOneClientCannotStallAnother:self._tasks.append(asyncio.create_task(transport.receive_forever()))switch_room_id = await _watched_room(transport)- await transport.send_message(room, "hello", sender_name="agent one")+ await transport.send_message(+ room, "hello", sender_name="agent one", metered=True+ )# The waker itself, rather than the fake's announce, which waits for# the reading it provokes.await transport._on_room_advanced(switch_room_id)@@ -799,7 +936,9 @@ class TestOneClientCannotStallAnother:self._tasks.append(asyncio.create_task(transport.receive_forever()))switch_room_id = await _watched_room(transport)- await transport.send_message(room, "hello", sender_name="agent one")+ await transport.send_message(+ room, "hello", sender_name="agent one", metered=True+ )await transport._on_room_advanced(switch_room_id)await transport._on_room_advanced(switch_room_id)await transport._on_room_advanced(switch_room_id)@@ -917,7 +1056,9 @@ class TestHearingYourOwnArrival:talker = _transport(session_factory, client_id=other_id, user_id=other_user)await talker.join_room(later)- await talker.send_message(later, "said before anyone joined", sender_name="a")+ await talker.send_message(+ later, "said before anyone joined", sender_name="a", metered=True+ )listener = _FakeListener()received = _Received()@@ -1003,7 +1144,10 @@ class TestDeliveryBindsTheRoomsTenant:switch_room_id = await _watched_room(transport)await transport.send_message(- transport_room_id, "hello", sender_name="agent one"+ transport_room_id,+ "hello",+ sender_name="agent one",+ metered=True,)await listener.announce(switch_room_id)@@ -1244,8 +1388,8 @@ class TestATransportActsInItsClientsTenant:self._tasks.append(asyncio.create_task(transport.receive_forever()))await _watched_room(transport)- await transport.send_message(mxid_a, "in a", sender_name="puppet")- await transport.send_message(mxid_b, "in b", sender_name="puppet")+ await transport.send_message(mxid_a, "in a", sender_name="puppet", metered=True)+ await transport.send_message(mxid_b, "in b", sender_name="puppet", metered=True)for room_id in room_ids:await listener.announce(room_id)@@ -1302,7 +1446,9 @@ class TestATransportActsInItsClientsTenant:tenant_id=tenant_id,)with pytest.raises(TransportError, match="is not a Switch room"):- await transport.send_message(elsewhere_mxid, "hello", sender_name="admin")+ await transport.send_message(+ elsewhere_mxid, "hello", sender_name="admin", metered=True+ )async def test_the_schema_forbids_a_client_row_in_another_tenants_room(@@ -1395,7 +1541,9 @@ class TestWhatIsMeasured:) -> None:transport, listener, room = await self._receiving(session_factory)- await transport.send_message(room, "hello", sender_name="agent one")+ await transport.send_message(+ room, "hello", sender_name="agent one", metered=True+ )await listener.announce(await _watched_room(transport))payloads = {p.name: p for p in _registry.collect()}@@ -1415,6 +1563,7 @@ class TestWhatIsMeasured:size=3,sender_name="agent one",msgtype="m.image",+ metered=True,)await listener.announce(await _watched_room(transport))@@ -1429,7 +1578,9 @@ class TestWhatIsMeasured:) -> None:transport, listener, room = await self._receiving(session_factory)- await transport.send_message(room, "hello", sender_name="agent one")+ await transport.send_message(+ room, "hello", sender_name="agent one", metered=True+ )await listener.announce(await _watched_room(transport))payload = next(@@ -1458,7 +1609,9 @@ class TestWhatIsMeasured:),)- await transport.send_message(room, "hello", sender_name="agent one")+ await transport.send_message(+ room, "hello", sender_name="agent one", metered=True+ )await listener.announce(await _watched_room(transport))# Swallowing the exception is what keeps the delivery loop alive for@@ -1481,7 +1634,10 @@ class TestWhatIsMeasured:with pytest.raises(Exception):await transport.send_message(- "!room-that-does-not-exist:test", "hello", sender_name="agent one"+ "!room-that-does-not-exist:test",+ "hello",+ sender_name="agent one",+ metered=True,)recorded = {payload.name for payload in _registry.collect()}@@ -1495,7 +1651,10 @@ class TestWhatIsMeasured:with pytest.raises(Exception):await transport.send_message(- "!room-that-does-not-exist:test", "hello", sender_name="agent one"+ "!room-that-does-not-exist:test",+ "hello",+ sender_name="agent one",+ metered=True,)payload = next(@@ -1582,7 +1741,9 @@ class TestBeingRemovedFromARoom:await _watched_room(member)# While a member, it hears the room.- await member.send_message(room, "while a member", sender_name="agent one")+ await member.send_message(+ room, "while a member", sender_name="agent one", metered=True+ )await listener.announce(room_id)assert [event.body for event in received.events] == ["while a member"]@@ -1593,7 +1754,9 @@ class TestBeingRemovedFromARoom:assert leaving[0] not in membersassert staying[0] in members- await member.send_message(room, "after removal", sender_name="agent one")+ await member.send_message(+ room, "after removal", sender_name="agent one", metered=True+ )await listener.announce(room_id)assert [event.body for event in received.events] == ["while a member"]@@ -1642,7 +1805,10 @@ class TestBeingRemovedFromARoom:provisioning = self._provisioning(session_factory, invites)await provisioning.kick_user(room, leaving[1])await member.send_message(- room, "said while it was out", sender_name="agent one"+ room,+ "said while it was out",+ sender_name="agent one",+ metered=True,)await listener.announce(room_id)@@ -1736,7 +1902,9 @@ class TestBeingRemovedFromARoom:await _watched_room(member)for i in range(4):- await member.send_message(room, f"line {i}", sender_name="agent one")+ await member.send_message(+ room, f"line {i}", sender_name="agent one", metered=True+ )await listener.announce(room_id)# The removal landed on the first delivery; the rest of the page is@@ -1893,7 +2061,9 @@ class TestBeingRemovedFromARoom:# More than one page, so the loop would come back for another.for i in range(_DELIVERY_PAGE + 25):- await member.send_message(room, f"line {i}", sender_name="agent one")+ await member.send_message(+ room, f"line {i}", sender_name="agent one", metered=True+ )await listener.announce(room_id)# The whole of page one, and none of page two.diff --git a/deploy/local/docker-compose.yml b/deploy/local/docker-compose.ymlindex 218f3e287..02aa39126 100644--- a/deploy/local/docker-compose.yml+++ b/deploy/local/docker-compose.yml@@ -111,6 +111,16 @@ services:depends_on:- mattermost+ # A mail catcher for invitation e-mails, started by `just local-cloud` only+ # (the `mail` profile keeps it out of `just up`). It accepts anything on+ # 1025 and shows it at http://localhost:8025; nothing is delivered onwards.+ mailpit:+ image: axllent/mailpit:latest+ profiles: ["mail"]+ ports:+ - "${SWITCH_BIND_ADDR:-127.0.0.1}:1025:1025"+ - "${SWITCH_BIND_ADDR:-127.0.0.1}:8025:8025"+volumes:pgdata:mmdata:diff --git a/deploy/local/standalone-docker-compose.yml b/deploy/local/standalone-docker-compose.ymlindex 9cfa0cc22..195966b2d 100644--- a/deploy/local/standalone-docker-compose.yml+++ b/deploy/local/standalone-docker-compose.yml@@ -217,6 +217,14 @@ services:SLACK_APP_CLIENT_ID: ${SLACK_APP_CLIENT_ID:-}SLACK_APP_CLIENT_SECRET: ${SLACK_APP_CLIENT_SECRET:-}SLACK_APP_SIGNING_SECRET: ${SLACK_APP_SIGNING_SECRET:-}+ DISCORD_APP_CLIENT_ID: ${DISCORD_APP_CLIENT_ID:-}+ DISCORD_APP_CLIENT_SECRET: ${DISCORD_APP_CLIENT_SECRET:-}+ DISCORD_APP_BOT_TOKEN: ${DISCORD_APP_BOT_TOKEN:-}+ DISCORD_APP_APPLICATION_ID: ${DISCORD_APP_APPLICATION_ID:-}+ # True/false flags, so bare keys for the reason given under LOG_FORMAT+ # below: `${VAR:-}` would hand them an empty string, which fails boot.+ DISCORD_APP_MESSAGE_CONTENT:+ DISCORD_APP_MEMBERS:# Observability and log format. Forwarded because this service names# every variable it passes, so without them here, setting any of these# in `.env` does nothing and the Helm chart is the only way to turndiff --git a/deploy/remote/helm/switch/templates/_helpers.tpl b/deploy/remote/helm/switch/templates/_helpers.tplindex 1c12f980e..b8b66116a 100644--- a/deploy/remote/helm/switch/templates/_helpers.tpl+++ b/deploy/remote/helm/switch/templates/_helpers.tpl@@ -62,6 +62,9 @@ MATTERMOST_USER_PASSWORD: {{ .Values.secrets.mattermostUserPassword | default .V{{- if .Values.switchCore.oidc.enabled }}GATEWAY_OIDC_CLIENT_SECRET: {{ required "secrets.gatewayOidcClientSecret is required when switchCore.oidc.enabled" .Values.secrets.gatewayOidcClientSecret | b64enc | quote }}{{- end }}+{{- if and .Values.switchCore.smtp.enabled .Values.switchCore.smtp.username }}+GATEWAY_SMTP_PASSWORD: {{ required "secrets.gatewaySmtpPassword is required when switchCore.smtp.username is set" .Values.secrets.gatewaySmtpPassword | b64enc | quote }}+{{- end }}{{- if .Values.secrets.otlpHeaders }}OTLP_HEADERS: {{ .Values.secrets.otlpHeaders | b64enc | quote }}{{- end }}@@ -69,6 +72,10 @@ OTLP_HEADERS: {{ .Values.secrets.otlpHeaders | b64enc | quote }}SLACK_APP_CLIENT_SECRET: {{ required "secrets.slackAppClientSecret is required when switchCore.slackApp.enabled" .Values.secrets.slackAppClientSecret | b64enc | quote }}SLACK_APP_SIGNING_SECRET: {{ required "secrets.slackAppSigningSecret is required when switchCore.slackApp.enabled" .Values.secrets.slackAppSigningSecret | b64enc | quote }}{{- end }}+{{- if .Values.switchCore.discordApp.enabled }}+DISCORD_APP_CLIENT_SECRET: {{ required "secrets.discordAppClientSecret is required when switchCore.discordApp.enabled" .Values.secrets.discordAppClientSecret | b64enc | quote }}+DISCORD_APP_BOT_TOKEN: {{ required "secrets.discordAppBotToken is required when switchCore.discordApp.enabled" .Values.secrets.discordAppBotToken | b64enc | quote }}+{{- end }}{{- end }}{{/*@@ -610,6 +617,45 @@ Include with `nindent 12`.value: "false"{{- end }}{{- end }}+{{- $signupMode := .Values.switchCore.signup.mode }}+{{- if not (has $signupMode (list "default_tenant" "invite_only" "open")) }}+{{- fail (printf "switchCore.signup.mode must be one of default_tenant, invite_only, open. Got %q." $signupMode) }}+{{- end }}+- name: GATEWAY_SIGNUP_MODE+ value: {{ $signupMode | quote }}+- name: GATEWAY_MAX_WORKSPACES_PER_USER+ value: {{ .Values.switchCore.signup.maxWorkspacesPerUser | quote }}+- name: GATEWAY_TENANT_CHOICE_ENABLED+ value: {{ .Values.switchCore.tenantChoiceEnabled | quote }}+{{- with .Values.switchCore.smtp }}+{{- if .enabled }}+{{- if not $.Values.switchCore.frontendBaseUrl }}+{{- fail "switchCore.frontendBaseUrl is required when switchCore.smtp.enabled — invitation e-mails link to the dashboard at that origin." }}+{{- end }}+{{- if not (has .tls (list "starttls" "tls" "none")) }}+{{- fail (printf "switchCore.smtp.tls must be one of starttls, tls, none. Got %q." .tls) }}+{{- end }}+- name: GATEWAY_SMTP_HOST+ value: {{ required "switchCore.smtp.host is required when smtp.enabled" .host | quote }}+- name: GATEWAY_SMTP_PORT+ value: {{ .port | quote }}+- name: GATEWAY_SMTP_TLS+ value: {{ .tls | quote }}+- name: GATEWAY_SMTP_FROM+ value: {{ required "switchCore.smtp.from is required when smtp.enabled" .from | quote }}+- name: GATEWAY_INVITE_EMAILS_PER_DAY+ value: {{ .emailsPerDayPerWorkspace | quote }}+{{- if .username }}+- name: GATEWAY_SMTP_USERNAME+ value: {{ .username | quote }}+- name: GATEWAY_SMTP_PASSWORD+ valueFrom:+ secretKeyRef:+ name: {{ include "switch.secretName" $ }}+ key: GATEWAY_SMTP_PASSWORD+{{- end }}+{{- end }}+{{- end }}- name: GATEWAY_COOKIE_SECUREvalue: {{ .Values.switchCore.cookieSecure | quote }}- name: SWITCH_LOG_LEVEL@@ -687,6 +733,34 @@ Include with `nindent 12`.name: {{ include "switch.secretName" . }}key: SLACK_APP_SIGNING_SECRET{{- end }}+{{- if .Values.switchCore.discordApp.enabled }}+{{- if not .Values.switchCore.slackApp.enabled }}+- name: MESSAGING_PUBLIC_URL+ value: {{ required "switchCore.discordApp.messagingPublicUrl is required when switchCore.discordApp.enabled" .Values.switchCore.discordApp.messagingPublicUrl | quote }}+{{- end }}+- name: DISCORD_APP_CLIENT_ID+ value: {{ required "switchCore.discordApp.clientId is required when switchCore.discordApp.enabled" .Values.switchCore.discordApp.clientId | quote }}+- name: DISCORD_APP_APPLICATION_ID+ value: {{ required "switchCore.discordApp.applicationId is required when switchCore.discordApp.enabled" .Values.switchCore.discordApp.applicationId | quote }}+- name: DISCORD_APP_CLIENT_SECRET+ valueFrom:+ secretKeyRef:+ name: {{ include "switch.secretName" . }}+ key: DISCORD_APP_CLIENT_SECRET+- name: DISCORD_APP_BOT_TOKEN+ valueFrom:+ secretKeyRef:+ name: {{ include "switch.secretName" . }}+ key: DISCORD_APP_BOT_TOKEN+{{- if .Values.switchCore.discordApp.messageContent }}+- name: DISCORD_APP_MESSAGE_CONTENT+ value: "true"+{{- end }}+{{- if .Values.switchCore.discordApp.members }}+- name: DISCORD_APP_MEMBERS+ value: "true"+{{- end }}+{{- end }}{{- end }}{{/*diff --git a/deploy/remote/helm/switch/values.yaml b/deploy/remote/helm/switch/values.yamlindex d6fde02fa..8f1f4de1e 100644--- a/deploy/remote/helm/switch/values.yaml+++ b/deploy/remote/helm/switch/values.yaml@@ -102,6 +102,9 @@ secrets:mattermostUserPassword: ""# Gateway OIDC client secret (required when switchCore.oidc.enabled).gatewayOidcClientSecret: ""+ # SMTP relay password for invitation e-mails (required when+ # switchCore.smtp.enabled and switchCore.smtp.username is set).+ gatewaySmtpPassword: ""# `key=value` pairs, comma-separated, sent on every OTLP request. Here rather# than beside the other observability settings because the documented use for# it is a collector's API key, and every other credential in this chart comes@@ -112,6 +115,12 @@ secrets:# a post by anyone who learned the URL.slackAppClientSecret: ""slackAppSigningSecret: ""+ # Distributed Discord app (required when switchCore.discordApp.enabled). The+ # bot token is the application-wide credential the single shared Gateway+ # connection authenticates with — it is deployment config, not per install, so+ # it lives here and is never stored against an install or revoked on disconnect.+ discordAppClientSecret: ""+ discordAppBotToken: ""# ── Switch Core (FastAPI) ─────────────────────────────────────────────────────switchCore:@@ -220,6 +229,43 @@ switchCore:requireEmailVerified: true# Set false to disable password login entirely (OIDC-only).passwordLoginEnabled: true+ # Where someone signing in through the IdP for the first time lands. Who may+ # sign in at all is the IdP's decision; this decides what they get.+ # default_tenant — joined to the deployment's one pre-existing workspace+ # invite_only — no workspace until they accept an invitation; only an+ # operator may create one+ # open — no workspace, and they may create their own, up to+ # maxWorkspacesPerUser+ signup:+ mode: default_tenant+ # Most workspaces one person may ever create (operators are exempt); 0+ # turns self-service creation off. Applies in every mode but invite_only,+ # which allows none.+ maxWorkspacesPerUser: 3+ # Answer a person with several workspaces and none selected with a 409 that+ # lists them, rather than a 403. The gateway UI does not need it; turn it on+ # once every API client authenticating against this deployment handles it.+ tenantChoiceEnabled: false+ # Invitation e-mails. When enabled, an invitation addressed to an e-mail is+ # sent there through this SMTP relay (SES SMTP, Postmark, a company relay —+ # anything that speaks SMTP). Off, the invitation is still created and the+ # admin is told to share the link themselves. Requires frontendBaseUrl, which+ # the link in the e-mail points at.+ smtp:+ enabled: false+ host: ""+ # 587 with starttls, 465 with tls; none is for a relay on a trusted network.+ port: 587+ tls: starttls+ # Leave empty for a relay that needs no login; set it and+ # secrets.gatewaySmtpPassword otherwise.+ username: ""+ # The From address, e.g. "Switch <invites@your-domain>".+ from: ""+ # Addressed invitations one workspace may send per 24 hours. With sign-up+ # open anyone can own a workspace, so this keeps the relay from being used+ # to mail arbitrary addresses. Operators are exempt.+ emailsPerDayPerWorkspace: 50# The distributed Slack app: the one a customer installs into their workspace# by clicking a button, as opposed to an app an operator registers themselves# and pastes a bot token for. Off unless you have registered such an app and@@ -238,6 +284,30 @@ switchCore:# move every deeplink along with it.messagingPublicUrl: ""clientId: ""+ # The distributed Discord app: one application we register that a customer adds+ # to their server by clicking "Add to Server", never seeing a token — as+ # opposed to a self-registered app an operator pastes a bot token for. Off+ # unless you have registered and are distributing such an app.+ #+ # Unlike Slack there is no inbound webhook: messages and interactions arrive+ # over the Gateway, so the only public route is the OAuth callback under+ # /messaging. Enabling it still commits the deployment to being reachable at+ # messagingPublicUrl (the callback origin) — add /messaging to+ # ingress.agentApiPaths as well. The client secret and bot token are supplied+ # through secrets.discordAppClientSecret / secrets.discordAppBotToken.+ discordApp:+ enabled: false+ # Public origin Discord sends the OAuth callback to — scheme + host, https,+ # no path. The same deployment-wide origin as slackApp.messagingPublicUrl; if+ # both apps are enabled the Slack value is used and this one is ignored.+ messagingPublicUrl: ""+ clientId: ""+ applicationId: ""+ # Privileged Gateway intents, each off by default and requiring Discord+ # verification past ~100 guilds (counted across every tenant). Off is+ # mention-only operation; leave both false unless the app is verified.+ messageContent: false+ members: false# Bearer-token resolution runs before every authenticated request and agents# beat continuously, so a successful resolution is memoised in process for# this many seconds. Only successes are cached — an unknown or revoked tokendiff --git a/docs/TELEMETRY.md b/docs/TELEMETRY.mdindex 56a8f2f61..c1407d88e 100644--- a/docs/TELEMETRY.md+++ b/docs/TELEMETRY.md@@ -118,7 +118,7 @@ id, no IP field, no Switch identity.| `onboarding_step_started` | `step_id`, one of exactly 4: `addServer`, `agentProviders`, `onboardAgents`, `createRoom` || `onboarding_checklist_dismissed` | *(no fields)* || `onboarding_completed` | *(no fields)* |-| `add_server_step` | `step`: `choose` / `local` / `remoteHost` / `external` / `signIn` / `linkAccounts` · `choice`: `none` / `local` / `remoteHost` / `external` |+| `add_server_step` | `step`: `choose` / `local` / `remoteHost` / `external` / `signIn` / `linkAccounts` · `choice`: `none` / `local` / `remoteHost` / `external` / `cloud` · `first_run`: `true` / `false` — whether the same step was reached on a fresh install rather than from the Add server dialog |**Agents and sessions**diff --git a/docs/old/GATEWAY_OIDC_SETUP.md b/docs/old/GATEWAY_OIDC_SETUP.mdindex 30e2340eb..a46aeca87 100644--- a/docs/old/GATEWAY_OIDC_SETUP.md+++ b/docs/old/GATEWAY_OIDC_SETUP.md@@ -138,6 +138,75 @@ Three things worth knowing before your first login:applies to a new account, not to one linked as above. Promote it by handafterwards if it needs elevated access.+### Which workspace a new account lands in++`GATEWAY_SIGNUP_MODE` decides this. The Helm chart sets it from+`switchCore.signup.mode`.++| Mode | A new account | Creating a workspace |+| --- | --- | --- |+| `default_tenant` (default) | joins the default workspace as a member | allowed, up to the cap |+| `open` | joins nothing, and is asked to create a workspace or accept an invitation | allowed, up to the cap |+| `invite_only` | joins nothing, and can get in only by accepting an invitation | operators only |++The cap is `GATEWAY_MAX_WORKSPACES_PER_USER`+(`switchCore.signup.maxWorkspacesPerUser`, default 3; `0` turns self-service+creation off). It counts the workspaces a person has created, not ones they+were invited to, and handing one over does not give the allowance back.+Deployment operators are exempt.++Your identity provider still decides who can sign in at all. With `open`,+anyone the provider lets through can create a workspace. If the server should+not be open to the world, use a provider that restricts sign-in. Changing the+mode does not affect existing accounts; they keep their memberships.++A person who belongs to several workspaces goes back to the one they used last+when they sign in, as long as they are still a member of it. If there is no+such workspace, the dashboard asks them to choose. Other API clients get a 403+on workspace routes until they pick one with `POST /tenants/{id}/switch`. If+`GATEWAY_TENANT_CHOICE_ENABLED` (`switchCore.tenantChoiceEnabled`) is set, they+get a 409 listing the workspaces instead.++### Invitation e-mails++A workspace admin can invite someone by e-mail address from the Workspace+page. With an SMTP relay configured, Switch sends that person an e-mail with a+link. They open it, sign in (or sign up through the provider), accept, and are+a member of the workspace. Any relay that speaks SMTP works: Amazon SES's SMTP+interface, Postmark, SendGrid, or your own.++| Variable | Helm value | Meaning |+| --- | --- | --- |+| `GATEWAY_SMTP_HOST` | `switchCore.smtp.host` (and `smtp.enabled: true`) | the relay; setting it turns e-mail on |+| `GATEWAY_SMTP_PORT` | `switchCore.smtp.port` | default 587 |+| `GATEWAY_SMTP_TLS` | `switchCore.smtp.tls` | `starttls` (default, port 587), `tls` (port 465), or `none` for a relay on a trusted network |+| `GATEWAY_SMTP_USERNAME` / `GATEWAY_SMTP_PASSWORD` | `switchCore.smtp.username` / `secrets.gatewaySmtpPassword` | set both or neither |+| `GATEWAY_SMTP_FROM` | `switchCore.smtp.from` | the From address, e.g. `Switch <invites@your-domain>` |+| `GATEWAY_INVITE_EMAILS_PER_DAY` | `switchCore.smtp.emailsPerDayPerWorkspace` | default 50 |++The link points at `FRONTEND_BASE_URL` (`switchCore.frontendBaseUrl`), which is+required once a host is set. The server refuses to start without it, rather+than building links from whatever `Host` header a request arrived with. The+token travels in the link's fragment (`/invite#token=…`), which browsers do+not send to servers, so it stays out of access logs.++The invitation is created whether or not the e-mail goes out, and the admin+always sees what happened:++- **Sent**: "Invitation e-mailed to …". The link is shown as well.+- **No relay configured**: the invitation is created, the dashboard says no+ e-mail was sent and shows the link to share, and the server logs a warning.+- **The relay refused or could not be reached**: the same, with the error in+ the server log.++An invitation addressed to an e-mail can be accepted only by someone signed in+with that address. Each workspace may send at most+`GATEWAY_INVITE_EMAILS_PER_DAY` addressed invitations in 24 hours; past that+the dashboard asks the admin to try tomorrow or share a link. This matters+with `open` sign-up, where anyone can own a workspace and would otherwise be+able to use your relay to mail any address. Operators are exempt, and link+invitations are not counted.+## Setting up WorkOS as the providerThis is the part that will otherwise burn an afternoon. WorkOS exposes twodiff --git a/docs/old/LOCAL_DEVELOPMENT.md b/docs/old/LOCAL_DEVELOPMENT.mdindex 13c1aac4a..20225b911 100644--- a/docs/old/LOCAL_DEVELOPMENT.md+++ b/docs/old/LOCAL_DEVELOPMENT.md@@ -177,10 +177,49 @@ and enter `http://localhost:5173` as the Gateway URL and`http://localhost:8000` as the API URL — with `just gateway-dev` alreadyrunning.+## A local Switch Cloud++A shared deployment runs whatever was last deployed to it, which is often+older than the branch you are testing. Switch Console can instead treat a+server run from your checkout as **Switch Cloud**, so the first-run Cloud+path, invite links and invitation e-mails can all be tried against your+code:++```bash+just up # Postgres and the rest, as usual+just local-cloud # switch-core on :8000, plus a mail catcher+just local-cloud-console # the Console, with Switch Cloud at http://localhost:8000+```++- **Sign-in** is by password. The gateway admin from `.env` works, and+ `just local-cloud-user <email> "<name>" <password>` adds more accounts.+ Every account made this way joins the admin's workspace; create another+ workspace in the Console to invite people into, or to open to a domain.+- **Invitation e-mails** are sent to Mailpit, which keeps them rather than+ delivering them: read them at `http://localhost:8025`. Their links point at+ `http://localhost:8000`, so pasting one into the Console's "Paste your+ invite link" finds the local Cloud. That comes from `FRONTEND_BASE_URL`,+ which `just local-cloud` sets to `:8000`. The dashboard's own links follow+ it, so in this mode they open switch-core's JSON rather than the dashboard.+- **Joining by domain** is offered only for the domain of the admin's own+ address: `switch.local` for the default admin. Give test accounts+ addresses there.+- **The Cloud address** must be https, except for `localhost`, `127.0.0.1`+ and `[::1]`, which may be plain http for exactly this. The Console matches+ its Switch Cloud entry by address, so an install that has signed in to the+ real Cloud gets a second "Switch Cloud" server for the local one rather+ than reusing it.+- **The Console's data** (servers, sign-ins, its database) lives in its own+ directory, `switchdash-local-cloud` under the system's app-data folder,+ rather than the one every other dev build shares. Branches that number+ their migrations differently cannot break each other's database this+ way. Delete that directory to start the Console from scratch.+## Other useful recipes| Command | What it does || --- | --- |+| `just local-cloud` / `just local-cloud-console` | Run switch-core as a stand-in for Switch Cloud, and the Console pointed at it (see above) || `just format` / `just check` | Format with ruff / lint-check in CI mode (no changes) || `just typecheck` | mypy over `core/switch_core/` and `connectors/` || `just test` / `just test -k name` | Run the test suite / a single test |diff --git a/docs/old/bridges/DISCORD_DISTRIBUTED_APP.md b/docs/old/bridges/DISCORD_DISTRIBUTED_APP.mdnew file mode 100644index 000000000..35345f21f--- /dev/null+++ b/docs/old/bridges/DISCORD_DISTRIBUTED_APP.md@@ -0,0 +1,214 @@+# The distributed Discord app++`DISCORD_SETUP.md` describes the app **an operator registers for themselves**:+they create it, add its bot to their own server with a token they hold, and+paste that token into Switch. This page describes the other one — the app **we**+register and distribute, which a customer installs by clicking **Add to Server**+and which never requires them to see a token at all.++They are two separate Discord applications and they will both exist. Nothing+here replaces the other page.++The install connects a Discord server (**guild**) to a tenant that **already+exists**. Creating a tenant is Switch Console's job and is not reachable from+Discord: the flow begins with an authenticated admin inside the tenant they are+installing into, so no amount of clicking in Discord brings a tenant into being.++## Why it cannot be the same app++The self-registered app opens its **own** Gateway connection, scoped to one+guild, using a bot token the operator holds. That is the right shape for a+self-hosted operator and the wrong shape here, because a distributed app has no+per-customer token to open a per-customer connection with:++- **Discord grants one bot token per application, not one per install.** Adding+ the bot to a guild returns the *guild* (so we learn its id) and nothing we+ need to keep — there is no per-guild credential to capture or store. The bot+ authenticates to every guild with the single application bot token.+- **One bot token means one connection.** A connection opened with that token+ receives every installing guild's events; it cannot be subscribed to one+ tenant's guilds. So a single connection **multiplexes every tenant's+ traffic**, and each inbound event is routed to a tenant by the `guild_id` it+ carries. That is not a choice — with one bot token it is the only shape.++So the delivery mechanism is the *same* as the self-registered app — an outbound+Gateway WebSocket, no inbound webhook — but the distributed app runs **one+shared connection for all tenants** instead of one per guild, and asks the+customer for nothing. Everything below follows from that.++## The one public URL++Discord delivers both messages and interactions over the Gateway, so unlike the+distributed Slack app there is **no events endpoint, no interactions endpoint,+and no request signature to verify**. The only route that must be reachable from+the internet is the **OAuth callback**:++| Discord Developer Portal setting | Path |+| --- | --- |+| **OAuth2 → Redirects** | `/messaging/discord/oauth/callback` |++The host is **`MESSAGING_PUBLIC_URL`**: scheme and host, no path, https only,+and the origin Discord itself sends the browser back to.++It is deliberately not `GATEWAY_PUBLIC_URL`. That one is the host a *person*+lands on following an "Open in Switch Console" deeplink, and on many deployments+it is reachable only over a private network — which is fine for a person and+useless as an OAuth redirect. Pointing it at an internet-facing host to satisfy+Discord would move every deeplink to that host as a side effect, so the two are+separate settings and a deployment may set either, both, or neither.++`/messaging` is a public prefix in its own right: it is unauthenticated by+nature, because an OAuth callback arrives before there is anything to+authenticate against. It is deliberately not `/gateway` — that prefix is+cookie-authenticated and is not routed to this application from the outside — and+deliberately not `/oauth`, which already belongs to agents authenticating *to*+Switch and would collide in name only, confusingly.++Reaching it from the internet needs the prefix added in two places: the+application's own public-path list, and the deployment's ingress path allowlist.++## Registering the app++Unlike Slack, Discord verifies no Request URL on save (there is none), so the+app can be created and its credentials collected before the callback endpoint is+live. The callback only has to be reachable by the time a customer installs.++1. [Discord Developer Portal](https://discord.com/developers/applications) →+ **New Application**, in an account we control. Name it (e.g. "Agent Switch").+2. **General Information → Application ID.** This is `DISCORD_APP_APPLICATION_ID`.+3. **OAuth2 → Client ID and Client Secret.** These are+ `DISCORD_APP_CLIENT_ID` and `DISCORD_APP_CLIENT_SECRET`, and are what exchange+ an install code for the guild the app was added to. Add the redirect URL from+ the table above under **OAuth2 → Redirects** — Discord compares it byte for+ byte against the one the install flow sends, so a trailing slash on one side+ is a refused install with a message that does not say so.+4. **Bot → Token.** This is `DISCORD_APP_BOT_TOKEN`. There is exactly one, it+ belongs to the application rather than to any install, and it is deployment+ configuration — it is never stored per install and never revoked when a+ customer disconnects.+5. **Installation → Activate public distribution.** This is what makes the app+ installable outside our own account and produces the *Add to Server* URL. For+ a private test guild you can skip it and install with the URL directly.++There is no slash-command step in the portal: the distributed app registers its+commands **globally**, once for the application, from code at boot (see below).++## The contract this app requests++The *Add to Server* URL asks for two OAuth scopes and a single least-privilege+permission integer, and sends the browser back to the callback. These three+values are the promise the running system has to keep: the scopes it requests+are the scopes the code asks for, the permission integer is the one the code+pins, and the redirect is the path this application serves. Nothing checks them+at runtime — Discord simply refuses a redirect that does not match, and a+permission the code needs but the URL never asked for surfaces as a customer's+bot silently unable to do its job.++So they are pinned in code and here, and a test compares the two. Substitute the+host in `redirect_uri`; `permissions` is a decimal bitfield and is exact.++```json+{+ "scopes": ["bot", "applications.commands"],+ "permissions": "310043053136",+ "redirect_uri": "https://HOST/messaging/discord/oauth/callback"+}+```++`applications.commands` is what lets Switch register its in-room commands as+native Discord slash commands. The permission integer is the sum of exactly the+bits the adapter uses, and nothing more:++| Permission | Bit | Why the adapter needs it |+| --- | --- | --- |+| View Channels | `1 << 10` | See the channels in the guild. |+| Send Messages | `1 << 11` | Post agent replies. |+| Create Public Threads | `1 << 35` | Open a thread off a message when a room maps to one. |+| Send Messages in Threads | `1 << 38` | Reply inside a thread. |+| Manage Webhooks | `1 << 29` | Mint the per-channel webhook agents post under — without it agents cannot appear under their own names. |+| Manage Channels | `1 << 4` | Provision access to a channel (`set_permissions`, private-room creation). |+| Manage Roles | `1 << 28` | Give each agent a mentionable role so its name completes when you type `@`. |+| Read Message History | `1 << 16` | Reply in context within a thread. |+| Attach Files | `1 << 15` | Relay agent attachments. |+| Add Reactions | `1 << 6` | Mark the message an agent is working on. |++Slash commands need no permission bit — they come from the `applications.commands`+scope. Editing and deleting the bot's own webhook messages needs no Manage+Messages. If you build the URL by hand in **OAuth2 → URL Generator**, selecting+these boxes produces the same integer.++## Three things left out on purpose++**The Message Content intent.** Reading arbitrary message text is a *privileged*+gateway intent, and requesting it while unapproved does not degrade gracefully —+Discord closes the whole connection with code 4014. So the intent is requested+conditionally, controlled by `DISCORD_APP_MESSAGE_CONTENT` and **defaulting+off**. Off, the connection opens fine and content still arrives for the cases the+intent is not needed for — messages that mention the bot and the bot's own+messages — which is exactly mention-only operation. On (once approved), agents+see all message content. Verification is *per application*, not per tenant, and+its ~100-guild threshold counts the total guilds across **every** tenant, so in+the distributed model the app crosses it quickly and verification is worth+starting early rather than deferring.++**Direct messages.** A Discord DM carries no guild id, so it cannot be+attributed to a tenant. DM events are dropped explicitly — never silently — and+the shared connection does not request DM message intents. Attributing a DM (for+example by the sender's single shared installed guild) is deferred, and would+still have to refuse the ambiguous case of a user present in two tenants' guilds.++**Per-guild slash commands.** The self-registered app registers its commands+per guild, because each of its bridges is scoped to one guild. The distributed+app registers them **globally**, once for the application, and routes each+invocation by the guild id it carries — there is no per-install registration+step and no registration traffic that grows with the number of guilds. The cost+is that a command-set change takes minutes to propagate rather than applying+immediately.++## What a customer's install produces++One row in `messaging_installs`: the guild it was installed into (as+`external_workspace_id`), a **null** `encrypted_bot_token` — a Discord install+stores no credential, because the bot token is deployment configuration and not+this install's to hold — the scopes Discord approved, and the tenant and user+who initiated it. `(platform, external_workspace_id)` is unique across the whole+deployment, because an inbound event carries a guild id and no tenant — a guild+claimed by two tenants would be an event with two possible destinations. A+second tenant attempting to claim an already-installed guild is refused by the+database.++Disconnecting ends that row and detaches its rooms, but **revokes no token**:+the credential is the application's, shared by every install, and is never ended+on one customer's disconnect.++## A bridge reaches only its own guild++The shared bot is in every tenant's guild, so it can see every tenant's+channels. Inbound traffic is routed by guild; outbound traffic goes wherever a+room is bound, and a room can be bound to an existing channel by id — when it+is created with a channel id, or moved onto a bridge with one. So the bridge+refuses a channel outside its own guild at both, and every channel lookup the+bridge makes refuses one as well, so nothing is posted to another guild even if+a room names its channel.++Which guild a bridge serves is fixed by its install, because the bridge's own+config is not proof of it: a shared bridge names a guild and nothing more, and+the shared bot would reach whichever one it named. So a shared bridge is made+only by installing the app — `POST /collaborations` refuses+`event_delivery: shared` — its guild cannot be changed by an edit, and before+one starts Switch checks that its tenant holds the live install of that guild.+A bridge that fails the check does not start, and the error says why.++## Linking an account before speaking++A new install reaches Discord as soon as its bridge starts: each bridge on the+shared connection is handed it then, not when its server's first message+arrives. So someone can find themselves in the server's member list and link+their Discord account straight after **Add to Discord**, before anyone has+said anything. The search matches the start of a username or nickname and+needs no privileged intent.++A member search is a message on the shared connection, and every tenant's+searches share it. Searches are capped at 60 a minute across the deployment;+past that, one is refused with a 429 saying how long to wait, rather than held+until it times out.diff --git a/docs/old/multi-tenancy-phase2-tenants.md b/docs/old/multi-tenancy-phase2-tenants.mdindex 65f6ae5b2..bbdf7d088 100644--- a/docs/old/multi-tenancy-phase2-tenants.md+++ b/docs/old/multi-tenancy-phase2-tenants.md@@ -1,10 +1,13 @@# Phase 2: several workspaces per person-Status: design, not built. Covers `CHOO-2723` (several memberships),-`CHOO-2722` (the tenant API and invitations), `CHOO-2724` (joining by email-domain) and `CHOO-2726` (how anyone becomes an administrator). They are four-tickets and one design: each is a different question about the same object,-and answering them separately produces four answers that do not fit together.+Status: built, except joining by email domain (§6), which is deferred. Covers+`CHOO-2723` (several memberships), `CHOO-2722` (the tenant API and+invitations), `CHOO-2724` (joining by email domain) and `CHOO-2726` (how anyone+becomes an administrator). They are four tickets and one design: each is a+different question about the same object, and answering them separately+produces four answers that do not fit together. §9a records how sign-up was+closed off afterwards. As everywhere in these notes, where this page and the+code disagree, the code is right.Phase 1 built the boundary. This phase is about crossing it deliberately —letting one person belong to several tenants, and giving them a way to create,@@ -230,6 +233,15 @@ three together take the workspace.`uses_remaining`, `revoked_at`, `created_by`, and a hash of the token ratherthan the token. Expiry and revocation are not optional.+**An addressed invitation is also e-mailed, when the deployment has a relay.**+The e-mail is delivery on top of the invitation, not a condition of it: the+invitation is minted first and stands if sending fails or no relay is+configured, and the create response reports which of those happened so the+admin can share the link instead. Only the plaintext token in that one+response can build the link, so a resend is a revoke and a new invitation. A+per-workspace daily cap on addressed invitations keeps self-service sign-up+from turning the relay into a way to mail arbitrary addresses.+**Accepting runs in its own tenant-bound session.** The request session isalready stamped with the caller's current workspace; inserting a membership fora different one on it is refused by the policy, and rebinding it raises. This@@ -332,6 +344,38 @@ that exists still costs its fan-out whether or not anyone uses it, and nothingreclaims an abandoned one — the cap bounds how many a person can open, not howmany a deployment ends up carrying.+## 9a. Sign-up, as built++§9's quota question and the path in for someone new were closed together.++- **`GATEWAY_SIGNUP_MODE`** decides what the OIDC callback does with an+ account it provisions. `default_tenant` (the default, and the behaviour+ before this) places it in tenant zero. `open` and `invite_only` place it+ nowhere: the person arrives with no workspace, and either creates one or+ accepts an invitation. Linking a verified email to an existing account+ follows the same rule. Password accounts are made by an operator and are+ unaffected.+- **Creating a workspace** is refused in `invite_only` for everyone but a+ deployment operator. In the other modes it is bounded by+ `GATEWAY_MAX_WORKSPACES_PER_USER`, as above. Operators are exempt.+ A taken slug gets a short random suffix rather than a 409, which would tell+ the caller a workspace of that name exists.+- **Signing in picks a workspace** rather than minting a null claim: the one+ last used, if the person still belongs to it, else their only one, else none.+ The last-used workspace is `last_tenant_id` in `users.metadata`, written by+ switching, creating and accepting. The claim is chosen from current+ memberships every time, so signing in still clears a stale selection.+- **Creating and accepting switch you in.** Both re-mint the session cookie+ for the workspace they land on, as `/tenants/{id}/switch` does.+- **`GET /auth/session`** reports what tenant resolution would decide for this+ cookie — `ready`, `needs_selection` or `needs_workspace` — with the caller's+ memberships and whether they may create a workspace. It answers the callers+ `/auth/me` refuses, which is what the dashboard needs to route someone with+ no workspace, or several and none chosen. `/auth/me` is unchanged.+- **Messaging app installs** are workspace administration+ (`require_tenant_admin`), not the operator bit: on a self-sign-up server+ nobody who runs a workspace is an operator.+## 10. Done when- One person holds memberships in two workspaces, and a request acts indiff --git a/docs/old/multi-tenancy.md b/docs/old/multi-tenancy.mdindex 6b9d55065..d4ca19351 100644--- a/docs/old/multi-tenancy.md+++ b/docs/old/multi-tenancy.md@@ -1,7 +1,10 @@# Multi-tenancy: design and planStatus: the design, plus the order of work it proposed. Phases 0 and 1 of §8-have since been built; the phases after them have not. Read this for the+have since been built, and most of Phase 2: several workspaces per person,+per-workspace roles, invitations by link, and self-service sign-up behind+`GATEWAY_SIGNUP_MODE` (see `multi-tenancy-phase2-tenants.md`, §9a). Joining by+email domain and per-tenant agent registration credentials have not. Read this for thereasoning and the shape, and the code for what actually exists — where the twodisagree, the code is right and this page is the record of what was intended.diff --git a/gateway/package-lock.json b/gateway/package-lock.jsonindex ff023dfe4..9eea52167 100644--- a/gateway/package-lock.json+++ b/gateway/package-lock.json@@ -20,13 +20,68 @@"react-router": "^7.14.0"},"devDependencies": {+ "@testing-library/dom": "^10.4.2",+ "@testing-library/react": "^16.3.3","@types/react": "^19.1.0","@types/react-dom": "^19.1.0","@vitejs/plugin-react": "^4.4.1",+ "jsdom": "^29.1.1","typescript": "~5.8.0",- "vite": "^6.3.0"+ "vite": "^6.3.0",+ "vitest": "^3.2.7"}},+ "node_modules/@asamuzakjp/css-color": {+ "version": "5.1.11",+ "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-5.1.11.tgz",+ "integrity": "sha512-KVw6qIiCTUQhByfTd78h2yD1/00waTmm9uy/R7Ck/ctUyAPj+AEDLkQIdJW0T8+qGgj3j5bpNKK7Q3G+LedJWg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@asamuzakjp/generational-cache": "^1.0.1",+ "@csstools/css-calc": "^3.2.0",+ "@csstools/css-color-parser": "^4.1.0",+ "@csstools/css-parser-algorithms": "^4.0.0",+ "@csstools/css-tokenizer": "^4.0.0"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },+ "node_modules/@asamuzakjp/dom-selector": {+ "version": "7.1.1",+ "resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-7.1.1.tgz",+ "integrity": "sha512-67RZDnYRc8H/8MLDgQCDE//zoqVFwajkepHZgmXrbwybzXOEwOWGPYGmALYl9J2DOLfFPPs6kKCqmbzV895hTQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@asamuzakjp/generational-cache": "^1.0.1",+ "@asamuzakjp/nwsapi": "^2.3.9",+ "bidi-js": "^1.0.3",+ "css-tree": "^3.2.1",+ "is-potential-custom-element-name": "^1.0.1"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },+ "node_modules/@asamuzakjp/generational-cache": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/@asamuzakjp/generational-cache/-/generational-cache-1.0.1.tgz",+ "integrity": "sha512-wajfB8KqzMCN2KGNFdLkReeHncd0AslUSrvHVvvYWuU8ghncRJoA50kT3zP9MVL0+9g4/67H+cdvBskj9THPzg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },+ "node_modules/@asamuzakjp/nwsapi": {+ "version": "2.3.9",+ "resolved": "https://registry.npmjs.org/@asamuzakjp/nwsapi/-/nwsapi-2.3.9.tgz",+ "integrity": "sha512-n8GuYSrI9bF7FFZ/SjhwevlHc8xaVlb/7HmHelnc/PZXBD2ZR49NnN9sMMuDdEGPeeRQ5d0hqlSlEpgCX3Wl0Q==",+ "dev": true,+ "license": "MIT"+ },"node_modules/@babel/code-frame": {"version": "7.29.7","resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz",@@ -315,6 +370,19 @@"node": ">=6.9.0"}},+ "node_modules/@bramus/specificity": {+ "version": "2.4.2",+ "resolved": "https://registry.npmjs.org/@bramus/specificity/-/specificity-2.4.2.tgz",+ "integrity": "sha512-ctxtJ/eA+t+6q2++vj5j7FYX3nRu311q1wfYH3xjlLOsczhlhxAg2FWNUXhpGvAw3BWo1xBcvOV6/YLc2r5FJw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "css-tree": "^3.0.0"+ },+ "bin": {+ "specificity": "bin/cli.js"+ }+ },"node_modules/@codemirror/autocomplete": {"version": "6.20.3","resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-6.20.3.tgz",@@ -423,6 +491,146 @@"w3c-keyname": "^2.2.4"}},+ "node_modules/@csstools/color-helpers": {+ "version": "6.1.1",+ "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-6.1.1.tgz",+ "integrity": "sha512-gLNsunvwf3mCi5u5o46/Z/JcJMnhbHSaZ69rkgPzNM3J4s8hWwpPUQB6/tt0EDFyCiWzxANlx+2LJwpYj4zS1w==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT-0",+ "engines": {+ "node": ">=20.19.0"+ }+ },+ "node_modules/@csstools/css-calc": {+ "version": "3.4.0",+ "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-3.4.0.tgz",+ "integrity": "sha512-XQKj5B7QiZcHiegCOCAzcAOJdhGgWOHbbu62h5e5mkHnn8lWcfiJhllkqWmxu5zWR9jucPHuo1iTB56P033hcg==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=20.19.0"+ },+ "peerDependencies": {+ "@csstools/css-parser-algorithms": "^4.0.0",+ "@csstools/css-tokenizer": "^4.0.0"+ }+ },+ "node_modules/@csstools/css-color-parser": {+ "version": "4.2.3",+ "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-4.2.3.tgz",+ "integrity": "sha512-y4LpL+lmpuyKDiEFq2PnZUVFdAjsoB/qQJod79yLNokXyW7jewi+/WJ69EfItj8A2unWtxXnGjw6LYXgXu5ZjA==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "@csstools/color-helpers": "^6.1.1",+ "@csstools/css-calc": "^3.4.0"+ },+ "engines": {+ "node": ">=20.19.0"+ },+ "peerDependencies": {+ "@csstools/css-parser-algorithms": "^4.0.0",+ "@csstools/css-tokenizer": "^4.0.0"+ }+ },+ "node_modules/@csstools/css-parser-algorithms": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.0.tgz",+ "integrity": "sha512-+B87qS7fIG3L5h3qwJ/IFbjoVoOe/bpOdh9hAjXbvx0o8ImEmUsGXN0inFOnk2ChCFgqkkGFQ+TpM5rbhkKe4w==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=20.19.0"+ },+ "peerDependencies": {+ "@csstools/css-tokenizer": "^4.0.0"+ }+ },+ "node_modules/@csstools/css-syntax-patches-for-csstree": {+ "version": "1.1.14",+ "resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.14.tgz",+ "integrity": "sha512-HpbVXyrofRXpHpgkNIjU/3EWR4WJvOkO3emNK/L6X/mTJU7bGUI3AkkpoTNXznQLp0KRjLHELTGeKI5dIkI9JQ==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT-0",+ "peerDependencies": {+ "css-tree": "^3.2.1"+ },+ "peerDependenciesMeta": {+ "css-tree": {+ "optional": true+ }+ }+ },+ "node_modules/@csstools/css-tokenizer": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-4.0.1.tgz",+ "integrity": "sha512-bPlN9S9O1A0euCpEWE4qnvB5YDuyYVsUTrxSgmAM1Is0j4tICHoVyOVAXfWMP/kS9ZrjvyIXWV2PmomiAXXqOw==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=20.19.0"+ }+ },"node_modules/@emotion/babel-plugin": {"version": "11.13.5","resolved": "https://registry.npmjs.org/@emotion/babel-plugin/-/babel-plugin-11.13.5.tgz",@@ -1011,6 +1219,24 @@"node": ">=18"}},+ "node_modules/@exodus/bytes": {+ "version": "1.16.0",+ "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.16.0.tgz",+ "integrity": "sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ },+ "peerDependencies": {+ "@noble/hashes": "^1.8.0 || ^2.0.0"+ },+ "peerDependenciesMeta": {+ "@noble/hashes": {+ "optional": true+ }+ }+ },"node_modules/@fontsource/space-grotesk": {"version": "5.3.0","resolved": "https://registry.npmjs.org/@fontsource/space-grotesk/-/space-grotesk-5.3.0.tgz",@@ -1789,12 +2015,67 @@"win32"]},+ "node_modules/@testing-library/dom": {+ "version": "10.4.2",+ "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.4.2.tgz",+ "integrity": "sha512-yzr2S9HyAIdhz2/6qHgbs665Q7PKVcDF05vsOlHPxG1mo36gKVesdYVeDLnXgfjJ03CrKRk08knc6+E/9m8v2Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/code-frame": "^7.10.4",+ "@babel/runtime": "^7.12.5",+ "@types/aria-query": "^5.0.1",+ "aria-query": "5.3.0",+ "dom-accessibility-api": "^0.5.9",+ "lz-string": "^1.5.0",+ "picocolors": "1.1.1",+ "pretty-format": "^27.0.2"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@testing-library/react": {+ "version": "16.3.3",+ "resolved": "https://registry.npmjs.org/@testing-library/react/-/react-16.3.3.tgz",+ "integrity": "sha512-Uo193NgQbPMz6lrrhtRQQFcMC6Re/ELLFbbuVL30WDlZxlpZf9/lMHTAVxPRLw1q1iu9OJmR1c2BLiENRstdBg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.12.5"+ },+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "@testing-library/dom": "^10.0.0",+ "@types/react": "^18.0.0 || ^19.0.0",+ "@types/react-dom": "^18.0.0 || ^19.0.0",+ "react": "^18.0.0 || ^19.0.0",+ "react-dom": "^18.0.0 || ^19.0.0"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },"node_modules/@tweenjs/tween.js": {"version": "25.0.0","resolved": "https://registry.npmjs.org/@tweenjs/tween.js/-/tween.js-25.0.0.tgz","integrity": "sha512-XKLA6syeBUaPzx4j3qwMqzzq+V4uo72BnlbOjmuljLrRqdsd3qnzvZZoxvMHZ23ndsRS4aufU6JOZYpCbU6T1A==","license": "MIT"},+ "node_modules/@types/aria-query": {+ "version": "5.0.4",+ "resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz",+ "integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==",+ "dev": true,+ "license": "MIT"+ },"node_modules/@types/babel__core": {"version": "7.20.5","resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",@@ -1840,6 +2121,24 @@"@babel/types": "^7.28.2"}},+ "node_modules/@types/chai": {+ "version": "5.2.3",+ "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",+ "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/deep-eql": "*",+ "assertion-error": "^2.0.1"+ }+ },+ "node_modules/@types/deep-eql": {+ "version": "4.0.2",+ "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",+ "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==",+ "dev": true,+ "license": "MIT"+ },"node_modules/@types/estree": {"version": "1.0.8","resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",@@ -1961,6 +2260,121 @@"vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0"}},+ "node_modules/@vitest/expect": {+ "version": "3.2.7",+ "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-3.2.7.tgz",+ "integrity": "sha512-E8eBXaKibuvH2pSZErOjdVb5vF4PbKYcrnluBTYxEk1l/VhhwZg1kZQsdtjq+CsF5CFydf2Rdkz7jDHKSisi3w==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/chai": "^5.2.2",+ "@vitest/spy": "3.2.7",+ "@vitest/utils": "3.2.7",+ "chai": "^5.2.0",+ "tinyrainbow": "^2.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/@vitest/mocker": {+ "version": "3.2.7",+ "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-3.2.7.tgz",+ "integrity": "sha512-Trr0hYO9CM3Wj6ksWHRhK9IZpIY6wTMO5u/MqXurMxT57sWBaOPEtP3Oq60ihZuh5JsiagKfz95OcxdEP6dBrA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/spy": "3.2.7",+ "estree-walker": "^3.0.3",+ "magic-string": "^0.30.17"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ },+ "peerDependencies": {+ "msw": "^2.4.9",+ "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0"+ },+ "peerDependenciesMeta": {+ "msw": {+ "optional": true+ },+ "vite": {+ "optional": true+ }+ }+ },+ "node_modules/@vitest/pretty-format": {+ "version": "3.2.7",+ "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-3.2.7.tgz",+ "integrity": "sha512-KUHlwqVu0sRlhCdyPdQ/wBoTfRahjUky1MubOmYw9fWfIZy1gNoHpuaaQBPAaMaVYdQYHJLurzj8ECCj5OwTqA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "tinyrainbow": "^2.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/@vitest/runner": {+ "version": "3.2.7",+ "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-3.2.7.tgz",+ "integrity": "sha512-sB9y4ovltoQP+WaUPwmSxO9WIg9Ig694Di5PalVPsYHklAdE027mehpWF2SQSVq+k6sFgaivbTjTJwZLSHbedA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/utils": "3.2.7",+ "pathe": "^2.0.3",+ "strip-literal": "^3.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/@vitest/snapshot": {+ "version": "3.2.7",+ "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-3.2.7.tgz",+ "integrity": "sha512-7C+MwShwtBSI5Buwoyg3s/iY1eHL9PKAf+O1wVh/TdnjXUtkoL/9YQtre90i4MtNXM6edP1wJ2zOBpfCyhIS7g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/pretty-format": "3.2.7",+ "magic-string": "^0.30.17",+ "pathe": "^2.0.3"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/@vitest/spy": {+ "version": "3.2.7",+ "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-3.2.7.tgz",+ "integrity": "sha512-Q2eQGI6d2L/hBtZ0qNuKcAGid68XK6cv1xsoaIma6PaJhHPoqcEJhYpXZ/5myCMqkNgtP6UKuBhbc0nHKnrkuQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "tinyspy": "^4.0.3"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/@vitest/utils": {+ "version": "3.2.7",+ "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-3.2.7.tgz",+ "integrity": "sha512-x6BDOd7dyo3PFLY3I9/HJ25X/6OurhGXk2/B9gOZNPF7XDVjeBK4k01lQE5uvDpbuheErh91qYuE1E2OEjK3Rw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/pretty-format": "3.2.7",+ "loupe": "^3.1.4",+ "tinyrainbow": "^2.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },"node_modules/accessor-fn": {"version": "1.5.3","resolved": "https://registry.npmjs.org/accessor-fn/-/accessor-fn-1.5.3.tgz",@@ -1970,6 +2384,49 @@"node": ">=12"}},+ "node_modules/ansi-regex": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",+ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/ansi-styles": {+ "version": "5.2.0",+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz",+ "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"+ }+ },+ "node_modules/aria-query": {+ "version": "5.3.0",+ "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.0.tgz",+ "integrity": "sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "dequal": "^2.0.3"+ }+ },+ "node_modules/assertion-error": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",+ "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12"+ }+ },"node_modules/babel-plugin-macros": {"version": "3.1.0","resolved": "https://registry.npmjs.org/babel-plugin-macros/-/babel-plugin-macros-3.1.0.tgz",@@ -2008,10 +2465,20 @@"url": "https://github.com/Pomax/bezierjs/blob/master/FUNDING.md"}},- "node_modules/browserslist": {- "version": "4.28.7",- "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.7.tgz",- "integrity": "sha512-JxV13hNrFxqjOc8alRbq9dK1MM79NEXYpma2B2J4wAtpWS5zIEIKqWPGCl7N4o7Uc7B7itylh7SuDujATRyyTw==",+ "node_modules/bidi-js": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.1.0.tgz",+ "integrity": "sha512-fX1Onk0tdVPC7obPWB5EbJ1z7NVhLq4m2xZLq2YXBkxzMXIGRpNMU88n0EPgWseKl12J7zXs7qrDxPK4sRs2fg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "require-from-string": "^2.0.2"+ }+ },+ "node_modules/browserslist": {+ "version": "4.28.7",+ "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.7.tgz",+ "integrity": "sha512-JxV13hNrFxqjOc8alRbq9dK1MM79NEXYpma2B2J4wAtpWS5zIEIKqWPGCl7N4o7Uc7B7itylh7SuDujATRyyTw==","dev": true,"funding": [{@@ -2042,6 +2509,16 @@"node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"}},+ "node_modules/cac": {+ "version": "6.7.14",+ "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz",+ "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },"node_modules/callsites": {"version": "3.1.0","resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz",@@ -2084,6 +2561,33 @@"node": ">=12"}},+ "node_modules/chai": {+ "version": "5.3.3",+ "resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz",+ "integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "assertion-error": "^2.0.1",+ "check-error": "^2.1.1",+ "deep-eql": "^5.0.1",+ "loupe": "^3.1.0",+ "pathval": "^2.0.0"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/check-error": {+ "version": "2.1.3",+ "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.3.tgz",+ "integrity": "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 16"+ }+ },"node_modules/clsx": {"version": "2.1.1","resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz",@@ -2158,6 +2662,20 @@"integrity": "sha512-VQ2MBenTq1fWZUH9DJNGti7kKv6EeAuYr3cLwxUWhIu1baTaXh4Ib5W2CqHVqib4/MqbYGJqiL3Zb8GJZr3l4g==","license": "MIT"},+ "node_modules/css-tree": {+ "version": "3.2.1",+ "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz",+ "integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "mdn-data": "2.27.1",+ "source-map-js": "^1.2.1"+ },+ "engines": {+ "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0"+ }+ },"node_modules/csstype": {"version": "3.2.3","resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",@@ -2380,6 +2898,20 @@"node": ">=12"}},+ "node_modules/data-urls": {+ "version": "7.0.0",+ "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-7.0.0.tgz",+ "integrity": "sha512-23XHcCF+coGYevirZceTVD7NdJOqVn+49IHyxgszm+JIiHLoB2TkmPtsYkNWT1pvRSGkc35L6NHs0yHkN2SumA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "whatwg-mimetype": "^5.0.0",+ "whatwg-url": "^16.0.0"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },"node_modules/debug": {"version": "4.4.3","resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",@@ -2397,6 +2929,40 @@}}},+ "node_modules/decimal.js": {+ "version": "10.6.0",+ "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz",+ "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/deep-eql": {+ "version": "5.0.2",+ "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz",+ "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/dequal": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz",+ "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/dom-accessibility-api": {+ "version": "0.5.16",+ "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz",+ "integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==",+ "dev": true,+ "license": "MIT"+ },"node_modules/dom-helpers": {"version": "5.2.1","resolved": "https://registry.npmjs.org/dom-helpers/-/dom-helpers-5.2.1.tgz",@@ -2414,6 +2980,19 @@"dev": true,"license": "ISC"},+ "node_modules/entities": {+ "version": "8.1.0",+ "resolved": "https://registry.npmjs.org/entities/-/entities-8.1.0.tgz",+ "integrity": "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==",+ "dev": true,+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=20.19.0"+ },+ "funding": {+ "url": "https://github.com/fb55/entities?sponsor=1"+ }+ },"node_modules/error-ex": {"version": "1.3.4","resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.4.tgz",@@ -2432,6 +3011,13 @@"node": ">= 0.4"}},+ "node_modules/es-module-lexer": {+ "version": "1.7.0",+ "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz",+ "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==",+ "dev": true,+ "license": "MIT"+ },"node_modules/esbuild": {"version": "0.25.12","resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz",@@ -2496,6 +3082,26 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/estree-walker": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",+ "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0"+ }+ },+ "node_modules/expect-type": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz",+ "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">=12.0.0"+ }+ },"node_modules/fdir": {"version": "6.5.0","resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",@@ -2621,6 +3227,19 @@"integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==","license": "MIT"},+ "node_modules/html-encoding-sniffer": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-6.0.0.tgz",+ "integrity": "sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@exodus/bytes": "^1.6.0"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },"node_modules/import-fresh": {"version": "3.3.1","resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz",@@ -2676,6 +3295,13 @@"url": "https://github.com/sponsors/ljharb"}},+ "node_modules/is-potential-custom-element-name": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz",+ "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==",+ "dev": true,+ "license": "MIT"+ },"node_modules/jerrypick": {"version": "1.1.2","resolved": "https://registry.npmjs.org/jerrypick/-/jerrypick-1.1.2.tgz",@@ -2691,6 +3317,57 @@"integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==","license": "MIT"},+ "node_modules/jsdom": {+ "version": "29.1.1",+ "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-29.1.1.tgz",+ "integrity": "sha512-ECi4Fi2f7BdJtUKTflYRTiaMxIB0O6zfR1fX0GXpUrf6flp8QIYn1UT20YQqdSOfk2dfkCwS8LAFoJDEppNK5Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@asamuzakjp/css-color": "^5.1.11",+ "@asamuzakjp/dom-selector": "^7.1.1",+ "@bramus/specificity": "^2.4.2",+ "@csstools/css-syntax-patches-for-csstree": "^1.1.3",+ "@exodus/bytes": "^1.15.0",+ "css-tree": "^3.2.1",+ "data-urls": "^7.0.0",+ "decimal.js": "^10.6.0",+ "html-encoding-sniffer": "^6.0.0",+ "is-potential-custom-element-name": "^1.0.1",+ "lru-cache": "^11.3.5",+ "parse5": "^8.0.1",+ "saxes": "^6.0.0",+ "symbol-tree": "^3.2.4",+ "tough-cookie": "^6.0.1",+ "undici": "^7.25.0",+ "w3c-xmlserializer": "^5.0.0",+ "webidl-conversions": "^8.0.1",+ "whatwg-mimetype": "^5.0.0",+ "whatwg-url": "^16.0.1",+ "xml-name-validator": "^5.0.0"+ },+ "engines": {+ "node": "^20.19.0 || ^22.13.0 || >=24.0.0"+ },+ "peerDependencies": {+ "canvas": "^3.0.0"+ },+ "peerDependenciesMeta": {+ "canvas": {+ "optional": true+ }+ }+ },+ "node_modules/jsdom/node_modules/lru-cache": {+ "version": "11.5.3",+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz",+ "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==",+ "dev": true,+ "license": "BlueOak-1.0.0",+ "engines": {+ "node": "20 || >=22"+ }+ },"node_modules/jsesc": {"version": "3.1.0","resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz",@@ -2758,6 +3435,13 @@"loose-envify": "cli.js"}},+ "node_modules/loupe": {+ "version": "3.2.1",+ "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz",+ "integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==",+ "dev": true,+ "license": "MIT"+ },"node_modules/lru-cache": {"version": "5.1.1","resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",@@ -2768,6 +3452,33 @@"yallist": "^3.0.2"}},+ "node_modules/lz-string": {+ "version": "1.5.0",+ "resolved": "https://registry.npmjs.org/lz-string/-/lz-string-1.5.0.tgz",+ "integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==",+ "dev": true,+ "license": "MIT",+ "bin": {+ "lz-string": "bin/bin.js"+ }+ },+ "node_modules/magic-string": {+ "version": "0.30.21",+ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",+ "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@jridgewell/sourcemap-codec": "^1.5.5"+ }+ },+ "node_modules/mdn-data": {+ "version": "2.27.1",+ "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz",+ "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==",+ "dev": true,+ "license": "CC0-1.0"+ },"node_modules/ms": {"version": "2.1.3","resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",@@ -2842,6 +3553,19 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/parse5": {+ "version": "8.0.1",+ "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.0.1.tgz",+ "integrity": "sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "entities": "^8.0.0"+ },+ "funding": {+ "url": "https://github.com/inikulin/parse5?sponsor=1"+ }+ },"node_modules/path-parse": {"version": "1.0.7","resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz",@@ -2857,6 +3581,23 @@"node": ">=8"}},+ "node_modules/pathe": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",+ "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/pathval": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.1.tgz",+ "integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 14.16"+ }+ },"node_modules/picocolors": {"version": "1.1.1","resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",@@ -2915,6 +3656,28 @@"url": "https://opencollective.com/preact"}},+ "node_modules/pretty-format": {+ "version": "27.5.1",+ "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-27.5.1.tgz",+ "integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "ansi-regex": "^5.0.1",+ "ansi-styles": "^5.0.0",+ "react-is": "^17.0.1"+ },+ "engines": {+ "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0"+ }+ },+ "node_modules/pretty-format/node_modules/react-is": {+ "version": "17.0.2",+ "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",+ "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==",+ "dev": true,+ "license": "MIT"+ },"node_modules/prop-types": {"version": "15.8.1","resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",@@ -2932,6 +3695,16 @@"integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==","license": "MIT"},+ "node_modules/punycode": {+ "version": "2.3.1",+ "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",+ "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },"node_modules/react": {"version": "19.2.6","resolved": "https://registry.npmjs.org/react/-/react-19.2.6.tgz",@@ -3039,6 +3812,16 @@"react-dom": ">=16.6.0"}},+ "node_modules/require-from-string": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",+ "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },"node_modules/reselect": {"version": "5.2.0","resolved": "https://registry.npmjs.org/reselect/-/reselect-5.2.0.tgz",@@ -3120,6 +3903,19 @@"fsevents": "~2.3.2"}},+ "node_modules/saxes": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",+ "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "xmlchars": "^2.2.0"+ },+ "engines": {+ "node": ">=v12.22.7"+ }+ },"node_modules/scheduler": {"version": "0.27.0","resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz",@@ -3142,6 +3938,13 @@"integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==","license": "MIT"},+ "node_modules/siginfo": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",+ "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==",+ "dev": true,+ "license": "ISC"+ },"node_modules/source-map": {"version": "0.5.7","resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz",@@ -3161,6 +3964,40 @@"node": ">=0.10.0"}},+ "node_modules/stackback": {+ "version": "0.0.2",+ "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",+ "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/std-env": {+ "version": "3.10.0",+ "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz",+ "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/strip-literal": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/strip-literal/-/strip-literal-3.1.0.tgz",+ "integrity": "sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "js-tokens": "^9.0.1"+ },+ "funding": {+ "url": "https://github.com/sponsors/antfu"+ }+ },+ "node_modules/strip-literal/node_modules/js-tokens": {+ "version": "9.0.1",+ "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-9.0.1.tgz",+ "integrity": "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==",+ "dev": true,+ "license": "MIT"+ },"node_modules/style-mod": {"version": "4.1.3","resolved": "https://registry.npmjs.org/style-mod/-/style-mod-4.1.3.tgz",@@ -3185,12 +4022,33 @@"url": "https://github.com/sponsors/ljharb"}},+ "node_modules/symbol-tree": {+ "version": "3.2.4",+ "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz",+ "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/tinybench": {+ "version": "2.9.0",+ "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",+ "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==",+ "dev": true,+ "license": "MIT"+ },"node_modules/tinycolor2": {"version": "1.6.0","resolved": "https://registry.npmjs.org/tinycolor2/-/tinycolor2-1.6.0.tgz","integrity": "sha512-XPaBkWQJdsf3pLKJV9p4qN/S+fm2Oj8AIPo1BTUhg5oxkvm9+SVEGFdhyOz7tTdUTfvxMiAs4sp6/eZO2Ew+pw==","license": "MIT"},+ "node_modules/tinyexec": {+ "version": "0.3.2",+ "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.2.tgz",+ "integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==",+ "dev": true,+ "license": "MIT"+ },"node_modules/tinyglobby": {"version": "0.2.16","resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.16.tgz",@@ -3208,6 +4066,82 @@"url": "https://github.com/sponsors/SuperchupuDev"}},+ "node_modules/tinypool": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-1.1.1.tgz",+ "integrity": "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^18.0.0 || >=20.0.0"+ }+ },+ "node_modules/tinyrainbow": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-2.0.0.tgz",+ "integrity": "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=14.0.0"+ }+ },+ "node_modules/tinyspy": {+ "version": "4.0.6",+ "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-4.0.6.tgz",+ "integrity": "sha512-u8KszXvGfU68hVcZpRHKG28T0krMuv2G5nDhiHaMLen/gIuFEgIJhaJuO69qjnXg5paSrbPMFfx3brNuN8eVSg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=14.0.0"+ }+ },+ "node_modules/tldts": {+ "version": "7.4.15",+ "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.4.15.tgz",+ "integrity": "sha512-SJVBeHOxDbNoq14CvpAoA2mLEWdbldGK8nR+yumpjY5nrlZxOflcA7p1Qj1gbTGmbu9DY9qLj/bENSWhBzjxRQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "tldts-core": "^7.4.15"+ },+ "bin": {+ "tldts": "bin/cli.js"+ }+ },+ "node_modules/tldts-core": {+ "version": "7.4.15",+ "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.4.15.tgz",+ "integrity": "sha512-ERuv0p98XgSzmlSLJr8vDNxX+uATGInlN97V3R+JpYWaSqn5IG3ewWgCwczk4bkOpgth/o8Nt5FOi4B4w0n/1A==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/tough-cookie": {+ "version": "6.0.2",+ "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.0.2.tgz",+ "integrity": "sha512-exgYmnmL/sJpR3upZfXG5PoatXQii55xAiXGXzY+sROLZ/Y+SLcp9PgJNI9Vz37HpQ74WvDcLT8eqm+kV3FzrA==",+ "dev": true,+ "license": "BSD-3-Clause",+ "dependencies": {+ "tldts": "^7.0.5"+ },+ "engines": {+ "node": ">=16"+ }+ },+ "node_modules/tr46": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/tr46/-/tr46-6.0.0.tgz",+ "integrity": "sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "punycode": "^2.3.1"+ },+ "engines": {+ "node": ">=20"+ }+ },"node_modules/typescript": {"version": "5.8.3","resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.3.tgz",@@ -3222,6 +4156,16 @@"node": ">=14.17"}},+ "node_modules/undici": {+ "version": "7.29.1",+ "resolved": "https://registry.npmjs.org/undici/-/undici-7.29.1.tgz",+ "integrity": "sha512-RYONW2MeafgYlkVOKYKkA/Ag7BmXqgIWCa8t1m0JcxrQg9pI9lEqRhAOruOBCbAohOa/gkCF+iPi9hrgvTzu6Q==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=20.18.1"+ }+ },"node_modules/update-browserslist-db": {"version": "1.2.3","resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz",@@ -3337,12 +4281,190 @@}}},+ "node_modules/vite-node": {+ "version": "3.2.4",+ "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-3.2.4.tgz",+ "integrity": "sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "cac": "^6.7.14",+ "debug": "^4.4.1",+ "es-module-lexer": "^1.7.0",+ "pathe": "^2.0.3",+ "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0"+ },+ "bin": {+ "vite-node": "vite-node.mjs"+ },+ "engines": {+ "node": "^18.0.0 || ^20.0.0 || >=22.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/vitest": {+ "version": "3.2.7",+ "resolved": "https://registry.npmjs.org/vitest/-/vitest-3.2.7.tgz",+ "integrity": "sha512-KrxIJ62Fd89gfysR4WotlgZABiz2dqFPgqGzX7s+CwsqLFomRH7777ZcrOD6+WVAh7khPQP41A+BKbpcJFrdEg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/chai": "^5.2.2",+ "@vitest/expect": "3.2.7",+ "@vitest/mocker": "3.2.7",+ "@vitest/pretty-format": "^3.2.7",+ "@vitest/runner": "3.2.7",+ "@vitest/snapshot": "3.2.7",+ "@vitest/spy": "3.2.7",+ "@vitest/utils": "3.2.7",+ "chai": "^5.2.0",+ "debug": "^4.4.1",+ "expect-type": "^1.2.1",+ "magic-string": "^0.30.17",+ "pathe": "^2.0.3",+ "picomatch": "^4.0.2",+ "std-env": "^3.9.0",+ "tinybench": "^2.9.0",+ "tinyexec": "^0.3.2",+ "tinyglobby": "^0.2.14",+ "tinypool": "^1.1.1",+ "tinyrainbow": "^2.0.0",+ "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0",+ "vite-node": "3.2.4",+ "why-is-node-running": "^2.3.0"+ },+ "bin": {+ "vitest": "vitest.mjs"+ },+ "engines": {+ "node": "^18.0.0 || ^20.0.0 || >=22.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ },+ "peerDependencies": {+ "@edge-runtime/vm": "*",+ "@types/debug": "^4.1.12",+ "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0",+ "@vitest/browser": "3.2.7",+ "@vitest/ui": "3.2.7",+ "happy-dom": "*",+ "jsdom": "*"+ },+ "peerDependenciesMeta": {+ "@edge-runtime/vm": {+ "optional": true+ },+ "@types/debug": {+ "optional": true+ },+ "@types/node": {+ "optional": true+ },+ "@vitest/browser": {+ "optional": true+ },+ "@vitest/ui": {+ "optional": true+ },+ "happy-dom": {+ "optional": true+ },+ "jsdom": {+ "optional": true+ }+ }+ },"node_modules/w3c-keyname": {"version": "2.2.8","resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz","integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==","license": "MIT"},+ "node_modules/w3c-xmlserializer": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz",+ "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "xml-name-validator": "^5.0.0"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/webidl-conversions": {+ "version": "8.0.1",+ "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz",+ "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==",+ "dev": true,+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/whatwg-mimetype": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz",+ "integrity": "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/whatwg-url": {+ "version": "16.0.1",+ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-16.0.1.tgz",+ "integrity": "sha512-1to4zXBxmXHV3IiSSEInrreIlu02vUOvrhxJJH5vcxYTBDAx51cqZiKdyTxlecdKNSjj8EcxGBxNf6Vg+945gw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@exodus/bytes": "^1.11.0",+ "tr46": "^6.0.0",+ "webidl-conversions": "^8.0.1"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },+ "node_modules/why-is-node-running": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",+ "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "siginfo": "^2.0.0",+ "stackback": "0.0.2"+ },+ "bin": {+ "why-is-node-running": "cli.js"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/xml-name-validator": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",+ "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/xmlchars": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz",+ "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==",+ "dev": true,+ "license": "MIT"+ },"node_modules/yallist": {"version": "3.1.1","resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",diff --git a/gateway/package.json b/gateway/package.jsonindex b759a6f67..10269815b 100644--- a/gateway/package.json+++ b/gateway/package.json@@ -6,6 +6,7 @@"dev": "vite","build": "tsc -b && vite build","preview": "vite preview",+ "test": "vitest run","gen:tokens": "node scripts/gen-hoot-tokens.mjs"},"dependencies": {@@ -23,10 +24,14 @@"react-router": "^7.14.0"},"devDependencies": {+ "@testing-library/dom": "^10.4.2",+ "@testing-library/react": "^16.3.3","@types/react": "^19.1.0","@types/react-dom": "^19.1.0","@vitejs/plugin-react": "^4.4.1",+ "jsdom": "^29.1.1","typescript": "~5.8.0",- "vite": "^6.3.0"+ "vite": "^6.3.0",+ "vitest": "^3.2.7"}}diff --git a/gateway/src/App.test.tsx b/gateway/src/App.test.tsxnew file mode 100644index 000000000..774753feb--- /dev/null+++ b/gateway/src/App.test.tsx@@ -0,0 +1,141 @@+import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { MemoryRouter } from "react-router";+import { afterEach, describe, expect, it, vi } from "vitest";+import { AppRoutes } from "./App";+import type { Session, TenantMembership } from "./data/api";+import { AuthProvider } from "./data/AuthContext";+import { clearPendingInvite, storePendingInvite } from "./data/sessionState";++const acme: TenantMembership = { id: "t1", slug: "acme", name: "Acme", role: "owner" };+const beta: TenantMembership = { id: "t2", slug: "beta", name: "Beta Co", role: "member" };++function session(overrides: Partial<Session>): Session {+ return {+ user: { id: "u1", name: "Ada", email: "[email protected]", is_operator: false },+ tenant: null,+ tenants: [],+ state: "needs_workspace",+ can_create_workspace: true,+ invite_email_enabled: false,+ ...overrides,+ };+}++/** Every request answers from `routes` by path; anything else is a 404 so an+ * unexpected call shows up as a failure rather than hanging. */+function mockFetch(routes: Record<string, [number, unknown]>) {+ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: RequestInfo | URL) => {+ const path = String(input).replace(/^\/gateway/, "").split("?")[0];+ const [status, body] = routes[path] ?? [404, { detail: `unmocked ${path}` }];+ return new Response(JSON.stringify(body), { status });+ }),+ );+}++function renderAt(path: string) {+ return render(+ <MemoryRouter initialEntries={[path]}>+ <AuthProvider>+ <AppRoutes />+ </AuthProvider>+ </MemoryRouter>,+ );+}++const authConfig = {+ oidc_enabled: true,+ oidc_provider_label: "Example SSO",+ password_login_enabled: true,+ signup_mode: "open",+};++describe("AppRoutes", () => {+ afterEach(() => {+ cleanup();+ clearPendingInvite();+ vi.unstubAllGlobals();+ });++ it("sends a signed-out visitor to sign in", async () => {+ mockFetch({ "/auth/session": [401, { detail: "Not authenticated" }], "/auth/config": [200, authConfig] });+ renderAt("/rooms");+ expect(await screen.findByText("Switch Gateway")).toBeTruthy();+ expect(+ await screen.findByText("Sign in with Example SSO to create a workspace or join one."),+ ).toBeTruthy();+ });++ it("keeps an invite link through sign-in", async () => {+ mockFetch({ "/auth/session": [401, { detail: "Not authenticated" }], "/auth/config": [200, authConfig] });+ renderAt("/invite#token=abc");+ expect(await screen.findByText("Sign in to accept your invitation.")).toBeTruthy();+ expect(window.sessionStorage.getItem("switch.pendingInvite")).toBe("abc");+ });++ it("offers to create a workspace to someone in none", async () => {+ mockFetch({ "/auth/session": [200, session({})] });+ renderAt("/");+ expect(await screen.findByText("Welcome to Switch")).toBeTruthy();+ expect(screen.getByRole("button", { name: "Create workspace" })).toBeTruthy();+ });++ it("only offers an invite when workspaces cannot be created", async () => {+ mockFetch({ "/auth/session": [200, session({ can_create_workspace: false })] });+ renderAt("/");+ expect(await screen.findByText(/Ask a workspace admin for an invite link/)).toBeTruthy();+ expect(screen.queryByRole("button", { name: "Create workspace" })).toBeNull();+ });++ it("asks someone in several workspaces to choose", async () => {+ mockFetch({+ "/auth/session": [200, session({ state: "needs_selection", tenants: [acme, beta] })],+ });+ renderAt("/rooms");+ expect(await screen.findByText("Choose a workspace")).toBeTruthy();+ expect(screen.getByText("Acme")).toBeTruthy();+ expect(screen.getByText("Beta Co")).toBeTruthy();+ });++ it("opens the app in the current workspace", async () => {+ mockFetch({+ "/auth/session": [200, session({ state: "ready", tenant: acme, tenants: [acme, beta] })],+ });+ renderAt("/workspace");+ expect(await screen.findByRole("heading", { name: "Acme" })).toBeTruthy();+ expect(screen.getByRole("link", { name: /Workspace/ })).toBeTruthy();+ expect(screen.queryByRole("link", { name: /Users/ })).toBeNull();+ });++ it("puts a pending invite before everything else", async () => {+ storePendingInvite("abc");+ mockFetch({+ "/auth/session": [200, session({ state: "ready", tenant: acme, tenants: [acme] })],+ });+ renderAt("/rooms");+ expect(await screen.findByText("Join a workspace")).toBeTruthy();+ });++ it("drops a pending invite on sign-out, so the next person does not inherit it", async () => {+ storePendingInvite("abc");+ mockFetch({+ "/auth/session": [200, session({ state: "ready", tenant: acme, tenants: [acme] })],+ "/auth/logout": [200, { ok: true }],+ "/auth/config": [200, authConfig],+ });+ renderAt("/");+ fireEvent.click(await screen.findByRole("button", { name: "Sign out" }));+ expect(await screen.findByText("Switch Gateway")).toBeTruthy();+ expect(window.sessionStorage.getItem("switch.pendingInvite")).toBeNull();+ });++ it("says so when the session cannot be read, instead of showing sign-in", async () => {+ mockFetch({ "/auth/session": [500, { detail: "database unavailable" }] });+ renderAt("/rooms");+ expect(+ await screen.findByText(/Could not load your session: database unavailable/),+ ).toBeTruthy();+ expect(screen.queryByText("Switch Gateway")).toBeNull();+ });+});diff --git a/gateway/src/App.tsx b/gateway/src/App.tsxindex bbb09b715..8dc522186 100644--- a/gateway/src/App.tsx+++ b/gateway/src/App.tsx@@ -1,6 +1,7 @@-import { Box, CircularProgress } from "@mui/material";+import { Alert, Box, Button, CircularProgress } from "@mui/material";import { BrowserRouter, Navigate, Route, Routes } from "react-router";import { AuthProvider, useAuth } from "./data/AuthContext";+import { appView, readPendingInvite } from "./data/sessionState";import PageShell from "./layout/PageShell";import AgentDetailPage from "./pages/agents/AgentDetailPage";import AgentsPage from "./pages/agents/AgentsPage";@@ -19,35 +20,88 @@ import RoomDetailPage from "./pages/rooms/RoomDetailPage";import RoomScopedDocumentView from "./pages/rooms/RoomScopedDocumentView";import RoomsGraphPage from "./pages/rooms/RoomsGraphPage";import RoomsPage from "./pages/rooms/RoomsPage";+import AcceptInvitePage from "./pages/onboarding/AcceptInvitePage";+import InviteCapture from "./pages/onboarding/InviteCapture";+import OnboardingPage from "./pages/onboarding/OnboardingPage";+import WorkspacePickerPage from "./pages/onboarding/WorkspacePickerPage";+import UsagePage from "./pages/usage/UsagePage";import UsersPage from "./pages/users/UsersPage";+import WorkspacePage from "./pages/workspace/WorkspacePage";-function AppRoutes() {- const { user, loading } = useAuth();+function FullScreen({ children }: { children: React.ReactNode }) {+ return (+ <Box+ sx={{+ display: "flex",+ height: "100vh",+ alignItems: "center",+ justifyContent: "center",+ }}+ >+ {children}+ </Box>+ );+}++export function AppRoutes() {+ const { session, loading, loadError } = useAuth();if (loading) {return (- <Box- sx={{- display: "flex",- height: "100vh",- alignItems: "center",- justifyContent: "center",- }}- >+ <FullScreen><CircularProgress />- </Box>+ </FullScreen>);}- if (!user) {+ if (loadError !== null) {+ return (+ <FullScreen>+ <Alert+ severity="error"+ action={+ <Button color="inherit" size="small" onClick={() => window.location.reload()}>+ Retry+ </Button>+ }+ >+ Could not load your session: {loadError}+ </Alert>+ </FullScreen>+ );+ }++ const pendingInvite = readPendingInvite();+ const view = appView(session, pendingInvite);++ if (view === "signed_out") {return (<Routes><Route path="/login" element={<LoginPage />} />+ <Route path="/invite" element={<InviteCapture />} /><Route path="*" element={<Navigate to="/login" replace />} /></Routes>);}+ if (view !== "ready") {+ const screen =+ view === "accept_invite" && pendingInvite !== null ? (+ <AcceptInvitePage token={pendingInvite} />+ ) : view === "needs_selection" ? (+ <WorkspacePickerPage />+ ) : (+ <OnboardingPage />+ );+ return (+ <Routes>+ <Route path="/invite" element={<InviteCapture />} />+ <Route path="/" element={screen} />+ <Route path="*" element={<Navigate to="/" replace />} />+ </Routes>+ );+ }+return (<Routes><Route element={<PageShell />}>@@ -83,8 +137,11 @@ function AppRoutes() {<Route path="agents/:agentId" element={<AgentDetailPage />} /><Route path="collaborations" element={<CollaborationsPage />} /><Route path="registration-keys" element={<RegistrationKeysPage />} />+ <Route path="usage" element={<UsagePage />} /><Route path="users" element={<UsersPage />} />+ <Route path="workspace" element={<WorkspacePage />} /></Route>+ <Route path="/invite" element={<InviteCapture />} /><Route path="/login" element={<Navigate to="/" replace />} /></Routes>);diff --git a/gateway/src/data/AuthContext.tsx b/gateway/src/data/AuthContext.tsxindex da30de35c..d7d7a7459 100644--- a/gateway/src/data/AuthContext.tsx+++ b/gateway/src/data/AuthContext.tsx@@ -1,47 +1,87 @@import { createContext, useCallback, useContext, useEffect, useState } from "react";import type { ReactNode } from "react";import {- type UserInfo,- fetchMe,+ type Session,+ type SessionUser,+ fetchSession,login as apiLogin,logout as apiLogout,+ switchTenant,} from "./api";+import { canAdminTenant as sessionCanAdminTenant, clearPendingInvite } from "./sessionState";interface AuthState {- user: UserInfo | null;+ session: Session | null;+ user: SessionUser | null;loading: boolean;+ // Set when the session could not be read for a reason other than being+ // signed out, so the app can say so instead of showing the login page.+ loadError: string | null;+ isOperator: boolean;+ canAdminTenant: boolean;+ refresh: () => Promise<void>;login: (email: string, password: string) => Promise<void>;logout: () => Promise<void>;+ switchTo: (tenantId: string) => Promise<void>;}const AuthContext = createContext<AuthState | null>(null);export function AuthProvider({ children }: { children: ReactNode }) {- const [user, setUser] = useState<UserInfo | null>(null);+ const [session, setSession] = useState<Session | null>(null);const [loading, setLoading] = useState(true);+ const [loadError, setLoadError] = useState<string | null>(null);- useEffect(() => {- fetchMe().then((u) => {- setUser(u);- setLoading(false);- });+ const refresh = useCallback(async () => {+ try {+ setSession(await fetchSession());+ setLoadError(null);+ } catch (err) {+ setLoadError(err instanceof Error ? err.message : "Could not load your session");+ }}, []);- const login = useCallback(async (email: string, password: string) => {- const u = await apiLogin(email, password);- setUser(u);- }, []);+ useEffect(() => {+ refresh().finally(() => setLoading(false));+ }, [refresh]);++ const login = useCallback(+ async (email: string, password: string) => {+ await apiLogin(email, password);+ await refresh();+ },+ [refresh],+ );const logout = useCallback(async () => {+ // The next person to sign in on this tab must not inherit an invitation+ // they never followed.+ clearPendingInvite();await apiLogout();- setUser(null);+ setSession(null);}, []);- return (- <AuthContext.Provider value={{ user, loading, login, logout }}>- {children}- </AuthContext.Provider>- );+ // A full reload rather than a state update: every page holds data fetched+ // for the workspace it was opened in, and none of it is valid in the next.+ const switchTo = useCallback(async (tenantId: string) => {+ await switchTenant(tenantId);+ window.location.assign("/");+ }, []);++ const value: AuthState = {+ session,+ user: session?.user ?? null,+ loading,+ loadError,+ isOperator: session?.user.is_operator ?? false,+ canAdminTenant: sessionCanAdminTenant(session),+ refresh,+ login,+ logout,+ switchTo,+ };++ return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;}export function useAuth(): AuthState {diff --git a/gateway/src/data/api.test.ts b/gateway/src/data/api.test.tsnew file mode 100644index 000000000..341011855--- /dev/null+++ b/gateway/src/data/api.test.ts@@ -0,0 +1,53 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { ApiError, errorText, fetchSession } from "./api";++describe("errorText", () => {+ it("returns a string detail as is", () => {+ expect(errorText("Only a workspace owner may grant ownership", "x")).toBe(+ "Only a workspace owner may grant ownership",+ );+ });++ it("joins validation messages", () => {+ expect(+ errorText([{ msg: "field required" }, { msg: "too long" }], "fallback"),+ ).toBe("field required; too long");+ });++ it("reads message, then error, from an object detail", () => {+ expect(errorText({ message: "Workspace limit reached", error: "cap" }, "x")).toBe(+ "Workspace limit reached",+ );+ expect(errorText({ error: "cap" }, "x")).toBe("cap");+ });++ it("falls back rather than printing an object", () => {+ expect(errorText({ code: 7 }, "fallback")).toBe("fallback");+ expect(errorText(null, "fallback")).toBe("fallback");+ expect(errorText([], "fallback")).toBe("fallback");+ });+});++function respond(status: number, body: unknown) {+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => new Response(JSON.stringify(body), { status })),+ );+}++describe("fetchSession", () => {+ afterEach(() => vi.unstubAllGlobals());++ it("is null when signed out", async () => {+ respond(401, { detail: "Not authenticated" });+ await expect(fetchSession()).resolves.toBeNull();+ });++ it("throws, keeping the status, on any other failure", async () => {+ respond(500, { detail: "boom" });+ const err = await fetchSession().catch((e: unknown) => e);+ expect(err).toBeInstanceOf(ApiError);+ expect((err as ApiError).status).toBe(500);+ expect((err as ApiError).message).toBe("boom");+ });+});diff --git a/gateway/src/data/api.ts b/gateway/src/data/api.tsindex 423aec0e3..5e751e846 100644--- a/gateway/src/data/api.ts+++ b/gateway/src/data/api.ts@@ -210,10 +210,26 @@ export interface UpdateRoomInput {write_visibility?: "public" | "private";}-/** FastAPI's `detail` is a string for HTTPException but an array of- * validation objects for a 422; render both as text so no error surfaces- * as "[object Object]". */-function errorText(detail: unknown, fallback: string): string {+/** A failed gateway call that keeps what the server said: the status, for+ * callers that branch on it, and `detail` as sent. `message` is `detail`+ * rendered as text. */+export class ApiError extends Error {+ readonly status: number;+ readonly detail: unknown;++ constructor(status: number, detail: unknown, message: string) {+ super(message);+ this.name = "ApiError";+ this.status = status;+ this.detail = detail;+ }+}++/** FastAPI's `detail` is a string for HTTPException, an array of validation+ * objects for a 422, and an object for the structured errors (tenant+ * resolution's `{error, message, ...}`). Render all three as text so no error+ * surfaces as "[object Object]". */+export function errorText(detail: unknown, fallback: string): string {if (typeof detail === "string") return detail;if (Array.isArray(detail)) {const msgs = detail@@ -221,6 +237,11 @@ function errorText(detail: unknown, fallback: string): string {.filter((m): m is string => m !== null);if (msgs.length > 0) return msgs.join("; ");}+ if (detail && typeof detail === "object") {+ const record = detail as Record<string, unknown>;+ if (typeof record.message === "string") return record.message;+ if (typeof record.error === "string") return record.error;+ }return fallback;}@@ -236,8 +257,13 @@ async function jsonRequest<T>(body: body !== undefined ? JSON.stringify(body) : undefined,});if (!res.ok) {- const detail = await res.json().catch(() => null);- throw new Error(errorText(detail?.detail, `${res.status} ${res.statusText}`));+ const payload = await res.json().catch(() => null);+ const detail = payload?.detail ?? null;+ throw new ApiError(+ res.status,+ detail,+ errorText(detail, `${res.status} ${res.statusText}`),+ );}return (await res.json()) as T;}@@ -907,17 +933,7 @@ export interface UserInfo {}export async function login(email: string, password: string): Promise<UserInfo> {- const res = await fetch(`${BASE}/auth/login`, {- method: "POST",- headers: { "Content-Type": "application/json" },- credentials: "include",- body: JSON.stringify({ email, password }),- });- if (!res.ok) {- const body = await res.json().catch(() => null);- throw new Error(body?.detail ?? `${res.status} ${res.statusText}`);- }- return (await res.json()) as UserInfo;+ return jsonRequest<UserInfo>("/auth/login", "POST", { email, password });}export async function logout(): Promise<void> {@@ -931,10 +947,151 @@ export async function fetchMe(): Promise<UserInfo | null> {return fetchJson<UserInfo>("/auth/me");}+export type SignupMode = "default_tenant" | "invite_only" | "open";+export interface AuthConfig {password_login_enabled: boolean;oidc_enabled: boolean;oidc_provider_label: string | null;+ signup_mode: SignupMode;+}++// ── Session and workspaces ──────────────────────────────────────────────────++export type TenantRole = "owner" | "admin" | "member";++export interface TenantMembership {+ id: string;+ slug: string;+ name: string;+ role: TenantRole;+}++export interface SessionUser {+ id: string;+ name: string;+ email: string;+ is_operator: boolean;+}++export type SessionStateName = "ready" | "needs_selection" | "needs_workspace";++export interface Session {+ user: SessionUser;+ tenant: TenantMembership | null;+ tenants: TenantMembership[];+ state: SessionStateName;+ can_create_workspace: boolean;+ // Whether an invitation naming an e-mail is sent there by this server.+ invite_email_enabled: boolean;+}++/** The signed-in session, or null when nobody is signed in. Any other+ * failure throws: a server error is not the same answer as "signed out". */+export async function fetchSession(): Promise<Session | null> {+ try {+ return await jsonRequest<Session>("/auth/session", "GET");+ } catch (err) {+ if (err instanceof ApiError && err.status === 401) return null;+ throw err;+ }+}++export async function createTenant(name: string): Promise<TenantMembership> {+ return jsonRequest<TenantMembership>("/tenants", "POST", { name });+}++export async function switchTenant(tenantId: string): Promise<void> {+ await jsonRequest(`/tenants/${encodeURIComponent(tenantId)}/switch`, "POST");+}++export interface Member {+ user_id: string;+ name: string;+ email: string;+ role: TenantRole;+ created_at: string;+}++export async function fetchMembers(tenantId: string): Promise<Member[]> {+ return jsonRequest<Member[]>(`/tenants/${encodeURIComponent(tenantId)}/members`, "GET");+}++export async function updateMemberRole(+ tenantId: string,+ userId: string,+ role: TenantRole,+): Promise<Member> {+ return jsonRequest<Member>(+ `/tenants/${encodeURIComponent(tenantId)}/members/${encodeURIComponent(userId)}`,+ "PATCH",+ { role },+ );+}++export async function removeMember(tenantId: string, userId: string): Promise<void> {+ await jsonRequest(+ `/tenants/${encodeURIComponent(tenantId)}/members/${encodeURIComponent(userId)}`,+ "DELETE",+ );+}++export interface Invitation {+ id: string;+ role: TenantRole;+ email: string | null;+ expires_at: string;+ uses_remaining: number;+ revoked_at: string | null;+ created_by: string;+ created_at: string;+}++export type EmailDelivery = "sent" | "not_configured" | "failed" | "not_requested";++export interface CreatedInvitation extends Invitation {+ // The plaintext token, returned once, at creation, and never again.+ token: string;+ email_delivery: EmailDelivery;+}++export interface CreateInvitationInput {+ role: TenantRole;+ email: string | null;+ expires_in_hours: number;+ uses_remaining: number;+}++export async function fetchInvitations(tenantId: string): Promise<Invitation[]> {+ return jsonRequest<Invitation[]>(+ `/tenants/${encodeURIComponent(tenantId)}/invitations`,+ "GET",+ );+}++export async function createInvitation(+ tenantId: string,+ input: CreateInvitationInput,+): Promise<CreatedInvitation> {+ return jsonRequest<CreatedInvitation>(+ `/tenants/${encodeURIComponent(tenantId)}/invitations`,+ "POST",+ input,+ );+}++export async function revokeInvitation(+ tenantId: string,+ invitationId: string,+): Promise<void> {+ await jsonRequest(+ `/tenants/${encodeURIComponent(tenantId)}/invitations/${encodeURIComponent(invitationId)}`,+ "DELETE",+ );+}++export async function acceptInvitation(token: string): Promise<TenantMembership> {+ return jsonRequest<TenantMembership>("/invitations/accept", "POST", { token });}// Unauthenticated: tells the login page which methods to offer.@@ -1695,3 +1852,127 @@ export async function validateTemplate(content,});}++// ── Workspace usage and budgets ─────────────────────────────────────────────++export interface CurrentTenant {+ id: string;+ slug: string;+ name: string;+ role: string;+ // Whether the caller may manage the workspace: an owner or admin+ // membership, or the operator bit.+ administers: boolean;+}++export type UsageMetric =+ | "messages"+ | "turns"+ | "input_tokens"+ | "output_tokens"+ | "cache_read_tokens"+ | "cache_write_tokens";++export const USAGE_METRICS: UsageMetric[] = [+ "messages",+ "turns",+ "input_tokens",+ "output_tokens",+ "cache_read_tokens",+ "cache_write_tokens",+];++// Messages and turns are not counted per model, so a budget on them covers+// every model and the server refuses one that names a model.+export const PER_MODEL_METRICS: UsageMetric[] = [+ "input_tokens",+ "output_tokens",+ "cache_read_tokens",+ "cache_write_tokens",+];++export interface UsageTotal {+ metric: UsageMetric;+ client_id: string;+ // Null when the client has since been deleted; its spend still counts.+ client_name: string | null;+ client_type: string | null;+ model: string;+ amount: number;+}++// The server's bounds on a budget: at most a leap year, and at most the largest+// integer a JavaScript number holds exactly.+export const MAX_BUDGET_PERIOD_HOURS = 8784;+export const MAX_BUDGET_AMOUNT = Number.MAX_SAFE_INTEGER;++export interface Budget {+ id: string;+ // Null covers every agent in the workspace.+ agent_id: string | null;+ agent_name: string | null;+ metric: UsageMetric;+ // Empty covers every model.+ model: string;+ amount_limit: number;+ period_hours: number;+ spent: number;+ resets_at: string;+ exhausted: boolean;+}++export interface BudgetCreate {+ agent_id: string | null;+ metric: UsageMetric;+ model: string;+ amount_limit: number;+ period_hours: number;+}++export interface BudgetUpdate {+ amount_limit: number;+ period_hours: number;+}++export async function fetchCurrentTenant(): Promise<CurrentTenant | null> {+ return fetchJson<CurrentTenant>("/tenants/current");+}++export async function fetchUsage(+ tenantId: string,+ since: Date,+ until: Date,+): Promise<UsageTotal[] | null> {+ const params = new URLSearchParams({+ since: since.toISOString(),+ until: until.toISOString(),+ });+ return fetchJson<UsageTotal[]>(`/tenants/${tenantId}/usage?${params}`);+}++export async function fetchBudgets(tenantId: string): Promise<Budget[] | null> {+ return fetchJson<Budget[]>(`/tenants/${tenantId}/budgets`);+}++export async function createBudget(tenantId: string, body: BudgetCreate): Promise<Budget> {+ return jsonRequest<Budget>(`/tenants/${tenantId}/budgets`, "POST", body);+}++export async function updateBudget(+ tenantId: string,+ budgetId: string,+ body: BudgetUpdate,+): Promise<Budget> {+ return jsonRequest<Budget>(`/tenants/${tenantId}/budgets/${budgetId}`, "PUT", body);+}++export async function deleteBudget(tenantId: string, budgetId: string): Promise<void> {+ const res = await fetch(`${BASE}/tenants/${tenantId}/budgets/${budgetId}`, {+ method: "DELETE",+ credentials: "include",+ });+ if (!res.ok) {+ const detail = await res.json().catch(() => null);+ throw new Error(errorText(detail?.detail, `${res.status} ${res.statusText}`));+ }+}diff --git a/gateway/src/data/hooks.ts b/gateway/src/data/hooks.tsindex 7f44e31ac..17409042d 100644--- a/gateway/src/data/hooks.ts+++ b/gateway/src/data/hooks.ts@@ -2,6 +2,9 @@ import { useCallback, useEffect, useState } from "react";import {type AgentDetail,type AgentSummary,+ type Budget,+ type CurrentTenant,+ type UsageTotal,type ApiKeyDetail,type BridgeDetail,type BridgeTypeInfo,@@ -28,6 +31,9 @@ import {fetchAgent,fetchAgents,fetchApiKeys,+ fetchBudgets,+ fetchCurrentTenant,+ fetchUsage,fetchAllExternalUsers,fetchBridges,fetchBridgeTypes,@@ -348,3 +354,24 @@ export function useTemplates();return useQuery(fetcher);}++export function useCurrentTenant(): UseQueryResult<CurrentTenant> {+ return useQuery(fetchCurrentTenant);+}++export function useBudgets(tenantId: string): UseQueryResult<Budget[]> {+ const fetcher = useCallback(() => fetchBudgets(tenantId), [tenantId]);+ return useQuery(fetcher);+}++export function useUsage(+ tenantId: string,+ since: Date,+ until: Date,+): UseQueryResult<UsageTotal[]> {+ const fetcher = useCallback(+ () => fetchUsage(tenantId, since, until),+ [tenantId, since, until],+ );+ return useQuery(fetcher);+}diff --git a/gateway/src/data/sessionState.test.ts b/gateway/src/data/sessionState.test.tsnew file mode 100644index 000000000..4f091e892--- /dev/null+++ b/gateway/src/data/sessionState.test.ts@@ -0,0 +1,129 @@+import { afterEach, describe, expect, it } from "vitest";+import type { Session, TenantMembership } from "./api";+import {+ appView,+ canAdminTenant,+ clearPendingInvite,+ deliveryNotice,+ inviteTokenFrom,+ inviteUrl,+ ownsTenant,+ readPendingInvite,+ storePendingInvite,+} from "./sessionState";++const acme: TenantMembership = { id: "t1", slug: "acme", name: "Acme", role: "member" };++function session(overrides: Partial<Session> = {}): Session {+ return {+ user: { id: "u1", name: "Ada", email: "[email protected]", is_operator: false },+ tenant: acme,+ tenants: [acme],+ state: "ready",+ can_create_workspace: true,+ invite_email_enabled: false,+ ...overrides,+ };+}++describe("appView", () => {+ it("is signed out without a session, pending invite or not", () => {+ expect(appView(null, null)).toBe("signed_out");+ expect(appView(null, "tok")).toBe("signed_out");+ });++ it("follows the server's state when there is no pending invite", () => {+ expect(appView(session(), null)).toBe("ready");+ expect(appView(session({ state: "needs_workspace", tenant: null, tenants: [] }), null)).toBe(+ "needs_workspace",+ );+ expect(appView(session({ state: "needs_selection", tenant: null }), null)).toBe(+ "needs_selection",+ );+ });++ it("puts a pending invite ahead of every signed-in state", () => {+ for (const state of ["ready", "needs_workspace", "needs_selection"] as const) {+ expect(appView(session({ state }), "tok")).toBe("accept_invite");+ }+ });+});++describe("canAdminTenant and ownsTenant", () => {+ it("follows the workspace role", () => {+ expect(canAdminTenant(session())).toBe(false);+ expect(canAdminTenant(session({ tenant: { ...acme, role: "admin" } }))).toBe(true);+ expect(canAdminTenant(session({ tenant: { ...acme, role: "owner" } }))).toBe(true);+ expect(ownsTenant(session({ tenant: { ...acme, role: "admin" } }))).toBe(false);+ expect(ownsTenant(session({ tenant: { ...acme, role: "owner" } }))).toBe(true);+ });++ it("grants both to an operator whatever the role", () => {+ const operator = session({+ user: { id: "u1", name: "Op", email: "[email protected]", is_operator: true },+ });+ expect(canAdminTenant(operator)).toBe(true);+ expect(ownsTenant(operator)).toBe(true);+ });++ it("grants neither with no session or no workspace", () => {+ expect(canAdminTenant(null)).toBe(false);+ expect(ownsTenant(null)).toBe(false);+ expect(canAdminTenant(session({ tenant: null, state: "needs_workspace" }))).toBe(false);+ });+});++describe("invite tokens", () => {+ afterEach(() => clearPendingInvite());++ it("reads a token from a full link or a bare token", () => {+ expect(inviteTokenFrom("https://switch.example.com/invite#token=abc123")).toBe("abc123");+ expect(inviteTokenFrom(" abc123 ")).toBe("abc123");+ });++ it("finds none in empty input, a link without one, or prose", () => {+ expect(inviteTokenFrom(" ")).toBeNull();+ expect(inviteTokenFrom("https://switch.example.com/invite")).toBeNull();+ expect(inviteTokenFrom("https://switch.example.com/invite?token=abc123")).toBeNull();+ expect(inviteTokenFrom("please let me in")).toBeNull();+ });++ it("builds links that keep the token out of the query string", () => {+ const link = inviteUrl("https://switch.example.com", "a+b/c=");+ expect(new URL(link).search).toBe("");+ expect(inviteTokenFrom(link)).toBe("a+b/c=");+ });++ it("keeps a pending invite in session storage until cleared", () => {+ expect(readPendingInvite()).toBeNull();+ storePendingInvite("tok");+ expect(readPendingInvite()).toBe("tok");+ clearPendingInvite();+ expect(readPendingInvite()).toBeNull();+ });+});++describe("deliveryNotice", () => {+ it("confirms a sent e-mail", () => {+ const notice = deliveryNotice("sent", "[email protected]");+ expect(notice.severity).toBe("success");+ expect(notice.text).toContain("e-mailed to [email protected]");+ });++ it("says plainly when nothing was sent, and why", () => {+ const off = deliveryNotice("not_configured", "[email protected]");+ expect(off.severity).toBe("warning");+ expect(off.text).toContain("No e-mail was sent");+ expect(off.text).toContain("[email protected]");++ const failed = deliveryNotice("failed", "[email protected]");+ expect(failed.severity).toBe("error");+ expect(failed.text).toContain("failed");+ });++ it("just hands over the link when no address was given", () => {+ const notice = deliveryNotice("not_requested", null);+ expect(notice.severity).toBe("success");+ expect(notice.text).not.toContain("null");+ });+});diff --git a/gateway/src/data/sessionState.ts b/gateway/src/data/sessionState.tsnew file mode 100644index 000000000..9d382fa7f--- /dev/null+++ b/gateway/src/data/sessionState.ts@@ -0,0 +1,110 @@+import type { EmailDelivery, Session } from "./api";++/** Which top-level screen the app shows. Pure, so the order of precedence is+ * testable without rendering anything. */+export type AppView =+ | "signed_out"+ | "accept_invite"+ | "needs_workspace"+ | "needs_selection"+ | "ready";++/** A pending invitation outranks everything a signed-in person could+ * otherwise be shown: someone who followed an invite link came to join that+ * workspace, not to create one or to pick among the ones they already have. */+export function appView(session: Session | null, pendingInvite: string | null): AppView {+ if (session === null) return "signed_out";+ if (pendingInvite !== null) return "accept_invite";+ return session.state;+}++/** May this session administer the workspace it is in? The operator bit, or+ * owner/admin of the current workspace — the same rule the server applies+ * (`require_tenant_admin`). */+export function canAdminTenant(session: Session | null): boolean {+ if (session === null) return false;+ if (session.user.is_operator) return true;+ const role = session.tenant?.role;+ return role === "owner" || role === "admin";+}++const INVITE_KEY = "switch.pendingInvite";++/** Session storage, not local: an invite token is a bearer credential, and+ * it should not outlive the tab that followed the link. */+export function readPendingInvite(): string | null {+ return window.sessionStorage.getItem(INVITE_KEY);+}++export function storePendingInvite(token: string): void {+ window.sessionStorage.setItem(INVITE_KEY, token);+}++export function clearPendingInvite(): void {+ window.sessionStorage.removeItem(INVITE_KEY);+}++/** The token in an invite link's fragment (`#token=…`), or null. */+export function inviteTokenFromHash(hash: string): string | null {+ return new URLSearchParams(hash.replace(/^#/, "")).get("token");+}++/** An invite token from whatever someone pasted: the full link, or the bare+ * token. Null when there is nothing token-like in it. */+export function inviteTokenFrom(input: string): string | null {+ const trimmed = input.trim();+ if (trimmed === "") return null;+ try {+ return inviteTokenFromHash(new URL(trimmed).hash);+ } catch {+ return /\s/.test(trimmed) ? null : trimmed;+ }+}++/** The token rides in the fragment, which the browser never sends, so it+ * stays out of proxy and access logs — the same reason the accept call takes+ * it in the request body. */+export function inviteUrl(origin: string, token: string): string {+ return `${origin}/invite#token=${encodeURIComponent(token)}`;+}++/** May this session change who owns the workspace — grant or revoke the+ * owner role? Narrower than `canAdminTenant`, matching the server's+ * `owns_tenant`. */+export function ownsTenant(session: Session | null): boolean {+ if (session === null) return false;+ return session.user.is_operator || session.tenant?.role === "owner";+}++export interface DeliveryNotice {+ severity: "success" | "warning" | "error";+ text: string;+}++/** What to tell the admin about the invitation they just created. Every+ * outcome but "sent" means the person has not heard about it, so the link+ * is theirs to pass on. */+export function deliveryNotice(delivery: EmailDelivery, email: string | null): DeliveryNotice {+ switch (delivery) {+ case "sent":+ return {+ severity: "success",+ text: `Invitation e-mailed to ${email}. The link below works too; it is shown only once.`,+ };+ case "not_configured":+ return {+ severity: "warning",+ text: `No e-mail was sent — this server has no mail set up. Send this link to ${email} yourself; it is shown only once.`,+ };+ case "failed":+ return {+ severity: "error",+ text: `Sending the e-mail to ${email} failed. The invitation was created: send this link yourself; it is shown only once.`,+ };+ case "not_requested":+ return {+ severity: "success",+ text: "Send this link to the person you are inviting. It is shown only once.",+ };+ }+}diff --git a/gateway/src/layout/NavRail.tsx b/gateway/src/layout/NavRail.tsxindex c3a161edc..3f7a4624e 100644--- a/gateway/src/layout/NavRail.tsx+++ b/gateway/src/layout/NavRail.tsx@@ -1,5 +1,7 @@+import AddOutlined from "@mui/icons-material/AddOutlined";import AccountTreeOutlined from "@mui/icons-material/AccountTreeOutlined";import ChatBubbleOutlineOutlined from "@mui/icons-material/ChatBubbleOutlineOutlined";+import DataUsageOutlined from "@mui/icons-material/DataUsageOutlined";import FolderOutlined from "@mui/icons-material/FolderOutlined";import LockOutlined from "@mui/icons-material/LockOutlined";import LogoutOutlined from "@mui/icons-material/LogoutOutlined";@@ -7,11 +9,27 @@ import MeetingRoomOutlined from "@mui/icons-material/MeetingRoomOutlined";import PeopleOutlined from "@mui/icons-material/PeopleOutlined";import SmartToyOutlined from "@mui/icons-material/SmartToyOutlined";import VpnKeyOutlined from "@mui/icons-material/VpnKeyOutlined";-import { Box, Divider, Menu, MenuItem, Stack, Tooltip, Typography } from "@mui/material";+import WorkspacesOutlined from "@mui/icons-material/WorkspacesOutlined";+import {+ Alert,+ Box,+ Dialog,+ DialogContent,+ DialogTitle,+ Divider,+ Menu,+ MenuItem,+ Snackbar,+ Stack,+ Tooltip,+ Typography,+} from "@mui/material";import { memo, useState } from "react";import { NavLink, useLocation } from "react-router";import type { ComponentType, MouseEvent } from "react";import { useAuth } from "../data/AuthContext";+import { useCurrentTenant } from "../data/hooks";+import CreateWorkspaceForm from "../pages/onboarding/CreateWorkspaceForm";import ChangePasswordDialog from "./ChangePasswordDialog";import ThemeModeToggle from "./ThemeModeToggle";@@ -28,6 +46,11 @@ const NAV_ITEMS: NavItem[] = [{ label: "Agents", path: "/agents", icon: SmartToyOutlined },{ label: "Apps", path: "/collaborations", icon: ChatBubbleOutlineOutlined },{ label: "API Keys", path: "/registration-keys", icon: VpnKeyOutlined },+ { label: "Workspace", path: "/workspace", icon: WorkspacesOutlined },+];++const WORKSPACE_ADMIN_ITEMS: NavItem[] = [+ { label: "Usage", path: "/usage", icon: DataUsageOutlined },];const ADMIN_ITEMS: NavItem[] = [{ label: "Users", path: "/users", icon: PeopleOutlined }];@@ -87,11 +110,30 @@ function RailItem({ item, active }: { item: NavItem; active: boolean }) {export default memo(function NavRail() {const location = useLocation();- const { user, logout } = useAuth();+ const { user, session, isOperator, logout, switchTo } = useAuth();const [anchor, setAnchor] = useState<HTMLElement | null>(null);const [passwordDialogOpen, setPasswordDialogOpen] = useState(false);+ const [createOpen, setCreateOpen] = useState(false);+ const [switchError, setSwitchError] = useState<string | null>(null);++ const switchWorkspace = async (tenantId: string) => {+ setAnchor(null);+ try {+ await switchTo(tenantId);+ } catch (err) {+ setSwitchError(err instanceof Error ? err.message : "Could not switch workspace");+ }+ };++ const { data: tenant } = useCurrentTenant();- const items = user?.role === "admin" ? [...NAV_ITEMS, ...ADMIN_ITEMS] : NAV_ITEMS;+ const items = [+ ...NAV_ITEMS,+ ...(tenant?.administers ? WORKSPACE_ADMIN_ITEMS : []),+ ...(isOperator ? ADMIN_ITEMS : []),+ ];+ const current = session?.tenant ?? null;+ const others = (session?.tenants ?? []).filter((t) => t.id !== current?.id);const initial = (user?.email ?? "?").charAt(0).toUpperCase();return (@@ -192,13 +234,44 @@ export default memo(function NavRail() {<Typography variant="body2" sx={{ fontWeight: 500 }} noWrap>{user?.email}</Typography>- {user?.role === "admin" && (+ {isOperator && (<Typography variant="caption" sx={{ color: "text.secondary" }}>- Admin+ Operator</Typography>)}</Box><Divider sx={{ my: 0.5 }} />+ <Box sx={{ px: 1.5, pt: 0.5, pb: 0.25 }}>+ <Typography variant="caption" sx={{ color: "text.secondary" }}>+ Workspace+ </Typography>+ <Typography variant="body2" sx={{ fontWeight: 500 }} noWrap>+ {current?.name}+ </Typography>+ </Box>+ {others.map((tenant) => (+ <MenuItem+ key={tenant.id}+ onClick={() => switchWorkspace(tenant.id)}+ >+ <Typography variant="body2" noWrap>+ Switch to {tenant.name}+ </Typography>+ </MenuItem>+ ))}+ {session?.can_create_workspace && (+ <MenuItem+ onClick={() => {+ setAnchor(null);+ setCreateOpen(true);+ }}+ sx={{ gap: 1 }}+ >+ <AddOutlined sx={{ fontSize: 16 }} />+ Create workspace+ </MenuItem>+ )}+ <Divider sx={{ my: 0.5 }} /><Boxsx={{display: "flex",@@ -228,6 +301,23 @@ export default memo(function NavRail() {</MenuItem></Menu>+ <Dialog open={createOpen} onClose={() => setCreateOpen(false)} maxWidth="xs" fullWidth>+ <DialogTitle>Create a workspace</DialogTitle>+ <DialogContent sx={{ pt: "8px !important" }}>+ <CreateWorkspaceForm onCancel={() => setCreateOpen(false)} />+ </DialogContent>+ </Dialog>++ <Snackbar+ open={switchError !== null}+ onClose={() => setSwitchError(null)}+ anchorOrigin={{ vertical: "bottom", horizontal: "left" }}+ >+ <Alert severity="error" onClose={() => setSwitchError(null)}>+ {switchError}+ </Alert>+ </Snackbar>+<ChangePasswordDialogopen={passwordDialogOpen}onClose={() => setPasswordDialogOpen(false)}diff --git a/gateway/src/layout/TopBar.tsx b/gateway/src/layout/TopBar.tsxindex 5e7ba07a4..173dc62cd 100644--- a/gateway/src/layout/TopBar.tsx+++ b/gateway/src/layout/TopBar.tsx@@ -1,6 +1,7 @@import MenuBookOutlined from "@mui/icons-material/MenuBookOutlined";import { Box, Button, Stack, Tooltip, Typography } from "@mui/material";import { useLocation } from "react-router";+import { useAuth } from "../data/AuthContext";const SECTION_LABELS: [prefix: string, label: string][] = [["/ecosystem", "Ecosystem"],@@ -10,13 +11,18 @@ const SECTION_LABELS: [prefix: string, label: string][] = [["/collaborations", "Messaging Apps"],["/registration-keys", "API Keys"],["/users", "Users"],+ ["/workspace", "Workspace"],];const DOCS_URL = "https://docs.flintai.dev/flintai/switch/getting-started";export default function TopBar() {const { pathname } = useLocation();+ const { session } = useAuth();const section = SECTION_LABELS.find(([prefix]) => pathname.startsWith(prefix))?.[1];+ const crumbs = [session?.tenant?.name, section].filter(+ (crumb): crumb is string => Boolean(crumb),+ );return (<Stack@@ -31,16 +37,16 @@ export default function TopBar() {><Typography sx={{ fontSize: "0.9375rem", fontWeight: 500, letterSpacing: "-0.02em", px: 2 }}>Switch- {section && (- <>+ {crumbs.map((crumb, i) => (+ <Box component="span" key={i}><Box component="span" sx={{ opacity: 0.4, mx: 1 }}>/</Box>- <Box component="span" sx={{ fontWeight: 700 }}>- {section}+ <Box component="span" sx={{ fontWeight: i === crumbs.length - 1 ? 700 : 500 }}>+ {crumb}</Box>- </>- )}+ </Box>+ ))}</Typography><Stack direction="row" sx={{ alignItems: "center", gap: 1 }}>diff --git a/gateway/src/pages/agents/AgentsPage.tsx b/gateway/src/pages/agents/AgentsPage.tsxindex dbc9fecb7..57153f737 100644--- a/gateway/src/pages/agents/AgentsPage.tsx+++ b/gateway/src/pages/agents/AgentsPage.tsx@@ -35,8 +35,7 @@ import RegisterAgentDialog from "./RegisterAgentDialog";export default function AgentsPage() {const navigate = useNavigate();- const { user } = useAuth();- const isAdmin = user?.role === "admin";+ const { user, canAdminTenant: isAdmin } = useAuth();const { data: agents, loading, refetch } = useAgents();const [deleteTarget, setDeleteTarget] = useState<AgentSummary | null>(null);const [deleting, setDeleting] = useState(false);diff --git a/gateway/src/pages/auth/LoginPage.tsx b/gateway/src/pages/auth/LoginPage.tsxindex 50839e9db..380637a77 100644--- a/gateway/src/pages/auth/LoginPage.tsx+++ b/gateway/src/pages/auth/LoginPage.tsx@@ -16,6 +16,7 @@ import {oidcLoginUrl,} from "../../data/api";import { useAuth } from "../../data/AuthContext";+import { readPendingInvite } from "../../data/sessionState";export default function LoginPage() {const { login } = useAuth();@@ -50,6 +51,11 @@ export default function LoginPage() {const passwordLoginEnabled = authConfig?.password_login_enabled ?? true;const oidcEnabled = authConfig?.oidc_enabled ?? false;const providerLabel = authConfig?.oidc_provider_label ?? "SSO";+ const subtitle = readPendingInvite()+ ? "Sign in to accept your invitation."+ : oidcEnabled && authConfig?.signup_mode === "open"+ ? `Sign in with ${providerLabel} to create a workspace or join one.`+ : "Sign in to manage your agents, rooms and resources.";return (<Box@@ -70,7 +76,7 @@ export default function LoginPage() {Switch Gateway</Typography><Typography variant="body2" sx={{ mb: 3, color: "text.secondary" }}>- Sign in to manage your agents, rooms and resources.+ {subtitle}</Typography><Stack spacing={2}>{error && <Alert severity="error">{error}</Alert>}diff --git a/gateway/src/pages/collaborations/CollaborationsPage.tsx b/gateway/src/pages/collaborations/CollaborationsPage.tsxindex fb2ddb86f..cf2420ba5 100644--- a/gateway/src/pages/collaborations/CollaborationsPage.tsx+++ b/gateway/src/pages/collaborations/CollaborationsPage.tsx@@ -38,8 +38,7 @@ const STATUS_COLOR: Record<string, "success" | "error" | "default"> = {};export default function CollaborationsPage() {- const { user } = useAuth();- const isAdmin = user?.role === "admin";+ const { canAdminTenant: isAdmin } = useAuth();const { data: bridges, loading, refetch } = useBridges();const [deleteTarget, setDeleteTarget] = useState<BridgeDetail | null>(null);const [deleting, setDeleting] = useState(false);diff --git a/gateway/src/pages/collaborations/DisconnectAppDialog.tsx b/gateway/src/pages/collaborations/DisconnectAppDialog.tsxindex 7f6b3c2f8..e177ca0f0 100644--- a/gateway/src/pages/collaborations/DisconnectAppDialog.tsx+++ b/gateway/src/pages/collaborations/DisconnectAppDialog.tsx@@ -14,15 +14,45 @@ import { titleCase } from "../../theme/hootFormat";/*** Disconnecting is the only way an install-created connection can be removed,- * because it is the only one that revokes the token at the platform first.- * Deleting the connection instead is refused, so this dialog carries the- * warning that would otherwise sit on the delete: the rooms survive and go- * internal-only, which is not obvious and cannot be undone by re-installing.+ * so this dialog carries the warning that would otherwise sit on the delete+ * (which is refused): the rooms survive and go internal-only, which is not+ * obvious and cannot be undone by re-installing.** It can fail with the platform's own refusal, in which case nothing has been* destroyed and trying again is the right move — so the error is shown here* rather than closing the dialog on the way out.*/++/**+ * What Disconnect does differs by platform, and telling an operator a+ * credential was revoked when it was not is the kind of thing that surfaces in+ * an incident review. Most platforms hold a token that Disconnect revokes and+ * so removes the app; the distributed Discord app holds none, so disconnecting+ * only stops Switch from using the bot — the bot stays in the server until it+ * is removed in Discord.+ *+ * Keyed on platform as a proxy for token-presence: the backend branches on+ * whether the install has a token, but that field is not surfaced here. Any+ * platform not listed gets the default (revoking) copy. `noun` is what the+ * platform calls the place installed into — a Discord "server", not a+ * "workspace".+ */+const PLATFORM_COPY: Record<string, { noun: string; effect: string }> = {+ discord: {+ noun: "server",+ effect:+ "Switch will stop mirroring messages to and from it. The bot stays in " ++ "the server until you remove it in Discord — disconnecting here does " ++ "not remove it.",+ },+};+const DEFAULT_COPY = {+ noun: "workspace",+ effect:+ "Switch's access token is revoked at the platform and the connection it " ++ "created is removed.",+};+interface Props {install: InstalledApp | null;onClose: () => void;@@ -36,6 +66,7 @@ export default function DisconnectAppDialog({}: Props) {const [submitting, setSubmitting] = useState(false);const [error, setError] = useState<string | null>(null);+ const copy = PLATFORM_COPY[install?.platform ?? ""] ?? DEFAULT_COPY;const handleClose = () => {if (submitting) return;@@ -62,13 +93,12 @@ export default function DisconnectAppDialog({<DialogTitle>Disconnect the app</DialogTitle><DialogContent><DialogContentText>- Remove Switch from the {titleCase(install?.platform ?? "")} workspace{" "}- <b>{install?.external_workspace_id}</b>? The token is revoked at the- platform and the connection it created is removed.+ Disconnect Switch from the {titleCase(install?.platform ?? "")}{" "}+ {copy.noun} <b>{install?.external_workspace_id}</b>? {copy.effect}</DialogContentText><DialogContentText sx={{ mt: 2 }}>Rooms that used this connection are kept, but become internal-only:- they stop mirroring to the workspace, and installing again creates a+ they stop mirroring to the {copy.noun}, and installing again creates anew connection rather than reattaching them.</DialogContentText>{error && (diff --git a/gateway/src/pages/collaborations/InstalledAppsSection.tsx b/gateway/src/pages/collaborations/InstalledAppsSection.tsxindex 61cd9ef5d..19caecdd3 100644--- a/gateway/src/pages/collaborations/InstalledAppsSection.tsx+++ b/gateway/src/pages/collaborations/InstalledAppsSection.tsx@@ -203,10 +203,10 @@ export default function InstalledAppsSection({<Typography variant="body2" color="text.secondary" mb={2}>Installing adds this Switch deployment's own app to your workspace.- The workspace grants it a token that Switch holds and you cannot see or- rotate, and the connection it creates receives messages over HTTPS- rather than the socket a registered app opens. Removing it has to go- through Disconnect, which revokes that token at the platform first.+ Unlike a registered app, whose token is yours to rotate, an installed app+ authenticates with credentials this deployment holds and you cannot see+ or rotate. Removing it has to go through Disconnect rather than deleting+ its connection.</Typography>{error && (diff --git a/gateway/src/pages/onboarding/AcceptInvitePage.tsx b/gateway/src/pages/onboarding/AcceptInvitePage.tsxnew file mode 100644index 000000000..d54625cda--- /dev/null+++ b/gateway/src/pages/onboarding/AcceptInvitePage.tsx@@ -0,0 +1,69 @@+import { Alert, Button, CircularProgress, Stack } from "@mui/material";+import { useState } from "react";+import { acceptInvitation } from "../../data/api";+import { useAuth } from "../../data/AuthContext";+import { clearPendingInvite } from "../../data/sessionState";+import CenteredCard from "./CenteredCard";++/** A signed-in person arriving with an invite token. The token names the+ * workspace, but only the server can read it, so what they are joining is+ * shown once they accept. */+export default function AcceptInvitePage({ token }: { token: string }) {+ const { refresh } = useAuth();+ const [error, setError] = useState<string | null>(null);+ const [submitting, setSubmitting] = useState(false);++ // Accepting switches the session into the workspace, so success reloads+ // into it. Either way the token is spent from this tab: a failed one will+ // not succeed on a retry, and should not keep this screen in front of+ // everything else.+ const accept = async () => {+ setSubmitting(true);+ setError(null);+ try {+ await acceptInvitation(token);+ clearPendingInvite();+ window.location.assign("/");+ } catch (err) {+ clearPendingInvite();+ setError(err instanceof Error ? err.message : "Could not accept the invitation");+ setSubmitting(false);+ }+ };++ const decline = async () => {+ clearPendingInvite();+ await refresh();+ };++ return (+ <CenteredCard+ title="Join a workspace"+ subtitle="You've been invited to a Switch workspace."+ >+ {error ? (+ <Stack spacing={2}>+ <Alert severity="error">{error}</Alert>+ <Button variant="outlined" onClick={decline}>+ Continue+ </Button>+ </Stack>+ ) : (+ <Stack direction="row" spacing={1}>+ <Button+ variant="contained"+ fullWidth+ onClick={accept}+ disabled={submitting}+ startIcon={submitting ? <CircularProgress size={16} /> : undefined}+ >+ Accept invitation+ </Button>+ <Button onClick={decline} disabled={submitting}>+ Decline+ </Button>+ </Stack>+ )}+ </CenteredCard>+ );+}diff --git a/gateway/src/pages/onboarding/CenteredCard.tsx b/gateway/src/pages/onboarding/CenteredCard.tsxnew file mode 100644index 000000000..e9111c44f--- /dev/null+++ b/gateway/src/pages/onboarding/CenteredCard.tsx@@ -0,0 +1,50 @@+import { Box, Button, Card, Stack, Typography } from "@mui/material";+import type { ReactNode } from "react";+import { useAuth } from "../../data/AuthContext";++/** The layout the sign-in page uses, for the screens a signed-in person sees+ * before they are in a workspace. */+export default function CenteredCard({+ title,+ subtitle,+ children,+}: {+ title: string;+ subtitle: ReactNode;+ children: ReactNode;+}) {+ const { user, logout } = useAuth();+ return (+ <Box+ sx={{+ display: "flex",+ minHeight: "100vh",+ alignItems: "center",+ justifyContent: "center",+ backgroundColor: "var(--hoot-canvas)",+ py: 4,+ }}+ >+ <Card sx={{ width: 420, p: 4, boxShadow: "var(--hoot-shadow-surface)" }}>+ <Typography variant="h6" sx={{ mb: 0.5 }}>+ {title}+ </Typography>+ <Typography variant="body2" sx={{ mb: 3, color: "text.secondary" }}>+ {subtitle}+ </Typography>+ {children}+ <Stack+ direction="row"+ sx={{ mt: 3, alignItems: "center", justifyContent: "space-between" }}+ >+ <Typography variant="caption" sx={{ color: "text.secondary" }} noWrap>+ {user ? `Signed in as ${user.email}` : ""}+ </Typography>+ <Button size="small" color="inherit" onClick={logout}>+ Sign out+ </Button>+ </Stack>+ </Card>+ </Box>+ );+}diff --git a/gateway/src/pages/onboarding/CreateWorkspaceForm.tsx b/gateway/src/pages/onboarding/CreateWorkspaceForm.tsxnew file mode 100644index 000000000..7fd4bb6b5--- /dev/null+++ b/gateway/src/pages/onboarding/CreateWorkspaceForm.tsx@@ -0,0 +1,54 @@+import { Alert, Button, CircularProgress, Stack, TextField } from "@mui/material";+import { useState } from "react";+import { createTenant } from "../../data/api";++/** Creating a workspace also switches the session into it (the server+ * re-mints the cookie), so success reloads into the app. */+export default function CreateWorkspaceForm({ onCancel }: { onCancel?: () => void }) {+ const [name, setName] = useState("");+ const [error, setError] = useState<string | null>(null);+ const [submitting, setSubmitting] = useState(false);++ const submit = async (e: React.FormEvent) => {+ e.preventDefault();+ setSubmitting(true);+ setError(null);+ try {+ await createTenant(name.trim());+ window.location.assign("/");+ } catch (err) {+ setError(err instanceof Error ? err.message : "Could not create the workspace");+ setSubmitting(false);+ }+ };++ return (+ <Stack component="form" onSubmit={submit} spacing={2}>+ {error && <Alert severity="error">{error}</Alert>}+ <TextField+ label="Workspace name"+ value={name}+ onChange={(e) => setName(e.target.value)}+ placeholder="e.g. your company or team"+ required+ autoFocus+ />+ <Stack direction="row" spacing={1}>+ <Button+ type="submit"+ variant="contained"+ fullWidth+ disabled={submitting || name.trim() === ""}+ startIcon={submitting ? <CircularProgress size={16} /> : undefined}+ >+ Create workspace+ </Button>+ {onCancel && (+ <Button onClick={onCancel} disabled={submitting}>+ Cancel+ </Button>+ )}+ </Stack>+ </Stack>+ );+}diff --git a/gateway/src/pages/onboarding/InviteCapture.tsx b/gateway/src/pages/onboarding/InviteCapture.tsxnew file mode 100644index 000000000..467eee883--- /dev/null+++ b/gateway/src/pages/onboarding/InviteCapture.tsx@@ -0,0 +1,22 @@+import { useEffect } from "react";+import { Navigate, useLocation } from "react-router";+import { useAuth } from "../../data/AuthContext";+import { inviteTokenFromHash, storePendingInvite } from "../../data/sessionState";++/** `/invite#token=…`: keep the token for this tab and carry on. Signed out,+ * that is the login page, and the token waits through sign-in (including an+ * identity-provider round trip, which is why it is not kept in memory). */+export default function InviteCapture() {+ const { hash } = useLocation();+ const { refresh } = useAuth();+ const token = inviteTokenFromHash(hash);++ useEffect(() => {+ if (token) {+ storePendingInvite(token);+ void refresh();+ }+ }, [token, refresh]);++ return <Navigate to="/" replace />;+}diff --git a/gateway/src/pages/onboarding/OnboardingPage.tsx b/gateway/src/pages/onboarding/OnboardingPage.tsxnew file mode 100644index 000000000..9aa8f2011--- /dev/null+++ b/gateway/src/pages/onboarding/OnboardingPage.tsx@@ -0,0 +1,59 @@+import { Alert, Button, Divider, Stack, TextField, Typography } from "@mui/material";+import { useState } from "react";+import { useAuth } from "../../data/AuthContext";+import { inviteTokenFrom, storePendingInvite } from "../../data/sessionState";+import CenteredCard from "./CenteredCard";+import CreateWorkspaceForm from "./CreateWorkspaceForm";++/** Signed in, and in no workspace yet. */+export default function OnboardingPage() {+ const { session, refresh } = useAuth();+ const [invite, setInvite] = useState("");+ const [inviteError, setInviteError] = useState<string | null>(null);+ const canCreate = session?.can_create_workspace ?? false;++ const joinWithInvite = async (e: React.FormEvent) => {+ e.preventDefault();+ const token = inviteTokenFrom(invite);+ if (token === null) {+ setInviteError("That doesn't look like an invite link.");+ return;+ }+ storePendingInvite(token);+ // The pending invite now outranks this screen; re-reading the session+ // re-renders the app into the accept step.+ await refresh();+ };++ return (+ <CenteredCard+ title="Welcome to Switch"+ subtitle={+ canCreate+ ? "Create a workspace for your team, or join one you've been invited to."+ : "You're not in a workspace yet. Ask a workspace admin for an invite link."+ }+ >+ <Stack spacing={3}>+ {canCreate && <CreateWorkspaceForm />}+ {canCreate && <Divider>or</Divider>}+ <Stack component="form" onSubmit={joinWithInvite} spacing={2}>+ <Typography variant="subtitle2">Have an invite link?</Typography>+ {inviteError && <Alert severity="error">{inviteError}</Alert>}+ <TextField+ label="Invite link"+ value={invite}+ onChange={(e) => {+ setInvite(e.target.value);+ setInviteError(null);+ }}+ size="small"+ />+ <Button type="submit" variant="outlined" disabled={invite.trim() === ""}>+ Join with invite+ </Button>+ </Stack>+ </Stack>+ </CenteredCard>+ );+}diff --git a/gateway/src/pages/onboarding/WorkspacePickerPage.tsx b/gateway/src/pages/onboarding/WorkspacePickerPage.tsxnew file mode 100644index 000000000..54a692ece--- /dev/null+++ b/gateway/src/pages/onboarding/WorkspacePickerPage.tsx@@ -0,0 +1,57 @@+import {+ Alert,+ List,+ ListItemButton,+ ListItemText,+ Typography,+} from "@mui/material";+import { useState } from "react";+import { useAuth } from "../../data/AuthContext";+import CenteredCard from "./CenteredCard";++/** Signed in to several workspaces, and this session has not picked one. */+export default function WorkspacePickerPage() {+ const { session, switchTo } = useAuth();+ const [pending, setPending] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);++ const choose = async (tenantId: string) => {+ setPending(tenantId);+ setError(null);+ try {+ await switchTo(tenantId);+ } catch (err) {+ setError(err instanceof Error ? err.message : "Could not open that workspace");+ setPending(null);+ }+ };++ return (+ <CenteredCard title="Choose a workspace" subtitle="You belong to more than one.">+ {error && (+ <Alert severity="error" sx={{ mb: 2 }}>+ {error}+ </Alert>+ )}+ <List disablePadding>+ {(session?.tenants ?? []).map((tenant) => (+ <ListItemButton+ key={tenant.id}+ onClick={() => choose(tenant.id)}+ disabled={pending !== null}+ sx={{ borderRadius: 1 }}+ >+ <ListItemText+ primary={tenant.name}+ secondary={+ <Typography variant="caption" sx={{ textTransform: "capitalize" }}>+ {tenant.role}+ </Typography>+ }+ />+ </ListItemButton>+ ))}+ </List>+ </CenteredCard>+ );+}diff --git a/gateway/src/pages/resources/DocumentDetailPage.tsx b/gateway/src/pages/resources/DocumentDetailPage.tsxindex 524a5f889..759b7412e 100644--- a/gateway/src/pages/resources/DocumentDetailPage.tsx+++ b/gateway/src/pages/resources/DocumentDetailPage.tsx@@ -34,7 +34,7 @@ import ResourceAttachmentsSection from "./ResourceAttachmentsSection";export default function DocumentDetailPage() {const { id } = useParams<{ id: string }>();const navigate = useNavigate();- const { user } = useAuth();+ const { user, canAdminTenant } = useAuth();const [doc, setDoc] = useState<DocumentDetail | null>(null);const [loading, setLoading] = useState(true);const [fetchError, setFetchError] = useState<string | null>(null);@@ -77,7 +77,7 @@ export default function DocumentDetailPage() {}const canMutate =- !!user && (user.id === doc.owner_id || user.role === "admin");+ !!user && (user.id === doc.owner_id || canAdminTenant);return (<Box>diff --git a/gateway/src/pages/resources/PackageDetailPage.tsx b/gateway/src/pages/resources/PackageDetailPage.tsxindex 88950a89d..78b326713 100644--- a/gateway/src/pages/resources/PackageDetailPage.tsx+++ b/gateway/src/pages/resources/PackageDetailPage.tsx@@ -33,7 +33,7 @@ import ResourceAttachmentsSection from "./ResourceAttachmentsSection";export default function PackageDetailPage() {const { id } = useParams<{ id: string }>();const navigate = useNavigate();- const { user } = useAuth();+ const { user, canAdminTenant } = useAuth();const [pkg, setPkg] = useState<PackageDetail | null>(null);const [loading, setLoading] = useState(true);const [fetchError, setFetchError] = useState<string | null>(null);@@ -76,7 +76,7 @@ export default function PackageDetailPage() {}const canMutate =- !!user && (user.id === pkg.owner_id || user.role === "admin");+ !!user && (user.id === pkg.owner_id || canAdminTenant);return (<Box>diff --git a/gateway/src/pages/resources/ReferenceDetailPage.tsx b/gateway/src/pages/resources/ReferenceDetailPage.tsxindex e43d4135d..9a74b5eb4 100644--- a/gateway/src/pages/resources/ReferenceDetailPage.tsx+++ b/gateway/src/pages/resources/ReferenceDetailPage.tsx@@ -36,7 +36,7 @@ import UrlsValueForm from "./value_forms/UrlsValueForm";export default function ReferenceDetailPage() {const { id } = useParams<{ id: string }>();const navigate = useNavigate();- const { user } = useAuth();+ const { user, canAdminTenant } = useAuth();const { data: types } = useReferenceTypes();const [ref, setRef] = useState<ReferenceDetail | null>(null);const [loading, setLoading] = useState(true);@@ -83,7 +83,7 @@ export default function ReferenceDetailPage() {// has. Its only job is the value hint; every label comes from the server.const visibleTypeSpec = (types ?? []).find((t) => t.type === ref.type);const canMutate =- !!user && (user.id === ref.owner_id || user.role === "admin");+ !!user && (user.id === ref.owner_id || canAdminTenant);return (<Box>diff --git a/gateway/src/pages/rooms/RoomDetailPage.tsx b/gateway/src/pages/rooms/RoomDetailPage.tsxindex b68f6212f..5877c7172 100644--- a/gateway/src/pages/rooms/RoomDetailPage.tsx+++ b/gateway/src/pages/rooms/RoomDetailPage.tsx@@ -67,7 +67,7 @@ import ExportRoomYamlDialog from "./ExportRoomYamlDialog";export default function RoomDetailPage() {const { roomId } = useParams<{ roomId: string }>();const navigate = useNavigate();- const { user } = useAuth();+ const { user, canAdminTenant } = useAuth();const { data: room, loading, error, refetch } = useRoom(roomId);const [exportOpen, setExportOpen] = useState(false);@@ -96,11 +96,11 @@ export default function RoomDetailPage() {const canWrite =!!user &&(user.id === room.owner_id ||- user.role === "admin" ||+ canAdminTenant ||room.write_visibility === "public");// Delete is stricter — owner or admin only, never via public write.const canDelete =- !!user && (user.id === room.owner_id || user.role === "admin");+ !!user && (user.id === room.owner_id || canAdminTenant);return (<Box>diff --git a/gateway/src/pages/usage/BudgetDialog.tsx b/gateway/src/pages/usage/BudgetDialog.tsxnew file mode 100644index 000000000..f4962ed27--- /dev/null+++ b/gateway/src/pages/usage/BudgetDialog.tsx@@ -0,0 +1,192 @@+import {+ Alert,+ Button,+ CircularProgress,+ Dialog,+ DialogActions,+ DialogContent,+ DialogTitle,+ MenuItem,+ Stack,+ TextField,+} from "@mui/material";+import { useCallback, useEffect, useState } from "react";+import {+ type Budget,+ type UsageMetric,+ MAX_BUDGET_AMOUNT,+ MAX_BUDGET_PERIOD_HOURS,+ PER_MODEL_METRICS,+ USAGE_METRICS,+ createBudget,+ updateBudget,+} from "../../data/api";+import { useAgents } from "../../data/hooks";+import { formatAmount, metricLabel, parseBound } from "./usageFormat";++const WHOLE_WORKSPACE = "";++interface Props {+ tenantId: string;+ // The budget being edited, or null to add one.+ budget: Budget | null;+ open: boolean;+ onClose: () => void;+ onSaved: () => void;+}++export default function BudgetDialog({ tenantId, budget, open, onClose, onSaved }: Props) {+ const { data: agents } = useAgents();+ const [agentId, setAgentId] = useState(WHOLE_WORKSPACE);+ const [metric, setMetric] = useState<UsageMetric>("output_tokens");+ const [model, setModel] = useState("");+ const [limit, setLimit] = useState("");+ const [periodHours, setPeriodHours] = useState("24");+ const [submitting, setSubmitting] = useState(false);+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ if (!open) return;+ setAgentId(budget?.agent_id ?? WHOLE_WORKSPACE);+ setMetric(budget?.metric ?? "output_tokens");+ setModel(budget?.model ?? "");+ setLimit(budget ? String(budget.amount_limit) : "");+ setPeriodHours(budget ? String(budget.period_hours) : "24");+ setError(null);+ }, [open, budget]);++ const perModel = PER_MODEL_METRICS.includes(metric);+ const limitValue = parseBound(limit, MAX_BUDGET_AMOUNT);+ const periodValue = parseBound(periodHours, MAX_BUDGET_PERIOD_HOURS);+ const limitInvalid = limit.trim() !== "" && limitValue === null;+ const periodInvalid = periodHours.trim() !== "" && periodValue === null;++ const handleSubmit = useCallback(async () => {+ if (limitValue === null || periodValue === null) return;+ setSubmitting(true);+ setError(null);+ try {+ if (budget) {+ await updateBudget(tenantId, budget.id, {+ amount_limit: limitValue,+ period_hours: periodValue,+ });+ } else {+ await createBudget(tenantId, {+ agent_id: agentId === WHOLE_WORKSPACE ? null : agentId,+ metric,+ model: perModel ? model.trim() : "",+ amount_limit: limitValue,+ period_hours: periodValue,+ });+ }+ onSaved();+ onClose();+ } catch (err) {+ setError(err instanceof Error ? err.message : "Failed to save the budget.");+ } finally {+ setSubmitting(false);+ }+ }, [budget, tenantId, agentId, metric, perModel, model, limitValue, periodValue, onSaved, onClose]);++ return (+ <Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>+ <DialogTitle>{budget ? "Edit budget" : "Add budget"}</DialogTitle>+ <DialogContent>+ <Stack spacing={2} sx={{ mt: 1 }}>+ {error && <Alert severity="error">{error}</Alert>}+ {budget && (+ <Alert severity="info">+ What a budget covers is fixed. To cover something else, add another budget.+ </Alert>+ )}+ <TextField+ select+ label="Applies to"+ value={agentId}+ onChange={(e) => setAgentId(e.target.value)}+ disabled={budget !== null}+ helperText="A workspace budget caps what all agents spend together."+ fullWidth+ >+ <MenuItem value={WHOLE_WORKSPACE}>Every agent in the workspace</MenuItem>+ {(agents ?? []).map((agent) => (+ <MenuItem key={agent.id} value={agent.id}>+ {agent.name}+ </MenuItem>+ ))}+ {budget?.agent_id && !(agents ?? []).some((a) => a.id === budget.agent_id) && (+ <MenuItem value={budget.agent_id}>{budget.agent_name ?? budget.agent_id}</MenuItem>+ )}+ </TextField>+ <TextField+ select+ label="Metric"+ value={metric}+ onChange={(e) => setMetric(e.target.value as UsageMetric)}+ disabled={budget !== null}+ fullWidth+ >+ {USAGE_METRICS.map((m) => (+ <MenuItem key={m} value={m}>+ {metricLabel(m)}+ </MenuItem>+ ))}+ </TextField>+ <TextField+ label="Model"+ value={perModel ? model : ""}+ onChange={(e) => setModel(e.target.value)}+ disabled={budget !== null || !perModel}+ placeholder="Every model"+ helperText={+ perModel+ ? "Leave empty to cover every model."+ : `${metricLabel(metric)} are not counted per model.`+ }+ fullWidth+ />+ <Stack direction="row" spacing={2}>+ <TextField+ label="Limit"+ type="number"+ value={limit}+ onChange={(e) => setLimit(e.target.value)}+ required+ fullWidth+ error={limitInvalid}+ helperText={limitInvalid ? `A whole number from 1 to ${formatAmount(MAX_BUDGET_AMOUNT)}.` : undefined}+ slotProps={{ htmlInput: { min: 1, max: MAX_BUDGET_AMOUNT, step: 1 } }}+ />+ <TextField+ label="Period (hours)"+ type="number"+ value={periodHours}+ onChange={(e) => setPeriodHours(e.target.value)}+ required+ fullWidth+ error={periodInvalid}+ helperText={+ periodInvalid+ ? `A whole number of hours from 1 to ${formatAmount(MAX_BUDGET_PERIOD_HOURS)}.`+ : "24 is a day, 168 a week."+ }+ slotProps={{ htmlInput: { min: 1, max: MAX_BUDGET_PERIOD_HOURS, step: 1 } }}+ />+ </Stack>+ </Stack>+ </DialogContent>+ <DialogActions>+ <Button onClick={onClose}>Cancel</Button>+ <Button+ variant="contained"+ onClick={handleSubmit}+ disabled={submitting || limitValue === null || periodValue === null}+ startIcon={submitting ? <CircularProgress size={16} /> : undefined}+ >+ {budget ? "Save" : "Add"}+ </Button>+ </DialogActions>+ </Dialog>+ );+}diff --git a/gateway/src/pages/usage/UsagePage.tsx b/gateway/src/pages/usage/UsagePage.tsxnew file mode 100644index 000000000..9bfa66926--- /dev/null+++ b/gateway/src/pages/usage/UsagePage.tsx@@ -0,0 +1,330 @@+import AddCircleOutline from "@mui/icons-material/AddCircleOutline";+import DeleteOutline from "@mui/icons-material/DeleteOutline";+import EditOutlined from "@mui/icons-material/EditOutlined";+import {+ Alert,+ Box,+ Button,+ Chip,+ CircularProgress,+ Dialog,+ DialogActions,+ DialogContent,+ DialogContentText,+ DialogTitle,+ IconButton,+ LinearProgress,+ MenuItem,+ Stack,+ TextField,+ Tooltip,+ Typography,+} from "@mui/material";+import type { GridColDef } from "@mui/x-data-grid";+import { useCallback, useMemo, useState } from "react";+import DataTable from "../../components/DataTable";+import { type Budget, type CurrentTenant, type UsageTotal, deleteBudget } from "../../data/api";+import { useBudgets, useCurrentTenant, useUsage } from "../../data/hooks";+import { formatDateTime } from "../../theme/hootFormat";+import BudgetDialog from "./BudgetDialog";+import { formatAmount, formatPeriod, metricLabel } from "./usageFormat";++const WINDOWS = [+ { label: "Last 24 hours", hours: 24 },+ { label: "Last 7 days", hours: 24 * 7 },+ { label: "Last 30 days", hours: 24 * 30 },+];++type UsageRow = UsageTotal & { id: string };++export default function UsagePage() {+ const { data: tenant, loading, error } = useCurrentTenant();++ if (loading) return <CircularProgress />;+ if (error || !tenant) {+ return <Alert severity="error">Could not load the current workspace.</Alert>;+ }+ if (!tenant.administers) {+ return (+ <Alert severity="info">+ Only owners and admins of {tenant.name} can see its usage and budgets.+ </Alert>+ );+ }+ return <WorkspaceUsage tenant={tenant} />;+}++function WorkspaceUsage({ tenant }: { tenant: CurrentTenant }) {+ return (+ <Box sx={{ display: "flex", flexDirection: "column", flexGrow: 1, minHeight: 0, gap: 3 }}>+ <Typography variant="h5">Usage · {tenant.name}</Typography>+ <BudgetsSection tenantId={tenant.id} />+ <UsageSection tenantId={tenant.id} />+ </Box>+ );+}++function BudgetsSection({ tenantId }: { tenantId: string }) {+ const { data: budgets, loading, error, refetch } = useBudgets(tenantId);+ const [dialogOpen, setDialogOpen] = useState(false);+ const [editing, setEditing] = useState<Budget | null>(null);+ const [deleteTarget, setDeleteTarget] = useState<Budget | null>(null);+ const [deleting, setDeleting] = useState(false);+ const [deleteError, setDeleteError] = useState<string | null>(null);++ const openEditor = useCallback((budget: Budget | null) => {+ setEditing(budget);+ setDialogOpen(true);+ }, []);++ const handleDelete = useCallback(async () => {+ if (!deleteTarget) return;+ setDeleting(true);+ setDeleteError(null);+ try {+ await deleteBudget(tenantId, deleteTarget.id);+ setDeleteTarget(null);+ refetch();+ } catch (err) {+ setDeleteError(err instanceof Error ? err.message : "Failed to remove the budget.");+ } finally {+ setDeleting(false);+ }+ }, [tenantId, deleteTarget, refetch]);++ const columns = useMemo<GridColDef<Budget>[]>(+ () => [+ {+ field: "agent_name",+ headerName: "Applies to",+ flex: 1,+ minWidth: 180,+ valueGetter: (_value, row) =>+ row.agent_id === null ? "Every agent" : (row.agent_name ?? row.agent_id),+ },+ {+ field: "metric",+ headerName: "Metric",+ width: 170,+ valueFormatter: (value) => metricLabel(value),+ },+ {+ field: "model",+ headerName: "Model",+ width: 160,+ valueFormatter: (value: string) => value || "Every model",+ },+ {+ field: "spent",+ headerName: "Spent this period",+ flex: 1,+ minWidth: 220,+ sortable: false,+ renderCell: ({ row }) => (+ <Stack justifyContent="center" sx={{ height: "100%" }} spacing={0.5}>+ <Typography variant="body2">+ {formatAmount(row.spent)} of {formatAmount(row.amount_limit)} per{" "}+ {formatPeriod(row.period_hours)}+ </Typography>+ <LinearProgress+ variant="determinate"+ value={Math.min(100, (row.spent / row.amount_limit) * 100)}+ color={row.exhausted ? "error" : "primary"}+ />+ </Stack>+ ),+ },+ {+ field: "resets_at",+ headerName: "Resets",+ width: 180,+ valueFormatter: (value: string) => formatDateTime(value),+ },+ {+ field: "exhausted",+ headerName: "Status",+ width: 120,+ renderCell: ({ row }) =>+ row.exhausted ? (+ <Chip size="small" color="error" label="Reached" />+ ) : (+ <Chip size="small" variant="outlined" label="Within" />+ ),+ },+ {+ field: "actions",+ headerName: "",+ width: 100,+ sortable: false,+ filterable: false,+ renderCell: ({ row }) => (+ <>+ <Tooltip title="Edit">+ <IconButton size="small" onClick={() => openEditor(row)}>+ <EditOutlined fontSize="small" />+ </IconButton>+ </Tooltip>+ <Tooltip title="Remove">+ <IconButton size="small" onClick={() => setDeleteTarget(row)}>+ <DeleteOutline fontSize="small" />+ </IconButton>+ </Tooltip>+ </>+ ),+ },+ ],+ [openEditor],+ );++ return (+ <Box>+ <Stack direction="row" alignItems="center" justifyContent="space-between" mb={1}>+ <Box>+ <Typography variant="subtitle1" sx={{ fontWeight: 600 }}>+ Budgets+ </Typography>+ <Typography variant="body2" color="text.secondary">+ An agent that reaches a budget stops taking work until it resets. People are+ never stopped. No budget means no limit.+ </Typography>+ </Box>+ <Button variant="contained" startIcon={<AddCircleOutline />} onClick={() => openEditor(null)}>+ Add budget+ </Button>+ </Stack>+ {loading ? (+ <CircularProgress />+ ) : error ? (+ <Alert severity="error">Could not load budgets.</Alert>+ ) : (+ <Box sx={{ display: "flex", flexDirection: "column", height: Math.min(420, 108 + (budgets?.length ?? 0) * 56) }}>+ <DataTable rows={budgets ?? []} columns={columns} fillHeight pageSize={10} />+ </Box>+ )}++ <BudgetDialog+ tenantId={tenantId}+ budget={editing}+ open={dialogOpen}+ onClose={() => setDialogOpen(false)}+ onSaved={refetch}+ />++ <Dialog open={!!deleteTarget} onClose={() => setDeleteTarget(null)}>+ <DialogTitle>Remove budget</DialogTitle>+ <DialogContent>+ {deleteError && (+ <Alert severity="error" sx={{ mb: 2 }}>+ {deleteError}+ </Alert>+ )}+ <DialogContentText>+ Remove the {deleteTarget ? metricLabel(deleteTarget.metric).toLowerCase() : ""} budget+ for {deleteTarget?.agent_id === null ? "every agent" : deleteTarget?.agent_name}? What+ it covers will no longer be limited.+ </DialogContentText>+ </DialogContent>+ <DialogActions>+ <Button onClick={() => setDeleteTarget(null)}>Cancel</Button>+ <Button+ color="error"+ variant="contained"+ onClick={handleDelete}+ disabled={deleting}+ startIcon={deleting ? <CircularProgress size={16} /> : undefined}+ >+ Remove+ </Button>+ </DialogActions>+ </Dialog>+ </Box>+ );+}++function UsageSection({ tenantId }: { tenantId: string }) {+ const [windowHours, setWindowHours] = useState(WINDOWS[0].hours);+ const [since, until] = useMemo(() => {+ const end = new Date();+ return [new Date(end.getTime() - windowHours * 3600 * 1000), end];+ }, [windowHours]);+ const { data: totals, loading, error } = useUsage(tenantId, since, until);++ const rows = useMemo<UsageRow[]>(+ () =>+ (totals ?? []).map((t) => ({ ...t, id: `${t.metric}:${t.client_id}:${t.model}` })),+ [totals],+ );++ const columns = useMemo<GridColDef<UsageRow>[]>(+ () => [+ {+ field: "client_name",+ headerName: "Consumer",+ flex: 1,+ minWidth: 200,+ valueGetter: (_value, row) => row.client_name ?? `Deleted (${row.client_id})`,+ },+ {+ field: "client_type",+ headerName: "Kind",+ width: 120,+ valueFormatter: (value: string | null) => value ?? "—",+ },+ {+ field: "metric",+ headerName: "Metric",+ width: 180,+ valueFormatter: (value) => metricLabel(value),+ },+ {+ field: "model",+ headerName: "Model",+ width: 180,+ valueFormatter: (value: string) => value || "—",+ },+ {+ field: "amount",+ headerName: "Amount",+ type: "number",+ width: 140,+ valueFormatter: (value: number) => formatAmount(value),+ },+ ],+ [],+ );++ return (+ <Box sx={{ display: "flex", flexDirection: "column", flexGrow: 1, minHeight: 320 }}>+ <Stack direction="row" alignItems="center" justifyContent="space-between" mb={1}>+ <Box>+ <Typography variant="subtitle1" sx={{ fontWeight: 600 }}>+ What was spent+ </Typography>+ <Typography variant="body2" color="text.secondary">+ Counted in whole hours. Tokens appear only for sessions that report them.+ </Typography>+ </Box>+ <TextField+ select+ size="small"+ value={windowHours}+ onChange={(e) => setWindowHours(Number(e.target.value))}+ sx={{ width: 200 }}+ >+ {WINDOWS.map((w) => (+ <MenuItem key={w.hours} value={w.hours}>+ {w.label}+ </MenuItem>+ ))}+ </TextField>+ </Stack>+ {loading ? (+ <CircularProgress />+ ) : error ? (+ <Alert severity="error">Could not load usage.</Alert>+ ) : (+ <DataTable rows={rows} columns={columns} fillHeight pageSize={25} />+ )}+ </Box>+ );+}diff --git a/gateway/src/pages/usage/usageFormat.ts b/gateway/src/pages/usage/usageFormat.tsnew file mode 100644index 000000000..49b8fabf2--- /dev/null+++ b/gateway/src/pages/usage/usageFormat.ts@@ -0,0 +1,33 @@+import type { UsageMetric } from "../../data/api";++const METRIC_LABELS: Record<UsageMetric, string> = {+ messages: "Messages",+ turns: "Turns",+ input_tokens: "Input tokens",+ output_tokens: "Output tokens",+ cache_read_tokens: "Cache read tokens",+ cache_write_tokens: "Cache write tokens",+};++/** A whole number from 1 to `max` typed as digits only, or null. */+export function parseBound(raw: string, max: number): number | null {+ if (!/^\d+$/.test(raw.trim())) return null;+ const value = Number(raw.trim());+ return value >= 1 && value <= max ? value : null;+}++export function metricLabel(metric: UsageMetric): string {+ return METRIC_LABELS[metric];+}++export function formatAmount(value: number): string {+ return value.toLocaleString();+}++/** `24h` → "day", `168h` → "week", anything else in hours. */+export function formatPeriod(hours: number): string {+ if (hours === 24) return "day";+ if (hours === 168) return "week";+ if (hours % 24 === 0) return `${hours / 24} days`;+ return `${hours}h`;+}diff --git a/gateway/src/pages/workspace/CreateInvitationDialog.test.tsx b/gateway/src/pages/workspace/CreateInvitationDialog.test.tsxnew file mode 100644index 000000000..17d2883eb--- /dev/null+++ b/gateway/src/pages/workspace/CreateInvitationDialog.test.tsx@@ -0,0 +1,66 @@+import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";+import CreateInvitationDialog from "./CreateInvitationDialog";++function answerCreateWith(body: Record<string, unknown>) {+ const fetchMock = vi.fn(async () => new Response(JSON.stringify(body), { status: 201 }));+ vi.stubGlobal("fetch", fetchMock);+ return fetchMock;+}++const created = {+ id: "i1",+ role: "member",+ email: "[email protected]",+ expires_at: "2030-01-01",+ uses_remaining: 1,+ revoked_at: null,+ created_by: "u1",+ created_at: "2029-12-25",+ token: "tok123",+};++function renderDialog(emailEnabled: boolean) {+ render(+ <CreateInvitationDialog+ open+ tenantId="t1"+ isOwner={false}+ emailEnabled={emailEnabled}+ onClose={() => {}}+ onCreated={() => {}}+ />,+ );+ fireEvent.change(screen.getByLabelText("Email (optional)"), {+ target: { value: "[email protected]" },+ });+}++describe("CreateInvitationDialog", () => {+ afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ });++ it("sends the invitation when mail is set up, and says it went", async () => {+ const fetchMock = answerCreateWith({ ...created, email_delivery: "sent" });+ renderDialog(true);++ fireEvent.click(screen.getByRole("button", { name: "Send invitation" }));++ expect(await screen.findByText(/e-mailed to [email protected]/)).toBeTruthy();+ expect(screen.getByDisplayValue(/\/invite#token=tok123$/)).toBeTruthy();+ const [, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];+ expect(JSON.parse(String(init.body)).email).toBe("[email protected]");+ });++ it("says nothing was sent when the server has no mail, and shows the link", async () => {+ answerCreateWith({ ...created, email_delivery: "not_configured" });+ renderDialog(false);++ fireEvent.click(screen.getByRole("button", { name: "Create link" }));++ expect(await screen.findByText(/No e-mail was sent/)).toBeTruthy();+ expect(screen.getByDisplayValue(/\/invite#token=tok123$/)).toBeTruthy();+ });+});diff --git a/gateway/src/pages/workspace/CreateInvitationDialog.tsx b/gateway/src/pages/workspace/CreateInvitationDialog.tsxnew file mode 100644index 000000000..8ee08a0f4--- /dev/null+++ b/gateway/src/pages/workspace/CreateInvitationDialog.tsx@@ -0,0 +1,187 @@+import ContentCopy from "@mui/icons-material/ContentCopy";+import {+ Alert,+ Button,+ CircularProgress,+ Dialog,+ DialogActions,+ DialogContent,+ DialogTitle,+ IconButton,+ InputAdornment,+ MenuItem,+ Stack,+ TextField,+ Tooltip,+} from "@mui/material";+import { useCallback, useState } from "react";+import { type TenantRole, createInvitation } from "../../data/api";+import { type DeliveryNotice, deliveryNotice, inviteUrl } from "../../data/sessionState";++interface Props {+ open: boolean;+ tenantId: string;+ isOwner: boolean;+ emailEnabled: boolean;+ onClose: () => void;+ onCreated: () => void;+}++/** An invitation naming an address is e-mailed when the server has mail set+ * up; either way the token is returned once, at creation, so the link is+ * shown here and nowhere else — alongside what happened to the e-mail. */+export default function CreateInvitationDialog({+ open,+ tenantId,+ isOwner,+ emailEnabled,+ onClose,+ onCreated,+}: Props) {+ const [role, setRole] = useState<TenantRole>("member");+ const [email, setEmail] = useState("");+ const [hours, setHours] = useState("168");+ const [uses, setUses] = useState("1");+ const [submitting, setSubmitting] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [link, setLink] = useState<string | null>(null);+ const [notice, setNotice] = useState<DeliveryNotice | null>(null);+ const [copied, setCopied] = useState(false);++ const handleClose = useCallback(() => {+ setRole("member");+ setEmail("");+ setHours("168");+ setUses("1");+ setError(null);+ setLink(null);+ setNotice(null);+ setCopied(false);+ onClose();+ }, [onClose]);++ const handleSubmit = useCallback(async () => {+ setSubmitting(true);+ setError(null);+ try {+ const created = await createInvitation(tenantId, {+ role,+ email: email.trim() === "" ? null : email.trim(),+ expires_in_hours: Number(hours),+ uses_remaining: Number(uses),+ });+ setLink(inviteUrl(window.location.origin, created.token));+ setNotice(deliveryNotice(created.email_delivery, created.email));+ onCreated();+ } catch (err) {+ setError(err instanceof Error ? err.message : "Could not create the invitation");+ } finally {+ setSubmitting(false);+ }+ }, [tenantId, role, email, hours, uses, onCreated]);++ const copy = useCallback(async () => {+ if (link === null) return;+ await navigator.clipboard.writeText(link);+ setCopied(true);+ }, [link]);++ const addressed = email.trim() !== "";+ const roles: TenantRole[] = isOwner ? ["member", "admin", "owner"] : ["member", "admin"];+ const valid =+ Number.isInteger(Number(hours)) && Number(hours) > 0 && Number(hours) <= 8760 &&+ Number.isInteger(Number(uses)) && Number(uses) > 0;++ return (+ <Dialog open={open} onClose={handleClose} maxWidth="sm" fullWidth>+ <DialogTitle>Invite to workspace</DialogTitle>+ <DialogContent>+ {link !== null && notice !== null ? (+ <Stack spacing={2} sx={{ pt: 1 }}>+ <Alert severity={notice.severity}>{notice.text}</Alert>+ <TextField+ value={link}+ label="Invite link"+ fullWidth+ slotProps={{+ input: {+ readOnly: true,+ endAdornment: (+ <InputAdornment position="end">+ <Tooltip title={copied ? "Copied" : "Copy"}>+ <IconButton onClick={copy} edge="end" aria-label="Copy invite link">+ <ContentCopy fontSize="small" />+ </IconButton>+ </Tooltip>+ </InputAdornment>+ ),+ },+ }}+ />+ </Stack>+ ) : (+ <Stack spacing={2} sx={{ pt: 1 }}>+ {error && <Alert severity="error">{error}</Alert>}+ <TextField+ select+ label="Role"+ value={role}+ onChange={(e) => setRole(e.target.value as TenantRole)}+ >+ {roles.map((r) => (+ <MenuItem key={r} value={r}>+ {r.charAt(0).toUpperCase() + r.slice(1)}+ </MenuItem>+ ))}+ </TextField>+ <TextField+ label="Email (optional)"+ value={email}+ onChange={(e) => setEmail(e.target.value)}+ helperText={+ emailEnabled+ ? "We'll e-mail them the link. Only someone signed in with this address can accept. Leave empty for anyone with the link."+ : "E-mail isn't set up on this server, so you'll get a link to send yourself. Only someone signed in with this address can accept. Leave empty for anyone with the link."+ }+ />+ <Stack direction="row" spacing={2}>+ <TextField+ label="Expires in (hours)"+ type="number"+ value={hours}+ onChange={(e) => setHours(e.target.value)}+ fullWidth+ />+ <TextField+ label="Uses"+ type="number"+ value={uses}+ onChange={(e) => setUses(e.target.value)}+ fullWidth+ />+ </Stack>+ </Stack>+ )}+ </DialogContent>+ <DialogActions>+ {link !== null ? (+ <Button onClick={handleClose} variant="contained">+ Done+ </Button>+ ) : (+ <>+ <Button onClick={handleClose}>Cancel</Button>+ <Button+ onClick={handleSubmit}+ variant="contained"+ disabled={submitting || !valid}+ startIcon={submitting ? <CircularProgress size={16} /> : undefined}+ >+ {emailEnabled && addressed ? "Send invitation" : "Create link"}+ </Button>+ </>+ )}+ </DialogActions>+ </Dialog>+ );+}diff --git a/gateway/src/pages/workspace/InvitationsSection.tsx b/gateway/src/pages/workspace/InvitationsSection.tsxnew file mode 100644index 000000000..6fc9e66e4--- /dev/null+++ b/gateway/src/pages/workspace/InvitationsSection.tsx@@ -0,0 +1,143 @@+import AddCircleOutline from "@mui/icons-material/AddCircleOutline";+import {+ Alert,+ Button,+ Chip,+ CircularProgress,+ Stack,+ Typography,+} from "@mui/material";+import type { GridColDef } from "@mui/x-data-grid";+import { useCallback, useEffect, useMemo, useState } from "react";+import DataTable from "../../components/DataTable";+import { type Invitation, fetchInvitations, revokeInvitation } from "../../data/api";+import { formatDate, titleCase } from "../../theme/hootFormat";+import CreateInvitationDialog from "./CreateInvitationDialog";+import { useLoad } from "./useLoad";++function invitationStatus(inv: Invitation, now: number): string {+ if (inv.revoked_at) return "Revoked";+ if (new Date(inv.expires_at).getTime() <= now) return "Expired";+ if (inv.uses_remaining <= 0) return "Used";+ return "Active";+}++export default function InvitationsSection({+ tenantId,+ isOwner,+ emailEnabled,+}: {+ tenantId: string;+ isOwner: boolean;+ emailEnabled: boolean;+}) {+ const load = useCallback(() => fetchInvitations(tenantId), [tenantId]);+ const { data: invitations, error, loading, refetch } = useLoad(load);+ const [createOpen, setCreateOpen] = useState(false);+ const [actionError, setActionError] = useState<string | null>(null);+ // Re-evaluated on a timer so an invitation that expires while the page is+ // open stops showing as active.+ const [now, setNow] = useState(() => Date.now());+ useEffect(() => {+ const timer = window.setInterval(() => setNow(Date.now()), 30_000);+ return () => window.clearInterval(timer);+ }, []);++ const revoke = useCallback(+ async (id: string) => {+ setActionError(null);+ try {+ await revokeInvitation(tenantId, id);+ await refetch();+ } catch (err) {+ setActionError(err instanceof Error ? err.message : "Could not revoke the invitation");+ }+ },+ [refetch, tenantId],+ );++ const columns = useMemo<GridColDef<Invitation>[]>(() => {+ return [+ {+ field: "email",+ headerName: "For",+ flex: 1.5,+ minWidth: 180,+ valueFormatter: (value) => (value as string | null) ?? "Anyone with the link",+ },+ {+ field: "role",+ headerName: "Role",+ width: 110,+ valueFormatter: (value) => titleCase(String(value)),+ },+ {+ field: "status",+ headerName: "Status",+ width: 110,+ valueGetter: (_value, row) => invitationStatus(row, now),+ renderCell: ({ value }) => (+ <Chip label={value} size="small" color={value === "Active" ? "primary" : "default"} />+ ),+ },+ { field: "uses_remaining", headerName: "Uses left", width: 100 },+ {+ field: "expires_at",+ headerName: "Expires",+ width: 140,+ valueFormatter: (value) => formatDate(value as string),+ },+ {+ field: "actions",+ headerName: "",+ width: 100,+ sortable: false,+ renderCell: ({ row }) =>+ invitationStatus(row, now) === "Active" ? (+ <Button size="small" color="error" onClick={() => revoke(row.id)}>+ Revoke+ </Button>+ ) : null,+ },+ ];+ }, [now, revoke]);++ return (+ <Stack spacing={1.5}>+ <Stack direction="row" alignItems="center" justifyContent="space-between">+ <Typography variant="h6">Invitations</Typography>+ <Button+ variant="contained"+ startIcon={<AddCircleOutline />}+ onClick={() => setCreateOpen(true)}+ >+ Invite+ </Button>+ </Stack>+ {error && <Alert severity="error">{error}</Alert>}+ {actionError && (+ <Alert severity="error" onClose={() => setActionError(null)}>+ {actionError}+ </Alert>+ )}+ {loading ? (+ <CircularProgress />+ ) : (+ <DataTable+ rows={invitations ?? []}+ columns={columns}+ height={Math.min(520, 108 + Math.max(1, invitations?.length ?? 0) * 52)}+ pageSize={25}+ />+ )}+ <CreateInvitationDialog+ open={createOpen}+ tenantId={tenantId}+ isOwner={isOwner}+ emailEnabled={emailEnabled}+ onClose={() => setCreateOpen(false)}+ onCreated={refetch}+ />+ </Stack>+ );+}diff --git a/gateway/src/pages/workspace/MembersSection.tsx b/gateway/src/pages/workspace/MembersSection.tsxnew file mode 100644index 000000000..a8027a7d6--- /dev/null+++ b/gateway/src/pages/workspace/MembersSection.tsx@@ -0,0 +1,159 @@+import DeleteOutline from "@mui/icons-material/DeleteOutline";+import {+ Alert,+ Chip,+ CircularProgress,+ IconButton,+ MenuItem,+ Select,+ Stack,+ Tooltip,+ Typography,+} from "@mui/material";+import type { GridColDef } from "@mui/x-data-grid";+import { useCallback, useMemo, useState } from "react";+import DataTable from "../../components/DataTable";+import { useAuth } from "../../data/AuthContext";+import {+ type Member,+ type TenantRole,+ fetchMembers,+ removeMember,+ updateMemberRole,+} from "../../data/api";+import { formatDate, titleCase } from "../../theme/hootFormat";+import { useLoad } from "./useLoad";++type MemberRow = Member & { id: string };++interface Props {+ tenantId: string;+ selfId: string;+ canAdmin: boolean;+ isOwner: boolean;+}++/** An admin may manage members and admins; only an owner may grant the owner+ * role or touch an existing owner. The server enforces the same, and refuses+ * the last owner — its message is shown as is. */+export default function MembersSection({ tenantId, selfId, canAdmin, isOwner }: Props) {+ const load = useCallback(() => fetchMembers(tenantId), [tenantId]);+ const { data: members, error, loading, refetch } = useLoad(load);+ const [actionError, setActionError] = useState<string | null>(null);+ const [busy, setBusy] = useState<string | null>(null);+ const { refresh } = useAuth();++ const act = useCallback(+ async (userId: string, action: () => Promise<unknown>) => {+ setBusy(userId);+ setActionError(null);+ try {+ await action();+ await refetch();+ // Your own role decides what this page offers you.+ if (userId === selfId) await refresh();+ } catch (err) {+ setActionError(err instanceof Error ? err.message : "The change failed");+ } finally {+ setBusy(null);+ }+ },+ [refetch, refresh, selfId],+ );++ const columns = useMemo<GridColDef<MemberRow>[]>(() => {+ const mayManage = (row: MemberRow) => canAdmin && (isOwner || row.role !== "owner");+ const roles: TenantRole[] = isOwner ? ["owner", "admin", "member"] : ["admin", "member"];+ return [+ {+ field: "name",+ headerName: "Name",+ flex: 1,+ minWidth: 140,+ renderCell: ({ row }) => (row.user_id === selfId ? `${row.name} (you)` : row.name),+ },+ { field: "email", headerName: "Email", flex: 1.5, minWidth: 200 },+ {+ field: "role",+ headerName: "Role",+ width: 150,+ renderCell: ({ row }) =>+ mayManage(row) ? (+ <Select+ size="small"+ value={row.role}+ disabled={busy !== null}+ onChange={(e) =>+ act(row.user_id, () =>+ updateMemberRole(tenantId, row.user_id, e.target.value as TenantRole),+ )+ }+ aria-label={`Role for ${row.email}`}+ sx={{ fontSize: "0.875rem" }}+ >+ {roles.map((role) => (+ <MenuItem key={role} value={role}>+ {titleCase(role)}+ </MenuItem>+ ))}+ </Select>+ ) : (+ <Chip+ label={titleCase(row.role)}+ size="small"+ color={row.role === "member" ? "default" : "primary"}+ />+ ),+ },+ {+ field: "created_at",+ headerName: "Joined",+ width: 140,+ valueFormatter: (value) => formatDate(value as string),+ },+ {+ field: "actions",+ headerName: "",+ width: 60,+ sortable: false,+ renderCell: ({ row }) =>+ mayManage(row) && row.user_id !== selfId ? (+ <Tooltip title="Remove from workspace">+ <span>+ <IconButton+ size="small"+ disabled={busy !== null}+ onClick={() => act(row.user_id, () => removeMember(tenantId, row.user_id))}+ aria-label={`Remove ${row.email}`}+ >+ <DeleteOutline fontSize="small" />+ </IconButton>+ </span>+ </Tooltip>+ ) : null,+ },+ ];+ }, [act, busy, canAdmin, isOwner, selfId, tenantId]);++ return (+ <Stack spacing={1.5}>+ <Typography variant="h6">Members</Typography>+ {error && <Alert severity="error">{error}</Alert>}+ {actionError && (+ <Alert severity="error" onClose={() => setActionError(null)}>+ {actionError}+ </Alert>+ )}+ {loading ? (+ <CircularProgress />+ ) : (+ <DataTable+ rows={(members ?? []).map((m) => ({ ...m, id: m.user_id }))}+ columns={columns}+ height={Math.min(520, 108 + (members?.length ?? 0) * 52)}+ pageSize={25}+ />+ )}+ </Stack>+ );+}diff --git a/gateway/src/pages/workspace/WorkspacePage.tsx b/gateway/src/pages/workspace/WorkspacePage.tsxnew file mode 100644index 000000000..b7a19ca50--- /dev/null+++ b/gateway/src/pages/workspace/WorkspacePage.tsx@@ -0,0 +1,42 @@+import { Alert, Box, CircularProgress, Stack, Typography } from "@mui/material";+import { useAuth } from "../../data/AuthContext";+import { ownsTenant } from "../../data/sessionState";+import InvitationsSection from "./InvitationsSection";+import MembersSection from "./MembersSection";++export default function WorkspacePage() {+ const { session, canAdminTenant } = useAuth();+ const tenant = session?.tenant;+ if (!tenant) return <CircularProgress />;+ const isOwner = ownsTenant(session);++ return (+ <Box>+ <Stack spacing={0.5} mb={3}>+ <Typography variant="h5">{tenant.name}</Typography>+ <Typography variant="body2" sx={{ color: "text.secondary" }}>+ You are {tenant.role === "admin" ? "an admin" : `a ${tenant.role}`} of this workspace.+ </Typography>+ </Stack>+ <Stack spacing={4}>+ <MembersSection+ tenantId={tenant.id}+ selfId={session.user.id}+ canAdmin={canAdminTenant}+ isOwner={isOwner}+ />+ {canAdminTenant ? (+ <InvitationsSection+ tenantId={tenant.id}+ isOwner={isOwner}+ emailEnabled={session.invite_email_enabled}+ />+ ) : (+ <Alert severity="info">+ Ask a workspace owner or admin to invite someone.+ </Alert>+ )}+ </Stack>+ </Box>+ );+}diff --git a/gateway/src/pages/workspace/useLoad.ts b/gateway/src/pages/workspace/useLoad.tsnew file mode 100644index 000000000..0b0dc9f8f--- /dev/null+++ b/gateway/src/pages/workspace/useLoad.ts@@ -0,0 +1,26 @@+import { useCallback, useEffect, useState } from "react";++/** Load with the error kept: these calls fail for reasons the person should+ * read (not an admin, workspace gone), not only for being offline. */+export function useLoad<T>(load: () => Promise<T>) {+ const [data, setData] = useState<T | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [loading, setLoading] = useState(true);++ const refetch = useCallback(async () => {+ try {+ setData(await load());+ setError(null);+ } catch (err) {+ setError(err instanceof Error ? err.message : "Failed to load");+ } finally {+ setLoading(false);+ }+ }, [load]);++ useEffect(() => {+ void refetch();+ }, [refetch]);++ return { data, error, loading, refetch };+}diff --git a/gateway/vitest.config.ts b/gateway/vitest.config.tsnew file mode 100644index 000000000..32cb08157--- /dev/null+++ b/gateway/vitest.config.ts@@ -0,0 +1,10 @@+import react from "@vitejs/plugin-react";+import { defineConfig } from "vitest/config";++export default defineConfig({+ plugins: [react()],+ test: {+ environment: "jsdom",+ include: ["src/**/*.test.{ts,tsx}"],+ },+});diff --git a/justfile b/justfileindex 19e9c78c3..2e528cd61 100644--- a/justfile+++ b/justfile@@ -73,6 +73,42 @@ reset:run:uv run --project core python -m switch_core.main+# ── Run switch-core as a stand-in for Switch Cloud ────────────────────────────+# For testing Switch Console against this checkout instead of whatever a shared+# deployment runs. Needs `just up` first. Invitation e-mails go to the Mailpit+# catcher, and their links point at :8000 so that pasting one into the Console+# matches the stand-in. docs/old/LOCAL_DEVELOPMENT.md, "A local Switch Cloud".+# Run switch-core as Switch Cloud, with invitation e-mail caught at :8025+local-cloud:+ docker compose -f deploy/local/docker-compose.yml --project-directory . --profile mail up -d mailpit+ GATEWAY_SMTP_HOST=127.0.0.1 GATEWAY_SMTP_PORT=1025 GATEWAY_SMTP_TLS=none \+ GATEWAY_SMTP_USERNAME= GATEWAY_SMTP_PASSWORD= \+ GATEWAY_SMTP_FROM="Switch <[email protected]>" \+ FRONTEND_BASE_URL=http://localhost:8000 \+ uv run --project core python -m switch_core.main++# Run Switch Console with "Switch Cloud" pointing at `just local-cloud`, in+# its own data directory so other dev builds' databases are left alone+local-cloud-console:+ cd console && SWITCH_CLOUD_URL=http://localhost:8000 SWITCH_CONSOLE_USER_DATA_DIR=switchdash-local-cloud pnpm dev++# Made by the gateway admin from .env, so it joins the admin's workspace, as+# every admin-made account does. Use the admin's domain (switch.local by+# default) for an account that should be able to join by domain.+# just local-cloud-user [email protected] "Ada Lovelace" <password>+# Create an account on `just local-cloud` to sign in with+local-cloud-user email name password:+ #!/usr/bin/env bash+ set -euo pipefail+ jar="$(mktemp)"+ trap 'rm -f "$jar"' EXIT+ curl -fsS -c "$jar" -H 'Content-Type: application/json' \+ -d "$(jq -n --arg e "$GATEWAY_ADMIN_EMAIL" --arg p "$GATEWAY_ADMIN_PASSWORD" '{email: $e, password: $p}')" \+ http://localhost:8000/gateway/auth/login >/dev/null+ curl -fsS -b "$jar" -H 'Content-Type: application/json' \+ -d "$(jq -n --arg e '{{ email }}' --arg n '{{ name }}' --arg p '{{ password }}' '{email: $e, name: $n, password: $p}')" \+ http://localhost:8000/gateway/users | jq .+# ── Format code with ruff ──────────────────────────────────────────────────────# Run from the repo root so ruff's hierarchical config discovery applies the# right config per file (core/, the sub-projects that carry their own, and@@ -147,6 +183,9 @@ gateway-dev:gateway-build:cd gateway && npm run build+gateway-test:+ cd gateway && npm test+# ── Standalone deployment (all-in-one Docker, no host toolchain) ──────────────# Repo users build from source: the build override re-adds the `build:` blocks# so images come from the working tree, not GHCR. All profiles are enabled to