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
One address per Switch server instead of two (CHOO-3202) (#753)
Christian McDermott98bac5db9303
diff --git a/.dockerignore b/.dockerignoreindex dfdd4456c..2dcbfc115 100644--- a/.dockerignore+++ b/.dockerignore@@ -4,6 +4,8 @@**/__pycache__*.pyc**/node_modules+# Rebuilt inside the image; a local build is only context to upload.+gateway/distinternal/deploy/terraform/.terraformdeploy/remote/helm/switch/charts.claudediff --git a/.env.example b/.env.exampleindex b410301f3..1fb0c340a 100644--- a/.env.example+++ b/.env.example@@ -237,6 +237,13 @@ GATEWAY_ADMIN_PASSWORD=# ── Frontend ─────────────────────────────────────────────────────────────────FRONTEND_BASE_URL=http://localhost:5173+# The dashboard's build output (gateway/dist). Set, and switch-core serves the+# dashboard on its own port beside the API, so the server has one address; the+# server image sets it. Leave unset in development and use the Vite dev server.+# With it set and FRONTEND_BASE_URL unset, links to the dashboard use+# GATEWAY_PUBLIC_URL.+# GATEWAY_UI_DIR=gateway/dist+# Public origin of the gateway HTTP API (used to build the switchdash:// deeplink# HTTP redirect so "Open in Switch Console" is clickable on Discord, Telegram# and other http-only platforms). Leave unset to post the raw switchdash://diff --git a/.github/workflows/pr-ci.yml b/.github/workflows/pr-ci.ymlindex 7021810e9..cefcbe077 100644--- a/.github/workflows/pr-ci.yml+++ b/.github/workflows/pr-ci.yml@@ -91,6 +91,10 @@ jobs:backend:- *shared- 'core/**'+ # switch-core serves the dashboard's pages from a list that+ # core/tests holds equal to this file's routes, so a new page+ # here has to run them too.+ - 'gateway/src/App.tsx'# Tested from core/tests, so a change to it alone still runs them.- 'scripts/check_migration_heads_for_open_prs.py'- 'scripts/pin_chart_images.py'diff --git a/console/apps/switch-console-desktop/drizzle/0052_one_server_url.sql b/console/apps/switch-console-desktop/drizzle/0052_one_server_url.sqlnew file mode 100644index 000000000..dfa05d852--- /dev/null+++ b/console/apps/switch-console-desktop/drizzle/0052_one_server_url.sql@@ -0,0 +1,22 @@+-- One address per server instead of a gateway address and an API address.+--+-- The address kept is the API's. It is the one every agent's credentials, every+-- controller and every sidecar already point at, on this machine and on remote+-- hosts, so nothing outside this table has to be rewritten; and switch-core+-- answers the management API under `/gateway` on it too. The id is untouched,+-- so workspaces, agents, saved sign-ins and view state all still match.+--+-- The gateway address survives only where it differed, as `dashboard_url`: the+-- place to open dashboard pages until the server serves its own dashboard. A+-- server registered with one address for both (Switch Cloud, a single-host+-- ingress) gets null there and nothing changes for it.+--+-- The unique index goes with the gateway address and is not recreated on the+-- API address: two rows may already share one, and refusing them here would+-- stop the app from starting. Adding a server refuses a duplicate instead.+ALTER TABLE `switch_servers` RENAME COLUMN "api_url" TO "url";--> statement-breakpoint+DROP INDEX `idx_switch_servers_gateway_url`;--> statement-breakpoint+ALTER TABLE `switch_servers` ADD `dashboard_url` text;--> statement-breakpoint+UPDATE `switch_servers` SET `dashboard_url` = rtrim(`gateway_url`, '/')+ WHERE lower(rtrim(`gateway_url`, '/')) <> lower(rtrim(`url`, '/'));--> statement-breakpoint+ALTER TABLE `switch_servers` DROP COLUMN `gateway_url`;diff --git a/console/apps/switch-console-desktop/drizzle/meta/0052_snapshot.json b/console/apps/switch-console-desktop/drizzle/meta/0052_snapshot.jsonnew file mode 100644index 000000000..dc6d9f39b--- /dev/null+++ b/console/apps/switch-console-desktop/drizzle/meta/0052_snapshot.json@@ -0,0 +1,974 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "0d212417-eac5-4e00-b1c7-5a0a38086511",+ "prevId": "a44f0db7-1021-46dc-90e6-810d28551f3a",+ "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+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "dashboard_url": {+ "name": "dashboard_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "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": {},+ "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": {+ "\"switch_servers\".\"api_url\"": "\"switch_servers\".\"url\""+ }+ },+ "internal": {+ "indexes": {}+ }+}diff --git a/console/apps/switch-console-desktop/drizzle/meta/_journal.json b/console/apps/switch-console-desktop/drizzle/meta/_journal.jsonindex cb8a8591c..bb9042fde 100644--- a/console/apps/switch-console-desktop/drizzle/meta/_journal.json+++ b/console/apps/switch-console-desktop/drizzle/meta/_journal.json@@ -365,6 +365,13 @@"when": 1790300000000,"tag": "0051_workspaces","breakpoints": true+ },+ {+ "idx": 52,+ "version": "6",+ "when": 1791559324805,+ "tag": "0052_one_server_url",+ "breakpoints": true}]}diff --git a/console/apps/switch-console-desktop/package.json b/console/apps/switch-console-desktop/package.jsonindex a83f55efb..4358c072a 100644--- a/console/apps/switch-console-desktop/package.json+++ b/console/apps/switch-console-desktop/package.json@@ -75,6 +75,7 @@"pidusage": "^4.0.1","smol-toml": "^1.8.0","ssh2": "^1.17.0",+ "tldts": "^7.4.2","zod": "^4.3.6"},"devDependencies": {diff --git a/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration.ts b/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration.tsindex dcd5683b2..34c8ddbe3 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration.ts@@ -651,7 +651,7 @@ async function controllerRefusal(serverId: string): Promise<string | null> {const server = await getServer(serverId);if (!server) throw new Error('Console no longer knows this Switch server.');const protocol = await controllerProtocol();- const response = await fetch(`${server.apiUrl}/v1/management/controllers/enroll`, {+ const response = await fetch(`${server.url}/v1/management/controllers/enroll`, {method: 'POST',headers: { 'content-type': 'application/json', 'Switch-Controller-Protocol': protocol },body: '{}',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 e373c7b78..f67a53a38 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@@ -116,7 +116,7 @@ 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 mockServer = vi.hoisted(() => ({ id: 'srv-1', url: 'https://switch.example.com' }));const { addAgent } = await import('./add-agent');const { trackEvent } = await import('@main/core/telemetry/telemetry-service');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 7560ee2a8..021726e27 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@@ -231,7 +231,7 @@ export async function checkNewAgent(params: AddAgentParams): Promise<NewAgentCheparams.sshHost,params.dir,params.name,- server.apiUrl+ server.url);if (foreignEndpoint !== null) {return {@@ -249,7 +249,7 @@ export async function checkNewAgent(params: AddAgentParams): Promise<NewAgentCheparams.sshHost,params.dir,params.name,- server.apiUrl+ server.url);if (slotAgentId !== null) {const [knownLocally] = await db@@ -372,7 +372,7 @@ async function runAddAgent(params: AddAgentParams): Promise<AddAgentResult> {// (CHOO-1440).await writeNeutralAgentSettingsFs(workdir.fs, {slug: params.name,- apiEndpoint: server.apiUrl,+ apiEndpoint: server.url,apiToken: registered.apiKey,agentId: registered.id,expectedAgentId: slotAgentId ?? undefined,@@ -394,7 +394,7 @@ async function runAddAgent(params: AddAgentParams): Promise<AddAgentResult> {name: params.name,providerId: params.providerId,switchAgentId: registered.id,- apiEndpoint: server.apiUrl,+ apiEndpoint: server.url,workspaceId: targetWorkspace.id,autoApprove: params.autoApprove,providerConfig: params.providerConfig ?? null,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 ff79b8655..8fb62838e 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@@ -88,7 +88,7 @@ vi.mock('@main/core/workspaces/workspaces-store', () => ({const mockServer = vi.hoisted(() => ({id: 'srv-1',name: 'Switch',- apiUrl: 'https://switch.example.com',+ url: 'https://switch.example.com',}));vi.mock('@main/core/workspaces/workspace-session', () => ({withWorkspaceSession: (_workspaceId: string, fn: (server: unknown) => unknown) => fn(mockServer),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 0cc10a079..5f7769660 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@@ -152,11 +152,11 @@ export async function attachConfiguredAgents(// are read from the same on-disk file. A difference is legitimate (one Switch// server reachable at two URLs) so it is surfaced, not corrected — correcting// it would mean writing to another install's credentials.- if (!sameApiEndpoint(found.apiEndpoint, server.apiUrl)) {+ if (!sameApiEndpoint(found.apiEndpoint, server.url)) {log.warn('attachConfiguredAgents: directory endpoint differs from the chosen server', {name,dirEndpoint: found.apiEndpoint,- serverEndpoint: server.apiUrl,+ serverEndpoint: server.url,serverId: server.id,});}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 c622c1803..e898ccd8e 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@@ -131,8 +131,8 @@ export async function discoverLoadableAgentsOnHost(viewerIsOwner: !!(me && info?.ownerId && info.ownerId === me.id),description: info?.description ?? null,source: 'server',- endpointMismatch: !sameApiEndpoint(agent.apiEndpoint, server.apiUrl),- blockedReason: blockedReasonFor(agent, server.apiUrl),+ endpointMismatch: !sameApiEndpoint(agent.apiEndpoint, server.url),+ blockedReason: blockedReasonFor(agent, server.url),});}} catch (error) {@@ -151,7 +151,7 @@ export async function discoverLoadableAgentsOnHost(}// --- Source 2: Bounded $HOME scan (opt-in) ---- if (!params.includeHomeScan) return { agents: [...seen.values()], serverApiUrl: server.apiUrl };+ if (!params.includeHomeScan) return { agents: [...seen.values()], serverApiUrl: server.url };try {const scannedDirs = await findSwitchAgentDirsOnHost(params.sshHost);for (const dir of scannedDirs) {@@ -176,8 +176,8 @@ export async function discoverLoadableAgentsOnHost(viewerIsOwner: false,description: null,source: 'scan',- endpointMismatch: !sameApiEndpoint(agent.apiEndpoint, server.apiUrl),- blockedReason: blockedReasonFor(agent, server.apiUrl),+ endpointMismatch: !sameApiEndpoint(agent.apiEndpoint, server.url),+ blockedReason: blockedReasonFor(agent, server.url),});}}@@ -196,7 +196,7 @@ export async function discoverLoadableAgentsOnHost(});}- return { agents: [...seen.values()], serverApiUrl: server.apiUrl };+ return { agents: [...seen.values()], serverApiUrl: server.url };}function blockedReasonFor(agent: DiscoveredConfiguredAgent, serverApiUrl: string): string | null {@@ -279,8 +279,8 @@ export async function discoverLoadableAgentsInDir(params: {viewerIsOwner: false,description: null,source: 'scan' as const,- endpointMismatch: !sameApiEndpoint(agent.apiEndpoint, server.apiUrl),- blockedReason: blockedReasonFor(agent, server.apiUrl),+ endpointMismatch: !sameApiEndpoint(agent.apiEndpoint, server.url),+ blockedReason: blockedReasonFor(agent, server.url),}));- return { agents, serverApiUrl: server.apiUrl };+ return { agents, serverApiUrl: server.url };}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 d3ed6dc4e..91c57a31b 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@@ -19,10 +19,10 @@ const { h } = vi.hoisted(() => ({} | null,agentExists: true,unauthorized: false,- server: { id: 'srv-1', name: 'Switch', apiUrl: 'https://switch.example.com' } as {+ server: { id: 'srv-1', name: 'Switch', url: 'https://switch.example.com' } as {id: string;name: string;- apiUrl: string;+ url: string;managementKind?: string;sshHost?: string;} | null,@@ -104,7 +104,7 @@ beforeEach(() => {h.detected = { agentId: 'sw-1', apiEndpoint: 'https://switch.example.com' };h.agentExists = true;h.unauthorized = false;- h.server = { id: 'srv-1', name: 'Switch', apiUrl: 'https://switch.example.com' };+ h.server = { id: 'srv-1', name: 'Switch', url: 'https://switch.example.com' };});describe('where an onboarded agent is said to have come from', () => {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 b943590f5..a91a8759a 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@@ -59,14 +59,14 @@ describe('propagateServerApiUrl', () => {{id: 'pilot',name: 'Pilot',- gatewayUrl: 'https://pilot-gateway.example.com',- apiUrl: 'https://old-api.example.com',+ url: 'https://old-api.example.com',+ dashboardUrl: 'https://pilot-gateway.example.com',},{id: 'other',name: 'Other',- gatewayUrl: 'https://other-gateway.example.com',- apiUrl: 'https://other-api.example.com',+ url: 'https://other-api.example.com',+ dashboardUrl: 'https://other-gateway.example.com',},]);diff --git a/console/apps/switch-console-desktop/src/main/core/embedded-controller/controller.ts b/console/apps/switch-console-desktop/src/main/core/embedded-controller/controller.tsindex dcc324c90..90a164d28 100644--- a/console/apps/switch-console-desktop/src/main/core/embedded-controller/controller.ts+++ b/console/apps/switch-console-desktop/src/main/core/embedded-controller/controller.ts@@ -60,7 +60,7 @@ export const embeddedControllerController = createRPCController({defaultWorkspace: async (params: { serverId: string; name: string }): Promise<string | null> => {const server = await getServer(params.serverId);if (!server) throw new Error(`No server ${params.serverId} in Console.`);- const path = defaultWorkspacePath(serverWorkspacesDir(homedir(), server.apiUrl), params.name);+ const path = defaultWorkspacePath(serverWorkspacesDir(homedir(), server.url), params.name);if (path === null) return null;const home = homedir();return path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path;diff --git a/console/apps/switch-console-desktop/src/main/core/embedded-controller/embedded-controllers.ts b/console/apps/switch-console-desktop/src/main/core/embedded-controller/embedded-controllers.tsindex f31aca427..d6dff4a9b 100644--- a/console/apps/switch-console-desktop/src/main/core/embedded-controller/embedded-controllers.ts+++ b/console/apps/switch-console-desktop/src/main/core/embedded-controller/embedded-controllers.ts@@ -116,7 +116,7 @@ export const embeddedControllerService = new EmbeddedControllerService({},}),records: new EnrollmentFile(() => join(base(), 'state.json')),- serverApiUrl: async (serverId) => (await getServer(serverId))?.apiUrl ?? null,+ serverApiUrl: async (serverId) => (await getServer(serverId))?.url ?? null,secrets: encryptedAppSecretsStore,management: gatewayManagementPort,files: {diff --git a/console/apps/switch-console-desktop/src/main/core/embedded-controller/management-port.test.ts b/console/apps/switch-console-desktop/src/main/core/embedded-controller/management-port.test.tsindex afa7e199c..2e2475964 100644--- a/console/apps/switch-console-desktop/src/main/core/embedded-controller/management-port.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/embedded-controller/management-port.test.ts@@ -23,7 +23,7 @@ vi.mock('@main/core/workspaces/workspace-session', () => ({withReachableWorkspaceSession: async (_workspaceId: string,fn: (server: unknown) => Promise<unknown>- ) => fn({ id: 'server-1', name: 'S', apiUrl: 'https://switch.example.com' }),+ ) => fn({ id: 'server-1', name: 'S', url: 'https://switch.example.com' }),}));const { gatewayManagementPort, placedOn } = await import('./management-port');diff --git a/console/apps/switch-console-desktop/src/main/core/embedded-controller/management-port.ts b/console/apps/switch-console-desktop/src/main/core/embedded-controller/management-port.tsindex b7dbe5e32..1ac008480 100644--- a/console/apps/switch-console-desktop/src/main/core/embedded-controller/management-port.ts+++ b/console/apps/switch-console-desktop/src/main/core/embedded-controller/management-port.ts@@ -51,7 +51,7 @@ export const gatewayManagementPort: ManagementPort = {try {return await withReachableWorkspaceSession(workspaceId, async (server) => {const enrolled = await enrollConsoleController(server, body);- return { serverId: server.id, apiUrl: server.apiUrl, ...enrolled };+ return { serverId: server.id, apiUrl: server.url, ...enrolled };});} catch (error) {if (error instanceof AgentManagementUnavailableError) throw error;diff --git a/console/apps/switch-console-desktop/src/main/core/host-controllers/host-controllers.ts b/console/apps/switch-console-desktop/src/main/core/host-controllers/host-controllers.tsindex eb000b0e5..a96a56cdb 100644--- a/console/apps/switch-console-desktop/src/main/core/host-controllers/host-controllers.ts+++ b/console/apps/switch-console-desktop/src/main/core/host-controllers/host-controllers.ts@@ -67,7 +67,7 @@ export const hostControllerService = new HostControllerService({);}},- serverApiUrl: async (serverId) => (await getServer(serverId))?.apiUrl ?? null,+ serverApiUrl: async (serverId) => (await getServer(serverId))?.url ?? null,read: async (workspaceId, controllerId) => {try {return await withReachableWorkspaceSession(workspaceId, async (server) => {diff --git a/console/apps/switch-console-desktop/src/main/core/managed-agents/give-machine-login.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-agents/give-machine-login.test.tsindex ec73bdb92..7436700a2 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-agents/give-machine-login.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-agents/give-machine-login.test.ts@@ -27,7 +27,7 @@ vi.mock('@main/core/host-controllers/host-controllers', () => ({ hostControllerSvi.mock('@main/core/workspaces/workspaces-store', () => ({ requireWorkspaceForServer: vi.fn() }));vi.mock('@main/core/workspaces/workspace-session', () => ({withReachableServerWorkspaceSession: (_serverId: string, run: (server: unknown) => unknown) =>- run({ id: 'server-1', gatewayUrl: 'https://switch.example.com' }),+ run({ id: 'server-1', url: 'https://switch.example.com' }),}));vi.mock('@main/core/switch-servers/local-provider-sign-in', () => ({localProviderAuthPath: () => '/home/me/.codex/auth.json',diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/controller.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/controller.tsindex ec775b952..39ebe3894 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/controller.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/controller.ts@@ -46,8 +46,8 @@ export const localSwitchServerController = createRPCController({const result = await localServerService.useAnotherPort(port);if (result.kind !== 'started' || !before) return result;const after = await getManagedServer();- if (after && after.apiUrl !== before.apiUrl) {- await propagateServerApiUrl(after.id, after.apiUrl);+ if (after && after.url !== before.url) {+ await propagateServerApiUrl(after.id, after.url);await embeddedControllerService.followServerApiUrl(after.id);}return result;diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/free-port.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/free-port.test.tsindex e60d7f637..1017b4f92 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/free-port.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/free-port.test.ts@@ -1,5 +1,11 @@import { describe, expect, it } from 'vitest';-import { apiUrlFor, gatewayUrlFor, isPorts, pickFreePorts } from './free-port';+import {+ apiUrlFor,+ gatewayUrlFor,+ isPorts,+ managedServerAddresses,+ pickFreePorts,+} from './free-port';describe('pickFreePorts', () => {it('returns four distinct, positive host ports', async () => {@@ -32,4 +38,12 @@ describe('url helpers', () => {expect(gatewayUrlFor(ports)).toBe('http://localhost:3300');expect(apiUrlFor(ports)).toBe('http://localhost:8000');});++ it('registers a managed stack on switch-core’s port, with the dashboard on its own', () => {+ const ports = { gateway: 3300, api: 8000, mattermost: 8065, postgres: 5432 };+ expect(managedServerAddresses(ports)).toEqual({+ url: 'http://localhost:8000',+ dashboardUrl: 'http://localhost:3300',+ });+ });});diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/free-port.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/free-port.tsindex e84ee23b5..80b0fae89 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/free-port.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/free-port.ts@@ -74,3 +74,17 @@ export function gatewayUrlFor(ports: LocalServerPorts): string {export function apiUrlFor(ports: LocalServerPorts): string {return `http://localhost:${ports.api}`;}++/**+ * The addresses a managed stack is registered with: switch-core's port as the+ * server's one address, and the dashboard container's port as where its pages+ * open. The compose Switch Console runs still starts that container, and the+ * switch-core it pins may predate serving the dashboard itself; once neither+ * holds, the dashboard address goes and so does this pairing.+ */+export function managedServerAddresses(ports: LocalServerPorts): {+ url: string;+ dashboardUrl: string;+} {+ return { url: apiUrlFor(ports), dashboardUrl: gatewayUrlFor(ports) };+}diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/health.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/health.tsindex 3bb8928e8..052e78914 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/health.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/health.ts@@ -27,12 +27,12 @@ const sleep = (ms: number, signal?: AbortSignal): Promise<void> =>* timeout. Honours `signal` so a stop/cancel aborts the wait.*/export async function waitForHealth(- apiUrl: string,+ serverUrl: string,opts: { signal?: AbortSignal; timeoutMs?: number } = {}): Promise<boolean> {const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;const deadline = Date.now() + timeoutMs;- const url = `${apiUrl}/gateway/auth/config`;+ const url = `${serverUrl}/gateway/auth/config`;while (Date.now() < deadline) {try {diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/host/host-for-server.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/host/host-for-server.test.tsindex 20a6b73d4..05739fac8 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/host/host-for-server.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/host/host-for-server.test.ts@@ -6,8 +6,8 @@ function server(overrides: Partial<SwitchServer>): SwitchServer {return {id: 'id',name: 'name',- gatewayUrl: 'http://localhost:1',- apiUrl: 'http://localhost:2',+ url: 'http://localhost:2',+ dashboardUrl: 'http://localhost:1',managed: true,managementKind: 'local',sshHost: null,diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/host/remote-free-port.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/host/remote-free-port.test.tsnew file mode 100644index 000000000..fa6d08445--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/host/remote-free-port.test.ts@@ -0,0 +1,32 @@+import { describe, expect, it, vi } from 'vitest';++const listManagedServers = vi.hoisted(() => vi.fn());+const findFreePort = vi.hoisted(() => vi.fn());++vi.mock('@main/core/switch-servers/servers-store', () => ({ listManagedServers }));+vi.mock('@main/lib/logger', () => ({ log: { warn: vi.fn() } }));+vi.mock('../free-port', () => ({ findFreePort }));++const { pickRemoteFreePorts } = await import('./remote-free-port');++describe('pickRemoteFreePorts', () => {+ it('avoids every port another managed server is registered on, and what the host listens on', async () => {+ listManagedServers.mockResolvedValue([+ { url: 'http://localhost:41001', dashboardUrl: 'http://localhost:41000' },+ // A stack registered without a dashboard of its own claims only its address.+ { url: 'http://localhost:42001', dashboardUrl: null },+ ]);+ const seen: Set<number>[] = [];+ let next = 50000;+ findFreePort.mockImplementation(async (taken: Set<number>) => {+ seen.push(new Set(taken));+ return next++;+ });+ const ctx = { exec: vi.fn(async () => ({ stdout: 'LISTEN 0 4096 0.0.0.0:5432 0.0.0.0:*\n' })) };++ const ports = await pickRemoteFreePorts(ctx as never);++ expect(ports).toEqual({ gateway: 50000, api: 50001, mattermost: 50002, postgres: 50003 });+ expect(seen[0]).toEqual(new Set([41001, 41000, 42001, 5432]));+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/host/remote-free-port.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/host/remote-free-port.tsindex 1b19de27e..b6455669f 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/host/remote-free-port.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/host/remote-free-port.ts@@ -32,14 +32,15 @@ export async function listRemoteListeningPorts(ctx: IExecutionContext): Promise<}/** Host ports already claimed by other managed servers (the local stack and any- * other remote hosts), parsed from their registered URLs. Mirrored remote ports- * are bound on the desktop loopback too, so two managed stacks must not share a- * number — this keeps the desktop listeners (and the unique gateway-URL index)- * from colliding. */+ * other remote hosts), parsed from their registered addresses. Mirrored remote+ * ports are bound on the desktop loopback too, so two managed stacks must not+ * share a number — this keeps the desktop listeners (and the servers'+ * addresses) from colliding. */async function reservedManagedPorts(): Promise<Set<number>> {const reserved = new Set<number>();for (const server of await listManagedServers()) {- for (const url of [server.gatewayUrl, server.apiUrl]) {+ for (const url of [server.url, server.dashboardUrl]) {+ if (url === null) continue;const port = Number.parseInt(new URL(url).port, 10);if (Number.isFinite(port) && port > 0) reserved.add(port);}diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/managed-server-status.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/managed-server-status.test.tsindex 31b4dbca2..30858f012 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/managed-server-status.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/managed-server-status.test.ts@@ -41,8 +41,8 @@ function server(overrides: Record<string, unknown>) {return {id: 'srv',name: 'S',- gatewayUrl: 'http://localhost:3300',- apiUrl: 'http://localhost:8000',+ url: 'http://localhost:8000',+ dashboardUrl: 'http://localhost:3300',managed: true,managementKind: 'local',sshHost: null,diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/native/native-stack.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/native/native-stack.tsindex 79512e81e..da0db65d2 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/native/native-stack.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/native/native-stack.ts@@ -450,7 +450,7 @@ export async function startNativeStack(opts: NativeStartOptions): Promise<Nativeconst serverId = await registerManagedServer(ref,serverName,- { gatewayUrl: apiUrl, apiUrl },+ { url: apiUrl, dashboardUrl: null },secrets,activate,onMessagediff --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 b692b0366..4e2875176 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@@ -23,7 +23,9 @@ const stampPublishedEnvMock = vi.hoisted(() =>);const composeUpMock = vi.hoisted(() => vi.fn(() => Promise.resolve()));const composeDownMock = vi.hoisted(() => vi.fn(() => Promise.resolve()));-const waitForHealthMock = vi.hoisted(() => vi.fn(() => Promise.resolve(true)));+const waitForHealthMock = vi.hoisted(() =>+ vi.fn((_url: string, _opts?: unknown) => Promise.resolve(true))+);const readDeployedVersionMock = vi.hoisted(() =>vi.fn((): Promise<{ kind: string; version?: string; source?: string }> =>@@ -291,8 +293,8 @@ describe('starting a shared stack', () => {expect(ensureManagedServerMock).toHaveBeenCalledWith({name: 'Team server',- gatewayUrl: 'http://localhost:41000',- apiUrl: 'http://localhost:41001',+ url: 'http://localhost:41001',+ dashboardUrl: 'http://localhost:41000',},{ kind: 'remote', sshHost: 'vm-1' });@@ -303,6 +305,30 @@ describe('starting a shared stack', () => {);});+ it('waits for switch-core on its own address, then for the dashboard container', async () => {+ inspectStackMock.mockResolvedValue(present());+ const { host } = sharedHost();++ await startStack(startOptions(host));++ expect(waitForHealthMock.mock.calls.map(([url]) => url)).toEqual([+ 'http://localhost:41001',+ 'http://localhost:41000',+ ]);+ });++ it('fails the start when the dashboard container never answers, registering nothing', async () => {+ inspectStackMock.mockResolvedValue(present());+ const { host } = sharedHost();+ waitForHealthMock.mockImplementation(async (url: string) => url !== 'http://localhost:41000');++ expect(await startStack(startOptions(host))).toEqual({+ kind: 'error',+ message: 'The server did not become healthy in time.',+ });+ expect(ensureManagedServerMock).not.toHaveBeenCalled();+ });+it('brings this account’s working dir in step with the stack before checking its version', async () => {inspectStackMock.mockResolvedValue(present());const { host, writeFile } = sharedHost();@@ -691,6 +717,19 @@ describe('connecting to a shared stack', () => {waitForHealthMock.mockResolvedValue(false);const { host } = sharedHost();+ expect(await connectStack(connectOptions(host))).toEqual({+ kind: 'error',+ message:+ 'The Switch server on vm-1 is running, but did not answer at http://localhost:41001.',+ });+ expect(ensureManagedServerMock).not.toHaveBeenCalled();+ });++ it('names the dashboard container’s address when that is the part not answering', async () => {+ inspectStackMock.mockResolvedValue(present());+ waitForHealthMock.mockImplementation(async (url: string) => url !== 'http://localhost:41000');+ const { host } = sharedHost();+expect(await connectStack(connectOptions(host))).toEqual({kind: 'error',message:@@ -979,7 +1018,8 @@ describe('the server lock through a start, a join, a stop and a reset', () => {expect(await connectStack(connectOptions(sharedHost().host))).toMatchObject({kind: 'connected',});- expect(order).toEqual(['release', 'health']);+ // Once for switch-core and once for the dashboard container, both after.+ expect(order).toEqual(['release', 'health', 'health']);});it('stops nothing when the lock was taken over before the stop', async () => {@@ -1032,7 +1072,7 @@ describe('what a start makes sure of before it changes anything', () => {await startStack(startOptions(host));expect(checkNetworking).toHaveBeenCalledWith(hostPorts);- expect(assertManagedServerUrlFreeMock).toHaveBeenCalledWith('http://localhost:41000', {+ expect(assertManagedServerUrlFreeMock).toHaveBeenCalledWith('http://localhost:41001', {kind: 'remote',sshHost: 'vm-1',});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 f6abab062..5ea11bfc6 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@@ -30,7 +30,7 @@ import {} from './constants';import { classifyVersionDrift, readDeployedVersion } from './deployed-version';import { buildEnvFile, keysDisagreeing, telemetryRequested } from './env-file';-import { apiUrlFor, gatewayUrlFor, type LocalServerPorts } from './free-port';+import { apiUrlFor, managedServerAddresses, type LocalServerPorts } from './free-port';import { waitForHealth } from './health';import type { ServerHost } from './host/types';import { finishUpgrade, type OwedUpgrade, prepareUpgrade } from './managed-upgrade';@@ -423,6 +423,26 @@ async function portsReachableHere(}}+/**+ * The first of a managed stack's addresses that never answers, or null once all+ * have. switch-core is asked on its own port, the one everything but dashboard+ * pages uses, and the dashboard container on its: the stack still runs one, and+ * the server is registered to open its pages there.+ */+async function unansweredAddress(+ ports: LocalServerPorts,+ signal: AbortSignal+): Promise<string | null> {+ const { url, dashboardUrl } = managedServerAddresses(ports);+ const addresses = [url, dashboardUrl];+ // Waited for together, so a stack that never comes up is reported after one+ // wait rather than two.+ const answered = await Promise.all(+ addresses.map((address) => waitForHealth(address, { signal }))+ );+ return addresses.find((_address, index) => !answered[index]) ?? null;+}+/*** Register the stack, activate it if asked, and sign in as its admin with the* password Switch Console generated. A failed sign-in is only logged: the@@ -438,7 +458,7 @@ async function registerAndSignIn(return registerManagedServer(ref,serverName,- { gatewayUrl: gatewayUrlFor(settings.ports), apiUrl: apiUrlFor(settings.ports) },+ managedServerAddresses(settings.ports),settings.secrets,activate,onMessage@@ -446,17 +466,17 @@ async function registerAndSignIn(}/** {@link registerAndSignIn} with the server's addresses given explicitly, for- * a server that is not a compose stack (a native local server serves the- * gateway on its API port). */+ * a server that is not a compose stack (a native local server runs no+ * dashboard of its own, so it has no separate dashboard address). */export async function registerManagedServer(ref: ManagedServerRef,serverName: string,- urls: { gatewayUrl: string; apiUrl: string },+ addresses: { url: string; dashboardUrl: string | null },secrets: LocalServerSecrets,activate: boolean,onMessage: (message: string) => void): Promise<string> {- const server = await ensureManagedServer({ name: serverName, ...urls }, ref);+ const server = await ensureManagedServer({ name: serverName, ...addresses }, ref);if (activate) await setActiveServerId(server.id);onMessage('Signing in…');@@ -546,7 +566,7 @@ export async function startStack(opts: StartStackOptions): Promise<StartLocalSer// this Console without it.const settings = await portsReachableHere(host, plan, await settingsFor(host, plan));await host.checkNetworking(settings.ports);- await assertManagedServerUrlFree(gatewayUrlFor(settings.ports), ref);+ await assertManagedServerUrlFree(apiUrlFor(settings.ports), ref);onMessage('Checking the deployed version…');const downgrade = await refuseDowngrade(host, checkoutRoot);@@ -628,8 +648,7 @@ export async function startStack(opts: StartStackOptions): Promise<StartLocalSerawait host.establishNetworking(settings.ports);onMessage('Waiting for the server to become healthy…');- const healthy = await waitForHealth(gatewayUrlFor(settings.ports), { signal });- if (!healthy) {+ if ((await unansweredAddress(settings.ports, signal)) !== null) {return { kind: 'error', message: 'The server did not become healthy in time.' };}@@ -718,11 +737,11 @@ export async function connectStack(opts: ConnectStackOptions): Promise<ConnectStawait host.establishNetworking(settings.ports);onMessage('Waiting for the server to answer…');- const gatewayUrl = gatewayUrlFor(settings.ports);- if (!(await waitForHealth(gatewayUrl, { signal }))) {+ const unanswered = await unansweredAddress(settings.ports, signal);+ if (unanswered !== null) {return {kind: 'error',- message: `The Switch server on ${host.label} is running, but did not answer at ${gatewayUrl}.`,+ message: `The Switch server on ${host.label} is running, but did not answer at ${unanswered}.`,};}diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/remote-server-service.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/remote-server-service.test.tsindex fca702953..68ac7a935 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/remote-server-service.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/remote-server-service.test.ts@@ -187,8 +187,8 @@ function fakeHost() {const RECORD = {id: 'srv-1',name: 'Team server',- gatewayUrl: 'http://localhost:41000',- apiUrl: 'http://localhost:41001',+ url: 'http://localhost:41001',+ dashboardUrl: 'http://localhost:41000',managed: true,managementKind: 'remote',sshHost: 'vm-1',@@ -509,8 +509,8 @@ describe('picking a shared stack back up', () => {inspectStack.mockResolvedValue(present(true));getRemoteManagedServer.mockResolvedValue({...RECORD,- gatewayUrl: 'http://localhost:3300',- apiUrl: 'http://localhost:8000',+ url: 'http://localhost:8000',+ dashboardUrl: 'http://localhost:3300',});const service = await loadService();@@ -519,8 +519,8 @@ describe('picking a shared stack back up', () => {expect(ensureManagedServer).toHaveBeenCalledWith({name: 'Team server',- gatewayUrl: 'http://localhost:41000',- apiUrl: 'http://localhost:41001',+ url: 'http://localhost:41001',+ dashboardUrl: 'http://localhost:41000',},{ kind: 'remote', sshHost: 'vm-1' });diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/remote-server-service.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/remote-server-service.tsindex 534c9442d..db683b756 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/remote-server-service.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/remote-server-service.ts@@ -41,7 +41,7 @@ import {import { coreStartedAt } from './compose';import { hostAccount, readRegister, writeRecord } from './console-register';import { readVersionStatus } from './deployed-version';-import { apiUrlFor, gatewayUrlFor, type LocalServerPorts } from './free-port';+import { managedServerAddresses, type LocalServerPorts } from './free-port';import { createRemoteServerHost, type RemoteServerHost } from './host/remote-host';import { hostSlug, remoteSecretsKey } from './host/remote-identity';import {@@ -724,19 +724,16 @@ export class RemoteServerService {serverId: string,ports: LocalServerPorts): Promise<boolean> {- const gatewayUrl = gatewayUrlFor(ports);- const apiUrl = apiUrlFor(ports);+ const addresses = managedServerAddresses(ports);const record = await getRemoteManagedServer(sshHost);- if (!record || (record.gatewayUrl === gatewayUrl && record.apiUrl === apiUrl)) return false;+ if (!record || (record.url === addresses.url && record.dashboardUrl === addresses.dashboardUrl))+ return false;log.info(`remote-switch-server: the stack on ${sshHost} now publishes different ports`, {serverId,- from: record.gatewayUrl,- to: gatewayUrl,+ from: record.url,+ to: addresses.url,});- await ensureManagedServer(- { name: record.name, gatewayUrl, apiUrl },- { kind: 'remote', sshHost }- );+ await ensureManagedServer({ name: record.name, ...addresses }, { kind: 'remote', sshHost });return true;}diff --git a/console/apps/switch-console-desktop/src/main/core/switch-rooms/mattermost-origin.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-rooms/mattermost-origin.test.tsnew file mode 100644index 000000000..59c24cdd0--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/switch-rooms/mattermost-origin.test.ts@@ -0,0 +1,43 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const getServer = vi.hoisted(() => vi.fn());+const readPersistedPorts = vi.hoisted(() => vi.fn());++vi.mock('@main/core/switch-servers/servers-store', () => ({ getServer }));+vi.mock('@main/core/managed-switch-server/ports', () => ({ readPersistedPorts }));+vi.mock('@main/core/managed-switch-server/host/host-for-server', () => ({+ managedServerStateDir: () => '/state',+}));++const { mattermostOriginFor } = await import('./mattermost-origin');++describe('mattermostOriginFor', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ readPersistedPorts.mockResolvedValue({ gateway: 3300, api: 8000, mattermost: 8065 });+ });++ it('pairs a managed server’s host with the Mattermost port its stack publishes', async () => {+ getServer.mockResolvedValue({+ managed: true,+ url: 'http://localhost:8000',+ dashboardUrl: 'http://localhost:3300',+ });++ expect(await mattermostOriginFor('srv')).toBe('http://localhost:8065');+ });++ it('knows no Mattermost for a server it does not run', async () => {+ getServer.mockResolvedValue({ managed: false, url: 'https://switch.example.com' });++ expect(await mattermostOriginFor('srv')).toBeNull();+ expect(readPersistedPorts).not.toHaveBeenCalled();+ });++ it('knows none for a managed server whose ports were never recorded', async () => {+ getServer.mockResolvedValue({ managed: true, url: 'http://localhost:8000' });+ readPersistedPorts.mockResolvedValue(null);++ expect(await mattermostOriginFor('srv')).toBeNull();+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/switch-rooms/mattermost-origin.ts b/console/apps/switch-console-desktop/src/main/core/switch-rooms/mattermost-origin.tsindex b4fb38497..0c806265b 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-rooms/mattermost-origin.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-rooms/mattermost-origin.ts@@ -16,8 +16,8 @@ export async function mattermostOriginFor(serverId: string): Promise<string | nuif (!ports) return null;// Remote-managed stacks publish onto the SSH host's loopback and are reached- // through the same forwarded ports the gateway URL already uses, so the- // gateway's hostname is the right one to pair with the Mattermost port.- const gatewayHost = new URL(server.gatewayUrl).hostname;- return `http://${gatewayHost}:${ports.mattermost}`;+ // through the same forwarded ports the server's address already uses, so its+ // hostname is the right one to pair with the Mattermost port.+ const host = new URL(server.url).hostname;+ return `http://${host}:${ports.mattermost}`;}diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/auth.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/auth.test.tsindex 1d8858425..c77b3f25a 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/auth.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/auth.test.ts@@ -1,11 +1,18 @@+import { get } from 'node:http';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const readSecrets = vi.hoisted(() => vi.fn());const getSessionCookie = vi.hoisted(() => vi.fn());const setSessionCookie = vi.hoisted(() => vi.fn(() => Promise.resolve()));const logWarn = vi.hoisted(() => vi.fn());+const keepSeparateDashboard = vi.hoisted(() => vi.fn(async () => {}));-vi.mock('electron', () => ({ BrowserWindow: vi.fn(), session: { fromPartition: vi.fn() } }));+vi.mock('electron', () => ({+ BrowserWindow: vi.fn(),+ session: { fromPartition: vi.fn() },+ shell: { openExternal: vi.fn(async () => {}) },+}));+vi.mock('@main/app/deeplinks', () => ({ appReturnUrl: () => null, bringToFront: vi.fn() }));vi.mock('@main/core/managed-switch-server/secrets', () => ({ readSecrets }));vi.mock('@main/core/managed-switch-server/host/host-for-server', () => ({managedServerSecretsKey: (server: { sshHost: string | null }) =>@@ -14,19 +21,28 @@ vi.mock('@main/core/managed-switch-server/host/host-for-server', () => ({: 'local-switch-server:secrets',}));vi.mock('./servers-store', () => ({ getSessionCookie, setSessionCookie }));+vi.mock('./server-address', () => ({ keepSeparateDashboard }));const consoleIdentityHeaders = vi.hoisted(() =>vi.fn(async (): Promise<Record<string, string>> => ({})));vi.mock('./console-identity', () => ({ consoleIdentityHeaders }));vi.mock('@main/lib/logger', () => ({ log: { warn: logWarn, error: vi.fn(), info: vi.fn() } }));-const { reauthenticateManagedServer, refreshSession, signup } = await import('./auth');+const {+ callbackHostHop,+ cancelOidcLogin,+ oidcLogin,+ reauthenticateManagedServer,+ refreshSession,+ signup,+} = await import('./auth');+const electron = await import('electron');const REMOTE = {id: 'srv-remote',name: 'Team server',- gatewayUrl: 'http://localhost:41000',- apiUrl: 'http://localhost:41001',+ url: 'http://localhost:41001',+ dashboardUrl: 'http://localhost:41000',managed: true,managementKind: 'remote',sshHost: 'vm-1',@@ -34,8 +50,8 @@ const REMOTE = {const EXTERNAL = {id: 'srv-external',name: 'Company server',- gatewayUrl: 'https://switch.example.com',- apiUrl: 'https://switch-api.example.com',+ url: 'https://switch-api.example.com',+ dashboardUrl: 'https://switch.example.com',managed: false,managementKind: null,sshHost: null,@@ -58,7 +74,7 @@ describe('reauthenticateManagedServer', () => {fetchMock.mockResolvedValue({status: 200,ok: true,- headers: { getSetCookie: () => ['switch_auth=fresh-jwt; Path=/; HttpOnly'] },+ headers: { get: () => null, getSetCookie: () => ['switch_auth=fresh-jwt; Path=/; HttpOnly'] },json: async () => ({ id: 'u1' }),});getSessionCookie.mockResolvedValue('fresh-jwt');@@ -67,7 +83,7 @@ describe('reauthenticateManagedServer', () => {expect(readSecrets).toHaveBeenCalledWith({ secretsKey: 'remote-switch-server:vm-1:secrets' });const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];- expect(url).toBe('http://localhost:41000/gateway/auth/login');+ expect(url).toBe('http://localhost:41001/gateway/auth/login');expect(JSON.parse(init.body as string)).toEqual({email: '[email protected]',password: 'stored-pw',@@ -99,7 +115,7 @@ describe('reauthenticateManagedServer', () => {fetchMock.mockResolvedValue({status: 401,ok: false,- headers: { getSetCookie: () => [] },+ headers: { get: () => null, getSetCookie: () => [] },text: async () => '',});@@ -116,13 +132,13 @@ describe('refreshSession', () => {});fetchMock.mockResolvedValue({ok: true,- headers: { getSetCookie: () => ['switch_auth=fresh-jwt; Path=/; HttpOnly'] },+ headers: { get: () => null, getSetCookie: () => ['switch_auth=fresh-jwt; Path=/; HttpOnly'] },});expect(await refreshSession(REMOTE, 'old-jwt')).toBe('fresh-jwt');const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];- expect(url).toBe('http://localhost:41000/gateway/auth/refresh');+ expect(url).toBe('http://localhost:41001/gateway/auth/refresh');expect(init.headers).toMatchObject({Cookie: 'switch_auth=old-jwt','X-Switch-Console-Id': 'console-1',@@ -132,7 +148,11 @@ describe('refreshSession', () => {});it('keeps the current session when renewal is refused', async () => {- fetchMock.mockResolvedValue({ ok: false, status: 401, headers: { getSetCookie: () => [] } });+ fetchMock.mockResolvedValue({+ ok: false,+ status: 401,+ headers: { get: () => null, getSetCookie: () => [] },+ });expect(await refreshSession(REMOTE, 'old-jwt')).toBeNull();expect(setSessionCookie).not.toHaveBeenCalled();@@ -142,7 +162,7 @@ describe('refreshSession', () => {const SIGNUP_SERVER = {id: 'srv-1',name: 'S',- gatewayUrl: 'https://switch.example.com',+ url: 'https://switch.example.com',managed: false,} as never;@@ -289,3 +309,319 @@ describe('signup', () => {expect(setSessionCookie).not.toHaveBeenCalled();});});++describe('oidcLogin', () => {+ /** Opens the sign-in window, reports the page it loaded, and closes it. */+ async function loadedPage(server: unknown): Promise<string> {+ const loadURL = vi.fn(async () => {});+ let closed: (() => void) | undefined;+ vi.mocked(electron.session.fromPartition).mockReturnValue({+ cookies: { get: vi.fn(async () => []) },+ } as never);+ vi.mocked(electron.BrowserWindow).mockImplementation(function () {+ return {+ loadURL,+ webContents: { on: vi.fn() },+ on: (event: string, listener: () => void) => {+ if (event === 'closed') closed = listener;+ },+ isDestroyed: () => false,+ destroy: vi.fn(),+ } as never;+ });+ const result = oidcLogin(server as never, null, false);+ closed?.();+ expect(await result).toMatchObject({ success: false, error: { kind: 'cancelled' } });+ return (loadURL.mock.calls[0] as unknown as [string])[0];+ }++ it('starts on the dashboard’s host for a server that keeps one apart', async () => {+ // The identity provider of an older split server returns to the dashboard's+ // host, and the server keeps the sign-in state in a cookie on the host the+ // flow started on.+ expect(await loadedPage(EXTERNAL)).toBe('https://switch.example.com/gateway/auth/oidc/login');+ });++ it('starts on the server’s own address otherwise', async () => {+ expect(+ await loadedPage({+ id: 'srv-one',+ name: 'One address',+ url: 'https://switch.example.org',+ dashboardUrl: null,+ managed: false,+ })+ ).toBe('https://switch.example.org/gateway/auth/oidc/login');+ });+});++describe('callbackHostHop', () => {+ const start = 'https://switch-api.example.com/gateway/auth/oidc/login';+ const idp = (redirectUri: string) =>+ `https://idp.example/authorize?${new URLSearchParams({ redirect_uri: redirectUri, state: 's' })}`;++ it('names the host the provider will return to, when it is another', () => {+ expect(+ callbackHostHop(start, idp('https://switch-gateway.example.com/gateway/auth/oidc/callback'))+ ).toBe('https://switch-gateway.example.com');+ });++ it.each([+ ['the host it started on', idp('https://switch-api.example.com/gateway/auth/oidc/callback')],+ ['the same host on another port', idp('https://switch-api.example.com:8443/cb')],+ ['no return address', 'https://idp.example/authorize?state=s'],+ ['a return address that is not a web address', idp('javascript:alert(1)')],+ ['a return address that does not parse', idp('not a url')],+ // A proxy with a sign-in of its own in front of the dashboard.+ ['a callback that is not Switch’s', idp('https://auth.example.com/oauth2/callback')],+ ])('leaves a sign-in alone that returns to %s', (_case, redirect) => {+ expect(callbackHostHop(start, redirect)).toBeNull();+ });+});++describe('oidcLogin following an older server to its callback host', () => {+ const ONE_ADDRESS = {+ id: 'srv-old',+ name: 'Older server',+ url: 'https://switch-api.example.com',+ dashboardUrl: null,+ managed: false,+ } as never;+ const CALLBACK = 'https://switch-gateway.example.com/gateway/auth/oidc/callback';+ const idp = (redirectUri: string) =>+ `https://idp.example/authorize?${new URLSearchParams({ redirect_uri: redirectUri, state: 's' })}`;++ /** Opens the sign-in window with handles on what it would see and do. */+ function signInWindow(firstLoad: Promise<void> = Promise.resolve()) {+ const listeners = new Map<string, ((...args: unknown[]) => void)[]>();+ const loadURL = vi.fn(async (_url: string) => {});+ loadURL.mockImplementationOnce(() => firstLoad);+ let cookie: string | null = null;+ vi.mocked(electron.session.fromPartition).mockReturnValue({+ cookies: { get: vi.fn(async () => (cookie === null ? [] : [{ value: cookie }])) },+ } as never);+ vi.mocked(electron.BrowserWindow).mockImplementation(function () {+ return {+ loadURL,+ webContents: {+ on: (event: string, listener: (...args: unknown[]) => void) => {+ listeners.set(event, [...(listeners.get(event) ?? []), listener]);+ },+ },+ on: vi.fn(),+ isDestroyed: () => false,+ destroy: vi.fn(),+ } as never;+ });+ const emit = (event: string, ...args: unknown[]) =>+ (listeners.get(event) ?? []).forEach((listener) => listener(...args));+ return {+ loadURL,+ /** A server-side redirect of the window's main frame, or of a subframe. */+ redirect(url: string, isMainFrame = true) {+ const preventDefault = vi.fn();+ emit('will-redirect', { url, isMainFrame, preventDefault });+ return preventDefault;+ },+ /** The server sets the session cookie, and the window lands. */+ signedIn() {+ cookie = 'jwt';+ emit('did-navigate');+ },+ };+ }++ it('restarts on the host the provider returns to, and keeps it as the dashboard', async () => {+ const win = signInWindow();+ const result = oidcLogin(ONE_ADDRESS, null, false);++ expect(win.redirect(idp(CALLBACK))).toHaveBeenCalledOnce();+ expect(win.loadURL.mock.calls.map(([url]) => url)).toEqual([+ 'https://switch-api.example.com/gateway/auth/oidc/login',+ 'https://switch-gateway.example.com/gateway/auth/oidc/login',+ ]);++ win.signedIn();+ expect(await result).toEqual({ success: true, data: true });+ expect(keepSeparateDashboard).toHaveBeenCalledExactlyOnceWith(+ ONE_ADDRESS,+ 'https://switch-gateway.example.com'+ );+ });++ it('carries the sign-in option to the host it restarts on', async () => {+ const win = signInWindow();+ const result = oidcLogin(ONE_ADDRESS, 'google', false);++ win.redirect(idp(CALLBACK));+ expect(win.loadURL.mock.calls.map(([url]) => url)).toEqual([+ 'https://switch-api.example.com/gateway/auth/oidc/login?provider=google',+ 'https://switch-gateway.example.com/gateway/auth/oidc/login?provider=google',+ ]);++ win.signedIn();+ expect(await result).toMatchObject({ success: true });+ });++ it('leaves a sign-in alone that returns to the host it started on', async () => {+ const win = signInWindow();+ const result = oidcLogin(ONE_ADDRESS, null, false);++ expect(+ win.redirect(idp('https://switch-api.example.com/gateway/auth/oidc/callback'))+ ).not.toHaveBeenCalled();++ win.signedIn();+ expect(await result).toMatchObject({ success: true });+ expect(win.loadURL).toHaveBeenCalledOnce();+ expect(keepSeparateDashboard).not.toHaveBeenCalled();+ });++ it('asks only the first redirect that leaves the starting host', async () => {+ const win = signInWindow();+ const result = oidcLogin(ONE_ADDRESS, null, false);++ // The same host again (an upgrade to HTTPS, say) is not the decision.+ expect(+ win.redirect('https://switch-api.example.com/gateway/auth/oidc/login?again=1')+ ).not.toHaveBeenCalled();+ // A subframe is not the sign-in.+ expect(win.redirect(idp(CALLBACK), false)).not.toHaveBeenCalled();+ expect(win.redirect(idp(CALLBACK))).toHaveBeenCalledOnce();+ // From here on the provider's pages cannot send it anywhere else.+ expect(win.redirect(idp('https://elsewhere.example.net/cb'))).not.toHaveBeenCalled();++ win.signedIn();+ await result;+ expect(win.loadURL).toHaveBeenCalledTimes(2);+ });++ it('does not take the first load, cancelled by the hop, for a failure', async () => {+ let cancel!: (cause: Error) => void;+ const win = signInWindow(new Promise((_resolve, reject) => (cancel = reject)));+ const result = oidcLogin(ONE_ADDRESS, null, false);++ win.redirect(idp(CALLBACK));+ cancel(new Error('ERR_ABORTED (-3)'));+ await Promise.resolve();+ win.signedIn();++ expect(await result).toMatchObject({ success: true });+ });++ it('is signed in even when the host cannot be kept', async () => {+ keepSeparateDashboard.mockRejectedValueOnce(new Error('database is locked'));+ const win = signInWindow();+ const result = oidcLogin(ONE_ADDRESS, null, false);++ win.redirect(idp(CALLBACK));+ win.signedIn();++ expect(await result).toMatchObject({ success: true });+ expect(logWarn).toHaveBeenCalledWith(+ 'switch-servers: could not keep the host the sign-in returned to',+ expect.objectContaining({ error: 'Error: database is locked' })+ );+ });+});++describe('oidcLogin in the system browser', () => {+ /** Starts the sign-in, reports the page the browser was sent to, and cancels it. */+ async function openedPage(server: { id: string }): Promise<URL> {+ const result = oidcLogin(server as never, 'google', true);+ await vi.waitFor(() => expect(electron.shell.openExternal).toHaveBeenCalledOnce());+ cancelOidcLogin(server.id);+ expect(await result).toMatchObject({ success: false, error: { kind: 'cancelled' } });+ return new URL(vi.mocked(electron.shell.openExternal).mock.calls[0]![0]);+ }++ it('starts on the dashboard’s host for a server that keeps one apart', async () => {+ const page = await openedPage(EXTERNAL);+ expect(`${page.origin}${page.pathname}`).toBe(+ 'https://switch.example.com/gateway/auth/oidc/login'+ );+ expect(page.searchParams.get('provider')).toBe('google');+ expect(page.searchParams.get('return_to')).toMatch(+ /^http:\/\/127\.0\.0\.1:\d+\/switch-sign-in$/+ );+ });++ it('starts on the server’s own address otherwise', async () => {+ // A current server answers a sign-in on its own address itself.+ fetchMock.mockResolvedValueOnce(+ new Response(null, { status: 302, headers: { location: 'https://idp.example/authorize' } })+ );+ const page = await openedPage({+ id: 'srv-one',+ name: 'One address',+ url: 'https://switch.example.org',+ dashboardUrl: null,+ managed: false,+ } as never);+ expect(`${page.origin}${page.pathname}`).toBe(+ 'https://switch.example.org/gateway/auth/oidc/login'+ );+ expect(keepSeparateDashboard).not.toHaveBeenCalled();+ });++ it('follows an older server to the host its sign-in returns to, and keeps it', async () => {+ const OLDER = {+ id: 'srv-older',+ name: 'Older',+ url: 'https://switch-api.example.com',+ dashboardUrl: null,+ managed: false,+ };+ const toProvider = `https://idp.example/authorize?${new URLSearchParams({+ redirect_uri: 'https://switch-gateway.example.com/gateway/auth/oidc/callback',+ })}`;+ fetchMock.mockImplementation(async (url: string) =>+ url.endsWith('/gateway/auth/oidc/login')+ ? new Response(null, { status: 302, headers: { location: toProvider } })+ : new Response('{}', { status: 200, headers: { 'set-cookie': 'switch_auth=jwt; Path=/' } })+ );++ const result = oidcLogin(OLDER as never, null, true);+ await vi.waitFor(() => expect(electron.shell.openExternal).toHaveBeenCalledOnce());+ const page = new URL(vi.mocked(electron.shell.openExternal).mock.calls[0]![0]);+ expect(`${page.origin}${page.pathname}`).toBe(+ 'https://switch-gateway.example.com/gateway/auth/oidc/login'+ );++ // The browser comes back to this computer with a code, as the server sends it.+ const back = new URL(page.searchParams.get('return_to')!);+ back.search = new URLSearchParams({+ code: 'c',+ state: page.searchParams.get('state')!,+ }).toString();+ await new Promise<void>((resolve, reject) =>+ get(back, (res) => res.resume().on('end', resolve)).on('error', reject)+ );++ expect(await result).toEqual({ success: true, data: true });+ expect(fetchMock).toHaveBeenCalledWith(+ 'https://switch-api.example.com/gateway/auth/oidc/exchange',+ expect.anything()+ );+ expect(keepSeparateDashboard).toHaveBeenCalledExactlyOnceWith(+ OLDER,+ 'https://switch-gateway.example.com'+ );+ });++ it('starts on the server’s own address when it cannot ask where sign-in returns', async () => {+ fetchMock.mockRejectedValueOnce(new TypeError('fetch failed'));+ const page = await openedPage({+ id: 'srv-down',+ name: 'Unreachable for a moment',+ url: 'https://switch.example.net',+ dashboardUrl: null,+ managed: false,+ } as never);+ expect(page.origin).toBe('https://switch.example.net');+ expect(logWarn).toHaveBeenCalledWith(+ 'switch-servers: could not ask where the server’s sign-in returns to',+ expect.objectContaining({ server: 'srv-down' })+ );+ });+});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 235262340..389f018e2 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@@ -8,15 +8,19 @@ import { LOCAL_SERVER_ADMIN_EMAIL } from '@main/core/managed-switch-server/constimport { managedServerSecretsKey } from '@main/core/managed-switch-server/host/host-for-server';import { readSecrets } from '@main/core/managed-switch-server/secrets';import { log } from '@main/lib/logger';-import type {- SignupResult,- SwitchServer,- SwitchUser,+import {+ dashboardOrigin,+ type SignupResult,+ type SwitchServer,+ type SwitchUser,} from '@shared/core/switch-servers/switch-servers';import { consoleIdentityHeaders } from './console-identity';+import { keepSeparateDashboard } from './server-address';import { getSessionCookie, setSessionCookie } from './servers-store';const SWITCH_AUTH_COOKIE = 'switch_auth';+/** Where switch-core's identity provider returns a browser sign-in. */+const OIDC_CALLBACK_PATH = '/auth/oidc/callback';const OIDC_LOGIN_TIMEOUT_MS = 300_000;export type LoginError =@@ -25,7 +29,48 @@ export type LoginError =| { kind: 'failed'; message: string };function gatewayUrl(server: SwitchServer, path: string): string {- return `${server.gatewayUrl}/gateway${path}`;+ return `${server.url}/gateway${path}`;+}++/**+ * The same path on the origin the server's web pages are served from. Browser+ * sign-in starts there: the server keeps the OIDC state in a cookie on the host+ * the flow starts on, and an older server's identity provider returns to its+ * dashboard's host, so starting anywhere else loses the state. Where Console+ * has no dashboard address for such a server, the sign-in window follows the+ * server to that host itself (see {@link callbackHostHop}).+ */+function webGatewayUrl(server: SwitchServer, path: string): string {+ return `${dashboardOrigin(server)}/gateway${path}`;+}++/**+ * Where to restart a browser sign-in that the server is sending to an identity+ * provider which will return it to another host, or null to let it go on.+ *+ * Asked of the first redirect that leaves the host the sign-in started on: the+ * server's own, on its way to the provider, carrying the `redirect_uri` the+ * provider will return to. The flow's state is in a cookie on the starting+ * host, so a return to a different one would find none. A current server makes+ * that hop itself before this point; an older one, whose dashboard is on a host+ * of its own, does not. Hostnames only, as cookies do. Nothing later is asked,+ * so a page on the provider's side cannot steer it, and only a return to a+ * Switch sign-in callback counts: a proxy with a sign-in of its own in front of+ * the dashboard returns somewhere else, and is left to run.+ */+export function callbackHostHop(startUrl: string, redirectUrl: string): string | null {+ const start = new URL(startUrl);+ let callback: URL;+ try {+ const redirectUri = new URL(redirectUrl).searchParams.get('redirect_uri');+ if (redirectUri === null) return null;+ callback = new URL(redirectUri);+ } catch {+ return null;+ }+ if (callback.protocol !== 'https:' && callback.protocol !== 'http:') return null;+ if (!callback.pathname.endsWith(OIDC_CALLBACK_PATH)) return null;+ return callback.hostname === start.hostname ? null : callback.origin;}/** Pull the `switch_auth` value out of the response's Set-Cookie headers. */@@ -69,7 +114,7 @@ async function postCredentials(} catch (cause) {return err({kind: 'failed',- message: `Could not reach ${server.gatewayUrl}. Check that the address is right and that the server is running. (${cause instanceof Error ? cause.message : String(cause)})`,+ message: `Could not reach ${server.url}. Check that the address is right and that the server is running. (${cause instanceof Error ? cause.message : String(cause)})`,});}}@@ -119,7 +164,7 @@ export async function passwordLogin(const detail = await response.text().catch(() => '');return err({kind: 'failed',- message: `${server.gatewayUrl} rejected the sign-in with HTTP ${response.status}. That is a problem on the server, not with your credentials.${+ message: `${server.url} rejected the sign-in with HTTP ${response.status}. That is a problem on the server, not with your credentials.${detail ? ` (${boundedBody(detail)})` : ''}`,});@@ -199,7 +244,7 @@ export async function signup(if (kind && refusal) return err({ kind, message: refusal });return err({kind: 'failed',- message: `${server.gatewayUrl} rejected the sign-up with HTTP ${response.status}.${+ message: `${server.url} rejected the sign-up with HTTP ${response.status}.${body ? ` (${refusal ?? boundedBody(body)})` : ''}`,});@@ -360,8 +405,10 @@ async function oidcBrowserLogin(const state = randomBytes(24).toString('base64url');const verifier = randomBytes(32).toString('base64url');const challenge = createHash('sha256').update(verifier).digest('base64url');+ const callbackOrigin = await browserCallbackHost(server);+ const startOrigin = callbackOrigin ?? dashboardOrigin(server);- return new Promise<Result<true, LoginError>>((resolve) => {+ const result = await new Promise<Result<true, LoginError>>((resolve) => {let settled = false;let port = 0;const page = (status: number, text: string, res: ServerResponse, returnUrl: string | null) => {@@ -426,7 +473,7 @@ async function oidcBrowserLogin(if (!posted.data.ok)return err({kind: 'failed',- message: `${server.gatewayUrl} refused the sign-in with HTTP ${posted.data.status}. Try again.`,+ message: `${server.url} refused the sign-in with HTTP ${posted.data.status}. Try again.`,});return persistSessionCookie(server, posted.data, 'Sign-in');};@@ -459,7 +506,9 @@ async function oidcBrowserLogin(challenge,});if (provider !== null) query.set('provider', provider);- shell.openExternal(gatewayUrl(server, `/auth/oidc/login?${query}`)).catch((cause) =>+ // Started where the server's web pages are, for the reason+ // `webGatewayUrl` gives; the code is traded on the server's own address.+ shell.openExternal(`${startOrigin}/gateway/auth/oidc/login?${query}`).catch((cause) =>finish(err({kind: 'failed',@@ -469,6 +518,49 @@ async function oidcBrowserLogin();});});++ if (result.success && callbackOrigin !== null) await keepCallbackHost(server, callbackOrigin);+ return result;+}++/**+ * The host an older server's identity provider returns a browser sign-in to,+ * when Console has no dashboard address for it and that host is another; null+ * otherwise. The system browser cannot be watched the way the sign-in window is+ * (see {@link callbackHostHop}), so the server's first answer to a sign-in is+ * read here instead. A current server makes that hop itself, and its answer+ * names no identity provider.+ */+async function browserCallbackHost(server: SwitchServer): Promise<string | null> {+ if (server.dashboardUrl !== null) return null;+ const startUrl = gatewayUrl(server, '/auth/oidc/login');+ let location: string | null;+ try {+ const response = await fetch(startUrl, {+ redirect: 'manual',+ signal: AbortSignal.timeout(10_000),+ });+ location = response.headers.get('location');+ } catch (cause) {+ log.warn('switch-servers: could not ask where the server’s sign-in returns to', {+ server: server.id,+ error: String(cause),+ });+ return null;+ }+ return location === null ? null : callbackHostHop(startUrl, new URL(location, startUrl).href);+}++/** Keep the host a sign-in was followed to as the server's dashboard address.+ * Signed in either way, so a failure to record it is only noted. */+async function keepCallbackHost(server: SwitchServer, callbackOrigin: string): Promise<void> {+ await keepSeparateDashboard(server, callbackOrigin).catch((error: unknown) => {+ log.warn('switch-servers: could not keep the host the sign-in returned to', {+ server: server.id,+ callbackOrigin,+ error: String(error),+ });+ });}async function oidcWindowLogin(@@ -488,7 +580,16 @@ async function oidcWindowLogin(webPreferences: { partition, nodeIntegration: false, contextIsolation: true },});- return new Promise<Result<true, LoginError>>((resolve) => {+ const login =+ provider === null+ ? '/auth/oidc/login'+ : `/auth/oidc/login?${new URLSearchParams({ provider })}`;+ const startUrl = webGatewayUrl(server, login);+ // Set when the window follows the server to the host its identity provider+ // returns to; see `callbackHostHop`.+ let callbackOrigin: string | null = null;++ const result = await new Promise<Result<true, LoginError>>((resolve) => {let settled = false;const finish = (result: Result<true, LoginError>) => {if (settled) return;@@ -518,6 +619,20 @@ async function oidcWindowLogin(win.webContents.on('did-redirect-navigation', () => void tryCapture());win.webContents.on('did-frame-finish-load', () => void tryCapture());+ let leftStartHost = false;+ win.webContents.on('will-redirect', (details) => {+ if (leftStartHost || !details.isMainFrame) return;+ if (new URL(details.url).hostname === new URL(startUrl).hostname) return;+ leftStartHost = true;+ const hop = callbackHostHop(startUrl, details.url);+ if (hop === null) return;+ details.preventDefault();+ callbackOrigin = hop;+ void win.loadURL(`${hop}/gateway${login}`).catch((cause) => {+ finish(err({ kind: 'failed', message: `Could not open sign-in page: ${cause.message}` }));+ });+ });+win.on('closed', () => {if (!settled) {settled = true;@@ -526,12 +641,14 @@ async function oidcWindowLogin(}});- const login =- provider === null- ? '/auth/oidc/login'- : `/auth/oidc/login?${new URLSearchParams({ provider })}`;- void win.loadURL(gatewayUrl(server, login)).catch((cause) => {+ void win.loadURL(startUrl).catch((cause) => {+ // Cancelled by the hop above, which has loaded the sign-in elsewhere.+ if (callbackOrigin !== null) return;finish(err({ kind: 'failed', message: `Could not open sign-in page: ${cause.message}` }));});});++ // Where the server's sign-in returns is where an older server keeps its dashboard.+ if (result.success && callbackOrigin !== null) await keepCallbackHost(server, callbackOrigin);+ return result;}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 eb96e81cc..980c9e2bf 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@@ -9,7 +9,10 @@ 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 findServerByGatewayUrl = vi.hoisted(() => vi.fn());+const findServerByUrl = vi.hoisted(() => vi.fn());+const findServerByWebAddress = vi.hoisted(() => vi.fn());+const assertServerAddress = vi.hoisted(() => vi.fn());+const assertServesDashboard = vi.hoisted(() => vi.fn());const passwordLogin = vi.hoisted(() => vi.fn());const signup = vi.hoisted(() => vi.fn());const reconcileServerWorkspaces = vi.hoisted(() => vi.fn());@@ -89,10 +92,15 @@ vi.mock('./gateway-client', () => ({registerKnownAgent: vi.fn(),GatewayError: class GatewayError extends Error {},}));+vi.mock('./server-address', () => ({+ assertServerAddress,+ assertServesDashboard,+}));vi.mock('./servers-store', () => ({getServer,addServer,- findServerByGatewayUrl,+ findServerByUrl,+ findServerByWebAddress,deleteSessionCookie: vi.fn(),listServers: vi.fn(),removeServer: vi.fn(),@@ -110,8 +118,8 @@ function server(overrides: Record<string, unknown>) {return {id: 'srv',name: 'S',- gatewayUrl: 'http://localhost:3300',- apiUrl: 'http://localhost:8000',+ url: 'http://localhost:8000',+ dashboardUrl: 'http://localhost:3300',managed: false,managementKind: null,sshHost: null,@@ -572,7 +580,7 @@ describe('editing a server', () => {propagateServerApiUrl.mockResolvedValue([]);});- it('moves this computer’s controller to a new API URL, after the agents', async () => {+ it('moves this computer’s controller to a new address, after the agents', async () => {const order: string[] = [];propagateServerApiUrl.mockImplementation(async () => {order.push('agents');@@ -581,40 +589,56 @@ describe('editing a server', () => {followServerApiUrl.mockImplementation(async () => {order.push('controller');});- getServer.mockResolvedValue(server({ apiUrl: 'http://localhost:8000' }));- updateServer.mockResolvedValue(server({ apiUrl: 'https://switch.example.com' }));+ getServer.mockResolvedValue(server({ url: 'http://localhost:8000' }));+ updateServer.mockResolvedValue(server({ url: 'https://switch.example.com' }));const result = await switchServersController.updateServer({id: 'srv',name: 'S',- gatewayUrl: 'http://localhost:3300',- apiUrl: 'https://switch.example.com',+ url: 'https://switch.example.com',});- expect(result.propagation.apiUrlChanged).toBe(true);+ expect(result.propagation.urlChanged).toBe(true);+ expect(assertServerAddress).toHaveBeenCalledExactlyOnceWith('https://switch.example.com');expect(propagateServerApiUrl).toHaveBeenCalledWith('srv', 'https://switch.example.com');expect(followServerApiUrl).toHaveBeenCalledExactlyOnceWith('srv');expect(order).toEqual(['agents', 'controller']);});- it('leaves the controller alone when the API URL did not change', async () => {+ it('leaves the controller alone, and the address unchecked, when it did not change', async () => {getServer.mockResolvedValue(server({}));- updateServer.mockResolvedValue(server({ gatewayUrl: 'http://localhost:3301' }));+ updateServer.mockResolvedValue(server({ name: 'Renamed' }));- await switchServersController.updateServer({+ const result = await switchServersController.updateServer({id: 'srv',- name: 'S',- gatewayUrl: 'http://localhost:3301',- apiUrl: 'http://localhost:8000',+ name: 'Renamed',+ url: 'http://localhost:8000/',});+ expect(result.propagation).toEqual({ urlChanged: false, agents: [] });+ expect(assertServerAddress).not.toHaveBeenCalled();expect(followServerApiUrl).not.toHaveBeenCalled();expect(propagateServerApiUrl).not.toHaveBeenCalled();});++ it('saves nothing when the new address is an older server’s dashboard', async () => {+ getServer.mockResolvedValue(server({}));+ assertServerAddress.mockRejectedValueOnce(new Error('answered with a web page'));++ await expect(+ switchServersController.updateServer({+ id: 'srv',+ name: 'S',+ url: 'https://switch-gateway.example.com',+ })+ ).rejects.toThrow('answered with a web page');+ expect(updateServer).not.toHaveBeenCalled();+ expect(propagateServerApiUrl).not.toHaveBeenCalled();+ });});describe('adding a server by URL', () => {- const params = { name: 'S', gatewayUrl: 'http://gateway', apiUrl: 'http://api' };+ const params = { name: 'S', url: 'http://switch' };beforeEach(() => {vi.clearAllMocks();@@ -631,6 +655,30 @@ describe('adding a server by URL', () => {});});+ it('checks the address before writing anything', async () => {+ addServer.mockResolvedValue(server({ id: 'new' }));++ await switchServersController.addServer(params);++ expect(assertServerAddress).toHaveBeenCalledExactlyOnceWith('http://switch');+ expect(assertServerAddress.mock.invocationCallOrder[0]).toBeLessThan(+ addServer.mock.invocationCallOrder[0]!+ );+ });++ it('adds nothing, and reports the failure, when the address is a dashboard’s', async () => {+ assertServerAddress.mockRejectedValueOnce(new Error('answered with a web page'));++ await expect(switchServersController.addServer(params)).rejects.toThrow(+ 'answered with a web page'+ );+ expect(addServer).not.toHaveBeenCalled();+ expect(trackEvent).toHaveBeenCalledExactlyOnceWith('server_added', {+ server_kind: 'external',+ outcome: 'failure',+ });+ });+it('reports the failure when the row itself cannot be written', async () => {addServer.mockRejectedValue(new Error('constraint failed'));@@ -647,7 +695,7 @@ describe('connecting to Switch Cloud', () => {const CLOUD = server({id: 'cloud',name: 'Switch Cloud',- gatewayUrl: 'https://cloud.example.com',+ url: 'https://cloud.example.com',});beforeEach(() => {@@ -655,21 +703,21 @@ describe('connecting to Switch Cloud', () => {vi.stubEnv('SWITCH_CLOUD_URL', 'https://cloud.example.com');vi.stubEnv('MAIN_VITE_SWITCH_CLOUD_URL', undefined);addServer.mockReset();- findServerByGatewayUrl.mockReset();+ findServerByUrl.mockReset();trackEvent.mockReset();});it('registers the Cloud once, on its one origin', async () => {- findServerByGatewayUrl.mockResolvedValue(null);+ findServerByUrl.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',+ url: 'https://cloud.example.com',});+ expect(assertServerAddress).not.toHaveBeenCalled();expect(trackEvent).toHaveBeenCalledWith('server_added', {server_kind: 'external',outcome: 'success',@@ -677,7 +725,7 @@ describe('connecting to Switch Cloud', () => {});it('hands back the row already registered rather than adding another', async () => {- findServerByGatewayUrl.mockResolvedValue(CLOUD);+ findServerByUrl.mockResolvedValue(CLOUD);await expect(switchServersController.connectToSwitchCloud()).resolves.toBe(CLOUD);@@ -699,20 +747,21 @@ describe('finding the server an invite link is for', () => {const CLOUD = server({id: 'cloud',name: 'Switch Cloud',- gatewayUrl: 'https://cloud.example.com',+ url: 'https://cloud.example.com',});- const OWN = server({ id: 'own', gatewayUrl: 'https://switch.example.org' });+ const OWN = server({ id: 'own', url: '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();+ findServerByUrl.mockReset();+ findServerByWebAddress.mockReset();});it('registers Switch Cloud when the link is for it', async () => {- findServerByGatewayUrl.mockResolvedValue(null);+ findServerByUrl.mockResolvedValue(null);addServer.mockResolvedValue(CLOUD);await expect(@@ -722,7 +771,7 @@ describe('finding the server an invite link is for', () => {});it('hands back a server already registered here', async () => {- findServerByGatewayUrl.mockResolvedValue(OWN);+ findServerByWebAddress.mockResolvedValue(OWN);await expect(switchServersController.serverForInvite('https://switch.example.org')@@ -730,8 +779,22 @@ describe('finding the server an invite link is for', () => {expect(addServer).not.toHaveBeenCalled();});+ it('looks the link up by the server’s address or the dashboard address it keeps', async () => {+ const split = server({+ id: 'split',+ url: 'https://switch-api.example.org',+ dashboardUrl: 'https://switch-gateway.example.org',+ });+ findServerByWebAddress.mockResolvedValue(split);++ await expect(+ switchServersController.serverForInvite('https://switch-gateway.example.org')+ ).resolves.toEqual({ kind: 'known', server: split, via: 'external' });+ expect(findServerByWebAddress).toHaveBeenCalledWith('https://switch-gateway.example.org');+ });+it('says a server it has never heard of is unknown, and registers nothing', async () => {- findServerByGatewayUrl.mockResolvedValue(null);+ findServerByWebAddress.mockResolvedValue(null);await expect(switchServersController.serverForInvite('https://switch.example.org')@@ -741,7 +804,7 @@ describe('finding the server an invite link is for', () => {it('does not treat a link as the Cloud when this build names none', async () => {vi.stubEnv('SWITCH_CLOUD_URL', undefined);- findServerByGatewayUrl.mockResolvedValue(null);+ findServerByWebAddress.mockResolvedValue(null);await expect(switchServersController.serverForInvite('https://cloud.example.com')@@ -749,6 +812,37 @@ describe('finding the server an invite link is for', () => {});});+describe('opening a dashboard page', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ managedServerHostBlocked.mockReturnValue(null);+ });++ it('checks an external server serves its dashboard before opening the page', async () => {+ const { appService } = await import('@main/core/app/service');+ getServer.mockResolvedValue(server({ managed: false }));++ await switchServersController.openGatewayPage({+ serverId: 'srv',+ url: 'http://localhost:3300/rooms/1',+ });++ expect(assertServesDashboard).toHaveBeenCalledOnce();+ expect(appService.openExternal).toHaveBeenCalledWith('http://localhost:3300/rooms/1');+ });++ it('opens nothing, and says why, where no dashboard is served', async () => {+ const { appService } = await import('@main/core/app/service');+ getServer.mockResolvedValue(server({ managed: false }));+ assertServesDashboard.mockRejectedValueOnce(new Error('S does not serve its dashboard'));++ await expect(+ switchServersController.openGatewayPage({ serverId: 'srv', url: 'http://localhost:8000/' })+ ).rejects.toThrow('does not serve its dashboard');+ expect(appService.openExternal).not.toHaveBeenCalled();+ });+});+describe('cloud machines', () => {beforeEach(() => {vi.clearAllMocks();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 670148139..122eab96b 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@@ -24,22 +24,23 @@ import {SWITCH_CLOUD_NAME,type SwitchCloudEndpoint,} from '@shared/core/switch-servers/switch-cloud';-import type {- AddServerParams,- BundledChatSignIn,- ClearTrustSettingsResult,- FetchTrustSettingsResult,- PasswordLoginParams,- RenameServerParams,- ServerConnectionStatus,- SignupParams,- SignupResult,- SwitchAuthConfig,- SwitchServer,- UpdateServerParams,- UpdateServerResult,- UpdateTrustSettingsParams,- UpdateTrustSettingsResult,+import {+ normaliseServerUrl,+ type AddServerParams,+ type BundledChatSignIn,+ type ClearTrustSettingsResult,+ type FetchTrustSettingsResult,+ type PasswordLoginParams,+ type RenameServerParams,+ type ServerConnectionStatus,+ type SignupParams,+ type SignupResult,+ type SwitchAuthConfig,+ type SwitchServer,+ type UpdateServerParams,+ type UpdateServerResult,+ type UpdateTrustSettingsParams,+ type UpdateTrustSettingsResult,} 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';@@ -91,10 +92,12 @@ import {} from './github-browser-flow';import { deleteManagedClaudeCredential } from './managed-claude-credential';import { hostUnreachable, requireReachableServer, requireServer } from './require-server';+import { assertServerAddress, assertServesDashboard } from './server-address';import {addServer,deleteSessionCookie,- findServerByGatewayUrl,+ findServerByUrl,+ findServerByWebAddress,getServer,listServers,removeServer,@@ -199,15 +202,15 @@ function reportSignIn(** 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.+ * and a server's address is not added twice, so a second insert would fail+ * rather than duplicate. Reported only when a row is actually added.*/async function registerSwitchCloud({ url }: SwitchCloudEndpoint): Promise<SwitchServer> {- const existing = await findServerByGatewayUrl(url);+ const existing = await findServerByUrl(url);if (existing) return existing;let server: SwitchServer;try {- server = await addServer({ name: SWITCH_CLOUD_NAME, gatewayUrl: url, apiUrl: url });+ server = await addServer({ name: SWITCH_CLOUD_NAME, url });} catch (error) {trackEvent('server_added', { server_kind: 'external', outcome: 'failure' });throw error;@@ -270,6 +273,7 @@ export const switchServersController = createRPCController({addServer: async (params: AddServerParams): Promise<SwitchServer> => {let server: SwitchServer;try {+ await assertServerAddress(params.url);server = await addServer(params);} catch (error) {trackEvent('server_added', { server_kind: 'external', outcome: 'failure' });@@ -289,39 +293,40 @@ export const switchServersController = createRPCController({/*** 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.+ * A server already registered here is handed back as it is, whether the link+ * names its address or the separate dashboard address an older server keeps.+ * Switch Cloud is registered on the spot when the link is for it, since its+ * address is the build's and there is nothing to ask. Any other server is+ * unknown, and the caller offers the link's address to add: on a current+ * server that is the server's own, and adding checks it really is.*/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);+ const existing = await findServerByWebAddress(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);+ // Compared normalised, so a no-op edit (or one that only respells the+ // address) neither re-checks it nor rewrites any agent's config.+ const urlChanged = normaliseServerUrl(previous.url) !== normaliseServerUrl(params.url);+ if (urlChanged) await assertServerAddress(params.url);const server = await updateServer(params);- // The API URL is what an agent's SWITCH_API_ENDPOINT points at. When it+ // The address 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- // keep authenticating against the stale endpoint (CHOO-1431). Compare the- // saved (normalised) values so a no-op edit doesn't rewrite configs.- const apiUrlChanged = previous.apiUrl !== server.apiUrl;- const propagatedAgents = apiUrlChanged- ? await propagateServerApiUrl(server.id, server.apiUrl)- : [];+ // keep authenticating against the stale endpoint (CHOO-1431).+ const propagatedAgents = urlChanged ? await propagateServerApiUrl(server.id, server.url) : [];// The managed agents this computer runs reach the server through its// controller, which has to reconnect at the new address too.- if (apiUrlChanged) await embeddedControllerService.followServerApiUrl(server.id);+ if (urlChanged) await embeddedControllerService.followServerApiUrl(server.id);- return { server, propagation: { apiUrlChanged, agents: propagatedAgents } };+ return { server, propagation: { urlChanged, agents: propagatedAgents } };},renameServer: (params: RenameServerParams): Promise<SwitchServer> => renameServer(params),@@ -626,6 +631,7 @@ export const switchServersController = createRPCController({if (server.managed) {await openAuthenticatedGatewayPage(server, params.url);} else {+ await assertServesDashboard(server);await appService.openExternal(params.url);}},diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.test.tsindex ef5057c07..1e53ab99c 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.test.ts@@ -24,7 +24,7 @@ const { fetchBridgeTypes } = await import('./gateway-client');const SERVER = {id: 'srv-1',name: 'S',- gatewayUrl: 'https://switch.example.com',+ url: 'https://switch.example.com',managed: false,} as never;@@ -54,7 +54,7 @@ function response(status: number, body: unknown): Response {status,ok: status >= 200 && status < 300,json: async () => (typeof body === 'string' ? {} : body),- headers: { getSetCookie: () => [] },+ headers: { get: () => null, getSetCookie: () => [] },text: async () => text,} as unknown as Response;}diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/create-room.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/create-room.test.tsindex 61135081e..e3c6e168a 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/create-room.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/create-room.test.ts@@ -23,7 +23,7 @@ const { createRoomOnServer } = await import('./create-room');const SERVER = {id: 'srv-1',name: 'S',- gatewayUrl: 'https://switch.example.com',+ url: 'https://switch.example.com',managed: false,} as never;@@ -48,7 +48,7 @@ function response(status: number, body: unknown): Response {status,ok: status >= 200 && status < 300,json: async () => (typeof body === 'string' ? {} : body),- headers: { getSetCookie: () => [] },+ headers: { get: () => null, getSetCookie: () => [] },text: async () => text,} as unknown as Response;}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 d4a78cab5..c9c73b392 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@@ -41,8 +41,8 @@ describe('deleteAgentsForServer', () => {await fixture.db.insert(switchServers).values({id,name: id,- gatewayUrl: `https://${id}.example.com`,- apiUrl: `https://api-${id}.example.com`,+ url: `https://api-${id}.example.com`,+ dashboardUrl: `https://${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.diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/disconnect-bridge.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/disconnect-bridge.test.tsindex ee7b0da10..d82438bc5 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/disconnect-bridge.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/disconnect-bridge.test.ts@@ -23,7 +23,7 @@ const { bridgeInstallState, disconnectBridgeOnServer } = await import('./disconnconst SERVER = {id: 'srv-1',name: 'S',- gatewayUrl: 'https://switch.example.com',+ url: 'https://switch.example.com',managed: false,} as never;@@ -41,7 +41,7 @@ function response(status: number, body: unknown): Response {status,ok: status >= 200 && status < 300,json: async () => (typeof body === 'string' ? {} : body),- headers: { getSetCookie: () => [] },+ headers: { get: () => null, getSetCookie: () => [] },text: async () => text,} as unknown as Response;}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 cb270951e..c018f9fa2 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@@ -122,14 +122,14 @@ const {const SERVER = {id: 'srv-1',name: 'S',- gatewayUrl: 'https://switch.example.com',- apiUrl: 'https://switch-api.example.com',+ url: 'https://switch.example.com',+ dashboardUrl: null,managed: false,} as never;const MANAGED = {id: 'srv-local',name: 'Local',- gatewayUrl: 'https://switch.example.com',+ url: 'https://switch.example.com',managed: true,} as never;@@ -138,7 +138,7 @@ const MANAGED = {* means it cannot be spread. Used where a test needs several distinct servers* (e.g. the per-server avatar-settings cache) without redeclaring every field. */function serverWithId(id: string): typeof SERVER {- return { id, name: 'S', gatewayUrl: 'https://switch.example.com', managed: false } as never;+ return { id, name: 'S', url: 'https://switch.example.com', managed: false } as never;}/** A structurally-valid JWT whose payload `exp` is `secondsFromNow` in the@@ -156,7 +156,7 @@ function okMeResponse(): Response {status: 200,ok: true,json: async () => ({ id: 'u1', name: 'Ada', email: '[email protected]', role: 'user' }),- headers: { getSetCookie: () => [] },+ headers: { get: () => null, getSetCookie: () => [] },text: async () => '',} as unknown as Response;}@@ -166,7 +166,7 @@ function unauthorizedResponse(): Response {status: 401,ok: false,json: async () => ({}),- headers: { getSetCookie: () => [] },+ headers: { get: () => null, getSetCookie: () => [] },text: async () => 'Token expired',} as unknown as Response;}@@ -460,7 +460,7 @@ function jsonResponse(body: unknown): Response {status: 200,ok: true,json: async () => body,- headers: { getSetCookie: () => [] },+ headers: { get: () => null, getSetCookie: () => [] },text: async () => JSON.stringify(body),} as unknown as Response;}@@ -470,7 +470,7 @@ function errorResponse(status: number, body: string): Response {status,ok: false,json: async () => ({}),- headers: { getSetCookie: () => [] },+ headers: { get: () => null, getSetCookie: () => [] },text: async () => body,} as unknown as Response;}@@ -740,7 +740,7 @@ describe('registerKnownAgent', () => {status: 200,ok: true,json: async () => ({ id: 'sw-1', api_key: 'tok-123' }),- headers: { getSetCookie: () => [] },+ headers: { get: () => null, getSetCookie: () => [] },text: async () => '',}) as unknown as Response);@@ -1129,6 +1129,25 @@ describe('GitHub connection transport', () => {})).rejects.toThrow('invalid GitHub authorization URL');});+ it('accepts the server’s own address on an older server that keeps its dashboard apart', async () => {+ const state = 'a'.repeat(43);+ fetchMock.mockResolvedValueOnce(+ new Response(+ JSON.stringify({+ id: state,+ url: `https://switch-api.example.com/gateway/provider-connections/github/authorize?state=${state}`,+ })+ )+ );+ const split = {+ ...(SERVER as object),+ url: 'https://switch-api.example.com',+ dashboardUrl: 'https://switch.example.com',+ } as never;+ await expect(+ startGitHubConnection(split, { port: 12345, state, completion_secret: 'b'.repeat(43) })+ ).resolves.toMatchObject({ id: state });+ });it('checks state matches the returned authorization id', async () => {fetchMock.mockResolvedValueOnce(new Response(@@ -1547,6 +1566,11 @@ describe('a service sign-in', () => {const state = 'a'.repeat(43);const input = { port: 12345, state, completion_secret: 'b'.repeat(43) };const flows = 'https://switch.example.com/gateway/service-connections/example/flows';+ // An older server that still keeps its dashboard on a host of its own.+ const SPLIT = {+ ...(SERVER as object),+ dashboardUrl: 'https://switch-dashboard.example.com',+ } as never;const vendor = (query: Record<string, string>) =>`https://auth.example.test/authorize?${new URLSearchParams(query)}`;const answer = (body: object) =>@@ -1584,17 +1608,17 @@ describe('a service sign-in', () => {);});- it('accepts Core’s authorize step on the server’s API host, where it returns', async () => {- const url = `https://switch-api.example.com/gateway/service-connections/example/flows/authorize?state=${state}`;+ it('accepts Core’s authorize step on the separate dashboard host an older server keeps', async () => {+ const url = `https://switch-dashboard.example.com/gateway/service-connections/example/flows/authorize?state=${state}`;answer({ id: state, mode: 'core', url });- expect((await startServiceConnection(SERVER, 'example', input)).url).toBe(url);+ expect((await startServiceConnection(SPLIT, 'example', input)).url).toBe(url);});it.each([[- 'the server’s API host over plain HTTP',+ 'the separate dashboard host over plain HTTP','core',- `http://switch-api.example.com/gateway/service-connections/example/flows/authorize?state=${state}`,+ `http://switch-dashboard.example.com/gateway/service-connections/example/flows/authorize?state=${state}`,],['another server in core mode',@@ -1623,7 +1647,7 @@ describe('a service sign-in', () => {],])('refuses %s', async (_name, mode, url) => {answer({ id: state, mode, url });- await expect(startServiceConnection(SERVER, 'example', input)).rejects.toThrow(+ await expect(startServiceConnection(SPLIT, 'example', input)).rejects.toThrow('invalid sign-in URL');});@@ -1748,6 +1772,35 @@ describe('sign-up support', () => {expect((await fetchAuthConfig(SERVER)).signupEnabled).toBe(false);});+ it.each([200, 404])(+ 'says the address does not route /gateway when a web page answers it (HTTP %i)',+ async (status) => {+ fetchMock.mockResolvedValueOnce(+ new Response('<!doctype html><title>dashboard</title>', {+ status,+ headers: { 'content-type': 'text/html; charset=utf-8' },+ })+ );+ await expect(fetchAuthConfig(SERVER)).rejects.toMatchObject({+ name: 'NoManagementApiError',+ message: expect.stringContaining('route /gateway on https://switch.example.com'),+ });+ }+ );++ it('reports a proxy’s 502 page as the failure it is, not as a missing route', async () => {+ fetchMock.mockResolvedValueOnce(+ new Response('<html>Bad Gateway</html>', {+ status: 502,+ headers: { 'content-type': 'text/html' },+ })+ );+ await expect(fetchAuthConfig(SERVER)).rejects.toMatchObject({+ name: 'GatewayError',+ status: 502,+ });+ });+it('warms the cloud machine with an authenticated POST', async () => {const machine = {machine_id: 'm-1',@@ -2054,7 +2107,7 @@ describe('distributed Teams team placement', () => {status: 200,ok: true,json: async () => ({}),- headers: { getSetCookie: () => [] },+ headers: { get: () => null, getSetCookie: () => [] },text: async () => '',arrayBuffer: async () => bytes,} as unknown as Response);@@ -2154,7 +2207,7 @@ describe('acceptInvitation', () => {status: 200,ok: true,json: async () => ({ id: 't1', slug: 'cryo', name: 'Cryo Team', role: 'member' }),- headers: { getSetCookie: () => setCookies },+ headers: { get: () => null, getSetCookie: () => setCookies },text: async () => '',} as unknown as Response;}@@ -2404,7 +2457,7 @@ describe('invitations addressed to the signed-in account', () => {status: 200,ok: true,json: async () => ({ id: 't1', slug: 'cryo', name: 'Cryo Team', role: 'member' }),- headers: { getSetCookie: () => ['switch_auth=scoped; Path=/; HttpOnly'] },+ headers: { get: () => null, getSetCookie: () => ['switch_auth=scoped; Path=/; HttpOnly'] },text: async () => '',} as never);@@ -2468,7 +2521,7 @@ describe('joining a workspace by e-mail domain', () => {status: 200,ok: true,json: async () => ({ id: 't9', slug: 'skunk', name: 'Skunkworks', role: 'member' }),- headers: { getSetCookie: () => ['switch_auth=scoped; Path=/; HttpOnly'] },+ headers: { get: () => null, getSetCookie: () => ['switch_auth=scoped; Path=/; HttpOnly'] },text: async () => '',} as never);@@ -2551,7 +2604,7 @@ describe('workspace invitations', () => {status: 200,ok: true,json: async () => body,- headers: { getSetCookie: () => [] },+ headers: { get: () => null, getSetCookie: () => [] },text: async () => '',} as unknown as Response;}@@ -2663,7 +2716,7 @@ describe('agent management calls', () => {status,ok: status >= 200 && status < 300,json: async () => JSON.parse(text),- headers: { getSetCookie: () => [] },+ headers: { get: () => null, getSetCookie: () => [] },text: async () => text,} as unknown as Response;}@@ -2798,7 +2851,7 @@ describe('agent management calls', () => {expect(JSON.parse(String(init.body))).toEqual({ sealed });await expect(giveMachineLogin(- { ...(SERVER as object), gatewayUrl: 'http://switch.example.com' } as never,+ { ...(SERVER as object), url: 'http://switch.example.com' } as never,'c','claude',sealeddiff --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 540a7fc5a..da6e8cb68 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@@ -64,35 +64,35 @@ import {serviceGrantWarningSchema,serviceGrantsSchema,} from '@shared/core/switch-servers/service-grants';-import type {- AddressingPolicy,- AddTeamsTeamResult,- BridgeConfigField,- BridgeDirectoryUser,- ChatClaim,- ConnectedChat,- DeleteBridgeResult,- LinkedIdentity,- MessagingAppInstall,- MessagingApps,- RemoteAgentRoom,- RemoteAgentSummary,- RemoteBridge,- RemoteBridgeType,- RemoteExternalUser,- RemoteRoomDetail,- RemoteRoomGroup,- RemoteRoomRole,- RemoteRoomSummary,- RemoveTeamsTeamResult,- SwitchAuthConfig,- SwitchServer,- SwitchServerDeclaration,- SwitchUser,- TeamsTeam,- TeamsTeamsResult,- TrustSettings,- UpdateTrustSettingsParams,+import {+ type AddressingPolicy,+ type AddTeamsTeamResult,+ type BridgeConfigField,+ type BridgeDirectoryUser,+ type ChatClaim,+ type ConnectedChat,+ type DeleteBridgeResult,+ type LinkedIdentity,+ type MessagingAppInstall,+ type MessagingApps,+ type RemoteAgentRoom,+ type RemoteAgentSummary,+ type RemoteBridge,+ type RemoteBridgeType,+ type RemoteExternalUser,+ type RemoteRoomDetail,+ type RemoteRoomGroup,+ type RemoteRoomRole,+ type RemoteRoomSummary,+ type RemoveTeamsTeamResult,+ type SwitchAuthConfig,+ type SwitchServer,+ type SwitchServerDeclaration,+ type SwitchUser,+ type TeamsTeam,+ type TeamsTeamsResult,+ type TrustSettings,+ type UpdateTrustSettingsParams,} from '@shared/core/switch-servers/switch-servers';import type {Invitation,@@ -104,11 +104,12 @@ import type {import type { WorkspaceRole } from '@shared/core/workspaces/workspaces';import { extractAuthCookie, reauthenticateManagedServer, refreshSession } from './auth';import { consoleIdentityHeaders } from './console-identity';+import { NoManagementApiError } from './server-address';import { getSessionCookie, setSessionCookie } from './servers-store';/** The gateway management API is mounted under `/gateway` on the server. */function gatewayUrl(server: SwitchServer, path: string): string {- return `${server.gatewayUrl}/gateway${path}`;+ return `${server.url}/gateway${path}`;}/** Renew the session once the stored JWT is within this window of its `exp`, so@@ -349,7 +350,7 @@ export async function gatewayRequest(noteManagedServerUnanswered(server);throw new GatewayError('network',- `Could not reach ${server.gatewayUrl}: ${cause instanceof Error ? cause.message : String(cause)}`+ `Could not reach ${server.url}: ${cause instanceof Error ? cause.message : String(cause)}`);}};@@ -371,9 +372,24 @@ export async function gatewayRequest(if (response.status === 401) {throw new GatewayError('unauthorized', 'Switch session expired — please sign in again.', 401);}+ if (answeredWithPage(response)) {+ throw new NoManagementApiError(server.name, server.url, response.status);+ }return response;}+/**+ * Whether something other than switch-core answered a `/gateway` call: every+ * answer the management API gives is JSON, its 404 included, so a page that+ * comes back successfully (a catch-all serving a web app) or as a 404 (a proxy+ * with no route for the path) is not from it. A proxy's 502 page means the+ * server is down, which the caller reports as it is.+ */+function answeredWithPage(response: Response): boolean {+ const html = (response.headers.get('content-type') ?? '').toLowerCase().startsWith('text/html');+ return html && (response.ok || response.status === 404);+}+/** The `retryable` beside `detail` in a coded refusal, or undefined without one. */function parseErrorRetryable(body: string): boolean | undefined {if (!body) return undefined;@@ -3376,7 +3392,7 @@ export async function startGitHubConnection(server: SwitchServer,input: { port: number; state: string; completion_secret: string }) {- if (!isHttpsOrLoopback(new URL(server.gatewayUrl)))+ if (!isHttpsOrLoopback(new URL(server.url)))throw new Error('GitHub connections require HTTPS, unless the server is on this computer.');const value = z.object({ id: z.string().regex(/^[A-Za-z0-9_-]{43}$/), url: z.string() }).parse(await (@@ -3388,8 +3404,13 @@ export async function startGitHubConnection().json());const url = new URL(value.url);+ // Core names its public address, which on an older server whose dashboard+ // has a host of its own is not where Console opens dashboard pages.if (- url.origin !== new URL(server.gatewayUrl).origin ||+ !isHttpsOrLoopback(url) ||+ ![server.url, server.dashboardUrl].some(+ (own) => own !== null && new URL(own).origin === url.origin+ ) ||url.pathname !== '/gateway/provider-connections/github/authorize' ||url.searchParams.get('state') !== value.id ||url.username ||@@ -3452,15 +3473,16 @@ const serviceFlows = (service: string) =>** Core's authorize step is at its public address (`GATEWAY_PUBLIC_URL`), the* host the vendor returns the browser to and whose cookie ties that return to- * the browser. A server that serves its gateway and its API on two hosts has it- * on the API's, so either of the server's own origins is accepted, over HTTPS.+ * the browser. That is normally the server's own address; an older server that+ * still keeps its dashboard on a host of its own may name that host instead, so+ * either is accepted, over HTTPS.*/export async function startServiceConnection(server: SwitchServer,service: string,input: { port: number; state: string; completion_secret: string }): Promise<ServiceFlowStart> {- if (!isHttpsOrLoopback(new URL(server.gatewayUrl)))+ if (!isHttpsOrLoopback(new URL(server.url)))throw new Error('Service connections require HTTPS, unless the server is on this computer.');const value = serviceFlowStartSchema.parse(await (@@ -3478,7 +3500,9 @@ export async function startServiceConnection(!url.password &&(value.mode === 'core'? isHttpsOrLoopback(url) &&- [server.gatewayUrl, server.apiUrl].some((own) => new URL(own).origin === url.origin) &&+ [server.url, server.dashboardUrl].some(+ (own) => own !== null && new URL(own).origin === url.origin+ ) &&url.pathname === `/gateway${serviceFlows(service)}/authorize` &&url.searchParams.get('state') === value.id: url.protocol === 'https:' &&@@ -3804,8 +3828,7 @@ export async function giveMachineLogin(): Promise<{ operationId: string; revision: number }> {// The login is sealed, but the key it was sealed to came from this server:// over plain HTTP anyone in between could have handed over their own.- const gateway = new URL(server.gatewayUrl);- if (!isHttpsOrLoopback(gateway))+ if (!isHttpsOrLoopback(new URL(server.url)))throw new Error('Giving a machine a provider login requires HTTPS.');const res = await managementFetch(server,diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-web.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-web.test.tsindex 362754733..bbc692914 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-web.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-web.test.ts@@ -30,13 +30,13 @@ const { openAuthenticatedGatewayPage } = await import('./gateway-web');const SERVER = {id: 'srv-1',name: 'S',- gatewayUrl: 'http://127.0.0.1:8080',+ url: 'http://127.0.0.1:8080',managed: false,} as never;const MANAGED = {id: 'srv-local',name: 'Local',- gatewayUrl: 'http://127.0.0.1:8080',+ url: 'http://127.0.0.1:8080',managed: true,} as never;@@ -45,12 +45,12 @@ describe('openAuthenticatedGatewayPage', () => {vi.clearAllMocks();});- it('rejects a url that is not on the gateway origin, before opening anything', async () => {+ it('rejects a url that is not on the dashboard origin, before opening anything', async () => {getSessionCookie.mockResolvedValue('jwt');await expect(openAuthenticatedGatewayPage(SERVER, 'http://evil.example.com/agents/1')- ).rejects.toThrow(/gateway origin/);+ ).rejects.toThrow(/dashboard origin/);expect(BrowserWindow).not.toHaveBeenCalled();expect(cookiesSet).not.toHaveBeenCalled();});@@ -74,6 +74,29 @@ describe('openAuthenticatedGatewayPage', () => {expect(reauthenticateManagedServer).not.toHaveBeenCalled();});+ it('opens pages on the dashboard address a server keeps apart, and nowhere else', async () => {+ getSessionCookie.mockResolvedValue('stored-jwt');+ const split = {+ id: 'srv-split',+ name: 'Split',+ url: 'https://switch-api.example.com',+ dashboardUrl: 'https://switch-gateway.example.com',+ managed: false,+ } as never;++ await expect(+ openAuthenticatedGatewayPage(split, 'https://switch-api.example.com/rooms/1')+ ).rejects.toThrow(/not on the dashboard origin https:\/\/switch-gateway\.example\.com/);+ expect(cookiesSet).not.toHaveBeenCalled();++ await openAuthenticatedGatewayPage(split, 'https://switch-gateway.example.com/rooms/1');++ expect(cookiesSet).toHaveBeenCalledWith(+ expect.objectContaining({ url: 'https://switch-gateway.example.com', secure: true })+ );+ expect(loadURL).toHaveBeenCalledWith('https://switch-gateway.example.com/rooms/1');+ });+it('mints a session for the managed server when none is stored', async () => {getSessionCookie.mockResolvedValue(null);reauthenticateManagedServer.mockResolvedValue('minted-jwt');diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-web.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-web.tsindex 6c6bf02cf..ecfc25604 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-web.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-web.ts@@ -1,6 +1,6 @@import { BrowserWindow, session as electronSession } from 'electron';import { log } from '@main/lib/logger';-import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';+import { dashboardOrigin, type SwitchServer } from '@shared/core/switch-servers/switch-servers';import { reauthenticateManagedServer } from './auth';import { consoleIdentityHeaders } from './console-identity';import { getSessionCookie } from './servers-store';@@ -17,17 +17,17 @@ const SWITCH_AUTH_COOKIE = 'switch_auth';* authenticated; other servers open with whatever session is stored, falling* back to the gateway's own sign-in page if none.*- * `url` must live on the server's gateway origin — the caller builds it from- * `server.gatewayUrl` — so the injected cookie is only ever exposed to the- * gateway itself.+ * `url` must live on the origin the server's dashboard is served from — the+ * caller builds it from `dashboardOrigin(server)` — so the injected cookie is+ * only ever exposed to the server itself.*/export async function openAuthenticatedGatewayPage(server: SwitchServer,url: string): Promise<void> {- const gatewayOrigin = new URL(server.gatewayUrl).origin;+ const gatewayOrigin = new URL(dashboardOrigin(server)).origin;if (new URL(url).origin !== gatewayOrigin) {- throw new Error(`Refusing to open ${url}: not on the gateway origin ${gatewayOrigin}`);+ throw new Error(`Refusing to open ${url}: not on the dashboard origin ${gatewayOrigin}`);}let jwt = await getSessionCookie(server.id);diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/github-browser-flow.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/github-browser-flow.test.tsindex 9117d29e8..5c931963b 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/github-browser-flow.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/github-browser-flow.test.ts@@ -21,7 +21,7 @@ vi.mock('./gateway-client', () => ({getGitHubFlow: vi.fn(),startGitHubConnection: vi.fn(),}));-const server = { id: 'server', gatewayUrl: 'https://switch.example.test' } as SwitchServer;+const server = { id: 'server', url: 'https://switch.example.test' } as SwitchServer;const flows: string[] = [];afterEach(async () => {for (const id of flows.splice(0)) await cancelGitHubBrowserFlow(server, id);diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/server-address.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/server-address.test.tsnew file mode 100644index 000000000..4da2650f4--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/server-address.test.ts@@ -0,0 +1,388 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';++const listServers = vi.hoisted(() => vi.fn());+const clearDashboardUrl = vi.hoisted(() => vi.fn(async () => {}));+const setDashboardUrl = vi.hoisted(() => vi.fn(async () => {}));+const logWarn = vi.hoisted(() => vi.fn());+const logInfo = vi.hoisted(() => vi.fn());++vi.mock('./servers-store', () => ({ listServers, clearDashboardUrl, setDashboardUrl }));+vi.mock('@main/lib/logger', () => ({ log: { warn: logWarn, info: logInfo, error: vi.fn() } }));++const {+ assertServerAddress,+ assertServesDashboard,+ keepSeparateDashboard,+ NoDashboardError,+ NotTheServerAddressError,+ retireDashboardFallback,+ retireDashboardFallbacks,+ separateDashboard,+ servesDashboard,+} = await import('./server-address');++const fetchMock = vi.fn();++beforeEach(() => {+ vi.clearAllMocks();+ fetchMock.mockReset();+ vi.stubGlobal('fetch', fetchMock);+});++function answer(status: number, contentType: string): Response {+ return new Response(contentType.startsWith('text/html') ? '<!doctype html>' : '{}', {+ status,+ headers: { 'content-type': contentType },+ });+}++const PAGE = () => answer(200, 'text/html; charset=utf-8');+const JSON_OK = () => answer(200, 'application/json');+const UNAUTHORIZED = () => answer(401, 'application/json');++function server(overrides: Partial<SwitchServer>): SwitchServer {+ return {+ id: 'srv',+ name: 'Split',+ url: 'https://switch-api.example.com',+ dashboardUrl: 'https://switch-gateway.example.com',+ managed: false,+ managementKind: null,+ sshHost: null,+ createdAt: '',+ updatedAt: '',+ ...overrides,+ };+}++/** Answer each origin's root as given; anything else is a network failure. */+function roots(byOrigin: Record<string, () => Response | Promise<never>>): void {+ fetchMock.mockImplementation(async (url: string) => {+ const respond = byOrigin[new URL(url).origin];+ if (!respond) throw new TypeError('fetch failed');+ return respond();+ });+}++describe('assertServerAddress', () => {+ it('accepts an address whose health check is the API’s', async () => {+ fetchMock.mockResolvedValue(JSON_OK());++ await expect(assertServerAddress('https://switch.example.com/')).resolves.toBeUndefined();+ expect(fetchMock).toHaveBeenCalledWith(+ 'https://switch.example.com/health',+ expect.objectContaining({ headers: { Accept: 'application/json' } })+ );+ });++ it('refuses an address that answers with a web page, saying what to enter', async () => {+ fetchMock.mockResolvedValue(PAGE());++ const checking = assertServerAddress('https://switch-gateway.example.com');++ await expect(checking).rejects.toBeInstanceOf(NotTheServerAddressError);+ await expect(checking).rejects.toThrow(+ /https:\/\/switch-gateway\.example\.com answered with a web page.*dashboard.*port 8000/+ );+ });++ it('leaves an address it cannot reach to the sign-in that follows', async () => {+ fetchMock.mockRejectedValue(new TypeError('fetch failed'));++ await expect(assertServerAddress('https://down.example.com')).resolves.toBeUndefined();+ expect(logWarn).toHaveBeenCalledWith(+ 'switch-servers: could not check the server address before saving it',+ expect.objectContaining({ url: 'https://down.example.com' })+ );+ });++ it('leaves any other answer to the sign-in too', async () => {+ fetchMock.mockResolvedValue(answer(404, 'application/json'));++ await expect(assertServerAddress('https://other.example.com')).resolves.toBeUndefined();+ });++ it('does not take a proxy’s own error page for a dashboard', async () => {+ fetchMock.mockResolvedValue(answer(502, 'text/html'));++ await expect(assertServerAddress('https://behind-proxy.example.com')).resolves.toBeUndefined();+ });+});++describe('servesDashboard', () => {+ it('is true for a page at the root', async () => {+ fetchMock.mockResolvedValue(PAGE());++ expect(await servesDashboard('https://switch.example.com/')).toBe(true);+ expect(fetchMock).toHaveBeenCalledWith(+ 'https://switch.example.com/',+ expect.objectContaining({ headers: { Accept: 'text/html' } })+ );+ });++ it('is false where switch-core’s API answers the root', async () => {+ fetchMock.mockResolvedValueOnce(UNAUTHORIZED());+ expect(await servesDashboard('https://old-api.example.com')).toBe(false);++ fetchMock.mockResolvedValueOnce(answer(404, 'text/plain'));+ expect(await servesDashboard('https://old-api.example.com')).toBe(false);+ });++ it('cannot tell when something else answers with a page, or with an outage', async () => {+ // A proxy's sign-in in front of the dashboard, its error page while the+ // server restarts: neither says the server has no dashboard.+ fetchMock.mockResolvedValueOnce(answer(401, 'text/html'));+ expect(await servesDashboard('https://behind-sign-in.example.com')).toBeNull();++ fetchMock.mockResolvedValueOnce(answer(502, 'text/html'));+ expect(await servesDashboard('https://proxy.example.com')).toBeNull();++ fetchMock.mockResolvedValueOnce(answer(503, 'text/plain'));+ expect(await servesDashboard('https://restarting.example.com')).toBeNull();+ });++ it('is null, and says why, when the address cannot be reached', async () => {+ fetchMock.mockRejectedValue(new TypeError('fetch failed'));++ expect(await servesDashboard('https://down.example.com')).toBeNull();+ expect(logWarn).toHaveBeenCalledWith(+ 'switch-servers: could not ask whether an address serves the dashboard',+ { origin: 'https://down.example.com', error: 'TypeError: fetch failed' }+ );+ });+});++describe('retireDashboardFallback', () => {+ it('drops the old address once the server serves its dashboard and the old host is gone', async () => {+ roots({ 'https://switch-api.example.com': PAGE });++ expect(await retireDashboardFallback(server({}))).toBe(true);+ expect(clearDashboardUrl).toHaveBeenCalledExactlyOnceWith(+ 'srv',+ 'https://switch-api.example.com'+ );+ expect(logInfo).toHaveBeenCalledWith(+ expect.stringContaining('serves its own dashboard'),+ expect.objectContaining({ oldAddressAnswered: false })+ );+ });++ it('drops it when the old host answers but no longer with the dashboard', async () => {+ roots({+ 'https://switch-api.example.com': PAGE,+ 'https://switch-gateway.example.com': () => answer(404, 'text/plain'),+ });++ expect(await retireDashboardFallback(server({}))).toBe(true);+ expect(clearDashboardUrl).toHaveBeenCalledOnce();+ });++ it('keeps it while the old host still serves the dashboard', async () => {+ // Its identity provider may still return there.+ roots({ 'https://switch-api.example.com': PAGE, 'https://switch-gateway.example.com': PAGE });++ expect(await retireDashboardFallback(server({}))).toBe(false);+ expect(clearDashboardUrl).not.toHaveBeenCalled();+ });++ it('keeps it while the server does not serve its own dashboard', async () => {+ roots({ 'https://switch-api.example.com': UNAUTHORIZED });++ expect(await retireDashboardFallback(server({}))).toBe(false);+ expect(clearDashboardUrl).not.toHaveBeenCalled();+ });++ it('keeps it when the server itself cannot be reached', async () => {+ roots({});++ expect(await retireDashboardFallback(server({}))).toBe(false);+ expect(clearDashboardUrl).not.toHaveBeenCalled();+ });++ it('asks nothing of a server with no separate dashboard', async () => {+ expect(await retireDashboardFallback(server({ dashboardUrl: null }))).toBe(false);+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('leaves a managed server to the addresses its stack registers', async () => {+ roots({ 'https://switch-api.example.com': PAGE });++ expect(await retireDashboardFallback(server({ managed: true }))).toBe(false);+ expect(fetchMock).not.toHaveBeenCalled();+ expect(clearDashboardUrl).not.toHaveBeenCalled();+ });+});++describe('retireDashboardFallbacks', () => {+ it('checks every server, and one that fails does not stop the rest', async () => {+ listServers.mockResolvedValue([+ server({ id: 'broken' }),+ server({+ id: 'upgraded',+ url: 'https://new-api.example.com',+ dashboardUrl: 'https://new-gateway.example.com',+ }),+ ]);+ roots({+ 'https://switch-api.example.com': PAGE,+ 'https://new-api.example.com': PAGE,+ });+ clearDashboardUrl.mockRejectedValueOnce(new Error('database is locked'));++ await retireDashboardFallbacks();++ expect(clearDashboardUrl).toHaveBeenCalledTimes(2);+ expect(clearDashboardUrl).toHaveBeenCalledWith('upgraded', 'https://new-api.example.com');+ expect(logWarn).toHaveBeenCalledWith(+ 'switch-servers: could not check whether a server still needs its old dashboard',+ { server: 'broken', error: 'Error: database is locked' }+ );+ });+});++describe('separateDashboard', () => {+ it('keeps the address a link came from when only it serves the dashboard', async () => {+ roots({+ 'https://switch-api.example.com': UNAUTHORIZED,+ 'https://switch-gateway.example.com': PAGE,+ });++ expect(+ await separateDashboard(+ 'https://switch-api.example.com',+ 'https://switch-gateway.example.com'+ )+ ).toBe('https://switch-gateway.example.com');+ });++ it('keeps nothing once the server serves its own dashboard', async () => {+ roots({+ 'https://switch-api.example.com': PAGE,+ 'https://switch-gateway.example.com': PAGE,+ });++ expect(+ await separateDashboard(+ 'https://switch-api.example.com',+ 'https://switch-gateway.example.com'+ )+ ).toBeNull();+ });++ it('keeps nothing that does not serve the dashboard itself', async () => {+ roots({ 'https://switch-api.example.com': UNAUTHORIZED });++ expect(+ await separateDashboard('https://switch-api.example.com', 'https://elsewhere.example.com')+ ).toBeNull();+ });++ it('asks nothing when the link was to the server’s own address', async () => {+ expect(+ await separateDashboard('https://switch.example.com', 'https://SWITCH.example.com/')+ ).toBeNull();+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('keeps a host deeper in the server’s own domain', async () => {+ roots({+ 'https://switch-api.acme.example.com': UNAUTHORIZED,+ 'https://switch-gateway.example.com': PAGE,+ });++ expect(+ await separateDashboard(+ 'https://switch-api.acme.example.com',+ 'https://switch-gateway.example.com'+ )+ ).toBe('https://switch-gateway.example.com');+ });++ it('keeps another port on the server’s own host', async () => {+ roots({ 'http://10.0.0.5:8000': UNAUTHORIZED, 'http://10.0.0.5:3000': PAGE });++ expect(await separateDashboard('http://10.0.0.5:8000', 'http://10.0.0.5:3000')).toBe(+ 'http://10.0.0.5:3000'+ );+ });++ it.each([+ ['another domain', 'https://switch-api.example.com', 'https://dashboard.example.net'],+ ['another address', 'http://10.0.0.5:8000', 'http://10.0.0.6:3000'],+ ['a shared tunnel domain', 'https://acme.ngrok.app', 'https://evil.ngrok.app'],+ ['a shared hosting domain', 'https://acme.herokuapp.com', 'https://evil.herokuapp.com'],+ ['a shared pages domain', 'https://acme.github.io', 'https://evil.github.io'],+ ['a two-part public suffix', 'https://acme.co.uk', 'https://evil.co.uk'],+ ])('takes no link’s word for a host on %s, and asks nothing', async (_case, url, candidate) => {+ roots({ [url]: UNAUTHORIZED, [candidate]: PAGE });++ expect(await separateDashboard(url, candidate)).toBeNull();+ expect(fetchMock).not.toHaveBeenCalled();+ });+});++describe('keepSeparateDashboard', () => {+ const OLDER = server({ dashboardUrl: null });++ it('keeps the host a sign-in returned to, when it serves the dashboard', async () => {+ roots({+ 'https://switch-api.example.com': UNAUTHORIZED,+ 'https://switch-gateway.example.com': PAGE,+ });++ await keepSeparateDashboard(OLDER, 'https://switch-gateway.example.com');++ expect(setDashboardUrl).toHaveBeenCalledExactlyOnceWith(+ 'srv',+ 'https://switch-api.example.com',+ 'https://switch-gateway.example.com'+ );+ });++ it('keeps nothing the dashboard checks refuse', async () => {+ roots({+ 'https://switch-api.example.com': PAGE,+ 'https://switch-gateway.example.com': PAGE,+ });++ await keepSeparateDashboard(OLDER, 'https://switch-gateway.example.com');++ expect(setDashboardUrl).not.toHaveBeenCalled();+ });++ it('leaves a managed server’s addresses to its stack', async () => {+ await keepSeparateDashboard(+ server({ managed: true, dashboardUrl: null }),+ 'https://switch-gateway.example.com'+ );++ expect(fetchMock).not.toHaveBeenCalled();+ expect(setDashboardUrl).not.toHaveBeenCalled();+ });+});++describe('assertServesDashboard', () => {+ it('refuses, naming the server and the address, where nothing serves the dashboard', async () => {+ roots({ 'https://switch-api.example.com': UNAUTHORIZED });++ const checking = assertServesDashboard(server({ dashboardUrl: null }));++ await expect(checking).rejects.toBeInstanceOf(NoDashboardError);+ await expect(checking).rejects.toThrow(+ /^Split does not serve its dashboard at https:\/\/switch-api\.example\.com\./+ );+ });++ it('asks the separate dashboard address a server keeps, not its own', async () => {+ roots({ 'https://switch-gateway.example.com': PAGE });++ await expect(assertServesDashboard(server({}))).resolves.toBeUndefined();+ });++ it('leaves an address it cannot reach for the browser to report', async () => {+ roots({});++ await expect(assertServesDashboard(server({ dashboardUrl: null }))).resolves.toBeUndefined();+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/server-address.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/server-address.tsnew file mode 100644index 000000000..3b71e5945--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/server-address.ts@@ -0,0 +1,243 @@+import { getDomain } from 'tldts';+import { log } from '@main/lib/logger';+import {+ dashboardOrigin,+ type SwitchServer,+ urlOrigin,+} from '@shared/core/switch-servers/switch-servers';+import { clearDashboardUrl, listServers, setDashboardUrl } from './servers-store';++const PROBE_TIMEOUT_MS = 5000;++/**+ * The address given for a server answered as a web page rather than as the+ * Switch API. On an older server the dashboard has an address of its own, and+ * it answers every path with its page, so it is the address people most often+ * paste by mistake.+ */+export class NotTheServerAddressError extends Error {+ constructor(url: string) {+ super(+ `${url} answered with a web page, not the Switch server. That is usually the address of ` ++ `an older server's dashboard. Enter the server's own address instead: the one its agents ` ++ `connect to, often the same host on port 8000.`+ );+ this.name = 'NotTheServerAddressError';+ }+}++function isHtml(response: Response): boolean {+ return (response.headers.get('content-type') ?? '').toLowerCase().startsWith('text/html');+}++/**+ * Refuse an address that is positively the wrong one: one whose health check+ * comes back as a page, successfully. Every switch-core answers `/health` with+ * JSON, and a dashboard served on an address of its own answers every path+ * with its page. A proxy's own error page (a 404 or a 502 in HTML) is not that,+ * and is left alone with everything else.+ *+ * Anything else is let through, unreachable included, because the sign-in that+ * follows adding a server reports those failures in its own words; refusing+ * here as well would turn "the server is down" into "the address is wrong".+ */+export async function assertServerAddress(url: string): Promise<void> {+ let response: Response;+ try {+ response = await fetch(`${url.replace(/\/+$/, '')}/health`, {+ headers: { Accept: 'application/json' },+ signal: AbortSignal.timeout(PROBE_TIMEOUT_MS),+ });+ } catch (error) {+ log.warn('switch-servers: could not check the server address before saving it', {+ url,+ error: String(error),+ });+ return;+ }+ if (response.ok && isHtml(response)) throw new NotTheServerAddressError(url);+}++/**+ * Whether `origin` serves the dashboard: true when its root answers with a+ * page, false when switch-core's API answers there instead (a refusal or a+ * not-found that is not a page). Null when that cannot be told: the address+ * could not be asked, or something else answered with a page of its own, such+ * as a proxy's sign-in or error page.+ */+export async function servesDashboard(origin: string): Promise<boolean | null> {+ let response: Response;+ try {+ response = await fetch(`${origin.replace(/\/+$/, '')}/`, {+ headers: { Accept: 'text/html' },+ signal: AbortSignal.timeout(PROBE_TIMEOUT_MS),+ });+ } catch (error) {+ log.warn('switch-servers: could not ask whether an address serves the dashboard', {+ origin,+ error: String(error),+ });+ return null;+ }+ if (isHtml(response)) return response.ok ? true : null;+ return response.status === 401 || response.status === 404 ? false : null;+}++/**+ * A server's own address does not answer the management API under `/gateway`:+ * something other than switch-core answered there with a web page. Console+ * reaches every server's management API at its own address, the one its agents+ * use, so a proxy in front of that address that routes only the agent API+ * leaves Console nothing to talk to.+ */+export class NoManagementApiError extends Error {+ constructor(serverName: string, url: string, status: number) {+ super(+ `${serverName} does not answer at ${url}/gateway: a web page came back (HTTP ${status}) ` ++ `where switch-core answers the management API. Switch Console reaches a server's ` ++ `management API at the server's own address. Ask whoever runs it to route /gateway on ` ++ `${url} to switch-core, as the agent API already is.`+ );+ this.name = 'NoManagementApiError';+ }+}++/** A server's dashboard pages cannot be opened, because nothing serves them. */+export class NoDashboardError extends Error {+ constructor(serverName: string, origin: string) {+ super(+ `${serverName} does not serve its dashboard at ${origin}. Either it is older than ` ++ `switch-core serving the dashboard on its own address, and its pages open from here ` ++ `once whoever runs it upgrades it, or its dashboard is turned off.`+ );+ this.name = 'NoDashboardError';+ }+}++/**+ * Refuse to open a dashboard page where there is no dashboard, rather than+ * handing the browser the API's refusal to read. The case is a server added+ * by its own address while it still kept its dashboard elsewhere: Console has+ * no other address for it. An address that cannot be asked at all is left to+ * the browser to report.+ */+export async function assertServesDashboard(server: SwitchServer): Promise<void> {+ const origin = dashboardOrigin(server);+ if ((await servesDashboard(origin)) === false) throw new NoDashboardError(server.name, origin);+}++/** The domain a hostname is registered under, by the public-suffix list with+ * its private section: `example.com` for `switch-api.example.com`, but+ * `acme.ngrok.app` for itself, since anyone can take a name beside it. Null for+ * an IP address, `localhost` or a single-label name. */+function registrableDomain(hostname: string): string | null {+ return getDomain(hostname, { allowPrivateDomains: true });+}++/** Whether two addresses are on one host, or on hosts of one registered domain:+ * `switch-gateway.example.com` beside `switch-api.example.com`, but not+ * `evil.ngrok.app` beside `acme.ngrok.app`, nor `evil.co.uk` beside+ * `acme.co.uk`. */+function onTheSameDomain(a: string, b: string): boolean {+ const [hostA, hostB] = [new URL(a).hostname, new URL(b).hostname];+ if (hostA === hostB) return true;+ const domain = registrableDomain(hostA);+ return domain !== null && domain === registrableDomain(hostB);+}++/**+ * The address to keep as a server's separate dashboard: `candidate`, when it+ * is on the server's own domain, serves the dashboard, and the server's own+ * address does not; otherwise null.+ *+ * An invite link to an older server names its dashboard's host, which is the+ * one place Console learns that address without asking anyone for it. A link+ * is anyone's to write, though, and the address kept is where browser sign-in+ * starts, so a host on another domain is not taken on its word.+ */+export async function separateDashboard(url: string, candidate: string): Promise<string | null> {+ if (urlOrigin(candidate) === urlOrigin(url)) return null;+ if (!onTheSameDomain(url, candidate)) {+ log.warn('switch-servers: not keeping an invite link’s host as the dashboard address', {+ url,+ candidate,+ reason: 'not on the server’s own domain',+ });+ return null;+ }+ const [own, other] = await Promise.all([servesDashboard(url), servesDashboard(candidate)]);+ return own !== true && other === true ? candidate : null;+}++/**+ * Keep `candidate` as a server's separate dashboard address, when+ * {@link separateDashboard} accepts it: the host an older server's browser+ * sign-in was found to return to. Managed servers are left alone, as in+ * {@link retireDashboardFallback}.+ */+export async function keepSeparateDashboard(+ server: SwitchServer,+ candidate: string+): Promise<void> {+ if (server.managed) return;+ const kept = await separateDashboard(server.url, candidate);+ if (kept === null) return;+ await setDashboardUrl(server.id, server.url, kept);+ log.info('switch-servers: kept the host the server’s sign-in returns to as its dashboard', {+ server: server.id,+ url: server.url,+ dashboardUrl: kept,+ });+}++/**+ * Drop a server's separate dashboard address once it has stopped being needed:+ * the server's own address serves the dashboard, and the separate one no+ * longer does.+ *+ * Both, not just the first. An operator who upgrades switch-core but keeps the+ * old dashboard host may still have its identity provider returning there, and+ * browser sign-in starts on the dashboard's address, so moving off a host that+ * still works could break sign-in for nothing. Once that host has gone,+ * nothing can depend on it any longer.+ *+ * Managed servers are left alone: each start registers the addresses its+ * stack publishes, so a value cleared here would only come back.+ */+export async function retireDashboardFallback(server: SwitchServer): Promise<boolean> {+ if (server.managed || server.dashboardUrl === null) return false;+ const [own, separate] = await Promise.all([+ servesDashboard(server.url),+ servesDashboard(server.dashboardUrl),+ ]);+ // An old address that cannot be reached counts as gone, on purpose. A host+ // whose DNS record was removed answers nothing forever, so waiting for a+ // definite "no dashboard here" would keep it for good. And dropping one that+ // was only briefly down costs nothing: `own` serving the dashboard means the+ // server also sends a sign-in started on its own address on to the host its+ // identity provider returns to, as Console's sign-in window does.+ if (own !== true || separate === true) return false;+ await clearDashboardUrl(server.id, server.url);+ log.info('switch-servers: the server now serves its own dashboard; dropped the old address', {+ server: server.id,+ url: server.url,+ dashboardUrl: server.dashboardUrl,+ oldAddressAnswered: separate !== null,+ });+ return true;+}++/** {@link retireDashboardFallback} for every registered server, one at a time+ * failing on its own. */+export async function retireDashboardFallbacks(): Promise<void> {+ const servers = await listServers();+ const results = await Promise.allSettled(servers.map(retireDashboardFallback));+ results.forEach((result, index) => {+ if (result.status === 'rejected') {+ log.warn('switch-servers: could not check whether a server still needs its old dashboard', {+ server: servers[index]?.id,+ error: String(result.reason),+ });+ }+ });+}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 7338c8a65..9f858911d 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@@ -40,10 +40,17 @@ vi.mock('@main/core/telemetry/telemetry-service', () => ({const {addServer,assertManagedServerUrlFree,+ clearDashboardUrl,+ DuplicateServerUrlError,ensureManagedServer,+ findServerByUrl,+ findServerByWebAddress,+ getServer,removeServer,renameServer,setActiveServerId,+ setDashboardUrl,+ updateServer,} = await import('./servers-store');const { getActiveWorkspaceId } = await import('@main/core/workspaces/workspaces-store');@@ -64,12 +71,12 @@ describe('servers-store: rename & delete', () => {});describe('renameServer', () => {- it('updates only the name, leaving URLs and managed metadata untouched', async () => {+ it('updates only the name, leaving addresses and managed metadata untouched', async () => {await fixture.db.insert(switchServers).values({id: 'remote-1',name: 'Old name',- gatewayUrl: 'https://gw.example.com',- apiUrl: 'https://api.example.com',+ url: 'https://switch.example.com',+ dashboardUrl: 'https://switch-dashboard.example.com',managed: true,managementKind: 'remote',sshHost: 'host-a',@@ -78,8 +85,8 @@ describe('servers-store: rename & delete', () => {const renamed = await renameServer({ id: 'remote-1', name: ' New name ' });expect(renamed.name).toBe('New name');- expect(renamed.gatewayUrl).toBe('https://gw.example.com');- expect(renamed.apiUrl).toBe('https://api.example.com');+ expect(renamed.url).toBe('https://switch.example.com');+ expect(renamed.dashboardUrl).toBe('https://switch-dashboard.example.com');expect(renamed.managed).toBe(true);expect(renamed.managementKind).toBe('remote');expect(renamed.sshHost).toBe('host-a');@@ -91,34 +98,34 @@ describe('servers-store: rename & delete', () => {});describe('ensureManagedServer name preservation', () => {- it('keeps a renamed managed server name across a restart (only URLs refresh)', async () => {+ it('keeps a renamed managed server name across a restart (only addresses refresh)', async () => {// First start: registers the local managed row under the default name.const created = await ensureManagedServer({name: 'Local Switch server',- gatewayUrl: 'http://localhost:8080',- apiUrl: 'http://localhost:8081',+ url: 'http://localhost:8080',+ dashboardUrl: 'http://localhost:8081',},{ kind: 'local' });// User renames it.await renameServer({ id: created.id, name: 'My box' });- // Restart repicks ports (new URLs) and passes the hardcoded default name.+ // Restart repicks ports (new addresses) and passes the hardcoded default name.const restarted = await ensureManagedServer({name: 'Local Switch server',- gatewayUrl: 'http://localhost:9090',- apiUrl: 'http://localhost:9091',+ url: 'http://localhost:9090',+ dashboardUrl: 'http://localhost:9091',},{ kind: 'local' });expect(restarted.id).toBe(created.id);- // The rename survives; the URLs still refresh to the new ports.+ // The rename survives; the addresses still refresh to the new ports.expect(restarted.name).toBe('My box');- expect(restarted.gatewayUrl).toBe('http://localhost:9090');- expect(restarted.apiUrl).toBe('http://localhost:9091');+ expect(restarted.url).toBe('http://localhost:9090');+ expect(restarted.dashboardUrl).toBe('http://localhost:9091');});});@@ -127,8 +134,7 @@ describe('servers-store: rename & delete', () => {await fixture.db.insert(switchServers).values({id: 'x',name: 'x',- gatewayUrl: 'http://localhost:1',- apiUrl: 'http://localhost:2',+ url: 'http://localhost:1',...values,});}@@ -137,8 +143,8 @@ describe('servers-store: rename & delete', () => {await insertServer({id: 'local-1',name: 'My local server',- gatewayUrl: 'http://localhost:41000',- apiUrl: 'http://localhost:41001',+ url: 'http://localhost:41000',+ dashboardUrl: 'http://localhost:41001',managed: true,managementKind: 'local',});@@ -147,8 +153,8 @@ describe('servers-store: rename & delete', () => {ensureManagedServer({name: 'Team server',- gatewayUrl: 'http://localhost:41000',- apiUrl: 'http://localhost:41001',+ url: 'http://localhost:41000',+ dashboardUrl: 'http://localhost:41001',},{ kind: 'remote', sshHost: 'vm-1' })@@ -166,8 +172,8 @@ describe('servers-store: rename & delete', () => {await insertServer({id: 'local-1',name: 'My local server',- gatewayUrl: 'http://localhost:41000',- apiUrl: 'http://localhost:41001',+ url: 'http://localhost:41000',+ dashboardUrl: 'http://localhost:41001',managed: true,managementKind: 'local',});@@ -185,7 +191,7 @@ describe('servers-store: rename & delete', () => {await insertServer({id: 'remote-1',name: 'Team server',- gatewayUrl: 'http://localhost:41000',+ url: 'http://localhost:41000',managed: true,managementKind: 'remote',sshHost: 'vm-1',@@ -193,7 +199,7 @@ describe('servers-store: rename & delete', () => {await expect(ensureManagedServer(- { name: 'Local', gatewayUrl: 'http://localhost:41000', apiUrl: 'http://localhost:41001' },+ { name: 'Local', url: 'http://localhost:41000', dashboardUrl: 'http://localhost:41001' },{ kind: 'local' })).rejects.toThrow(/on this computer/);@@ -203,7 +209,7 @@ describe('servers-store: rename & delete', () => {await insertServer({id: 'remote-2',name: 'Other VM',- gatewayUrl: 'http://localhost:41000',+ url: 'http://localhost:41000',managed: true,managementKind: 'remote',sshHost: 'vm-2',@@ -211,7 +217,7 @@ describe('servers-store: rename & delete', () => {await expect(ensureManagedServer(- { name: 'Team', gatewayUrl: 'http://localhost:41000', apiUrl: 'http://localhost:41001' },+ { name: 'Team', url: 'http://localhost:41000', dashboardUrl: 'http://localhost:41001' },{ kind: 'remote', sshHost: 'vm-1' })).rejects.toThrow(/runs on vm-2/);@@ -221,12 +227,12 @@ describe('servers-store: rename & delete', () => {await insertServer({id: 'external-1',name: 'Tunnel to the VM',- gatewayUrl: 'http://localhost:41000',- apiUrl: 'http://localhost:41001',+ url: 'http://localhost:41000',+ dashboardUrl: 'http://localhost:41001',});const adopted = await ensureManagedServer(- { name: 'Team', gatewayUrl: 'http://localhost:41000', apiUrl: 'http://localhost:41001' },+ { name: 'Team', url: 'http://localhost:41000', dashboardUrl: 'http://localhost:41001' },{ kind: 'remote', sshHost: 'vm-1' });@@ -242,8 +248,8 @@ describe('servers-store: rename & delete', () => {await insertServer({id: 'remote-1',name: 'Team',- gatewayUrl: 'http://localhost:3300',- apiUrl: 'http://localhost:8000',+ url: 'http://localhost:3300',+ dashboardUrl: 'http://localhost:8000',managed: true,managementKind: 'remote',sshHost: 'vm-1',@@ -251,14 +257,13 @@ describe('servers-store: rename & delete', () => {await insertServer({id: 'external-1',name: 'Company server',- gatewayUrl: 'http://localhost:41000',- apiUrl: 'http://localhost:41001',+ url: 'http://localhost:41000',+ dashboardUrl: 'http://localhost:41001',});- // Without the check this is a raw unique-index failure.await expect(ensureManagedServer(- { name: 'Team', gatewayUrl: 'http://localhost:41000', apiUrl: 'http://localhost:41001' },+ { name: 'Team', url: 'http://localhost:41000', dashboardUrl: 'http://localhost:41001' },{ kind: 'remote', sshHost: 'vm-1' })).rejects.toThrow(/already the address of “Company server”/);@@ -268,22 +273,22 @@ describe('servers-store: rename & delete', () => {await insertServer({id: 'remote-1',name: 'Team',- gatewayUrl: 'http://localhost:3300',- apiUrl: 'http://localhost:8000',+ url: 'http://localhost:3300',+ dashboardUrl: 'http://localhost:8000',managed: true,managementKind: 'remote',sshHost: 'vm-1',});const moved = await ensureManagedServer(- { name: 'ignored', gatewayUrl: 'http://localhost:41000', apiUrl: 'http://localhost:41001' },+ { name: 'ignored', url: 'http://localhost:41000', dashboardUrl: 'http://localhost:41001' },{ kind: 'remote', sshHost: 'vm-1' });expect(moved).toMatchObject({id: 'remote-1',name: 'Team',- gatewayUrl: 'http://localhost:41000',+ url: 'http://localhost:41000',});});});@@ -293,8 +298,8 @@ describe('servers-store: rename & delete', () => {await ensureManagedServer({name: 'Local Switch server',- gatewayUrl: 'http://localhost:8080',- apiUrl: 'http://localhost:8081',+ url: 'http://localhost:8080',+ dashboardUrl: 'http://localhost:8081',},{ kind: 'local' });@@ -310,8 +315,8 @@ describe('servers-store: rename & delete', () => {await ensureManagedServer({name: 'Remote Switch server',- gatewayUrl: 'http://localhost:8080',- apiUrl: 'http://localhost:8081',+ url: 'http://localhost:8080',+ dashboardUrl: 'http://localhost:8081',},{ kind: 'remote', sshHost: 'host-a' });@@ -327,14 +332,14 @@ describe('servers-store: rename & delete', () => {const ref = { kind: 'local' } as const;const params = {name: 'Local Switch server',- gatewayUrl: 'http://localhost:8080',- apiUrl: 'http://localhost:8081',+ url: 'http://localhost:8080',+ dashboardUrl: 'http://localhost:8081',};await ensureManagedServer(params, ref);telemetryMocks.trackEvent.mockClear();await ensureManagedServer(- { ...params, gatewayUrl: 'http://localhost:9090', apiUrl: 'http://localhost:9091' },+ { ...params, url: 'http://localhost:9090', dashboardUrl: 'http://localhost:9091' },ref);@@ -348,8 +353,7 @@ describe('servers-store: rename & delete', () => {// cannot produce a success here and a failure there.await addServer({name: 'External server',- gatewayUrl: 'https://gw.example.com',- apiUrl: 'https://api.example.com',+ url: 'https://switch.example.com',});expect(telemetryMocks.trackEvent).not.toHaveBeenCalled();@@ -361,8 +365,8 @@ describe('servers-store: rename & delete', () => {await fixture.db.insert(switchServers).values({id: 'srv-ext',name: 'External',- gatewayUrl: 'https://gw.example.com',- apiUrl: 'https://api.example.com',+ url: 'https://switch.example.com',+ dashboardUrl: 'https://switch-dashboard.example.com',});await removeServer('srv-ext');@@ -376,8 +380,7 @@ describe('servers-store: rename & delete', () => {await fixture.db.insert(switchServers).values({id: 'srv-rm',name: 'Remote',- gatewayUrl: 'https://gw2.example.com',- apiUrl: 'https://api2.example.com',+ url: 'https://switch2.example.com',managed: true,managementKind: 'remote',sshHost: 'build-box',@@ -408,8 +411,8 @@ describe('servers-store: rename & delete', () => {await fixture.db.insert(switchServers).values({id: 'srv-1',name: 'Server',- gatewayUrl: 'https://gw.example.com',- apiUrl: 'https://api.example.com',+ url: 'https://switch.example.com',+ dashboardUrl: 'https://switch-dashboard.example.com',});await fixture.db.insert(workspaces).values({ id: 'ws-1', serverId: 'srv-1', name: 'Server' });await fixture.db.insert(agents).values([@@ -463,8 +466,7 @@ describe('selecting a server', () => {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',+ url: 'https://srv-1.example.com',});});@@ -571,3 +573,287 @@ describe('selecting a server', () => {await expect(setActiveServerId('srv-1')).rejects.toThrow('no workspace');});});++describe('servers-store: one address per server', () => {+ let fixture: Awaited<ReturnType<typeof openFixture>>;++ beforeEach(async () => {+ fixture = await openFixture('empty');+ mocks.db = fixture.db;+ fixture.sqlite.pragma('foreign_keys = OFF');+ telemetryMocks.trackEvent.mockReset();+ });++ afterEach(() => {+ fixture.close();+ mocks.db = undefined;+ });++ async function insertServer(values: Partial<typeof switchServers.$inferInsert>) {+ await fixture.db.insert(switchServers).values({ id: 'x', name: 'x', url: 'x', ...values });+ }++ describe('addServer', () => {+ it('stores the address without a trailing slash and with no separate dashboard', async () => {+ const added = await addServer({+ name: ' Team ',+ url: ' https://switch.example.com/ ',+ });++ expect(added).toMatchObject({+ name: 'Team',+ url: 'https://switch.example.com',+ dashboardUrl: null,+ managed: false,+ });+ });++ it('refuses an address another server already has, naming it', async () => {+ await insertServer({ id: 'a', name: 'Company server', url: 'https://switch.example.com' });++ const adding = addServer({+ name: 'Again',+ url: 'https://switch.example.com/',+ });++ await expect(adding).rejects.toBeInstanceOf(DuplicateServerUrlError);+ await expect(adding).rejects.toThrow(+ 'https://switch.example.com is already the address of “Company server”.'+ );+ expect(await fixture.db.select().from(switchServers)).toHaveLength(1);+ });+ });++ describe('address spelling', () => {+ it('stores one spelling: lowercased host, no default port, no trailing slash', async () => {+ const added = await addServer({ name: 'Team', url: 'HTTPS://Switch.Example.com:443/' });++ expect(added).toMatchObject({ url: 'https://switch.example.com', dashboardUrl: null });+ });++ it('refuses another spelling of an address already saved, however it was stored', async () => {+ // A row carried over by migration keeps whatever spelling it had.+ await insertServer({ id: 'a', name: 'Company server', url: 'https://Switch.example.com' });++ await expect(+ addServer({ name: 'Again', url: 'https://switch.example.com:443' })+ ).rejects.toBeInstanceOf(DuplicateServerUrlError);+ expect((await findServerByUrl('https://SWITCH.example.com/'))?.id).toBe('a');+ });++ it('keeps the dashboard address when an edit only respells the server’s address', async () => {+ await insertServer({+ id: 'a',+ name: 'Split',+ url: 'https://Switch-API.example.com',+ dashboardUrl: 'https://switch-gateway.example.com',+ });++ const saved = await updateServer({+ id: 'a',+ name: 'Split',+ url: 'https://switch-api.example.com:443',+ });++ expect(saved).toMatchObject({+ url: 'https://switch-api.example.com',+ dashboardUrl: 'https://switch-gateway.example.com',+ });+ });+ });++ describe('updateServer', () => {+ it('drops a separate dashboard address when the server’s address changes', async () => {+ await insertServer({+ id: 'a',+ name: 'Split',+ url: 'https://switch-api.example.com',+ dashboardUrl: 'https://switch-gateway.example.com',+ });++ const saved = await updateServer({ id: 'a', name: 'Split', url: 'https://new.example.com' });++ expect(saved).toMatchObject({ url: 'https://new.example.com', dashboardUrl: null });+ });++ it('keeps a separate dashboard address when only the name changes', async () => {+ await insertServer({+ id: 'a',+ name: 'Split',+ url: 'https://switch-api.example.com',+ dashboardUrl: 'https://switch-gateway.example.com',+ });++ const saved = await updateServer({+ id: 'a',+ name: 'Renamed',+ url: 'https://switch-api.example.com/',+ });++ expect(saved).toMatchObject({+ name: 'Renamed',+ url: 'https://switch-api.example.com',+ dashboardUrl: 'https://switch-gateway.example.com',+ });+ });++ it('refuses to move a server onto another server’s address', async () => {+ await insertServer({ id: 'a', name: 'First', url: 'https://one.example.com' });+ await insertServer({ id: 'b', name: 'Second', url: 'https://two.example.com' });++ await expect(+ updateServer({ id: 'b', name: 'Second', url: 'https://one.example.com' })+ ).rejects.toThrow('already the address of “First”');+ expect((await getServer('b'))?.url).toBe('https://two.example.com');+ });++ it('still saves one of two servers that already share an address', async () => {+ // Migration 0052 keeps rows whose API address was the same.+ await insertServer({ id: 'a', name: 'First', url: 'https://one.example.com' });+ await insertServer({+ id: 'b',+ name: 'Second',+ url: 'https://one.example.com',+ dashboardUrl: 'https://two.example.com',+ });++ const saved = await updateServer({+ id: 'b',+ name: 'Renamed',+ url: 'https://one.example.com',+ });++ expect(saved).toMatchObject({ name: 'Renamed', dashboardUrl: 'https://two.example.com' });+ });++ it('throws for an unknown server id', async () => {+ await expect(+ updateServer({ id: 'nope', name: 'x', url: 'https://x.example.com' })+ ).rejects.toThrow('No Switch server with id nope');+ });+ });++ describe('finding a server by address', () => {+ it('finds a server by its address, however the slash is written', async () => {+ await insertServer({ id: 'a', name: 'Team', url: 'https://switch.example.com' });++ expect((await findServerByUrl('https://switch.example.com/'))?.id).toBe('a');+ expect(await findServerByUrl('https://other.example.com')).toBeNull();+ });++ it('finds a server by its own address or by the dashboard address it keeps', async () => {+ await insertServer({+ id: 'split',+ name: 'Split',+ url: 'https://switch-api.example.com',+ dashboardUrl: 'https://switch-gateway.example.com',+ });++ expect((await findServerByWebAddress('https://switch-api.example.com'))?.id).toBe('split');+ expect((await findServerByWebAddress('https://SWITCH-GATEWAY.example.com/'))?.id).toBe(+ 'split'+ );+ expect(await findServerByWebAddress('https://elsewhere.example.com')).toBeNull();+ expect(await findServerByWebAddress('not an address')).toBeNull();+ });++ it('prefers a server whose own address it is over one that keeps it for its dashboard', async () => {+ await insertServer({+ id: 'old',+ name: 'Old',+ url: 'https://old-api.example.com',+ dashboardUrl: 'https://switch.example.com',+ });+ await insertServer({ id: 'new', name: 'New', url: 'https://switch.example.com' });++ expect((await findServerByWebAddress('https://switch.example.com'))?.id).toBe('new');+ });+ });++ describe('clearDashboardUrl', () => {+ it('forgets the separate dashboard address of the address that was checked', async () => {+ await insertServer({+ id: 'a',+ url: 'https://switch-api.example.com',+ dashboardUrl: 'https://switch-gateway.example.com',+ });++ await clearDashboardUrl('a', 'https://switch-api.example.com');++ expect((await getServer('a'))?.dashboardUrl).toBeNull();+ });++ it('leaves it alone when the server has moved since the check', async () => {+ await insertServer({+ id: 'a',+ url: 'https://moved.example.com',+ dashboardUrl: 'https://switch-gateway.example.com',+ });++ await clearDashboardUrl('a', 'https://switch-api.example.com');++ expect((await getServer('a'))?.dashboardUrl).toBe('https://switch-gateway.example.com');+ });+ });++ describe('setDashboardUrl', () => {+ it('keeps a separate dashboard address for the address that was checked', async () => {+ await insertServer({ id: 'a', url: 'https://switch-api.example.com' });++ await setDashboardUrl(+ 'a',+ 'https://switch-api.example.com',+ 'https://Switch-Gateway.example.com/'+ );++ expect((await getServer('a'))?.dashboardUrl).toBe('https://switch-gateway.example.com');+ });++ it('leaves it alone when the server has moved since the check', async () => {+ await insertServer({ id: 'a', url: 'https://moved.example.com' });++ await setDashboardUrl(+ 'a',+ 'https://switch-api.example.com',+ 'https://switch-gateway.example.com'+ );++ expect((await getServer('a'))?.dashboardUrl).toBeNull();+ });+ });++ describe('managed servers', () => {+ it('registers a managed stack with its dashboard container’s address', async () => {+ const server = await ensureManagedServer(+ { name: 'Local', url: 'http://localhost:8010/', dashboardUrl: 'http://localhost:3010/' },+ { kind: 'local' }+ );++ expect(server).toMatchObject({+ url: 'http://localhost:8010',+ dashboardUrl: 'http://localhost:3010',+ });+ });++ it('registers one with no dashboard address when its stack has none', async () => {+ const server = await ensureManagedServer(+ { name: 'Local', url: 'http://localhost:8010', dashboardUrl: null },+ { kind: 'local' }+ );++ expect(server.dashboardUrl).toBeNull();+ });++ it('registers one row when the same stack is registered twice at once', async () => {+ const params = { name: 'Local', url: 'http://localhost:8010', dashboardUrl: null };++ const [first, second] = await Promise.all([+ ensureManagedServer(params, { kind: 'local' }),+ ensureManagedServer(params, { kind: 'local' }),+ ]);++ expect(second.id).toBe(first.id);+ expect(await fixture.db.select().from(switchServers)).toHaveLength(1);+ });+ });+});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 b311047bf..68756648d 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@@ -18,8 +18,10 @@ import { db } from '@main/db/client';import { type SwitchServerRow, switchServers } from '@main/db/schema';import { log } from '@main/lib/logger';import {+ normaliseServerUrl,urlOrigin,type AddServerParams,+ type ManagedServerParams,type ManagedServerRef,type RenameServerParams,type SwitchServer,@@ -45,8 +47,8 @@ function mapRow(row: SwitchServerRow): SwitchServer {return {id: row.id,name: row.name,- gatewayUrl: row.gatewayUrl,- apiUrl: row.apiUrl,+ url: row.url,+ dashboardUrl: row.dashboardUrl ?? null,managed: row.managed,managementKind,sshHost: row.sshHost ?? null,@@ -55,21 +57,19 @@ function mapRow(row: SwitchServerRow): SwitchServer {};}-/** Strip a trailing slash so `${url}/gateway` never doubles up. */-function normaliseUrl(url: string): string {- return url.trim().replace(/\/+$/, '');-}+/** The spelling an address is stored and compared in; see {@link normaliseServerUrl}. */+const normaliseUrl = normaliseServerUrl;/*** Find the registered server an agent endpoint belongs to, by matching the- * endpoint's origin against each server's API (agent bridge) URL — the endpoint- * an agent's `SWITCH_API_ENDPOINT` points at. Returns null when none matches.+ * endpoint's origin against each server's address — what an agent's+ * `SWITCH_API_ENDPOINT` points at. Returns null when none matches.*/export async function findServerByEndpoint(endpoint: string): Promise<SwitchServer | null> {const target = urlOrigin(endpoint);if (!target) return null;const servers = await listServers();- return servers.find((s) => urlOrigin(s.apiUrl) === target) ?? null;+ return servers.find((s) => urlOrigin(s.url) === target) ?? null;}export async function listServers(): Promise<SwitchServer[]> {@@ -128,12 +128,12 @@ function managedPlace(server: SwitchServer): string {: 'on this computer';}-/** Two server records cannot share a gateway URL, and a shared remote stack's+/** Two server records cannot share an address, and a shared remote stack's* mirrored `localhost` port may be one this Console already gave another server. */export class ManagedServerUrlConflictError extends Error {- constructor(gatewayUrl: string, holder: SwitchServer, target: string) {+ constructor(url: string, holder: SwitchServer, target: string) {super(- `${gatewayUrl} is already the address of “${holder.name}”` ++ `${url} is already the address of “${holder.name}”` +(holder.managed ? ` (the server Switch Console runs ${managedPlace(holder)})` : '') +`, and the server ${target} uses the same port. Switch Console reaches a remote ` +`server through the same port number on this computer, so both cannot be registered. ` +@@ -143,18 +143,32 @@ export class ManagedServerUrlConflictError extends Error {}}-/** The record `ref` already has, and the one at `gatewayUrl`, refusing a- * clash as {@link ensureManagedServer} describes. */+/** The record `ref` already has, and the one at `url`, refusing a clash as+ * {@link ensureManagedServer} describes. */async function managedServerSlot(- gatewayUrl: string,+ url: string,ref: ManagedServerRef): Promise<{ existingForTarget: SwitchServer | null; atUrl: SwitchServer | null }> {+ return slotAmong(await listServers(), url, ref);+}++/** {@link managedServerSlot} over servers already read, so that a transaction+ * can decide and write on one reading. */+function slotAmong(+ servers: SwitchServer[],+ url: string,+ ref: ManagedServerRef+): { existingForTarget: SwitchServer | null; atUrl: SwitchServer | null } {const existingForTarget =- ref.kind === 'remote' ? await getRemoteManagedServer(ref.sshHost) : await getManagedServer();- const atUrl = await getServerByGatewayUrl(gatewayUrl);+ servers.find((server) =>+ ref.kind === 'remote'+ ? server.managementKind === 'remote' && server.sshHost === ref.sshHost+ : server.managementKind === 'local'+ ) ?? null;+ const atUrl = servers.find((server) => normaliseUrl(server.url) === url) ?? null;if (atUrl && atUrl.id !== existingForTarget?.id && (existingForTarget || atUrl.managed)) {throw new ManagedServerUrlConflictError(- gatewayUrl,+ url,atUrl,ref.kind === 'remote' ? `on ${ref.sshHost}` : 'on this computer');@@ -165,17 +179,17 @@ async function managedServerSlot(/** Throw {@link ManagedServerUrlConflictError} when {@link ensureManagedServer}* would, without writing anything, so a start can check before changing the stack. */export async function assertManagedServerUrlFree(- gatewayUrl: string,+ url: string,ref: ManagedServerRef): Promise<void> {- await managedServerSlot(normaliseUrl(gatewayUrl), ref);+ await managedServerSlot(normaliseUrl(url), ref);}/*** Upsert a managed server record for the given target (the single local stack,* or the stack on a specific remote host). Reuses the existing row for that- * target if there is one (updating its URLs, which change when ports are- * repicked), else adopts an external row already at this gateway URL, else+ * target if there is one (updating its addresses, which change when ports are+ * repicked), else adopts an external row already at this address, else* inserts. Keeps exactly one row per managed target rather than duplicating on* URL changes.*@@ -184,83 +198,138 @@ export async function assertManagedServerUrlFree(* throw {@link ManagedServerUrlConflictError}.*/export async function ensureManagedServer(- params: AddServerParams,+ params: ManagedServerParams,ref: ManagedServerRef): Promise<SwitchServer> {- const gatewayUrl = normaliseUrl(params.gatewayUrl);- const apiUrl = normaliseUrl(params.apiUrl);+ const url = normaliseUrl(params.url);+ const dashboardUrl = params.dashboardUrl === null ? null : normaliseUrl(params.dashboardUrl);const managementKind = ref.kind;const sshHost = ref.kind === 'remote' ? ref.sshHost : null;- const { existingForTarget, atUrl } = await managedServerSlot(gatewayUrl, ref);- const existing = existingForTarget ?? atUrl;- if (existing) {- // Preserve the stored name on restart: the name is set once at creation and- // then owned by the user (rename). Only the URLs/kind refresh when a managed- // stack restarts (ports can change), so overwriting name here would clobber a- // rename — the local stack always restarts with a hardcoded default name.- const [row] = await db- .update(switchServers)- .set({- gatewayUrl,- apiUrl,+ // One transaction for the decision and the write: with no unique index on+ // the address, two registrations at once must not both insert.+ const { server, inserted } = db.transaction((tx) => {+ const servers = tx+ .select()+ .from(switchServers)+ .orderBy(desc(switchServers.createdAt))+ .all()+ .map(mapRow);+ const { existingForTarget, atUrl } = slotAmong(servers, url, ref);+ const existing = existingForTarget ?? atUrl;+ if (existing) {+ // Preserve the stored name on restart: the name is set once at creation and+ // then owned by the user (rename). Only the addresses/kind refresh when a managed+ // stack restarts (ports can change), so overwriting name here would clobber a+ // rename — the local stack always restarts with a hardcoded default name.+ const [row] = tx+ .update(switchServers)+ .set({+ url,+ dashboardUrl,+ managed: true,+ managementKind,+ sshHost,+ updatedAt: sql`CURRENT_TIMESTAMP`,+ })+ .where(eq(switchServers.id, existing.id))+ .returning()+ .all();+ return { server: mapRow(row!), inserted: false };+ }+ const [row] = tx+ .insert(switchServers)+ .values({+ id: randomUUID(),+ name: params.name.trim(),+ url,+ dashboardUrl,managed: true,managementKind,sshHost,updatedAt: sql`CURRENT_TIMESTAMP`,})- .where(eq(switchServers.id, existing.id))- .returning();- const server = mapRow(row);- await ensureServerWorkspace(server);- return server;- }- const [row] = await db- .insert(switchServers)- .values({- id: randomUUID(),- name: params.name.trim(),- gatewayUrl,- apiUrl,- managed: true,- managementKind,- sshHost,- updatedAt: sql`CURRENT_TIMESTAMP`,- })- .returning();- const server = mapRow(row);+ .returning()+ .all();+ return { server: mapRow(row!), inserted: true };+ });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',- });+ if (inserted) {+ trackEvent('server_added', {+ server_kind: ref.kind === 'remote' ? 'remote_managed' : 'local',+ outcome: 'success',+ });+ }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));+/** The server registered at an address, compared the way it was stored. */+export async function findServerByUrl(url: string): Promise<SwitchServer | null> {+ return getServerByUrl(normaliseUrl(url));}-async function getServerByGatewayUrl(gatewayUrl: string): Promise<SwitchServer | null> {- const [row] = await db+/**+ * The server a web address belongs to: its own address, or the separate+ * dashboard address it still keeps. An invite link carries the dashboard's+ * address, which on an older server is not the server's own.+ */+export async function findServerByWebAddress(address: string): Promise<SwitchServer | null> {+ const target = urlOrigin(address);+ if (!target) return null;+ const servers = await listServers();+ return (+ servers.find((s) => urlOrigin(s.url) === target) ??+ servers.find((s) => s.dashboardUrl !== null && urlOrigin(s.dashboardUrl) === target) ??+ null+ );+}++/**+ * Compared in the normalised spelling on both sides rather than by the column:+ * a row saved before addresses were normalised, or carried over by migration+ * 0052, may be stored in another spelling of the same address.+ */+async function getServerByUrl(url: string): Promise<SwitchServer | null> {+ const target = normaliseUrl(url);+ return (await listServers()).find((server) => normaliseUrl(server.url) === target) ?? null;+}++/** A server is already registered at the address being saved. */+export class DuplicateServerUrlError extends Error {+ constructor(url: string, holder: SwitchServer) {+ super(`${url} is already the address of “${holder.name}”.`);+ this.name = 'DuplicateServerUrlError';+ }+}++type StoreTransaction = Parameters<Parameters<typeof db.transaction>[0]>[0];++/**+ * Refuse `url` when a server other than `exceptId` already has it. Read inside+ * the transaction that writes the row: with no unique index to fall back on,+ * that is what keeps two saves of one address from both passing the check.+ */+function assertUrlFree(tx: StoreTransaction, url: string, exceptId: string | null): void {+ const holder = tx.select().from(switchServers)- .where(eq(switchServers.gatewayUrl, gatewayUrl))- .limit(1);- return row ? mapRow(row) : null;+ .all()+ .map(mapRow)+ .find((server) => normaliseUrl(server.url) === url && server.id !== exceptId);+ if (holder) throw new DuplicateServerUrlError(url, holder);}export async function addServer(params: AddServerParams): Promise<SwitchServer> {+ const url = normaliseUrl(params.url);const server = db.transaction((tx) => {+ assertUrlFree(tx, url, null);const [row] = tx.insert(switchServers).values({id: randomUUID(),name: params.name.trim(),- gatewayUrl: normaliseUrl(params.gatewayUrl),- apiUrl: normaliseUrl(params.apiUrl),+ url,updatedAt: sql`CURRENT_TIMESTAMP`,}).returning()@@ -277,22 +346,61 @@ export async function addServer(params: AddServerParams): Promise<SwitchServer>return server;}+/**+ * Save an edited server. A changed address also drops any separate dashboard+ * address: that belonged to the address being replaced, and the new one is+ * checked for its own dashboard the next time it is reached.+ */export async function updateServer(params: UpdateServerParams): Promise<SwitchServer> {- const [row] = await db+ const url = normaliseUrl(params.url);+ const row = db.transaction((tx) => {+ const [previous] = tx.select().from(switchServers).where(eq(switchServers.id, params.id)).all();+ if (!previous) throw new Error(`No Switch server with id ${params.id}`);+ // Only a new address is checked: rows that already share one (migration+ // 0052 keeps them) stay editable.+ const urlChanged = normaliseUrl(previous.url) !== url;+ if (urlChanged) assertUrlFree(tx, url, params.id);+ const [updated] = tx+ .update(switchServers)+ .set({+ name: params.name.trim(),+ url,+ ...(urlChanged ? { dashboardUrl: null } : {}),+ updatedAt: sql`CURRENT_TIMESTAMP`,+ })+ .where(eq(switchServers.id, params.id))+ .returning()+ .all();+ return updated!;+ });+ await renameServerWorkspaces(params.id, params.name.trim());+ return mapRow(row);+}++/**+ * Record a server's separate dashboard address, or forget it with null. Leaves+ * the row alone when the address it was checked against is no longer the+ * server's, so a check that raced an edit cannot write the dashboard of the+ * address that replaced it.+ */+export async function setDashboardUrl(+ id: string,+ checkedUrl: string,+ dashboardUrl: string | null+): Promise<void> {+ await db.update(switchServers).set({- name: params.name.trim(),- gatewayUrl: normaliseUrl(params.gatewayUrl),- apiUrl: normaliseUrl(params.apiUrl),+ dashboardUrl: dashboardUrl === null ? null : normaliseUrl(dashboardUrl),updatedAt: sql`CURRENT_TIMESTAMP`,})- .where(eq(switchServers.id, params.id))- .returning();- if (!row) {- throw new Error(`No Switch server with id ${params.id}`);- }- await renameServerWorkspaces(params.id, params.name.trim());- return mapRow(row);+ .where(and(eq(switchServers.id, id), eq(switchServers.url, checkedUrl)));+}++/** Forget a server's separate dashboard address, once its own address has been+ * seen serving the dashboard; see {@link setDashboardUrl}. */+export async function clearDashboardUrl(id: string, checkedUrl: string): Promise<void> {+ await setDashboardUrl(id, checkedUrl, null);}export async function renameServer(params: RenameServerParams): Promise<SwitchServer> {diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/service-browser-flow.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/service-browser-flow.test.tsindex e334fc31e..c879685e2 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/service-browser-flow.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/service-browser-flow.test.ts@@ -25,7 +25,11 @@ vi.mock('./gateway-client', () => ({getServiceFlow: vi.fn(),startServiceConnection: vi.fn(),}));-const server = { id: 'server', gatewayUrl: 'https://switch.example.test' } as SwitchServer;+const server = {+ id: 'server',+ url: 'https://switch.example.test',+ dashboardUrl: null,+} as SwitchServer;const flows: [string, string][] = [];/** The service as the server lists it: on any port, or only on `ports`. */function listed(ports: number[] | null): ConnectionCatalogEntry[] {diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/teams-package.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/teams-package.test.tsindex ece931ab0..20610c766 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/teams-package.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/teams-package.test.ts@@ -17,7 +17,7 @@ const { saveTeamsPackage } = await import('./teams-package');const SERVER = {id: 'srv-1',name: 'S',- gatewayUrl: 'https://switch.example.com',+ url: 'https://switch.example.com',managed: false,} as never;diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/trust-settings.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/trust-settings.test.tsindex 1b739b363..e4c8f7b83 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/trust-settings.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/trust-settings.test.ts@@ -24,7 +24,8 @@ const { fetchTrustSettingsFromServer, updateTrustSettingsOnServer, clearTrustSetconst SERVER = {id: 'srv-1',name: 'S',- gatewayUrl: 'https://switch.example.com',+ url: 'https://switch.example.com',+ dashboardUrl: null,managed: false,} as never;@@ -47,7 +48,7 @@ function response(status: number, body: unknown): Response {status,ok: status >= 200 && status < 300,json: async () => (typeof body === 'string' ? {} : body),- headers: { getSetCookie: () => [] },+ headers: { get: () => null, getSetCookie: () => [] },text: async () => text,} as unknown as Response;}diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/update-bridge.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/update-bridge.test.tsindex 522e93970..87ea232f7 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/update-bridge.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/update-bridge.test.ts@@ -23,7 +23,7 @@ const { updateBridgeOnServer } = await import('./update-bridge');const SERVER = {id: 'srv-1',name: 'S',- gatewayUrl: 'https://switch.example.com',+ url: 'https://switch.example.com',managed: false,} as never;@@ -46,7 +46,7 @@ function response(status: number, body: unknown): Response {status,ok: status >= 200 && status < 300,json: async () => (typeof body === 'string' ? {} : body),- headers: { getSetCookie: () => [] },+ headers: { get: () => null, getSetCookie: () => [] },text: async () => text,} as unknown as Response;}diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/update-template.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/update-template.test.tsindex 68bc422ab..1b5e94fc1 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/update-template.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/update-template.test.ts@@ -21,7 +21,7 @@ const { updateTemplate, GatewayError } = await import('./gateway-client');const SERVER = {id: 'srv-1',name: 'S',- gatewayUrl: 'https://switch.example.com',+ url: 'https://switch.example.com',managed: false,} as never;@@ -37,7 +37,7 @@ function response(status: number, body: unknown): Response {status,ok: status >= 200 && status < 300,json: async () => body,- headers: { getSetCookie: () => [] },+ headers: { get: () => null, getSetCookie: () => [] },text: async () => JSON.stringify(body),} as unknown as Response;}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.tsindex 6c3bc67e9..20cef3dc2 100644--- 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.ts@@ -133,8 +133,8 @@ function server(overrides: Record<string, unknown>) {return {id: 'srv',name: 'S',- gatewayUrl: 'http://localhost:3300',- apiUrl: 'http://localhost:8000',+ url: 'http://localhost:8000',+ dashboardUrl: 'http://localhost:3300',managed: false,managementKind: null,sshHost: null,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.tsindex 3182066b6..2e8257d8f 100644--- 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.ts@@ -10,8 +10,8 @@ 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',+ url: 'https://switch.example.com/',+ dashboardUrl: null as string | null,}));vi.mock('./workspaces-store', () => ({ requireWorkspace }));@@ -63,7 +63,7 @@ describe('workspace invitations', () => {expect(leased).toEqual(['ws-1']);});- it('hands back the link built from the gateway address, never the bare token', async () => {+ it('hands back the link built from the server’s address, never the bare token', async () => {createInvitation.mockResolvedValue({invitation: INVITATION,token: 'a+b/c',@@ -91,6 +91,27 @@ describe('workspace invitations', () => {});});+ it('builds the link on the dashboard address an older server keeps apart', async () => {+ createInvitation.mockResolvedValue({+ invitation: INVITATION,+ token: 'tok',+ emailDelivery: 'not_requested',+ });+ SERVER.dashboardUrl = 'https://switch-gateway.example.com';+ try {+ const created = await createWorkspaceInvitation({+ workspaceId: 'ws-1',+ role: 'member',+ email: null,+ expiresInHours: 168,+ usesRemaining: 1,+ });+ expect(created.link).toBe('https://switch-gateway.example.com/invite#token=tok');+ } finally {+ SERVER.dashboardUrl = null;+ }+ });+it('revokes one by id on the workspace tenant', async () => {revokeInvitation.mockResolvedValue({ ...INVITATION, revokedAt: '2026-09-28T01:00:00.000Z' });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.tsindex 7c0348d0d..2c223fdb0 100644--- a/console/apps/switch-console-desktop/src/main/core/workspaces/invitations.ts+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/invitations.ts@@ -7,6 +7,7 @@ import {removeJoinDomain,revokeInvitation,} from '@main/core/switch-servers/gateway-client';+import { dashboardOrigin } from '@shared/core/switch-servers/switch-servers';import {inviteLink,type CreatedInvitation,@@ -54,7 +55,7 @@ export async function createWorkspaceInvitation({const created = await createInvitation(server, tenantId, params);return {invitation: created.invitation,- link: inviteLink(server.gatewayUrl, created.token),+ link: inviteLink(dashboardOrigin(server), created.token),emailDelivery: created.emailDelivery,};});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.tsindex 3edcc3cb9..9efe105d1 100644--- 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.ts@@ -66,8 +66,8 @@ describe('reconcile-workspaces', () => {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',+ url: 'https://api-srv-1.example.com',+ dashboardUrl: 'https://srv-1.example.com',});listServers.mockResolvedValue([{ id: 'srv-1' }]);});@@ -482,8 +482,8 @@ describe('reconcile-workspaces', () => {await fixture.db.insert(switchServers).values({id: 'srv-2',name: 'Staging',- gatewayUrl: 'https://srv-2.example.com',- apiUrl: 'https://api-srv-2.example.com',+ url: 'https://api-srv-2.example.com',+ dashboardUrl: 'https://srv-2.example.com',});await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });await ensureServerWorkspace({ id: 'srv-2', name: 'Staging' });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.tsindex 0abc22d39..b8fe1bb81 100644--- 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.ts@@ -45,8 +45,8 @@ describe('workspaces-store', () => {await fixture.db.insert(switchServers).values({id,name,- gatewayUrl: `https://${id}.example.com`,- apiUrl: `https://api-${id}.example.com`,+ url: `https://api-${id}.example.com`,+ dashboardUrl: `https://${id}.example.com`,});}diff --git a/console/apps/switch-console-desktop/src/main/db/schema.ts b/console/apps/switch-console-desktop/src/main/db/schema.tsindex d88ef167d..69d0fbf17 100644--- a/console/apps/switch-console-desktop/src/main/db/schema.ts+++ b/console/apps/switch-console-desktop/src/main/db/schema.ts@@ -93,42 +93,43 @@ export const appSettings = sqliteTable(* keyed by server id — so this table holds only non-secret connection* metadata.*/-export const switchServers = sqliteTable(- 'switch_servers',- {- id: text('id').primaryKey(),- name: text('name').notNull(),- /** Origin of the gateway deployment; the management API is at- * `${gatewayUrl}/gateway`. */- gatewayUrl: text('gateway_url').notNull(),- /**- * Origin of the Switch *core* (agent bridge) API — what an agent's- * `SWITCH_API_ENDPOINT` points at, and what an onboarded agent is matched to- * its server by. May differ from `gatewayUrl` (e.g. `switch-api.*` vs- * `switch-gateway.*`).- */- apiUrl: text('api_url').notNull(),- /** True when Switch Console provisions and runs this server itself via- * docker compose. Managed servers get lifecycle controls (start/stop/reset)- * and are not user-editable connection records. */- managed: integer('managed', { mode: 'boolean' }).notNull().default(false),- /** Where a managed server runs: `local` (this computer) or `remote` (an SSH- * host). Null for external servers; a legacy managed row with a null kind is- * read as `local`. */- managementKind: text('management_kind'),- /** SSH alias of the host a remote-managed server runs on; null otherwise. */- sshHost: text('ssh_host'),- createdAt: text('created_at')- .notNull()- .default(sql`CURRENT_TIMESTAMP`),- updatedAt: text('updated_at')- .notNull()- .default(sql`CURRENT_TIMESTAMP`),- },- (table) => ({- gatewayUrlIdx: uniqueIndex('idx_switch_servers_gateway_url').on(table.gatewayUrl),- })-);+export const switchServers = sqliteTable('switch_servers', {+ id: text('id').primaryKey(),+ name: text('name').notNull(),+ /**+ * The server's one address: the origin of switch-core, which serves the+ * agent API at its root, the management API under `/gateway`, and the+ * dashboard. What an agent's `SWITCH_API_ENDPOINT` points at, and what an+ * onboarded agent is matched to its server by.+ *+ * Not unique in the schema: before migration 0052 the gateway address was+ * the unique one, so two rows may already share this. Adding a server+ * refuses a duplicate instead.+ */+ url: text('url').notNull(),+ /**+ * Where the dashboard opens when `url` does not serve it: a server older+ * than switch-core serving its own dashboard, or a managed stack still+ * running a separate dashboard container. Null when `url` serves it.+ */+ dashboardUrl: text('dashboard_url'),+ /** True when Switch Console provisions and runs this server itself via+ * docker compose. Managed servers get lifecycle controls (start/stop/reset)+ * and are not user-editable connection records. */+ managed: integer('managed', { mode: 'boolean' }).notNull().default(false),+ /** Where a managed server runs: `local` (this computer) or `remote` (an SSH+ * host). Null for external servers; a legacy managed row with a null kind is+ * read as `local`. */+ managementKind: text('management_kind'),+ /** SSH alias of the host a remote-managed server runs on; null otherwise. */+ sshHost: text('ssh_host'),+ createdAt: text('created_at')+ .notNull()+ .default(sql`CURRENT_TIMESTAMP`),+ updatedAt: text('updated_at')+ .notNull()+ .default(sql`CURRENT_TIMESTAMP`),+});/*** A workspace: the unit everything in the window is scoped to. A server hostsdiff --git a/console/apps/switch-console-desktop/src/main/db/tests/migrations/0052-one-server-url.test.ts b/console/apps/switch-console-desktop/src/main/db/tests/migrations/0052-one-server-url.test.tsnew file mode 100644index 000000000..3beece0a3--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/db/tests/migrations/0052-one-server-url.test.ts@@ -0,0 +1,166 @@+/**+ * Migration 0052 — one address per server.+ *+ * Every saved server keeps its API address as its one address, because that is+ * what its agents, controllers and sidecars already point at. The gateway+ * address is kept, as the dashboard address, only where it differed. Nothing+ * else about a server may change: its id is what workspaces, agents, saved+ * sign-ins and view state are keyed by.+ *+ * Runs the real migration runner over `pre-0052.db`: the baseline fixture at+ * 0051 with one saved server of every shape the upgrade meets, each with its+ * workspace, and agents attached to two of them.+ */++import { openFixture, type FixtureDb } from '@tooling/utils/db';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++type ServerRow = {+ id: string;+ name: string;+ url: string;+ dashboard_url: string | null;+ managed: number;+ management_kind: string | null;+ ssh_host: string | null;+};++describe('migration 0052: one server url', () => {+ let fixture: FixtureDb;++ beforeEach(async () => {+ fixture = await openFixture('pre-0052');+ });++ afterEach(() => {+ fixture.close();+ });++ function server(id: string): ServerRow {+ const row = fixture.sqlite+ .prepare(+ `SELECT id, name, url, dashboard_url, managed, management_kind, ssh_host+ FROM switch_servers WHERE id = ?`+ )+ .get(id) as ServerRow | undefined;+ if (!row) throw new Error(`no server ${id}`);+ return row;+ }++ it('leaves one address column and an optional dashboard column', () => {+ const columns = fixture.sqlite.prepare('PRAGMA table_info(switch_servers)').all() as {+ name: string;+ notnull: number;+ }[];+ const byName = new Map(columns.map((column) => [column.name, column]));+ expect(byName.has('gateway_url')).toBe(false);+ expect(byName.has('api_url')).toBe(false);+ expect(byName.get('url')?.notnull).toBe(1);+ expect(byName.get('dashboard_url')?.notnull).toBe(0);+ });++ it('keeps the API address of a split server and its gateway as the dashboard', () => {+ expect(server('5e000001-0000-0000-0000-000000000000')).toMatchObject({+ name: 'Split',+ url: 'https://switch-api.example.com',+ dashboard_url: 'https://switch-gateway.example.com',+ });+ });++ it('keeps no dashboard address for a server registered with one address', () => {+ expect(server('5e000002-0000-0000-0000-000000000000')).toMatchObject({+ url: 'https://switch.example.com',+ dashboard_url: null,+ });+ });++ it('treats the same address written in a different case or with a slash as one', () => {+ expect(server('5e000003-0000-0000-0000-000000000000')).toMatchObject({+ url: 'https://mixed.example.com',+ dashboard_url: null,+ });+ });++ it('moves managed servers onto their API port and keeps the dashboard port', () => {+ expect(server('5e000004-0000-0000-0000-000000000000')).toMatchObject({+ url: 'http://localhost:8010',+ dashboard_url: 'http://localhost:3010',+ managed: 1,+ management_kind: 'local',+ ssh_host: null,+ });+ expect(server('5e000005-0000-0000-0000-000000000000')).toMatchObject({+ url: 'http://localhost:8011',+ dashboard_url: 'http://localhost:3011',+ managed: 1,+ management_kind: null,+ });+ expect(server('5e000006-0000-0000-0000-000000000000')).toMatchObject({+ url: 'http://localhost:8020',+ dashboard_url: 'http://localhost:3020',+ managed: 1,+ management_kind: 'remote',+ ssh_host: 'build-box',+ });+ });++ it('keeps both servers that already shared an API address', () => {+ // The gateway address was the unique one; two rows on one API address must+ // both survive the upgrade rather than stop the app from starting.+ expect(server('5e000007-0000-0000-0000-000000000000')).toMatchObject({+ url: 'https://twice.example.com',+ dashboard_url: 'https://gateway-a.example.com',+ });+ expect(server('5e000008-0000-0000-0000-000000000000')).toMatchObject({+ url: 'https://twice.example.com',+ dashboard_url: 'https://gateway-b.example.com',+ });+ });++ it('keeps every server, workspace and agent attached', () => {+ const count = (table: string) =>+ (fixture.sqlite.prepare(`SELECT count(*) AS n FROM ${table}`).get() as { n: number }).n;+ expect(count('switch_servers')).toBe(8);+ expect(count('workspaces')).toBe(8);+ const agents = fixture.sqlite+ .prepare(`SELECT id, workspace_id, api_endpoint FROM agents ORDER BY id`)+ .all();+ expect(agents).toEqual([+ {+ id: 'a9e70001-0000-0000-0000-000000000000',+ workspace_id: '5e000001-0000-0000-0000-000000000000',+ api_endpoint: 'https://switch-api.example.com',+ },+ {+ id: 'a9e70002-0000-0000-0000-000000000000',+ workspace_id: null,+ api_endpoint: 'https://switch.example.com',+ },+ {+ id: 'a9e70003-0000-0000-0000-000000000000',+ workspace_id: '5e000006-0000-0000-0000-000000000000',+ api_endpoint: 'http://localhost:8020',+ },+ ]);+ expect(fixture.sqlite.prepare('PRAGMA foreign_key_check').all()).toEqual([]);+ });++ it('leaves no index on the server addresses', () => {+ const indexes = fixture.sqlite.prepare('PRAGMA index_list(switch_servers)').all() as {+ name: string;+ origin: string;+ }[];+ // The primary key's own index is the only one left.+ expect(indexes.filter((index) => index.origin === 'c')).toEqual([]);+ });++ it('reads every row through the schema', async () => {+ const { switchServers } = await import('@main/db/schema');+ const rows = fixture.db.select().from(switchServers).all();+ expect(rows).toHaveLength(8);+ expect(rows.find((row) => row.name === 'Split')).toMatchObject({+ url: 'https://switch-api.example.com',+ dashboardUrl: 'https://switch-gateway.example.com',+ });+ });+});diff --git a/console/apps/switch-console-desktop/src/main/index.ts b/console/apps/switch-console-desktop/src/main/index.tsindex ae9ce688e..d628489c1 100644--- a/console/apps/switch-console-desktop/src/main/index.ts+++ b/console/apps/switch-console-desktop/src/main/index.ts@@ -37,6 +37,7 @@ import { searchService } from './core/search/search-service';import { appSettingsService } from './core/settings/settings-service';import { sshConnectionManager } from './core/ssh/lifecycle/production-ssh-connection-manager';import { autoSessionWatcher } from './core/switch-rooms/auto-session-watcher';+import { retireDashboardFallbacks } from './core/switch-servers/server-address';import { currentInternalFlag } from './core/telemetry/internal-account';import { readThisLaunch, reportLaunch } from './core/telemetry/launch-history';import { registerTelemetryListeners } from './core/telemetry/telemetry-listeners';@@ -203,6 +204,13 @@ void app.whenReady().then(async () => {log.error('Workspace reconcile could not run; every server was left as it was:', error);});+ // A server registered with a separate dashboard address keeps it until the+ // server serves its own dashboard and the old address has gone. Unawaited+ // for the same reason as the reconcile: it asks every external server.+ void retireDashboardFallbacks().catch((error: unknown) => {+ log.error('Could not check which servers still need a separate dashboard address:', error);+ });+// Each server's feature flags, read on a schedule so a redeploy that changes// them reaches the window without a restart. Started once the managed stacks// report themselves, for the same reason as the reconcile above.diff --git a/console/apps/switch-console-desktop/src/renderer/features/command-palette/search-utils.ts b/console/apps/switch-console-desktop/src/renderer/features/command-palette/search-utils.tsindex 38a7f6804..02be1c9f5 100644--- a/console/apps/switch-console-desktop/src/renderer/features/command-palette/search-utils.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/command-palette/search-utils.ts@@ -87,18 +87,16 @@ export function matchRooms(rooms: RemoteRoomSummary[], query: string): SearchIte);}-/** Matches Switch servers. Also matches on gateway URL, since a server is as- * often recognised by where it lives as by what it was named. */+/** Matches Switch servers. Also matches on the server's address, since a server+ * is as often recognised by where it lives as by what it was named. */export function matchServers(servers: SwitchServer[], query: string): SearchItem[] {const q = query.trim().toLowerCase();if (!q) return [];return finalise(servers.flatMap((server) => {- const score = rank(server.name, q) ?? rank(server.gatewayUrl, q);- return score === null- ? []- : [item('server', server.id, server.name, server.gatewayUrl, score)];+ const score = rank(server.name, q) ?? rank(server.url, q);+ return score === null ? [] : [item('server', server.id, server.name, server.url, score)];}));}diff --git a/console/apps/switch-console-desktop/src/renderer/features/deeplinks/open-console-link.test.ts b/console/apps/switch-console-desktop/src/renderer/features/deeplinks/open-console-link.test.tsindex fd5963ccc..5d16d25f1 100644--- a/console/apps/switch-console-desktop/src/renderer/features/deeplinks/open-console-link.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/deeplinks/open-console-link.test.ts@@ -7,8 +7,9 @@ const list = vi.hoisted(() => vi.fn());const servers = vi.hoisted(() => ({activeServerId: 'srv-1' as string | null,servers: [- { id: 'srv-1', gatewayUrl: 'http://localhost:3000' },- { id: 'srv-2', gatewayUrl: 'https://switch.example.com' },+ { id: 'srv-1', url: 'http://localhost:8000', dashboardUrl: null },+ { id: 'srv-2', url: 'https://switch.example.com', dashboardUrl: null },+ { id: 'srv-3', url: 'https://old-api.example.com', dashboardUrl: 'https://old.example.com' },],setActive: vi.fn(async (id: string) => {servers.activeServerId = id;@@ -106,6 +107,12 @@ describe('openConsoleLink', () => {expect(navigate).toHaveBeenCalledWith('switchBuddy', { serverId: 'srv-2' });});+ it('knows an older server by the separate host its dashboard is on', async () => {+ await openConsoleLink('switchdash://open/rooms?server=https%3A%2F%2Fold.example.com');+ expect(servers.setActive).toHaveBeenCalledWith('srv-3');+ expect(navigate).toHaveBeenCalledWith('serverRooms', { serverId: 'srv-3' });+ });+it('refuses a server it is not connected to, and a malformed link', async () => {await openConsoleLink('switchdash://open/home?server=https%3A%2F%2Felsewhere.test');await openConsoleLink('switchdash://open/nowhere');diff --git a/console/apps/switch-console-desktop/src/renderer/features/deeplinks/open-console-link.ts b/console/apps/switch-console-desktop/src/renderer/features/deeplinks/open-console-link.tsindex b9ba38fb6..58f0d0d91 100644--- a/console/apps/switch-console-desktop/src/renderer/features/deeplinks/open-console-link.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/deeplinks/open-console-link.ts@@ -46,8 +46,11 @@ function serverFor(link: ConsoleLink): string | null {return active;}const origin = originOf(link.server);+ // An older server's link may name the separate host its dashboard is on.const match = switchServersStore.servers.find(- (server) => origin !== null && originOf(server.gatewayUrl) === origin+ (server) =>+ origin !== null &&+ [server.url, server.dashboardUrl].some((own) => own !== null && originOf(own) === origin));if (!match) {toast.error('Could not open that link', {diff --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 c029e7bfa..f901cfe73 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@@ -9,6 +9,7 @@ import {getLocationStore,locationViewKind,} from '@renderer/features/locations/stores/location-selectors';+import { openServerPage } from '@renderer/features/switch-servers/open-server-page';import { ServerStatusPill } from '@renderer/features/switch-servers/server-presentation';import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';@@ -129,11 +130,7 @@ const AgentActionsMenu = observer(function AgentActionsMenu({/><DropdownMenuContent align="end">{gatewayUrl && agent?.serverId && (- <DropdownMenuItem- onClick={() =>- void rpc.switchServers.openGatewayPage({ serverId: agent.serverId!, url: gatewayUrl })- }- >+ <DropdownMenuItem onClick={() => void openServerPage(agent.serverId!, gatewayUrl)}><ExternalLink className="size-4" />Open in gateway</DropdownMenuItem>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.tsxindex fbe146ba5..8d90cdef8 100644--- 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.tsx@@ -338,8 +338,7 @@ function currentPage(return (<ExternalServerStep- initialGatewayUrl={null}- initialApiUrl={null}+ initialUrl={null}initialName={null}serverId={null}isEdit={false}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-links.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-links.tsindex d776fb959..01135174a 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-links.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-links.ts@@ -1,7 +1,8 @@+import { openServerPage } from '@renderer/features/switch-servers/open-server-page';import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';import { rpc } from '@renderer/lib/ipc';-import { openExternalUrl, reportOpenAttempt, reportOpenFailure } from '@renderer/lib/open-external';+import { reportOpenAttempt, reportOpenFailure } from '@renderer/lib/open-external';/*** Open a room's bridged channel in the messaging app it lives in, falling back@@ -34,5 +35,6 @@ export function openRoomChannel(roomId: string): void {/** Open a room's detail page in the gateway web app. */export function openRoomGatewayPage(roomId: string): void {const url = switchRoomsStore.gatewayRoomUrl(roomId);- if (url) void openExternalUrl(url, 'Could not open the room in the gateway');+ const serverId = switchRoomsStore.roomServerId(roomId);+ if (url && serverId) void openServerPage(serverId, url);}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 ea1b7eeef..55a0dea63 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@@ -49,12 +49,12 @@ 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+ * Turn a server-address cascade into a user-facing toast: confirm how many* agents were re-pointed (and that running sessions need a restart), and flag* any that failed so the edit never looks cleanly done when it wasn't.*/function notifyPropagation(propagation: ServerApiUrlPropagation): void {- if (!propagation.apiUrlChanged) return;+ if (!propagation.urlChanged) return;const updated = propagation.agents.filter((a) => a.outcome === 'updated');const failed = propagation.agents.filter((a) => a.outcome === 'failed');@@ -71,16 +71,14 @@ function notifyPropagation(propagation: ServerApiUrlPropagation): void {toast({title: `Updated ${updated.length} agent config${updated.length === 1 ? '' : 's'}`,description:- 'Each agent now points at the new API URL. Restart any running sessions to pick it up.',+ 'Each agent now points at the new address. Restart any running sessions to pick it up.',});}}type Props = BaseModalProps<void> & {- /** Prefill the gateway URL. */- initialGatewayUrl?: string;- /** Prefill the API (agent bridge) URL. */- initialApiUrl?: string;+ /** Prefill the server's address. */+ initialUrl?: string;/** Prefill the name. */initialName?: string;/** When set, the modal edits this existing server instead of adding one. */@@ -331,8 +329,7 @@ export const AddServerModal = observer(function AddServerModal(props: Props) {<ExternalServerSteponSuccess={props.onSuccess}onClose={props.onClose}- initialGatewayUrl={props.initialGatewayUrl ?? null}- initialApiUrl={props.initialApiUrl ?? null}+ initialUrl={props.initialUrl ?? null}initialName={props.initialName ?? null}serverId={props.serverId ?? null}isEdit={isEdit}@@ -369,9 +366,7 @@ export const ChooseStep = observer(function ChooseStep({// switcher, and offering to add it again would only lead back to it.const cloudAdded =cloud.kind === 'open' &&- switchServersStore.servers.some(- (server) => urlOrigin(server.gatewayUrl) === urlOrigin(cloud.url)- );+ switchServersStore.servers.some((server) => urlOrigin(server.url) === urlOrigin(cloud.url));const [cloudAttempt, setCloudAttempt] = useState<{ connecting: boolean; error: string | null }>({connecting: false,error: null,@@ -445,7 +440,7 @@ export const ChooseStep = observer(function ChooseStep({<ChoiceCardicon={<Globe className="size-5" />}title="Connect to an existing server"- description="Point Switch Console at a Switch gateway someone else runs, by URL."+ description="Point Switch Console at a Switch server someone else runs, by its address."onClick={onExternal}/></div>@@ -1214,20 +1209,19 @@ function looksLikeUrl(value: string): boolean {* 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 {+function nameFromUrl(url: 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;+ return new URL(url).host;}export const ExternalServerStep = observer(function ExternalServerStep({onSuccess,onClose,onBack,- initialGatewayUrl,- initialApiUrl,+ initialUrl,initialName,serverId,isEdit,@@ -1235,8 +1229,7 @@ export const ExternalServerStep = observer(function ExternalServerStep({existing,onConnected,}: {- initialGatewayUrl: string | null;- initialApiUrl: string | null;+ initialUrl: string | null;initialName: string | null;serverId: string | null;isEdit: boolean;@@ -1252,29 +1245,22 @@ export const ExternalServerStep = observer(function ExternalServerStep({onConnected: (server: SwitchServer) => void;}) {const [name, setName] = useState(initialName ?? existing?.name ?? '');- const [gatewayUrl, setGatewayUrl] = useState(initialGatewayUrl ?? existing?.gatewayUrl ?? '');- const [apiUrl, setApiUrl] = useState(initialApiUrl ?? existing?.apiUrl ?? '');+ const [url, setUrl] = useState(initialUrl ?? existing?.url ?? '');const [submitting, setSubmitting] = useState(false);const [error, setError] = useState<string | null>(null);const trimmedName = name.trim();- const trimmedGateway = gatewayUrl.trim();- const trimmedApi = apiUrl.trim();- const gatewayValid = looksLikeUrl(trimmedGateway);- const apiValid = looksLikeUrl(trimmedApi);+ const trimmedUrl = url.trim();+ const urlValid = looksLikeUrl(trimmedUrl);// 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.+ // run it comes from the address, 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 isValid = (!asksForName || trimmedName.length > 0) && urlValid;+ const submittedName = firstRun && urlValid ? nameFromUrl(trimmedUrl) : trimmedName;- const gatewayMessage =- trimmedGateway.length > 0 && !gatewayValid- ? 'Enter a full URL, e.g. https://switch-gateway.example.com'- : undefined;- const apiMessage =- trimmedApi.length > 0 && !apiValid- ? 'Enter a full URL, e.g. https://switch-api.example.com'+ const urlMessage =+ trimmedUrl.length > 0 && !urlValid+ ? 'Enter a full address, e.g. https://switch.example.com': undefined;// The row this form writes to, when one already exists: the server being@@ -1286,12 +1272,7 @@ export const ExternalServerStep = observer(function ExternalServerStep({setSubmitting(true);setError(null);if (savedId) {- const result = await switchServersStore.updateServer(- savedId,- submittedName,- trimmedGateway,- trimmedApi- );+ const result = await switchServersStore.updateServer(savedId, submittedName, trimmedUrl);if (!result) {setError(switchServersStore.errorText ?? 'Could not save the server.');setSubmitting(false);@@ -1303,7 +1284,7 @@ export const ExternalServerStep = observer(function ExternalServerStep({return;}} else {- const saved = await switchServersStore.addServer(submittedName, trimmedGateway, trimmedApi);+ const saved = await switchServersStore.addServer(submittedName, trimmedUrl);if (!saved) {setError(switchServersStore.errorText ?? 'Could not add the server.');setSubmitting(false);@@ -1313,7 +1294,7 @@ export const ExternalServerStep = observer(function ExternalServerStep({return;}onSuccess();- }, [isValid, isEdit, savedId, submittedName, trimmedGateway, trimmedApi, onSuccess, onConnected]);+ }, [isValid, isEdit, savedId, submittedName, trimmedUrl, 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@@ -1342,7 +1323,7 @@ export const ExternalServerStep = observer(function ExternalServerStep({? 'Connect to your server': 'Connect to an existing server'}- subtitle={firstRun ? 'Whoever set it up can give you these addresses.' : null}+ subtitle={firstRun ? 'Whoever set it up can give you its address.' : null}/* Editing a connection is one dialog rather than a flow, and a pager onit would invent pages either side that do not exist. */pager={@@ -1382,35 +1363,20 @@ export const ExternalServerStep = observer(function ExternalServerStep({</Field>)}<Field>- <FieldLabel>Gateway URL</FieldLabel>+ <FieldLabel>Server address</FieldLabel><Input- value={gatewayUrl}- onChange={(e) => setGatewayUrl(e.target.value)}- placeholder="https://switch-gateway.example.com"+ value={url}+ onChange={(e) => setUrl(e.target.value)}+ placeholder="https://switch.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>+ <p className="mt-1 text-xs text-foreground-muted">The address its agents connect to.</p>)}- {apiMessage && <p className="mt-1 text-xs text-destructive">{apiMessage}</p>}+ {urlMessage && <p className="mt-1 text-xs text-destructive">{urlMessage}</p>}{error && <p className="mt-1 text-xs text-destructive">{error}</p>}</Field>{firstRun && (@@ -1502,7 +1468,7 @@ export const SignInStep = observer(function SignInStep({<ServerSignInFieldssignIn={signIn}idPrefix="connect-server-sign-in"- gatewayUrl={server.gatewayUrl}+ serverUrl={server.url}onSignedIn={onSignedIn}/></WizardFrame>diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/open-server-page.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/open-server-page.test.tsnew file mode 100644index 000000000..6106d89ba--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/open-server-page.test.ts@@ -0,0 +1,53 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { RpcError } from '@shared/lib/ipc/rpc-error';++const openGatewayPage = vi.hoisted(() => vi.fn());+const toastError = vi.hoisted(() => vi.fn());++vi.mock('@renderer/lib/ipc', () => ({ rpc: { switchServers: { openGatewayPage } } }));+vi.mock('sonner', () => ({ toast: { error: toastError } }));++const { openServerPage } = await import('./open-server-page');++describe('openServerPage', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('asks the main process to open the page on that server', async () => {+ openGatewayPage.mockResolvedValue(undefined);++ await openServerPage('srv', 'https://switch.example.com/rooms/1');++ expect(openGatewayPage).toHaveBeenCalledWith({+ serverId: 'srv',+ url: 'https://switch.example.com/rooms/1',+ });+ expect(toastError).not.toHaveBeenCalled();+ });++ it('says why when the server has no dashboard to open', async () => {+ const message = 'Team does not serve its dashboard at https://switch-api.example.com.';+ openGatewayPage.mockRejectedValue(+ new RpcError({+ __switchConsoleRpcError: true,+ code: 'NoDashboardError',+ message,+ } as unknown as ConstructorParameters<typeof RpcError>[0])+ );++ await openServerPage('srv', 'https://switch-api.example.com/');++ expect(toastError).toHaveBeenCalledWith(message, undefined);+ });++ it('falls back to a plain sentence for a failure it does not recognise', async () => {+ openGatewayPage.mockRejectedValue(new Error('boom'));++ await openServerPage('srv', 'https://switch.example.com/');++ expect(toastError).toHaveBeenCalledWith('Could not open the dashboard.', {+ description: 'boom',+ });+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/open-server-page.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/open-server-page.tsnew file mode 100644index 000000000..33b34d1fb--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/open-server-page.ts@@ -0,0 +1,17 @@+import { toast } from 'sonner';+import { describeFailure } from '@renderer/lib/errors/describe-failure';+import { rpc } from '@renderer/lib/ipc';++/**+ * Open one of a server's dashboard pages, and say why when it cannot be: the+ * server may not be reachable, or may not serve a dashboard at the address+ * Console has for it.+ */+export async function openServerPage(serverId: string, url: string): Promise<void> {+ try {+ await rpc.switchServers.openGatewayPage({ serverId, url });+ } catch (cause) {+ const { headline, detail } = describeFailure(cause, 'Could not open the dashboard.');+ toast.error(headline, detail ? { description: detail } : undefined);+ }+}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 4acb56cfc..58899bb01 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@@ -37,6 +37,7 @@ import type { Agent } from '@shared/core/agents/agents';import type { ManagedAgentView } from '@shared/core/managed-agents/managed-agents';import { providerDisplayName } from '@shared/core/providers/agent-provider-registry';import { isFrozenServer } from './managed-server-state';+import { openServerPage } from './open-server-page';import { ServerPage } from './server-page';import { ServerSectionTitlebar } from './server-section-titlebar';import { switchRoomsStore } from './switch-rooms-store';@@ -224,11 +225,7 @@ const AgentCard = observer(function AgentCard({/><DropdownMenuContent align="end">{gatewayUrl && (- <DropdownMenuItem- onClick={() =>- void rpc.switchServers.openGatewayPage({ serverId, url: gatewayUrl })- }- >+ <DropdownMenuItem onClick={() => void openServerPage(serverId, gatewayUrl)}><ExternalLink className="size-4" />Open in gateway</DropdownMenuItem>diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-icon.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-icon.test.tsindex b2521b528..1480e3544 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-icon.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-icon.test.ts@@ -3,8 +3,7 @@ import { describe, expect, it, vi } from 'vitest';import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';vi.mock('./switch-cloud-store', () => ({- isSwitchCloudServer: (server: SwitchServer) =>- server.gatewayUrl === 'https://cloud.example.invalid',+ isSwitchCloudServer: (server: SwitchServer) => server.url === 'https://cloud.example.invalid',}));const { serverIcon } = await import('./server-icon');@@ -13,8 +12,8 @@ function server(patch: Partial<SwitchServer>): SwitchServer {return {id: 'srv',name: 'srv',- gatewayUrl: 'https://srv.example.invalid',- apiUrl: 'https://srv.example.invalid',+ url: 'https://srv.example.invalid',+ dashboardUrl: null,managed: false,managementKind: null,sshHost: null,@@ -26,7 +25,7 @@ function server(patch: Partial<SwitchServer>): SwitchServer {describe('the icon for a server', () => {it('is a cloud for Switch Cloud', () => {- expect(serverIcon(server({ gatewayUrl: 'https://cloud.example.invalid' }))).toBe(Cloud);+ expect(serverIcon(server({ url: 'https://cloud.example.invalid' }))).toBe(Cloud);});it('is a globe for any other server reached by URL', () => {diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-sign-in.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-sign-in.tsxindex 92b8d25db..e7e457413 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-sign-in.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-sign-in.tsx@@ -232,7 +232,7 @@ function FieldError({ id, message }: { id: string; message: string | undefined }export const ServerSignInFields = observer(function ServerSignInFields({signIn,idPrefix,- gatewayUrl,+ serverUrl,passwordSubmit,onSignedIn,}: {@@ -241,7 +241,7 @@ export const ServerSignInFields = observer(function ServerSignInFields({idPrefix: string;/** Shown under the password as the address being signed in to. Omit where* the surrounding page already says which server this is. */- gatewayUrl?: string;+ serverUrl?: string;passwordSubmit?: React.ReactNode;onSignedIn: (signedIn: SignedIn) => void;}) {@@ -362,8 +362,8 @@ export const ServerSignInFields = observer(function ServerSignInFields({{signingUp && (<FieldError id={`${idPrefix}-password-error`} message={fieldErrors.password} />)}- {gatewayUrl && !signingUp && (- <p className="truncate text-xs text-foreground-muted">Signing in to {gatewayUrl}</p>+ {serverUrl && !signingUp && (+ <p className="truncate text-xs text-foreground-muted">Signing in to {serverUrl}</p>)}</div>{signingUp && (@@ -387,9 +387,9 @@ export const ServerSignInFields = observer(function ServerSignInFields({id={`${idPrefix}-confirm-password-error`}message={fieldErrors.confirmPassword}/>- {gatewayUrl && (+ {serverUrl && (<p className="truncate text-xs text-foreground-muted">- Creating an account on {gatewayUrl}+ Creating an account on {serverUrl}</p>)}</div>diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-cloud-origin.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-cloud-origin.test.tsnew file mode 100644index 000000000..e53ca16b9--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-cloud-origin.test.ts@@ -0,0 +1,19 @@+import { describe, expect, it, vi } from 'vitest';++const switchCloud = vi.hoisted(() => vi.fn(async () => ({ url: 'https://cloud.example.com' })));++vi.mock('@renderer/lib/ipc', () => ({ rpc: { switchServers: { switchCloud } } }));+vi.mock('@renderer/utils/logger', () => ({ log: { error: vi.fn() } }));+vi.mock('./switch-servers-store', () => ({ switchServersStore: { servers: [] } }));++const { isSwitchCloudServer, loadSwitchCloudOrigin } = await import('./switch-cloud-origin');++describe('isSwitchCloudServer', () => {+ it('recognises the Cloud by its one address', async () => {+ await loadSwitchCloudOrigin();++ expect(isSwitchCloudServer({ url: 'https://cloud.example.com' })).toBe(true);+ expect(isSwitchCloudServer({ url: 'https://CLOUD.example.com/' })).toBe(true);+ expect(isSwitchCloudServer({ url: 'https://switch.example.com' })).toBe(false);+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-cloud-origin.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-cloud-origin.tsindex 8e0bb909d..96a29f3f4 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-cloud-origin.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-cloud-origin.ts@@ -29,14 +29,10 @@ export function loadSwitchCloudOrigin(): Promise<void> {* False until the Cloud's address has been read; observers render again once* it has.*/-export function isSwitchCloudServer(server: Pick<SwitchServer, 'gatewayUrl' | 'apiUrl'>): boolean {+export function isSwitchCloudServer(server: Pick<SwitchServer, 'url'>): boolean {void loadSwitchCloudOrigin();const origin = switchCloudOrigin.get();- return (- origin !== null &&- urlOrigin(server.gatewayUrl) === urlOrigin(origin) &&- urlOrigin(server.apiUrl) === urlOrigin(origin)- );+ return origin !== null && urlOrigin(server.url) === urlOrigin(origin);}/** The Switch Cloud server registered here, or null when there is none or no Cloud is named. */diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-cloud-store.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-cloud-store.tsindex 7389ab5f4..4d3fe6b3b 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-cloud-store.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-cloud-store.ts@@ -44,7 +44,7 @@ export function isSwitchCloudServer(server: SwitchServer): boolean {const origin = switchCloudStore.origin;if (origin === null) return false;try {- return new URL(server.gatewayUrl).origin === origin;+ return new URL(server.url).origin === origin;} catch {return false;}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 419cb1d46..ff67ef714 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@@ -4,7 +4,13 @@ import type { RemoteRoomSummary } from '@shared/core/switch-servers/switch-serveconst listRooms = vi.hoisted(() => vi.fn());const listAgentRooms = vi.hoisted(() => vi.fn());const serversStore = vi.hoisted(() => ({- servers: [] as { id: string; name?: string; managed?: boolean }[],+ servers: [] as {+ id: string;+ name?: string;+ managed?: boolean;+ url?: string;+ dashboardUrl?: string | null;+ }[],isConnected: (_serverId: string): boolean => true,// These servers answer; they are simply not signed in to.isUnreachable: (_serverId: string): boolean => false,@@ -571,3 +577,52 @@ it('does not clear a newer loading state or error from an older request', asyncexpect(store.isLoading('server', 'agent')).toBe(false);expect(store.errorFor('server', 'agent')).toContain('Current failure');});++describe('dashboard links', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ twoWorkspaces();+ workspaces.activeId = null;+ serversStore.servers = [+ { id: 'srv-a', url: 'https://alpha.example.com/', dashboardUrl: null },+ {+ id: 'srv-b',+ url: 'https://beta-api.example.com',+ dashboardUrl: 'https://beta-gateway.example.com/',+ },+ ];+ listRooms.mockImplementation(async (workspaceId: string) =>+ workspaceId === 'ws-a' ? [room('room-a', null)] : [room('room-b', null)]+ );+ });++ it('opens a room on its server’s own address', async () => {+ const store = new SwitchRoomsStore();+ await store.loadRoomNames();++ expect(store.gatewayRoomUrl('room-a')).toBe('https://alpha.example.com/rooms/room-a');+ });++ it('opens a room on the dashboard address an older server keeps apart', async () => {+ const store = new SwitchRoomsStore();+ await store.loadRoomNames();++ expect(store.gatewayRoomUrl('room-b')).toBe('https://beta-gateway.example.com/rooms/room-b');+ });++ it('has no link for a room whose server it does not know yet', () => {+ expect(new SwitchRoomsStore().gatewayRoomUrl('room-a')).toBeNull();+ });++ it('opens an agent on the same address its server’s rooms open on', () => {+ const store = new SwitchRoomsStore();++ expect(store.gatewayAgentUrl('srv-a', 'agent-1')).toBe(+ 'https://alpha.example.com/agents/agent-1'+ );+ expect(store.gatewayAgentUrl('srv-b', 'agent-1')).toBe(+ 'https://beta-gateway.example.com/agents/agent-1'+ );+ expect(store.gatewayAgentUrl('srv-unknown', 'agent-1')).toBeNull();+ });+});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 77b64476f..9a8111940 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@@ -2,9 +2,10 @@ 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 {- RemoteAgentRoom,- RemoteRoomSummary,+import {+ dashboardOrigin,+ type RemoteAgentRoom,+ type RemoteRoomSummary,} from '@shared/core/switch-servers/switch-servers';import { UNBRIDGED_FILTER_VALUE } from '@shared/view-state';import { serverAvailability } from './server-availability';@@ -130,7 +131,7 @@ export class SwitchRoomsStore {if (!serverId) return null;const server = switchServersStore.servers.find((s) => s.id === serverId);if (!server) return null;- const base = server.gatewayUrl.replace(/\/+$/, '');+ const base = dashboardOrigin(server).replace(/\/+$/, '');return `${base}/rooms/${roomId}`;}@@ -142,7 +143,7 @@ export class SwitchRoomsStore {gatewayAgentUrl(serverId: string, switchAgentId: string): string | null {const server = switchServersStore.servers.find((s) => s.id === serverId);if (!server) return null;- const base = server.gatewayUrl.replace(/\/+$/, '');+ const base = dashboardOrigin(server).replace(/\/+$/, '');return `${base}/agents/${switchAgentId}`;}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 2d44d5a22..b7bf7f64d 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@@ -11,6 +11,7 @@ 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());+const oidcLogin = vi.hoisted(() => vi.fn());/** SSH hosts the reachability manager currently considers down. */const blockedHosts = vi.hoisted(() => new Set<string>());@@ -25,6 +26,7 @@ vi.mock('@renderer/lib/ipc', () => ({removeServer,addServer,connectToSwitchCloud,+ oidcLogin,},onboarding: { installIsEmpty },},@@ -79,8 +81,8 @@ function server(id: string, overrides: Partial<SwitchServer> = {}): SwitchServerreturn {id,name: id,- gatewayUrl: `https://${id}.example.com`,- apiUrl: `https://api.${id}.example.com`,+ url: `https://api.${id}.example.com`,+ dashboardUrl: `https://${id}.example.com`,managed: false,managementKind: null,sshHost: null,@@ -385,7 +387,7 @@ describe('adding the first server', () => {addServer.mockResolvedValue(server('a'));listServers.mockResolvedValue([server('a')]);installIsEmpty.mockResolvedValue(false);- await store.addServer('a', 'https://a.example.com', 'https://a.example.com');+ await store.addServer('a', 'https://a.example.com');expect(store.installIsEmpty).toBe(false);});@@ -405,6 +407,18 @@ describe('adding the first server', () => {});});+describe('signing in through the browser', () => {+ it('reads the list again, for a dashboard address the sign-in found', async () => {+ const store = newStore([server('a', { dashboardUrl: null })]);+ oidcLogin.mockResolvedValue({ success: true, data: true });+ listServers.mockResolvedValue([server('a', { dashboardUrl: 'https://a.example.com' })]);++ expect(await store.oidcLogin('a', null)).toBe(true);++ expect(store.servers[0]?.dashboardUrl).toBe('https://a.example.com');+ });+});+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')]);@@ -694,7 +708,7 @@ describe('keeping a server active', () => {addServer.mockResolvedValue(created);listServers.mockResolvedValue([created]);- await store.addServer('New', created.gatewayUrl, created.apiUrl);+ await store.addServer('New', created.url);expect(store.activeServerId).toBe('srv-new');});@@ -709,7 +723,7 @@ describe('keeping a server active', () => {addServer.mockResolvedValue(created);listServers.mockResolvedValue([server('srv-a'), created]);- await store.addServer('B', created.gatewayUrl, created.apiUrl);+ await store.addServer('B', created.url);expect(store.activeServerId).toBe('srv-a');});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 0255a720d..6e8bca837 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@@ -445,10 +445,10 @@ export class SwitchServersStore {}}- async addServer(name: string, gatewayUrl: string, apiUrl: string): Promise<SwitchServer | null> {+ async addServer(name: string, url: string): Promise<SwitchServer | null> {this.clearError();try {- const created = await rpc.switchServers.addServer({ name, gatewayUrl, apiUrl });+ const created = await rpc.switchServers.addServer({ name, url });const [servers, installIsEmpty] = await Promise.all([rpc.switchServers.listServers(),rpc.onboarding.installIsEmpty(),@@ -513,15 +513,10 @@ export class SwitchServersStore {return found;}- async updateServer(- id: string,- name: string,- gatewayUrl: string,- apiUrl: string- ): Promise<UpdateServerResult | null> {+ async updateServer(id: string, name: string, url: string): Promise<UpdateServerResult | null> {this.clearError();try {- const result = await rpc.switchServers.updateServer({ id, name, gatewayUrl, apiUrl });+ const result = await rpc.switchServers.updateServer({ id, name, url });const servers = await rpc.switchServers.listServers();runInAction(() => {this.servers = servers;@@ -683,7 +678,16 @@ export class SwitchServersStore {}return false;}- await Promise.all([this.refreshStatus(serverId), workspacesStore.refresh()]);+ // Signing in may also have taught Console where an older server keeps its+ // dashboard, which the links built here read from the list.+ const [servers] = await Promise.all([+ rpc.switchServers.listServers(),+ this.refreshStatus(serverId),+ workspacesStore.refresh(),+ ]);+ runInAction(() => {+ this.servers = servers;+ });return true;}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 76f330301..274309d8f 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@@ -19,7 +19,6 @@ import { WorkspaceAvatar } from '@renderer/features/workspaces/workspace-avatar'import { workspaceTitle } from '@renderer/features/workspaces/workspace-title';import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { toast } 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 { Alert, AlertDescription, AlertTitle } from '@renderer/lib/ui/alert';@@ -33,10 +32,11 @@ import {DropdownMenuTrigger,} from '@renderer/lib/ui/dropdown-menu';import { Spinner } from '@renderer/lib/ui/spinner';-import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';+import { dashboardOrigin, type SwitchServer } from '@shared/core/switch-servers/switch-servers';import { GuardrailsSection } from './GuardrailsSection';import { localServerStore } from './local-server-store';import { MessagingAppsCard } from './MessagingAppsCard';+import { openServerPage } from './open-server-page';import { remoteServerStore } from './remote-server-store';import { serverIcon } from './server-icon';import { serverPlacementLabel } from './server-presentation';@@ -176,8 +176,8 @@ const ServerMainPanel = observer(function ServerMainPanel() {// button asks for, so the page should not look idle while one is in flight.const busy = refreshingPage || store.refreshing.has(serverId);const unreachable = store.isUnreachable(serverId);- // A local server run without Docker has no dashboard process: its gateway- // URL is switch-core itself, which serves the API and no pages.+ // A local server run without Docker has no dashboard: switch-core runs there+ // without the dashboard's pages, so its address serves the API alone.const servesNoDashboard =server.managed && server.managementKind === 'local' && localServerStore.isNative;const PlacementIcon = serverIcon(server);@@ -246,8 +246,7 @@ const ServerMainPanel = observer(function ServerMainPanel() {showEditServerModal({serverId,initialName: server.name,- initialGatewayUrl: server.gatewayUrl,- initialApiUrl: server.apiUrl,+ initialUrl: server.url,})}>@@ -325,12 +324,7 @@ const ServerMainPanel = observer(function ServerMainPanel() {variant="outline"size="sm"className="shrink-0"- onClick={() =>- void rpc.switchServers.openGatewayPage({- serverId: server.id,- url: server.gatewayUrl,- })- }+ onClick={() => void openServerPage(server.id, dashboardOrigin(server))}><ExternalLink className="size-4" />Opendiff --git a/console/apps/switch-console-desktop/src/renderer/lib/errors/describe-failure.test.ts b/console/apps/switch-console-desktop/src/renderer/lib/errors/describe-failure.test.tsindex 9036f324e..f06e6db5b 100644--- a/console/apps/switch-console-desktop/src/renderer/lib/errors/describe-failure.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/lib/errors/describe-failure.test.ts@@ -125,6 +125,19 @@ describe('describeFailure', () => {});});+ it.each([+ 'NotTheServerAddressError',+ 'DuplicateServerUrlError',+ 'NoDashboardError',+ 'NoManagementApiError',+ ])('passes a refusal about a server’s address straight through (%s)', (code) => {+ const message = 'https://switch.example.com answered with a web page, not the Switch server.';+ expect(describeFailure(rpcError(code, message), 'Could not add the server.')).toEqual({+ headline: message,+ detail: null,+ });+ });+it('passes a refusal to remove a machine running moved agents straight through', () => {const message ='build-box runs builder as managed agents for this Console, so it cannot be removed yet. Delete those agents first.';diff --git a/console/apps/switch-console-desktop/src/renderer/lib/errors/describe-failure.ts b/console/apps/switch-console-desktop/src/renderer/lib/errors/describe-failure.tsindex 36b67dd5f..6be368866 100644--- a/console/apps/switch-console-desktop/src/renderer/lib/errors/describe-failure.ts+++ b/console/apps/switch-console-desktop/src/renderer/lib/errors/describe-failure.ts@@ -90,9 +90,13 @@ export function describeFailure(error: unknown, fallback: string): FailureDescricase 'ManagedServerStoppedError':case 'ServerBusyError':case 'MovedAgentsHereError':+ case 'NotTheServerAddressError':+ case 'DuplicateServerUrlError':+ case 'NoDashboardError':+ case 'NoManagementApiError':// Already a modeled, actionable sentence: the server and the page to- // fix it on, who is changing the server and when to try again, or- // which agents to bring back first.+ // fix it on, who is changing the server and when to try again, which+ // agents to bring back first, or which address to enter instead.return { headline: error.message, detail: null };}}diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/add-server-choose-step.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/add-server-choose-step.test.tsxindex be6f40116..263523bb6 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/add-server-choose-step.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/add-server-choose-step.test.tsx@@ -47,8 +47,8 @@ function server(url: string): SwitchServer {return {id: url,name: url,- gatewayUrl: url,- apiUrl: url,+ url,+ dashboardUrl: null,managed: false,managementKind: null,sshHost: null,diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/delete-server-modal.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/delete-server-modal.test.tsxindex 4c264ebc9..a80c4d193 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/delete-server-modal.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/delete-server-modal.test.tsx@@ -81,8 +81,8 @@ afterEach(async () => {const REMOTE_SERVER = {id: 'srv-1',name: 'Team Server',- gatewayUrl: 'https://gateway.example',- apiUrl: 'https://api.example',+ url: 'https://api.example',+ dashboardUrl: 'https://gateway.example',managed: true,managementKind: 'remote' as const,sshHost: 'vm-1',@@ -93,8 +93,8 @@ const REMOTE_SERVER = {const EXTERNAL_SERVER = {id: 'srv-2',name: 'External Server',- gatewayUrl: 'https://gateway.example',- apiUrl: 'https://api.example',+ url: 'https://api.example',+ dashboardUrl: 'https://gateway.example',managed: false,managementKind: null,sshHost: null,diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/managed-server-view.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/managed-server-view.test.tsxindex 9f88818bf..3f90d7074 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/managed-server-view.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/managed-server-view.test.tsx@@ -118,8 +118,8 @@ import '@renderer/index.css';const LOCAL = {id: 'srv-1',name: 'Local dev',- gatewayUrl: 'http://localhost:41000',- apiUrl: 'http://localhost:41001',+ url: 'http://localhost:41001',+ dashboardUrl: 'http://localhost:41000',managed: true,managementKind: 'local' as const,sshHost: null,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.tsxindex 4975a5767..0f51fd2dd 100644--- 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.tsx@@ -12,6 +12,8 @@ import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const addServer = vi.hoisted(() => vi.fn());+const updateServer = vi.hoisted(() => vi.fn());+const storeError = vi.hoisted(() => ({ text: null as string | null }));const setActive = vi.hoisted(() => vi.fn());const navigate = vi.hoisted(() => vi.fn());const listHosts = vi.hoisted(() => vi.fn());@@ -41,11 +43,14 @@ vi.mock('@renderer/lib/ipc', () => ({vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({switchServersStore: {addServer,+ updateServer,connectToSwitchCloud,setActive,serverById: (id: string | null) => servers.find((s) => s.id === id) ?? null,isConnected: () => false,- errorText: null,+ get errorText() {+ return storeError.text;+ },ensureAuthConfig: () => Promise.resolve(),authConfigFor: () => ({passwordLoginEnabled: true,@@ -105,12 +110,16 @@ vi.mock('@renderer/lib/hooks/useTheme', () => ({}));import { onboardingStore } from '@renderer/features/onboarding/onboarding-store';+import { ExternalServerStep } from '@renderer/features/switch-servers/AddServerModal';+import { Dialog, DialogContent } from '@renderer/lib/ui/dialog';let container: HTMLDivElement | null = null;let root: Root | null = null;beforeEach(() => {addServer.mockReset();+ updateServer.mockReset();+ storeError.text = null;setActive.mockReset();navigate.mockReset();listHosts.mockReset();@@ -140,8 +149,8 @@ function serverAdded(id: string) {const server = {id,name: 'switch.example.com',- gatewayUrl: 'https://switch.example.com',- apiUrl: 'https://switch.example.com:8000',+ url: 'https://switch.example.com',+ dashboardUrl: null,};servers.push(server);addServer.mockResolvedValue(server);@@ -153,8 +162,7 @@ async function addFromConnectPage(el: HTMLElement) {await act(async () => button(el, 'Get started').click());await choose(el, 'Join an existing server');await act(async () => button(el, 'Continue').click());- await type(field(el, 'Gateway URL')!, 'https://switch.example.com');- await type(field(el, 'API URL')!, 'https://switch.example.com:8000');+ await type(field(el, 'Server address')!, 'https://switch.example.com');await choose(el, 'Sign in to this server');}@@ -271,17 +279,29 @@ describe('the first-run flow', () => {expect(onboardingStore.page).toBe('local');});- it('asks for the addresses, and not for a name, on the connect page', async () => {+ it('asks for the one address, and not for a name, on the connect page', async () => {const el = await renderFlow();await act(async () => button(el, 'Get started').click());await choose(el, 'Join an existing server');await act(async () => button(el, 'Continue').click());- expect(field(el, 'Gateway URL')).not.toBeNull();- expect(field(el, 'API URL')).not.toBeNull();+ expect(field(el, 'Server address')).not.toBeNull();+ expect(field(el, 'Gateway URL')).toBeNull();+ expect(field(el, 'API URL')).toBeNull();expect(field(el, 'Name')).toBeNull();});+ it('names the server after its address, 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');+ });+it('keeps the flow on screen after the server is added, for the sign-in still to come', async () => {serverAdded('srv-1');const el = await renderFlow();@@ -315,8 +335,8 @@ 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',+ url: 'https://cloud.example.com',+ dashboardUrl: null,};beforeEach(() => {@@ -361,3 +381,80 @@ describe('the first-run flow with Switch Cloud named', () => {expect(el.querySelector('[role="alert"]')?.textContent).toContain('disk full');});});++describe('the server address form', () => {+ it('says why an address was refused, and stays on the form', async () => {+ addServer.mockResolvedValue(null);+ storeError.text =+ 'https://switch-gateway.example.com answered with a web page, not the Switch server.';+ const el = await renderFlow();++ await act(async () => button(el, 'Get started').click());+ await choose(el, 'Join an existing server');+ await act(async () => button(el, 'Continue').click());+ await type(field(el, 'Server address')!, 'https://switch-gateway.example.com');+ await choose(el, 'Sign in to this server');++ expect(el.textContent).toContain('answered with a web page, not the Switch server.');+ expect(field(el, 'Server address')).not.toBeNull();+ });++ it('asks for a full address before it will go on', async () => {+ const el = await renderFlow();++ await act(async () => button(el, 'Get started').click());+ await choose(el, 'Join an existing server');+ await act(async () => button(el, 'Continue').click());+ await type(field(el, 'Server address')!, 'switch.example.com');++ expect(el.textContent).toContain('Enter a full address, e.g. https://switch.example.com');+ const submit = [...el.querySelectorAll<HTMLButtonElement>('button')].find((b) =>+ b.textContent?.includes('Sign in to this server')+ );+ expect(submit?.disabled).toBe(true);+ });++ it('edits a connection through its one address', async () => {+ updateServer.mockResolvedValue({+ server: { id: 'srv-1', name: 'Team', url: 'https://new.example.com', dashboardUrl: null },+ propagation: { urlChanged: true, agents: [] },+ });+ const onSuccess = vi.fn();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ await act(async () =>+ root!.render(+ <Dialog open>+ <DialogContent>+ <ExternalServerStep+ initialUrl="https://switch.example.com"+ initialName="Team"+ serverId="srv-1"+ isEdit+ firstRun={false}+ existing={null}+ onSuccess={onSuccess}+ onClose={vi.fn()}+ onBack={null}+ onConnected={vi.fn()}+ />+ </DialogContent>+ </Dialog>+ )+ );+ // The dialog renders into a portal on the body, not inside the container.+ const el = document.body;++ expect(el.textContent).toContain('Edit connection');+ expect(field(el, 'Server address')?.value).toBe('https://switch.example.com');+ expect(field(el, 'Gateway URL')).toBeNull();+ expect(field(el, 'API URL')).toBeNull();++ await type(field(el, 'Server address')!, 'https://new.example.com');+ await choose(el, 'Save changes');++ expect(updateServer).toHaveBeenCalledWith('srv-1', 'Team', 'https://new.example.com');+ expect(onSuccess).toHaveBeenCalledOnce();+ });+});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.tsxindex 3d796ca04..d19784936 100644--- 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.tsx@@ -54,8 +54,8 @@ vi.mock('@renderer/features/workspaces/workspaces-store', () => ({const SERVER = vi.hoisted(() => ({id: 'srv-1',name: 'switch.example.com',- gatewayUrl: 'https://switch.example.com',- apiUrl: 'https://switch.example.com:8000',+ url: 'https://switch.example.com:8000',+ dashboardUrl: 'https://switch.example.com',}));vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/server-sign-up.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/server-sign-up.test.tsxindex 71bdc617a..839f4be4e 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/server-sign-up.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/server-sign-up.test.tsx@@ -42,8 +42,8 @@ const CLOUD_ORIGIN = 'https://cloud.example.com';const SERVER: SwitchServer = {id: 'server',name: 'Switch',- gatewayUrl: CLOUD_ORIGIN,- apiUrl: CLOUD_ORIGIN,+ url: CLOUD_ORIGIN,+ dashboardUrl: null,} as SwitchServer;let container: HTMLDivElement | null = null;diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/server-view-shared.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/server-view-shared.test.tsxindex a85176693..1ff477590 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/server-view-shared.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/server-view-shared.test.tsx@@ -118,8 +118,8 @@ import '@renderer/index.css';const REMOTE = {id: 'srv-1',name: 'Team Server',- gatewayUrl: 'http://localhost:41000',- apiUrl: 'http://localhost:41001',+ url: 'http://localhost:41001',+ dashboardUrl: 'http://localhost:41000',managed: true,managementKind: 'remote' as const,sshHost: 'vm-1',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.tsxindex 626214fcd..df5c359c6 100644--- 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.tsx@@ -152,8 +152,8 @@ function server(id: string, name: string): SwitchServer {return {id,name,- gatewayUrl: `https://${id}.example.invalid`,- apiUrl: `https://${id}.example.invalid/api`,+ url: `https://${id}.example.invalid/api`,+ dashboardUrl: `https://${id}.example.invalid`,managed: false,managementKind: null,sshHost: null,diff --git a/console/apps/switch-console-desktop/src/renderer/tests/palette-search-utils.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/palette-search-utils.test.tsindex 10fb96ec3..bd8f3df35 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/palette-search-utils.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/tests/palette-search-utils.test.ts@@ -101,8 +101,8 @@ describe('matchRooms', () => {function server(over: Pick<SwitchServer, 'id' | 'name'> & Partial<SwitchServer>): SwitchServer {return {- gatewayUrl: 'https://gateway.example',- apiUrl: 'https://api.example',+ url: 'https://api.example',+ dashboardUrl: 'https://gateway.example',managed: false,managementKind: null,sshHost: null,@@ -115,7 +115,7 @@ function server(over: Pick<SwitchServer, 'id' | 'name'> & Partial<SwitchServer>)describe('matchServers', () => {const SERVERS = [server({ id: 's1', name: 'production' }),- server({ id: 's2', name: 'staging', gatewayUrl: 'https://switch.internal' }),+ server({ id: 's2', name: 'staging', url: 'https://switch.internal' }),];it('matches on name', () => {diff --git a/console/apps/switch-console-desktop/src/shared/core/deeplinks/console-links.ts b/console/apps/switch-console-desktop/src/shared/core/deeplinks/console-links.tsindex d8df6a1e9..238170def 100644--- a/console/apps/switch-console-desktop/src/shared/core/deeplinks/console-links.ts+++ b/console/apps/switch-console-desktop/src/shared/core/deeplinks/console-links.ts@@ -7,7 +7,7 @@* the app on the page; a click inside the app's own chat moves it there* directly.*- * `server` names the Switch server the link means, by its gateway address.+ * `server` names the Switch server the link means, by its address.* Without it the link opens on the server the person is looking at, which is* what an agent wants: it talks to them on that server and does not know the* address Console reaches it by.@@ -61,7 +61,7 @@ export type ConsoleLink = {/** The agent, room or template the page shows; null for a page with no id. */id: string | null;tab: string | null;- /** The gateway address of the server the link means, or null for the current one. */+ /** The address of the server the link means, or null for the current one. */server: string | null;};diff --git a/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.test.ts b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.test.tsnew file mode 100644index 000000000..6f1308e69--- /dev/null+++ b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.test.ts@@ -0,0 +1,19 @@+import { describe, expect, it } from 'vitest';+import { dashboardOrigin } from './switch-servers';++describe('dashboardOrigin', () => {+ it('is the server’s own address when it keeps no dashboard apart', () => {+ expect(dashboardOrigin({ url: 'https://switch.example.com', dashboardUrl: null })).toBe(+ 'https://switch.example.com'+ );+ });++ it('is the separate dashboard address while the server keeps one', () => {+ expect(+ dashboardOrigin({+ url: 'https://switch-api.example.com',+ dashboardUrl: 'https://switch-gateway.example.com',+ })+ ).toBe('https://switch-gateway.example.com');+ });+});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 8cdec4c7e..c36a55f30 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@@ -40,17 +40,47 @@ export function sameApiEndpoint(a: string, b: string): boolean {return a.trim().replace(/\/+$/, '') === b.trim().replace(/\/+$/, '');}+/**+ * One spelling per server address, so two that name the same server compare+ * equal: scheme and host lowercased, a default port dropped, no trailing slash,+ * a path kept. Input that does not parse is only trimmed.+ */+export function normaliseServerUrl(url: string): string {+ const trimmed = url.trim();+ try {+ const parsed = new URL(trimmed);+ return `${parsed.protocol}//${parsed.host}${parsed.pathname}`.replace(/\/+$/, '');+ } catch {+ return trimmed.replace(/\/+$/, '');+ }+}++/** Where a server's dashboard pages open: its own address, unless it still+ * keeps the dashboard elsewhere. */+export function dashboardOrigin(server: Pick<SwitchServer, 'url' | 'dashboardUrl'>): string {+ return server.dashboardUrl ?? server.url;+}+/** A registered Switch server. Non-secret connection metadata only. */export type SwitchServer = {id: string;name: string;- /** Origin of the gateway deployment, e.g. `https://switch-gateway.example.com`.- * The management API lives under `${gatewayUrl}/gateway`. */- gatewayUrl: string;- /** Origin of the Switch core (agent bridge) API, e.g.- * `https://switch-api.example.com` — what an agent's `SWITCH_API_ENDPOINT`- * points at, and what an onboarded agent is matched to its server by. */- apiUrl: string;+ /** The server's one address, e.g. `https://switch.example.com`: the origin+ * of switch-core, which serves the agent API at its root, the management API+ * under `${url}/gateway`, and the dashboard. What an agent's+ * `SWITCH_API_ENDPOINT` points at, and what an onboarded agent is matched to+ * its server by. */+ url: string;+ /** Where the dashboard opens when `url` does not serve it, else null. Open+ * dashboard pages through {@link dashboardOrigin}, never from this directly.+ *+ * A fallback with an end date. A server older than switch-core serving its+ * own dashboard keeps the gateway address it was registered with (migration+ * 0052), cleared once its `url` answers with the dashboard; a managed stack+ * gets its dashboard container's port while the compose it runs still has+ * one. Remove it once Console no longer supports servers that predate the+ * built-in dashboard and the bundled compose no longer runs the container. */+ dashboardUrl: string | null;/** True when Switch Console runs this server itself (docker compose). Managed* servers are driven by the lifecycle controls, not the add/edit-server UI. */managed: boolean;@@ -67,8 +97,15 @@ export type SwitchServer = {export type AddServerParams = {name: string;- gatewayUrl: string;- apiUrl: string;+ url: string;+};++/** What a managed stack registers itself with: its own address, and where its+ * dashboard container answers while it still runs one. */+export type ManagedServerParams = {+ name: string;+ url: string;+ dashboardUrl: string | null;};/** Identifies which managed server to upsert/look up: the single local stack,@@ -78,8 +115,7 @@ export type ManagedServerRef = { kind: 'local' } | { kind: 'remote'; sshHost: stexport type UpdateServerParams = {id: string;name: string;- gatewayUrl: string;- apiUrl: string;+ url: string;};/** Rename a server (display name only). Works for managed and external servers;@@ -90,7 +126,7 @@ export type RenameServerParams = {};/**- * What happened to one agent when a server's API URL was cascaded to its+ * What happened to one agent when a server's address was cascaded to its* members. `updated` — the agent's `SWITCH_API_ENDPOINT` was rewritten.* `not-provisioned` — the agent has no Switch credentials on disk yet, so there* was nothing to update (skipped, not an error). `failed` — the rewrite threw@@ -98,7 +134,7 @@ export type RenameServerParams = {*/export type AgentApiUrlPropagationOutcome = 'updated' | 'not-provisioned' | 'failed';-/** Per-agent result of a server-API-URL cascade. */+/** Per-agent result of a server-address cascade. */export type AgentApiUrlPropagation = {agentId: string;agentName: string;@@ -109,11 +145,11 @@ export type AgentApiUrlPropagation = {error?: string;};-/** Summary of cascading a server's API-URL edit to its member agents. */+/** Summary of cascading a server's address edit to its member agents. */export type ServerApiUrlPropagation = {- /** True when the API URL actually changed, so propagation ran. When false the- * `agents` list is empty (the edit was name/gateway-only). */- apiUrlChanged: boolean;+ /** True when the address actually changed, so propagation ran. When false the+ * `agents` list is empty (the edit was name-only). */+ urlChanged: boolean;agents: AgentApiUrlPropagation[];};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.tsindex ba8bb412b..4f17d93ca 100644--- a/console/apps/switch-console-desktop/src/shared/core/workspaces/invitations.ts+++ b/console/apps/switch-console-desktop/src/shared/core/workspaces/invitations.ts@@ -73,13 +73,14 @@ export function invitationStatus(invitation: Invitation, now: number): Invitatio/*** 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.+ * Built from where the server's dashboard is served, as the dashboard builds it+ * from the page it is on: the link opens the dashboard's invite page, and+ * Switch Console finds the server again from its address. 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)}`;+export function inviteLink(dashboardOrigin: string, token: string): string {+ return `${dashboardOrigin.replace(/\/+$/, '')}/invite#token=${encodeURIComponent(token)}`;}/**diff --git a/console/apps/switch-console-desktop/tooling/fixtures/baseline.db b/console/apps/switch-console-desktop/tooling/fixtures/baseline.dbindex 30615464e..dd1bee76e 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/empty.db b/console/apps/switch-console-desktop/tooling/fixtures/empty.dbindex 6ce3d7ee2..f14e2d434 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/pre-0052.db b/console/apps/switch-console-desktop/tooling/fixtures/pre-0052.dbnew file mode 100644index 000000000..b38fce17dBinary files /dev/null and b/console/apps/switch-console-desktop/tooling/fixtures/pre-0052.db differdiff --git a/console/pnpm-lock.yaml b/console/pnpm-lock.yamlindex dcef7ff62..beb781c98 100644--- a/console/pnpm-lock.yaml+++ b/console/pnpm-lock.yaml@@ -79,6 +79,9 @@ importers:ssh2:specifier: ^1.17.0version: 1.17.0+ tldts:+ specifier: ^7.4.2+ version: 7.4.2zod:specifier: ^4.3.6version: 4.4.3diff --git a/core/switch_core/bridges/agent/app.py b/core/switch_core/bridges/agent/app.pyindex 8e4ebea0f..3c13f1d42 100644--- a/core/switch_core/bridges/agent/app.py+++ b/core/switch_core/bridges/agent/app.py@@ -37,6 +37,7 @@ from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgefrom switch_core.db.stores.external_user_store import ExternalUserStorefrom switch_core.db.stores.room_store import RoomStorefrom switch_core.db.stores.task_store import TaskStore+from switch_core.gateway.ui import GatewayUi, GatewayUiMiddlewarefrom switch_core.logging_context import log_contextfrom switch_core.observability.http import MetricsMiddlewarefrom switch_core.refusal_breaker import RefusalBreaker@@ -70,6 +71,7 @@ def create_agent_bridge_app(approval_outcomes: ApprovalOutcomes,controller_auth: ControllerAuthenticator | None,trust_client: TrustClient,+ gateway_ui: GatewayUi | None,connections: AgentConnectionRegistry | None = None,telemetry: TelemetryService | None = None,) -> tuple[FastAPI, AgentCore]:@@ -180,6 +182,10 @@ def create_agent_bridge_app(# Outside the bearer middleware, so a caller that keeps repeating a refused# request is answered before its credential is looked up again.app.add_middleware(RefusalBreaker, clock=time.monotonic)+ # Outside the bearer middleware and the breaker, because a page load carries+ # a cookie and no agent key; inside the metrics, so page loads are counted.+ if gateway_ui is not None:+ app.add_middleware(GatewayUiMiddleware, ui=gateway_ui, router=app.router)# Outside the bearer middleware, so a request rejected for bad credentials# is still counted and timed — an authentication failure is traffic, and a# spike of it is the thing you most want a dashboard to show.diff --git a/core/switch_core/config.py b/core/switch_core/config.pyindex 3aa7181fc..ddbc632c0 100644--- a/core/switch_core/config.py+++ b/core/switch_core/config.py@@ -11,7 +11,7 @@ from urllib.parse import urlsplitfrom cryptography import x509from cryptography.hazmat.primitives import serializationfrom cryptography.hazmat.primitives.asymmetric import rsa-from pydantic import AliasChoices, BaseModel, Field, model_validator+from pydantic import AliasChoices, BaseModel, Field, field_validator, model_validatorfrom pydantic_settings import BaseSettings, SettingsConfigDictfrom switch_core.feature_flags import (@@ -562,6 +562,24 @@ class SwitchConfig(BaseSettings):# machine dialog shows; unset, it shows no enrollment command.gateway_public_url: str | None = None+ # The operator dashboard's build output (the `dist/` that `npm run build`+ # writes in gateway/). Set, and switch-core serves the dashboard on its own+ # port beside the API, so the server has one address; the image sets it.+ # Unset or empty, it serves no dashboard: a development run uses the Vite+ # dev server instead. Set to a directory with no build in it is a startup+ # error. With it set, links to the dashboard default to GATEWAY_PUBLIC_URL+ # when FRONTEND_BASE_URL is unset (`dashboard_base_url`).+ gateway_ui_dir: Path | None = None++ @field_validator("gateway_ui_dir", mode="before")+ @classmethod+ def _blank_gateway_ui_dir_is_unset(cls, value: object) -> object:+ # `GATEWAY_UI_DIR=` is how an env file or a chart turns it off, and+ # `Path("")` would otherwise be the working directory.+ if isinstance(value, str) and not value.strip():+ return None+ return value+# Credentials of the distributed Slack app *we* registered — the one a# customer installs by clicking a button, as opposed to the app an operator# registers themselves and pastes tokens for. See@@ -1121,6 +1139,29 @@ class SwitchConfig(BaseSettings):def invite_email_enabled(self) -> bool:return bool(self.gateway_smtp_host)+ @property+ def dashboard_base_url(self) -> str | None:+ """The origin links to the dashboard are built on.++ FRONTEND_BASE_URL when set. Otherwise, when switch-core serves the+ dashboard: the host browser sign-in returns to, where one is+ configured, because a sign-in begun anywhere is sent there and leaves+ its session there; and the server's own origin failing that. On a+ server with one address the two are the same host. Not where a sign-in+ lands, which stays on the host that set the session cookie unless+ FRONTEND_BASE_URL names another.+ """+ if self.frontend_base_url:+ return self.frontend_base_url+ if self.gateway_ui_dir is None:+ return None+ if self.gateway_oidc_enabled and self.gateway_oidc_redirect_url:+ callback = urlsplit(self.gateway_oidc_redirect_url)+ return f"{callback.scheme}://{callback.netloc}"+ if self.gateway_public_url:+ return self.gateway_public_url.rstrip("/")+ return None+@model_validator(mode="after")def _validate_smtp(self) -> "SwitchConfig":if self.gateway_invite_emails_per_day < 1:@@ -1140,7 +1181,7 @@ class SwitchConfig(BaseSettings):"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:+ if not self.dashboard_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."diff --git a/core/switch_core/gateway/oidc_routes.py b/core/switch_core/gateway/oidc_routes.pyindex daf8c44f5..5308596a5 100644--- a/core/switch_core/gateway/oidc_routes.py+++ b/core/switch_core/gateway/oidc_routes.py@@ -9,7 +9,7 @@ import reimport timefrom contextlib import AbstractContextManager, nullcontextfrom typing import Annotated, Any-from urllib.parse import urlencode, urlsplit+from urllib.parse import urlencode, urlsplit, urlunsplitimport httpxfrom authlib.integrations.starlette_client import OAuth, OAuthError@@ -43,6 +43,10 @@ router = APIRouter()oauth = OAuth()_CLIENT_NAME = "gateway_oidc"+# Marks the second leg of the hop to the callback's host (`_callback_host_hop`),+# so a proxy that rewrites the Host header costs one redirect and not a loop.+_ON_CALLBACK_HOST = "on_callback_host"+def register_oidc_client(config: SwitchConfig) -> None:"""Register the gateway OIDC client from config.@@ -69,6 +73,49 @@ def _client() -> Any:return client+def _callback_host_hop(request: Request, redirect_url: str | None) -> str | None:+ """Where to restart a sign-in begun on another host than the callback's.++ The flow's state is kept in a cookie on the host the browser starts on, and+ the identity provider returns the browser to `redirect_url`. A server that+ answers on two hosts, its own serving the dashboard beside a separate+ dashboard host the provider still returns to, would lose the state on the+ way back. Hostnames only: a cookie is shared across ports, and a proxy may+ drop the port from the Host header. None to start the flow here.+ """+ if not redirect_url:+ return None+ callback = urlsplit(redirect_url)+ if callback.hostname == request.url.hostname:+ return None+ if request.query_params.get(_ON_CALLBACK_HOST):+ logger.warning(+ "OIDC login reached %s after being sent to %s, the host the identity "+ "provider returns to; a proxy may be rewriting the Host header. "+ "Starting the sign-in here, where it may lose its state on return.",+ request.url.hostname,+ callback.hostname,+ )+ return None+ # The sign-in's own parameters go with it: a sign-in option, or the+ # hand-back to an app on this computer, starts over there unchanged.+ query = [+ (key, value)+ for key, value in request.query_params.multi_items()+ if key != _ON_CALLBACK_HOST+ ]+ query.append((_ON_CALLBACK_HOST, "1"))+ return urlunsplit(+ (+ callback.scheme,+ callback.netloc,+ request.url_for("oidc_login").path,+ urlencode(query),+ "",+ )+ )++# ── Handing a sign-in back to an app on this computer ────────────────────────## Switch Console signs in through the system browser: it listens on the@@ -119,7 +166,7 @@ def _challenge_of(verifier: str) -> str:return base64.urlsafe_b64encode(digest).rstrip(b"=").decode()[email protected]("/auth/oidc/login")[email protected]("/auth/oidc/login", name="oidc_login")async def oidc_login(request: Request,config: Annotated[SwitchConfig, Depends(get_config)],@@ -134,6 +181,9 @@ async def oidc_login(if not config.gateway_oidc_enabled:raise HTTPException(status_code=404, detail="OIDC login is not configured")client = _client()+ hop = _callback_host_hop(request, config.gateway_oidc_redirect_url)+ if hop is not None:+ return RedirectResponse(url=hop, status_code=302)params: dict[str, str] = {}if provider is not None:option = next(@@ -320,7 +370,11 @@ async def oidc_callback()query = urlencode({"code": code, "state": handoff["state"]})return RedirectResponse(url=f"{handoff['return_to']}?{query}", status_code=303)- # Land the browser back on the SPA with our own session cookie set.+ # Land the browser back on the SPA with our own session cookie set: on this+ # host, where the cookie is, unless FRONTEND_BASE_URL names the dashboard's+ # origin. Not `dashboard_base_url`, whose default is the server's public+ # origin, which on a split deployment is not the host the provider+ # returned to.response = RedirectResponse(url=config.frontend_base_url or "/", status_code=303)set_session_cookie(response,diff --git a/core/switch_core/gateway/tenants.py b/core/switch_core/gateway/tenants.pyindex 9d2194781..970c8f3a9 100644--- a/core/switch_core/gateway/tenants.py+++ b/core/switch_core/gateway/tenants.py@@ -622,12 +622,12 @@ async def _deliver_invitation(invitation.tenant_id,)return "not_configured"- assert config.frontend_base_url is not None+ assert config.dashboard_base_url is not Nonetry:await mailer.send_invitation(InviteEmail(to=invitation.email,- link=invite_link(config.frontend_base_url, token),+ link=invite_link(config.dashboard_base_url, token),workspace_name=workspace_name,inviter_name=inviter_name,role=invitation.role,diff --git a/core/switch_core/gateway/ui.py b/core/switch_core/gateway/ui.pynew file mode 100644index 000000000..7252ef48a--- /dev/null+++ b/core/switch_core/gateway/ui.py@@ -0,0 +1,177 @@+"""The operator dashboard, served by switch-core on the API's own origin.++The dashboard is a single-page app: every page is the same `index.html`, and+the browser's router picks what to draw from the path. Serving it here gives a+server one address, the one agents already use, rather than the API on one+origin and the dashboard on another.++It answers ahead of the bearer middleware, because a person loading a page+holds a cookie rather than an agent key. So what it answers is an exact list+and never a fallback: the built files by name, and the dashboard's page paths,+which `test_gateway_ui.py` holds equal to the routes in `gateway/src/App.tsx`.+Everything else passes through untouched.++The API wins any path both could answer. `/agents` is where they meet: the+dashboard has pages at `/agents` and `/agents/{agent_id}`, while the API+registers agents with a POST to `/agents` and also answers GET+`/agents/feature-flags`. So before serving, the middleware asks the app's+router whether an API route takes the request as a GET or a HEAD, and passes+it on if one does. That holds for routes added after the middleware is built, such as+the management and messaging routes `main.run` installs.+"""++from __future__ import annotations++import logging+import re+from dataclasses import dataclass+from pathlib import Path++from starlette.responses import FileResponse+from starlette.routing import Match, Router+from starlette.types import ASGIApp, Receive, Scope, Send++from switch_core.observability.http import GATEWAY_UI_SCOPE_KEY++logger = logging.getLogger(__name__)++# The dashboard's page routes, as `gateway/src/App.tsx` declares them.+PAGE_PATHS: tuple[str, ...] = (+ "/",+ "/login",+ "/invite",+ "/ecosystem",+ "/rooms",+ "/rooms/new",+ "/rooms/groups",+ "/rooms/graph",+ "/rooms/{room_id}",+ "/rooms/{room_id}/documents/{document_id}",+ "/resources",+ "/resources/references/{id}",+ "/resources/documents/{id}",+ "/resources/packages/{id}",+ "/resources/templates/{id}",+ "/agents",+ "/agents/{agent_id}",+ "/machines",+ "/collaborations",+ "/registration-keys",+ "/usage",+ "/users",+ "/connectors",+ "/workspace",+)++_PARAM = re.compile(r"\{[^/}]+\}")++_PAGE_PATTERNS: tuple[re.Pattern[str], ...] = tuple(+ re.compile(+ "^"+ + "/".join(+ "[^/]+" if _PARAM.fullmatch(segment) else re.escape(segment)+ for segment in path.split("/")+ )+ + "$"+ )+ for path in PAGE_PATHS+)++# Vite names every file under `assets/` by its content hash, so a cached copy+# can never be stale. Everything else, `index.html` above all, names whichever+# build is current and must be revalidated.+_HASHED_PREFIX = "/assets/"+_IMMUTABLE = "public, max-age=31536000, immutable"+_REVALIDATE = "no-cache"+++def is_page(path: str) -> bool:+ """Whether `path` is one of the dashboard's pages."""+ if len(path) > 1 and path.endswith("/"):+ path = path[:-1]+ return any(pattern.match(path) for pattern in _PAGE_PATTERNS)+++class GatewayUiNotBuiltError(RuntimeError):+ """The configured directory holds no built dashboard."""+++@dataclass(frozen=True)+class GatewayUi:+ """A built dashboard: its `index.html` and every file beside it, by URL path."""++ index: Path+ files: dict[str, Path]++ @classmethod+ def load(cls, directory: Path) -> GatewayUi:+ """Read the build in `directory` (the dashboard's `dist/`).++ Raises rather than serving nothing: a server told where its dashboard+ is, and finding none, would otherwise answer every page with a 401 from+ the bearer middleware, which reads as a sign-in problem.+ """+ index = directory / "index.html"+ if not index.is_file():+ raise GatewayUiNotBuiltError(+ f"GATEWAY_UI_DIR is {directory}, which has no index.html. Point "+ "it at the dashboard's build output (`npm run build` in "+ "gateway/ writes gateway/dist), or unset it to serve no dashboard."+ )+ files = {+ "/" + path.relative_to(directory).as_posix(): path+ for path in sorted(directory.rglob("*"))+ if path.is_file()+ }+ logger.info("serving the dashboard from %s (%d files)", directory, len(files))+ return cls(index=index, files=files)++ def resolve(self, path: str) -> tuple[Path, str] | None:+ """The file answering `path` and its Cache-Control, or None to pass it on."""+ file = self.files.get(path)+ if file is not None:+ return file, _IMMUTABLE if path.startswith(_HASHED_PREFIX) else _REVALIDATE+ if is_page(path):+ return self.index, _REVALIDATE+ return None+++def _api_answers(router: Router, scope: Scope) -> bool:+ """Whether a route on `router` would take this request as a GET or a HEAD.++ Both, whatever the request's own method: FastAPI gives a GET route no HEAD+ of its own, so a HEAD for an API path would otherwise match only partially+ and be taken for a page, and a route declared for HEAD alone would be+ missed by asking only for GET.+ """+ return any(+ route.matches({**scope, "method": method})[0] is Match.FULL+ for method in ("GET", "HEAD")+ for route in router.routes+ )+++class GatewayUiMiddleware:+ """Answers a GET or HEAD for a dashboard file or page; passes on the rest.++ `router` is the app's own, read on every request rather than copied, so a+ route added once the app is built still takes precedence over a page.+ """++ def __init__(self, app: ASGIApp, ui: GatewayUi, router: Router) -> None:+ self.app = app+ self.ui = ui+ self.router = router++ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:+ if scope["type"] != "http" or scope["method"] not in ("GET", "HEAD"):+ await self.app(scope, receive, send)+ return+ resolved = self.ui.resolve(scope["path"])+ if resolved is None or _api_answers(self.router, scope):+ await self.app(scope, receive, send)+ return+ file, cache_control = resolved+ scope[GATEWAY_UI_SCOPE_KEY] = True+ response = FileResponse(file, headers={"Cache-Control": cache_control})+ await response(scope, receive, send)diff --git a/core/switch_core/main.py b/core/switch_core/main.pyindex fdab837e4..c36762e76 100644--- a/core/switch_core/main.py+++ b/core/switch_core/main.py@@ -180,6 +180,7 @@ from switch_core.delivery.router import GROUP_SWEEP_SECONDS, MessageRouterfrom switch_core.gateway.app import create_gateway_appfrom switch_core.gateway.auth import hash_passwordfrom switch_core.gateway.invite_mail import SmtpInviteMailer+from switch_core.gateway.ui import GatewayUifrom switch_core.logging_config import configure_loggingfrom switch_core.management.wiring import Management, create_managementfrom switch_core.messages.notify import MessageListener@@ -817,7 +818,7 @@ async def run(config: SwitchConfig, process_id: str) -> None:room_role_store=room_role_store,external_user_store=external_user_store,connections=connections,- frontend_base_url=config.frontend_base_url,+ frontend_base_url=config.dashboard_base_url,message_telemetry=message_telemetry,),message_store=message_store,@@ -955,7 +956,7 @@ async def run(config: SwitchConfig, process_id: str) -> None:agent_session_store=agent_session_store,room_service=room_service,connections=connections,- frontend_base_url=config.frontend_base_url,+ frontend_base_url=config.dashboard_base_url,follow_the_conversation_enabled=config.follow_the_conversation_enabled,)@@ -990,6 +991,11 @@ async def run(config: SwitchConfig, process_id: str) -> None:connections=connections,telemetry=telemetry,trust_client=trust_client,+ gateway_ui=(+ GatewayUi.load(config.gateway_ui_dir)+ if config.gateway_ui_dir is not None+ else None+ ),)# Every close reports, whichever of the five paths did it — and only for a# connection the handler saw start.diff --git a/core/switch_core/observability/http.py b/core/switch_core/observability/http.pyindex f071efc05..5e4153585 100644--- a/core/switch_core/observability/http.py+++ b/core/switch_core/observability/http.py@@ -25,6 +25,15 @@ from switch_core.observability.metrics import metrics# endpoint it is attacker-chosen.UNMATCHED_ROUTE = "unmatched"+# Every file and page of the operator dashboard, which switch-core serves ahead+# of its router (`gateway/ui.py`), so no route template is ever set for one. One+# label for all of them: the path is the page, and the page is not this server's+# behaviour.+GATEWAY_UI_ROUTE = "gateway-ui"++# Set on the scope by the dashboard middleware when it answers a request itself.+GATEWAY_UI_SCOPE_KEY = "switch.gateway_ui"+# A request whose response never started — the client went away mid-flight, or# the app raised before sending anything.NO_STATUS = "none"@@ -58,6 +67,8 @@ def route_label(scope: Scope) -> str:the prefix is "already there" looks like a guard but silently drops it fromany inner route whose name starts with the mount's own string."""+ if scope.get(GATEWAY_UI_SCOPE_KEY):+ return GATEWAY_UI_ROUTEroute = scope.get("route")path = getattr(route, "path", None)if not isinstance(path, str) or not path:diff --git a/core/tests/benchmarks/server.py b/core/tests/benchmarks/server.pyindex 25a5b79ca..1e38b99c7 100644--- a/core/tests/benchmarks/server.py+++ b/core/tests/benchmarks/server.py@@ -525,7 +525,7 @@ async def _serve(room_role_store=session_env.room_role_store,external_user_store=session_env.external_user_store,connections=connections,- frontend_base_url=config.frontend_base_url,+ frontend_base_url=config.dashboard_base_url,message_telemetry=message_telemetry,),message_store=session_env.message_store,@@ -639,6 +639,7 @@ async def _serve(approval_outcomes=ApprovalOutcomes(activity_listener, activity),controller_auth=None,trust_client=NullTrustClient(),+ gateway_ui=None,connections=connections,)diff --git a/core/tests/integration/conftest.py b/core/tests/integration/conftest.pyindex 043322545..17880ea16 100644--- a/core/tests/integration/conftest.py+++ b/core/tests/integration/conftest.py@@ -624,7 +624,7 @@ async def harness(room_role_store=session_env.room_role_store,external_user_store=session_env.external_user_store,connections=connections,- frontend_base_url=config.frontend_base_url,+ frontend_base_url=config.dashboard_base_url,message_telemetry=message_telemetry,),message_store=session_env.message_store,diff --git a/core/tests/integration/test_switch_trust_agent_e2e.py b/core/tests/integration/test_switch_trust_agent_e2e.pyindex 89951fdf3..3237d9c93 100644--- a/core/tests/integration/test_switch_trust_agent_e2e.py+++ b/core/tests/integration/test_switch_trust_agent_e2e.py@@ -88,7 +88,7 @@ async def _wire_admin_client(harness: Harness, session_env: SessionEnv) -> None:agent_session_store=session_env.agent_session_store,room_service=harness.room_service,connections=AgentConnectionRegistry(),- frontend_base_url=session_env.config.frontend_base_url,+ frontend_base_url=session_env.config.dashboard_base_url,follow_the_conversation_enabled=False,)await harness.client_lifecycle.ensure_system_client("admin")diff --git a/core/tests/switch_core/gateway/test_gateway_ui.py b/core/tests/switch_core/gateway/test_gateway_ui.pynew file mode 100644index 000000000..4b13c6a50--- /dev/null+++ b/core/tests/switch_core/gateway/test_gateway_ui.py@@ -0,0 +1,373 @@+"""switch-core serves the operator dashboard on the API's own origin.++What matters most is what it must not do: answer a request the API owns. The+dashboard runs ahead of the bearer middleware, so a page path that shadowed an+API route would serve HTML where an agent expects JSON, and would do it without+asking for credentials.+"""++import re+from pathlib import Path++import pytest+from fastapi import FastAPI, Request+from fastapi.responses import JSONResponse+from starlette.testclient import TestClient+from starlette.types import ASGIApp, Receive, Scope, Send++from switch_core.bridges.agent.app import create_agent_bridge_app+from switch_core.bridges.agent.protocol.event_buffer import EventBuffer+from switch_core.gateway.ui import (+ PAGE_PATHS,+ GatewayUi,+ GatewayUiMiddleware,+ GatewayUiNotBuiltError,+ is_page,+)+from switch_core.keys import Keyring+from switch_core.observability.catalogue import HTTP_REQUESTS+from switch_core.observability.http import GATEWAY_UI_ROUTE, MetricsMiddleware+from switch_core.observability.metrics import MetricsRegistry, install, uninstall+from switch_core.trust.client import NullTrustClient+from tests.db_buffer import QuietRooms++_APP_TSX = Path(__file__).resolve().parents[4] / "gateway/src/App.tsx"++_INDEX = "<!doctype html><title>dashboard</title>"+_SCRIPT = "console.log('dashboard')"+_LOGO = "<svg/>"+++def dist(tmp_path: Path) -> Path:+ (tmp_path / "assets").mkdir()+ (tmp_path / "index.html").write_text(_INDEX)+ (tmp_path / "assets/index-3f9a1c.js").write_text(_SCRIPT)+ (tmp_path / "switch_logo_dark.svg").write_text(_LOGO)+ return tmp_path+++class _RejectEverything:+ """Stands in for the bearer middleware: nothing gets past without a key."""++ def __init__(self, app: ASGIApp) -> None:+ self.app = app++ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:+ if scope["type"] != "http":+ await self.app(scope, receive, send)+ return+ await JSONResponse({"detail": "unauthorized"}, status_code=401)(+ scope, receive, send+ )+++def _app(dist: Path) -> FastAPI:+ app = FastAPI()++ @app.post("/agents")+ async def register(request: Request) -> dict[str, str]:+ return {"registered": "yes"}++ @app.get("/rooms/special")+ async def special() -> dict[str, str]:+ return {"api": "yes"}++ app.add_middleware(_RejectEverything)+ app.add_middleware(GatewayUiMiddleware, ui=GatewayUi.load(dist), router=app.router)+ return app+++def _client(dist: Path) -> TestClient:+ return TestClient(_app(dist))+++# ── Which paths are pages ────────────────────────────────────────────────────+++def _normalized(path: str) -> str:+ return re.sub(r"\{[^}]+\}", "{}", path)+++def _app_tsx_routes() -> set[str]:+ """Every page route `gateway/src/App.tsx` declares, as an absolute template."""+ source = _APP_TSX.read_text()+ routes = {"/"} if re.search(r"<Route\s+index\b", source) else set()+ for path in re.findall(r'<Route\b[^>]*?\bpath="([^"]+)"', source, re.DOTALL):+ if path == "*":+ continue+ absolute = path if path.startswith("/") else f"/{path}"+ routes.add(re.sub(r":[A-Za-z_]+", "{}", absolute))+ return routes+++def test_the_page_list_is_exactly_the_dashboards_routes() -> None:+ declared = _app_tsx_routes()+ listed = {_normalized(path) for path in PAGE_PATHS}+ assert declared, "found no routes in gateway/src/App.tsx; has it moved?"+ assert listed == declared, (+ "PAGE_PATHS in switch_core/gateway/ui.py must match the routes in "+ f"gateway/src/App.tsx. Missing: {sorted(declared - listed)}; "+ f"not in the dashboard: {sorted(listed - declared)}."+ )+++ "path",+ [+ "/",+ "/login",+ "/rooms",+ "/rooms/",+ "/rooms/new",+ "/rooms/4b1d",+ "/rooms/4b1d/documents/77",+ "/resources/templates/9",+ "/agents",+ "/agents/4b1d",+ "/workspace",+ ],+)+def test_a_dashboard_path_is_a_page(path: str) -> None:+ assert is_page(path)+++ "path",+ [+ "/agents/4b1d/events",+ "/agents/4b1d/connection/ws",+ "/rooms/4b1d/members",+ "/health",+ "/mcp",+ "/gateway/rooms",+ "/v1/management/controllers",+ "/version",+ "",+ ],+)+def test_any_other_path_is_not_a_page(path: str) -> None:+ assert not is_page(path)+++def _agent_bridge_app(gateway_ui: GatewayUi | None) -> FastAPI:+ class _Config:+ agent_auth_cache_ttl_seconds = 1+ agent_auth_cache_max_entries = 16+ keyring = Keyring.parse("test:" + "x" * 40, legacy_secret=None)+ oauth_issuer_url = None+ oauth_audience = None+ oauth_verify_issuer = True+ id_server_name = "test"+ service_connections_enabled = True++ app, _ = create_agent_bridge_app(+ agent_store=object(), # type: ignore[arg-type]+ agent_session_store=object(), # type: ignore[arg-type]+ room_store=object(), # type: ignore[arg-type]+ room_service=object(), # type: ignore[arg-type]+ client_lifecycle=object(), # type: ignore[arg-type]+ collab_lifecycle=object(), # type: ignore[arg-type]+ event_buffer=EventBuffer(object(), sequence_base=0, rooms=QuietRooms()), # type: ignore[arg-type]+ task_store=object(), # type: ignore[arg-type]+ resource_service=object(), # type: ignore[arg-type]+ api_key_store=object(), # type: ignore[arg-type]+ external_user_store=object(), # type: ignore[arg-type]+ bridge_store=object(), # type: ignore[arg-type]+ session_factory=object(),+ config=_Config(), # type: ignore[arg-type]+ approval_outcomes=object(), # type: ignore[arg-type]+ controller_auth=None,+ trust_client=NullTrustClient(),+ gateway_ui=gateway_ui,+ )+ return app+++def test_the_api_wins_a_path_both_could_answer(dist: Path) -> None:+ # `/rooms/special` fits the dashboard's `/rooms/{room_id}`, but the app has+ # a GET route there, so it reaches the app (here, a rejection) and is never+ # served the page.+ assert _client(dist).get("/rooms/special").status_code == 401+ assert _client(dist).head("/rooms/special").status_code == 401+++def test_a_route_added_after_the_middleware_still_wins(dist: Path) -> None:+ app = _app(dist)+ client = TestClient(app)+ assert client.get("/rooms/later").text == _INDEX++ @app.get("/rooms/later")+ async def later() -> dict[str, str]:+ return {"api": "yes"}++ assert client.get("/rooms/later").status_code == 401+++def test_a_route_declared_for_head_alone_still_wins(dist: Path) -> None:+ app = _app(dist)++ @app.api_route("/rooms/probe", methods=["HEAD"])+ async def probe() -> None:+ return None++ client = TestClient(app)+ assert client.head("/rooms/probe").status_code == 401+ assert client.get("/rooms/probe").status_code == 401+++def test_the_agent_apis_own_get_under_agents_is_not_a_page(dist: Path) -> None:+ # The one place the API and the dashboard meet today: `/agents/{agent_id}`+ # is a page, and the API answers GET `/agents/feature-flags`.+ client = TestClient(_agent_bridge_app(gateway_ui=GatewayUi.load(dist)))+ response = client.get("/agents/feature-flags")+ assert response.status_code == 401+ assert response.text != _INDEX+++# ── Loading a build ──────────────────────────────────────────────────────────+++def test_a_directory_with_no_build_is_refused(tmp_path: Path) -> None:+ with pytest.raises(GatewayUiNotBuiltError, match="GATEWAY_UI_DIR"):+ GatewayUi.load(tmp_path)+++def test_a_missing_directory_is_refused(tmp_path: Path) -> None:+ with pytest.raises(GatewayUiNotBuiltError, match="no index.html"):+ GatewayUi.load(tmp_path / "absent")+++def test_a_path_that_climbs_out_of_the_build_resolves_to_nothing(dist: Path) -> None:+ # Only exact names are served, so there is nothing to climb with; the HTTP+ # client would normalise the dots away before sending, so this asks directly.+ ui = GatewayUi.load(dist)+ assert ui.resolve("/assets/../index.html") is None+ assert ui.resolve("/../index.html") is None+++def test_every_built_file_is_indexed_by_its_url_path(dist: Path) -> None:+ ui = GatewayUi.load(dist)+ assert set(ui.files) == {+ "/index.html",+ "/assets/index-3f9a1c.js",+ "/switch_logo_dark.svg",+ }+ assert ui.index == dist / "index.html"+++# ── Serving ──────────────────────────────────────────────────────────────────+++ "path", ["/", "/rooms", "/rooms/4b1d", "/agents", "/agents/4b1d", "/login"]+)+def test_a_page_is_the_index_and_is_always_revalidated(dist: Path, path: str) -> None:+ response = _client(dist).get(path)+ assert response.status_code == 200+ assert response.text == _INDEX+ assert response.headers["content-type"].startswith("text/html")+ assert response.headers["cache-control"] == "no-cache"+++def test_a_hashed_asset_is_cached_for_good(dist: Path) -> None:+ response = _client(dist).get("/assets/index-3f9a1c.js")+ assert response.status_code == 200+ assert response.text == _SCRIPT+ assert "javascript" in response.headers["content-type"]+ assert response.headers["cache-control"] == "public, max-age=31536000, immutable"+++def test_an_unhashed_file_is_revalidated(dist: Path) -> None:+ response = _client(dist).get("/switch_logo_dark.svg")+ assert response.status_code == 200+ assert response.text == _LOGO+ assert response.headers["cache-control"] == "no-cache"+++def test_a_head_request_gets_headers_and_no_body(dist: Path) -> None:+ response = _client(dist).head("/rooms")+ assert response.status_code == 200+ assert response.content == b""+ assert response.headers["content-length"] == str(len(_INDEX))+++ "path",+ [+ "/agents/4b1d/events",+ "/health",+ "/mcp",+ "/assets/missing.js",+ "/rooms/4b1d/members",+ ],+)+def test_a_get_the_dashboard_does_not_own_reaches_the_api(+ dist: Path, path: str+) -> None:+ response = _client(dist).get(path)+ assert response.status_code == 401+ assert response.json() == {"detail": "unauthorized"}++[email protected]("method", ["POST", "PUT", "DELETE", "PATCH"])+def test_only_a_read_is_answered_at_a_page_path(dist: Path, method: str) -> None:+ # `/agents` is where an agent registers, with a POST.+ response = _client(dist).request(method, "/agents")+ assert response.status_code == 401+++# ── On the real agent bridge app ─────────────────────────────────────────────+++def test_the_agent_bridge_serves_pages_without_a_key(dist: Path) -> None:+ client = TestClient(_agent_bridge_app(gateway_ui=GatewayUi.load(dist)))+ for path in ("/", "/agents", "/agents/4b1d", "/rooms/4b1d"):+ response = client.get(path)+ assert response.status_code == 200, path+ assert response.text == _INDEX+++def test_the_agent_bridge_still_demands_a_key_for_the_api(dist: Path) -> None:+ client = TestClient(_agent_bridge_app(gateway_ui=GatewayUi.load(dist)))+ assert client.post("/agents", json={}).status_code == 401+ assert client.get("/agents/4b1d/events").status_code == 401+ assert client.get("/version").status_code == 401+++def test_without_a_build_the_agent_bridge_serves_no_pages() -> None:+ client = TestClient(_agent_bridge_app(gateway_ui=None))+ assert client.get("/").status_code == 401+ assert client.get("/rooms").status_code == 401+++# ── Metrics ──────────────────────────────────────────────────────────────────+++def registry():+ registry = MetricsRegistry()+ install(registry)+ yield registry+ uninstall()+++def test_every_page_load_is_counted_under_one_label(+ dist: Path, registry: MetricsRegistry+) -> None:+ app = FastAPI()+ app.add_middleware(_RejectEverything)+ app.add_middleware(GatewayUiMiddleware, ui=GatewayUi.load(dist), router=app.router)+ app.add_middleware(MetricsMiddleware)+ client = TestClient(app)+ for path in ("/rooms/a", "/rooms/b", "/assets/index-3f9a1c.js", "/agents/c"):+ client.get(path)++ payload = next(p for p in registry.collect() if p.name == HTTP_REQUESTS.name)+ counts = {+ point.attributes["route"]: point.value+ for point in payload.numbers+ if point.attributes["status_class"] == "2xx"+ }+ # A label per page would be a series per room id.+ assert counts == {GATEWAY_UI_ROUTE: 4.0}diff --git a/core/tests/switch_core/gateway/test_oidc_routes.py b/core/tests/switch_core/gateway/test_oidc_routes.pyindex a804b7939..44143e9a5 100644--- a/core/tests/switch_core/gateway/test_oidc_routes.py+++ b/core/tests/switch_core/gateway/test_oidc_routes.py@@ -2,12 +2,16 @@ from __future__ import annotationsimport jsonfrom types import SimpleNamespace+from urllib.parse import parse_qs, urlsplitimport httpximport pytest-from fastapi import HTTPException+from fastapi import FastAPI, HTTPExceptionfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker+from starlette.middleware.sessions import SessionMiddleware+from starlette.responses import RedirectResponse+from starlette.testclient import TestClientimport switch_core.gateway.oidc_routes as oidc_routesfrom switch_core.config import SwitchConfig@@ -21,6 +25,7 @@ from switch_core.db.models import (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+from switch_core.gateway.dependencies import get_configdef _tenant_claim(set_cookie: str) -> str | None:@@ -832,6 +837,138 @@ class TestAuthConfigEndpoint:assert result.signup_mode == "invite_only"+class _FakeAuthorize:+ """Stands in for the authlib OIDC client at the login."""++ def __init__(self) -> None:+ self.redirect_uris: list[str] = []++ async def authorize_redirect(+ self, _request: object, redirect_uri: str, **_params: str+ ) -> RedirectResponse:+ self.redirect_uris.append(redirect_uri)+ return RedirectResponse("https://idp.example/authorize", status_code=302)+++class TestTheLoginStartsOnTheCallbacksHost:+ """The flow's state cookie must be on the host the provider returns to.++ A server serving its dashboard on its own address may still have a separate+ dashboard host that the identity provider returns to; a login begun on the+ server's own host is first sent there.+ """++ _CALLBACK = "https://switch-dashboard.example.com/gateway/auth/oidc/callback"++ def _client(+ self,+ monkeypatch: pytest.MonkeyPatch,+ host: str,+ redirect_url: str | None,+ ) -> tuple[TestClient, _FakeAuthorize]:+ fake = _FakeAuthorize()+ monkeypatch.setattr(oidc_routes, "_client", lambda: fake)+ config = _config(gateway_oidc_redirect_url=redirect_url)+ gateway = FastAPI()+ gateway.include_router(oidc_routes.router)+ gateway.dependency_overrides[get_config] = lambda: config+ gateway.add_middleware(SessionMiddleware, secret_key="test")+ app = FastAPI()+ app.mount("/gateway", gateway)+ return TestClient(app, base_url=host, follow_redirects=False), fake++ def test_a_login_on_another_host_is_sent_to_the_callbacks(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ client, fake = self._client(+ monkeypatch, "https://switch.example.com", self._CALLBACK+ )+ response = client.get("/gateway/auth/oidc/login")+ assert response.status_code == 302+ assert response.headers["location"] == (+ "https://switch-dashboard.example.com/gateway/auth/oidc/login"+ "?on_callback_host=1"+ )+ assert fake.redirect_uris == []++ def test_the_sign_ins_own_parameters_go_with_it(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ # Switch Console's hand-back to this computer, and a sign-in option,+ # must reach the host the sign-in really starts on.+ client, fake = self._client(+ monkeypatch, "https://switch.example.com", self._CALLBACK+ )+ response = client.get(+ "/gateway/auth/oidc/login",+ params={+ "provider": "google",+ "return_to": "http://127.0.0.1:5123/switch-sign-in",+ "state": "s" * 16,+ "challenge": "c" * 43,+ },+ )+ location = urlsplit(response.headers["location"])+ assert (location.netloc, location.path) == (+ "switch-dashboard.example.com",+ "/gateway/auth/oidc/login",+ )+ assert parse_qs(location.query) == {+ "provider": ["google"],+ "return_to": ["http://127.0.0.1:5123/switch-sign-in"],+ "state": ["s" * 16],+ "challenge": ["c" * 43],+ "on_callback_host": ["1"],+ }+ assert fake.redirect_uris == []++ def test_a_login_on_the_callbacks_host_starts_there(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ client, fake = self._client(+ monkeypatch, "https://switch-dashboard.example.com", self._CALLBACK+ )+ response = client.get("/gateway/auth/oidc/login")+ assert response.headers["location"] == "https://idp.example/authorize"+ assert fake.redirect_uris == [self._CALLBACK]++ def test_another_port_on_the_same_host_is_the_same_host(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ # A cookie is shared across ports, and a proxy may drop the port from+ # the Host header; sending the browser on would only loop.+ client, fake = self._client(+ monkeypatch,+ "http://localhost:8000",+ "http://localhost:3000/gateway/auth/oidc/callback",+ )+ client.get("/gateway/auth/oidc/login")+ assert fake.redirect_uris == [+ "http://localhost:3000/gateway/auth/oidc/callback"+ ]++ def test_a_proxy_rewriting_the_host_costs_one_hop_not_a_loop(+ self, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture+ ) -> None:+ client, fake = self._client(+ monkeypatch, "http://switch-core:8000", self._CALLBACK+ )+ with caplog.at_level("WARNING", logger=oidc_routes.__name__):+ response = client.get("/gateway/auth/oidc/login?on_callback_host=1")+ assert response.headers["location"] == "https://idp.example/authorize"+ assert fake.redirect_uris == [self._CALLBACK]+ assert "rewriting the Host header" in caplog.text++ def test_without_a_configured_callback_the_login_starts_where_it_is(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ client, fake = self._client(monkeypatch, "https://switch.example.com", None)+ client.get("/gateway/auth/oidc/login")+ assert fake.redirect_uris == [+ "https://switch.example.com/gateway/auth/oidc/callback"+ ]++_GOOGLE = {"id": "google", "label": "Google", "params": {"provider": "GoogleOAuth"}}_VERIFIER = "v" * 43diff --git a/core/tests/switch_core/gateway/test_tenant_api_routes.py b/core/tests/switch_core/gateway/test_tenant_api_routes.pyindex e5936bdff..9f77511eb 100644--- a/core/tests/switch_core/gateway/test_tenant_api_routes.py+++ b/core/tests/switch_core/gateway/test_tenant_api_routes.py@@ -172,7 +172,7 @@ def _app(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/",+ dashboard_base_url="https://switch.example.com/",)return appdiff --git a/core/tests/switch_core/management/test_middleware.py b/core/tests/switch_core/management/test_middleware.pyindex adeab0150..d82289628 100644--- a/core/tests/switch_core/management/test_middleware.py+++ b/core/tests/switch_core/management/test_middleware.py@@ -319,6 +319,7 @@ class TestTheFlagOff:approval_outcomes=object(), # type: ignore[arg-type]controller_auth=None,trust_client=NullTrustClient(),+ gateway_ui=None,)paths = [getattr(route, "path", "") for route in app.routes]assert pathsdiff --git a/core/tests/switch_core/telemetry/test_emitters_are_live.py b/core/tests/switch_core/telemetry/test_emitters_are_live.pyindex 4f41407d5..baae2a4d2 100644--- a/core/tests/switch_core/telemetry/test_emitters_are_live.py+++ b/core/tests/switch_core/telemetry/test_emitters_are_live.py@@ -64,6 +64,7 @@ def _build(telemetry: TelemetryService) -> Any:approval_outcomes=object(), # type: ignore[arg-type]controller_auth=None,trust_client=NullTrustClient(),+ gateway_ui=None,telemetry=telemetry,)return protocoldiff --git a/core/tests/switch_core/test_config_gateway_ui_dir.py b/core/tests/switch_core/test_config_gateway_ui_dir.pynew file mode 100644index 000000000..e1dc6871a--- /dev/null+++ b/core/tests/switch_core/test_config_gateway_ui_dir.py@@ -0,0 +1,123 @@+from pathlib import Path++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",+ id_server_name="switch.local",+ agent_registration_token="token",+ secret_keys="test:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",+ gateway_admin_email="[email protected]",+ gateway_admin_password="pw",+)+++def test_unset_serves_no_dashboard() -> None:+ assert SwitchConfig(**_BASE_KWARGS).gateway_ui_dir is None # type: ignore[arg-type]+++def test_read_from_the_environment_as_a_path(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("GATEWAY_UI_DIR", "/app/gateway-ui")+ config = SwitchConfig(**_BASE_KWARGS) # type: ignore[arg-type]+ assert config.gateway_ui_dir == Path("/app/gateway-ui")++[email protected]("blank", ["", " "])+def test_an_empty_value_serves_no_dashboard(+ monkeypatch: pytest.MonkeyPatch, blank: str+) -> None:+ # `Path("")` is the working directory; an env file's `GATEWAY_UI_DIR=` means off.+ monkeypatch.setenv("GATEWAY_UI_DIR", blank)+ assert SwitchConfig(**_BASE_KWARGS).gateway_ui_dir is None # type: ignore[arg-type]+++def _config(**overrides: object) -> SwitchConfig:+ return SwitchConfig(**{**_BASE_KWARGS, **overrides}) # type: ignore[arg-type]+++def test_the_dashboard_origin_defaults_to_the_servers_own() -> None:+ config = _config(+ gateway_ui_dir="/app/gateway-ui",+ gateway_public_url="https://switch.example.com/",+ )+ assert config.dashboard_base_url == "https://switch.example.com"+++def test_the_dashboard_origin_follows_the_host_sign_in_returns_to() -> None:+ # A sign-in begun on the server's own origin is sent on to the callback's+ # host and leaves its session there, so links there find it signed in.+ config = _config(+ gateway_ui_dir="/app/gateway-ui",+ gateway_public_url="https://switch-api.example.com",+ gateway_oidc_issuer_url="https://idp.example.com",+ gateway_oidc_client_id="cid",+ gateway_oidc_client_secret="secret",+ gateway_oidc_scopes="openid email profile",+ gateway_oidc_redirect_url="https://switch.example.com/gateway/auth/oidc/callback",+ )+ assert config.dashboard_base_url == "https://switch.example.com"+++def test_a_callback_without_sign_in_configured_moves_nothing() -> None:+ config = _config(+ gateway_ui_dir="/app/gateway-ui",+ gateway_public_url="https://switch-api.example.com",+ gateway_oidc_redirect_url="https://switch.example.com/gateway/auth/oidc/callback",+ )+ assert config.dashboard_base_url == "https://switch-api.example.com"+++def test_the_default_does_not_move_where_a_sign_in_lands() -> None:+ # A browser sign-in lands on FRONTEND_BASE_URL when one is set, and on the+ # host that set its cookie otherwise. A split deployment's public origin+ # need not be that host, so the default leaves FRONTEND_BASE_URL unset.+ config = _config(+ gateway_ui_dir="/app/gateway-ui",+ gateway_public_url="https://switch-api.example.com",+ )+ assert config.frontend_base_url is None+++def test_a_named_dashboard_origin_is_kept() -> None:+ config = _config(+ gateway_ui_dir="/app/gateway-ui",+ gateway_public_url="https://switch-api.example.com",+ frontend_base_url="https://switch-gateway.example.com",+ )+ assert config.dashboard_base_url == "https://switch-gateway.example.com"+++def test_no_dashboard_origin_is_assumed_when_switch_core_serves_none() -> None:+ config = _config(gateway_public_url="https://switch.example.com")+ assert config.dashboard_base_url is None+++def test_no_dashboard_origin_is_assumed_without_a_public_origin() -> None:+ assert _config(gateway_ui_dir="/app/gateway-ui").dashboard_base_url is None+++def test_invitation_mail_is_satisfied_by_the_servers_own_origin() -> None:+ # The SMTP check requires a dashboard origin to link to; the default is in+ # place before it runs.+ config = _config(+ gateway_ui_dir="/app/gateway-ui",+ gateway_public_url="https://switch.example.com",+ gateway_smtp_host="smtp.example.com",+ gateway_smtp_from="Switch <[email protected]>",+ )+ assert config.dashboard_base_url == "https://switch.example.com"+++def test_invitation_mail_still_requires_a_dashboard_origin_otherwise() -> None:+ with pytest.raises(ValueError, match="FRONTEND_BASE_URL is required"):+ _config(+ gateway_public_url="https://switch.example.com",+ gateway_smtp_host="smtp.example.com",+ gateway_smtp_from="Switch <[email protected]>",+ )diff --git a/core/tests/switch_core/test_ingress_agent_api_paths.py b/core/tests/switch_core/test_ingress_agent_api_paths.pyindex bb05c4f7a..0d85f6125 100644--- a/core/tests/switch_core/test_ingress_agent_api_paths.py+++ b/core/tests/switch_core/test_ingress_agent_api_paths.py@@ -65,6 +65,7 @@ def _served_prefixes() -> set[str]:approval_outcomes=object(), # type: ignore[arg-type]controller_auth=None,trust_client=NullTrustClient(),+ gateway_ui=None,)prefixes = set(_ADDED_IN_MAIN)# The agents controller's routes join the agent bridge app only when agentdiff --git a/deploy/remote/helm/switch/README.md b/deploy/remote/helm/switch/README.mdindex 98e4252de..b0b1c377a 100644--- a/deploy/remote/helm/switch/README.md+++ b/deploy/remote/helm/switch/README.md@@ -142,7 +142,9 @@ Full walkthrough, including the Azure side:with your own manifest; [`samples/ingress.example.yaml`](samples/ingress.example.yaml)is copy-pasteable.- **`managed`** — the chart renders one path-routed Ingress on `ingress.host`:- `agentApiPaths` to switch-core, everything else to the gateway SPA.+ `agentApiPaths` to switch-core, everything else to the gateway SPA — or, with+ `gateway.enabled: false`, everything to switch-core, which serves the+ dashboard itself. That drops the separate gateway Deployment.`switchCore.teamsBridge.ingress.mode` is independent of this — `dedicated` worksunder either.diff --git a/deploy/remote/helm/switch/samples/ingress.example.yaml b/deploy/remote/helm/switch/samples/ingress.example.yamlindex 93045386b..d3c2e51da 100644--- a/deploy/remote/helm/switch/samples/ingress.example.yaml+++ b/deploy/remote/helm/switch/samples/ingress.example.yaml@@ -12,7 +12,9 @@## Routing mirrors the managed Ingress: the agent/MCP surface goes to# switch-core; everything else (the gateway SPA, which proxies /gateway to-# switch-core) goes to the gateway.+# switch-core) goes to the gateway. With `gateway.enabled=false` there is no+# gateway Service: send `/` to switch-core too, which serves the dashboard and+# /gateway itself (see the last path below).apiVersion: networking.k8s.io/v1kind: Ingressmetadata:@@ -92,6 +94,8 @@ spec:- path: /api/teams/notificationspathType: Prefixbackend: { service: { name: RELEASE-switch-core, port: { number: 3978 } } }+ # With gateway.enabled=false:+ # backend: { service: { name: RELEASE-switch-core, port: { number: 8000 } } }- path: /pathType: Prefixbackend: { service: { name: RELEASE-gateway, port: { number: 3000 } } }diff --git a/deploy/remote/helm/switch/templates/NOTES.txt b/deploy/remote/helm/switch/templates/NOTES.txtindex 4dad7bf24..22aa30048 100644--- a/deploy/remote/helm/switch/templates/NOTES.txt+++ b/deploy/remote/helm/switch/templates/NOTES.txt@@ -4,11 +4,11 @@ To check pod status:kubectl get pods -n {{ .Release.Namespace }}To access services via port-forward:-+{{ if .Values.gateway.enabled }}# Gateway (dashboard)kubectl port-forward svc/{{ include "switch.fullname" . }}-gateway 3000:3000 -n {{ .Release.Namespace }}-- # Switch Core (API)+{{ end }}+ # Switch Core (API{{ if not .Values.gateway.enabled }} and dashboard{{ end }})kubectl port-forward svc/{{ include "switch.fullname" . }}-switch-core 8000:8000 -n {{ .Release.Namespace }}# Mattermostdiff --git a/deploy/remote/helm/switch/templates/_helpers.tpl b/deploy/remote/helm/switch/templates/_helpers.tplindex 93e2f264f..0a82cc7b9 100644--- a/deploy/remote/helm/switch/templates/_helpers.tpl+++ b/deploy/remote/helm/switch/templates/_helpers.tpl@@ -837,10 +837,13 @@ this one. Drop it once the oldest supported image reads ID_SERVER_NAME. */}}- name: FEATURE_FLAGS_ENABLEDvalue: {{ join "," . | quote }}{{- end }}+{{- if not (or .Values.gateway.enabled .Values.switchCore.serveDashboard) }}+{{- fail "gateway.enabled and switchCore.serveDashboard are both off, so nothing serves the operator dashboard. Turn one of them on." }}+{{- end }}{{- 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." }}+{{- if not (or $.Values.switchCore.frontendBaseUrl (and $.Values.switchCore.serveDashboard $.Values.switchCore.gatewayPublicUrl)) }}+{{- fail "switchCore.frontendBaseUrl is required when switchCore.smtp.enabled — invitation e-mails link to the dashboard at that origin. (With switchCore.serveDashboard on, switchCore.gatewayPublicUrl does instead.)" }}{{- end }}{{- if not (has .tls (list "starttls" "tls" "none")) }}{{- fail (printf "switchCore.smtp.tls must be one of starttls, tls, none. Got %q." .tls) }}@@ -943,6 +946,11 @@ this one. Drop it once the oldest supported image reads ID_SERVER_NAME. */}}- name: GATEWAY_PUBLIC_URLvalue: {{ .Values.switchCore.gatewayPublicUrl | quote }}{{- end }}+{{- if not .Values.switchCore.serveDashboard }}+{{- /* The image points it at its dashboard build; empty serves none. */}}+- name: GATEWAY_UI_DIR+ value: ""+{{- end }}{{- if or .Values.switchCore.slackApp.enabled .Values.switchCore.discordApp.enabled .Values.switchCore.teamsApp.enabled .Values.switchCore.telegramApp.enabled }}- name: MESSAGING_PUBLIC_URLvalue: {{ required "switchCore.messagingPublicUrl is required when a distributed messaging app is enabled" (include "switch.messagingPublicUrl" .) | quote }}diff --git a/deploy/remote/helm/switch/templates/common/generic-ingress.yaml b/deploy/remote/helm/switch/templates/common/generic-ingress.yamlindex e4a53aeda..e8f5a4d21 100644--- a/deploy/remote/helm/switch/templates/common/generic-ingress.yaml+++ b/deploy/remote/helm/switch/templates/common/generic-ingress.yaml@@ -4,9 +4,10 @@# Generic Ingress for the Switch web surface (ingress.mode=managed).## One host, path-routed. The agent/MCP surface goes straight to switch-core;-# everything else (the gateway SPA, which itself proxies /gateway to-# switch-core) goes to the gateway. Bring your own ingress-# controller: set ingress.className, ingress.host and, for HTTPS, ingress.tls.+# everything else goes to the gateway (the dashboard SPA, which itself proxies+# /gateway to switch-core), or with gateway.enabled=false to switch-core, which+# serves the dashboard too. Bring your own ingress controller: set+# ingress.className, ingress.host and, for HTTPS, ingress.tls.## ingress.mode=existing renders nothing — see samples/ingress.example.yaml for# a copy-pasteable manifest to hand to your own controller instead.@@ -69,7 +70,13 @@ spec:pathType: Prefixbackend:service:+ {{- if .Values.gateway.enabled }}name: {{ $svcGateway }}port:number: {{ .Values.gateway.service.port }}+ {{- else }}+ name: {{ $svcCore }}+ port:+ number: {{ .Values.switchCore.service.port }}+ {{- end }}{{- end }}diff --git a/deploy/remote/helm/switch/templates/gateway/configmap-nginx.yaml b/deploy/remote/helm/switch/templates/gateway/configmap-nginx.yamlindex b549039b8..412d2dc27 100644--- a/deploy/remote/helm/switch/templates/gateway/configmap-nginx.yaml+++ b/deploy/remote/helm/switch/templates/gateway/configmap-nginx.yaml@@ -1,3 +1,4 @@+{{- if .Values.gateway.enabled }}apiVersion: v1kind: ConfigMapmetadata:@@ -29,3 +30,4 @@ data:try_files $uri $uri/ /index.html;}}+{{- end }}diff --git a/deploy/remote/helm/switch/templates/gateway/deployment.yaml b/deploy/remote/helm/switch/templates/gateway/deployment.yamlindex 90b37df63..bb992d145 100644--- a/deploy/remote/helm/switch/templates/gateway/deployment.yaml+++ b/deploy/remote/helm/switch/templates/gateway/deployment.yaml@@ -1,3 +1,4 @@+{{- if .Values.gateway.enabled }}apiVersion: apps/v1kind: Deploymentmetadata:@@ -51,3 +52,4 @@ spec:- name: nginx-configconfigMap:name: {{ include "switch.fullname" . }}-gateway-nginx+{{- end }}diff --git a/deploy/remote/helm/switch/templates/gateway/service.yaml b/deploy/remote/helm/switch/templates/gateway/service.yamlindex 9e3ae359a..0b2b265b7 100644--- a/deploy/remote/helm/switch/templates/gateway/service.yaml+++ b/deploy/remote/helm/switch/templates/gateway/service.yaml@@ -1,3 +1,4 @@+{{- if .Values.gateway.enabled }}apiVersion: v1kind: Servicemetadata:@@ -14,3 +15,4 @@ spec:name: httpselector:{{- include "switch.selectorLabels" (dict "Release" .Release "component" "gateway") | nindent 4 }}+{{- end }}diff --git a/deploy/remote/helm/switch/values.yaml b/deploy/remote/helm/switch/values.yamlindex 20271fee7..0ede8437f 100644--- a/deploy/remote/helm/switch/values.yaml+++ b/deploy/remote/helm/switch/values.yaml@@ -310,6 +310,8 @@ switchCore:enabled: true# Public base URL the gateway is served on (used for links / OIDC redirects).+ # Empty while serveDashboard is on, links to the dashboard use+ # gatewayPublicUrl, and a sign-in lands back on the host that set its cookie.frontendBaseUrl: ""# Public origin (scheme + host, no path) of the gateway HTTP API itself, used# to build the switchdash:// deeplink HTTP redirect so the "Open in Switch@@ -317,6 +319,13 @@ switchCore:# platforms. Leave empty to# post the raw switchdash:// deeplink.gatewayPublicUrl: ""+ # switch-core serves the operator dashboard on its own port beside the API,+ # from the build in its image. Its pages answer without credentials, as the+ # gateway's do, and include /agents and /agents/<id>, which agentApiPaths+ # route to switch-core. Turn it off to keep switch-core to the API, e.g. where+ # its host is public and the dashboard is not; gateway.enabled must then+ # stay on, or there is no dashboard at all.+ serveDashboard: true# Set the Secure flag on the switch_auth session cookie. True here because the# gateway is served over HTTPS (ALB / Tailscale); keep false only for plain-HTTP# local dev.@@ -695,7 +704,19 @@ switchCore:cpu: "1000m"# ── Gateway (React + nginx) ──────────────────────────────────────────────────+# A separate container serving the operator dashboard and forwarding /gateway+# to switch-core. switch-core now serves the same dashboard itself, on its own+# port, so the server has one address; set enabled: false to drop this+# Deployment, and with ingress.mode=managed the Ingress then sends every path+# to switch-core. Left on by default so the chart renders what it did before.+#+# While both run, a hard refresh of /agents or /agents/<id> (agentApiPaths, so+# switch-core) loads switch-core's copy of the page, which then fetches its+# hashed /assets/* from this container. That holds while both images are built+# from one commit, as a published chart pins them; pin this image and+# switchCore's to different releases and those pages load blank.gateway:+ enabled: trueimage: gateway:latest# Empty: IfNotPresent when the image is pinned by digest (as in a published# chart), Always otherwise. Set it to override.diff --git a/deploy/shared_resources/images/Dockerfile.switch b/deploy/shared_resources/images/Dockerfile.switchindex ba30be209..00a44a106 100644--- a/deploy/shared_resources/images/Dockerfile.switch+++ b/deploy/shared_resources/images/Dockerfile.switch@@ -1,3 +1,16 @@+# The operator dashboard, which switch-core serves on its own port beside the+# API (`GATEWAY_UI_DIR`), so a server has one address. The same build steps as+# Dockerfile.gateway, but run on the build host's own platform rather than+# under emulation for each target: the output is static files, the same for+# every architecture the image targets.+FROM --platform=$BUILDPLATFORM node:22-alpine@sha256:c610fcdfb1d5b4740dd70c284ed3cb16bb857e0f7166196e36a5501df7a3aa32 AS gateway-ui++WORKDIR /gateway+COPY gateway/package.json gateway/package-lock.json ./+RUN npm ci+COPY gateway/ .+RUN npm run build+FROM python:3.12-slim# Pin uv and install exactly what uv.lock resolves, so the image matches what@@ -34,6 +47,9 @@ COPY core/README.md ./RUN uv sync --frozen --no-dev+COPY --from=gateway-ui /gateway/dist /app/gateway-ui+ENV GATEWAY_UI_DIR=/app/gateway-ui+# The commit and repository this image was built from, reported with every# metric and log so two builds of the same version can be told apart. Declared# last so a new commit does not invalidate the layers above. Left empty, thediff --git a/docs/old/GATEWAY_OIDC_SETUP.md b/docs/old/GATEWAY_OIDC_SETUP.mdindex 90782577c..1eea74af8 100644--- a/docs/old/GATEWAY_OIDC_SETUP.md+++ b/docs/old/GATEWAY_OIDC_SETUP.md@@ -82,6 +82,14 @@ value registered with the IdP **character for character** — scheme, host,port and path — or the provider refuses the callback before Switch ever seesit.+The login route keeps the flow's state in a cookie on the host sign-in runs+on, so it has to run on the host the provider returns to. When this variable is+set and a sign-in starts on another host, the login route first redirects to+this URL's host and starts there. A server serving its own dashboard has one+address, and that is normally the host to put here. A server still split+across two hosts can keep the redirect URL on the dashboard's host until that+host is retired; then move it (here and at the IdP) to the server's own address.+### What turning off email-verified enforcement meansBy default, a login is refused unless the IdP's token assertsdiff --git a/docs/old/LOCAL_DEVELOPMENT.md b/docs/old/LOCAL_DEVELOPMENT.mdindex feba83cad..5b9bad6d3 100644--- a/docs/old/LOCAL_DEVELOPMENT.md+++ b/docs/old/LOCAL_DEVELOPMENT.md@@ -119,11 +119,17 @@ The operator dashboard you'd open in a browser is a separate Vite devserver, started with `just gateway-dev` (`cd gateway && npm run dev`), and itlistens on **`:5173`**, not `:8000`. Forget to start it and there is simplynothing at `localhost:5173`; go to `localhost:8000` instead expecting a UI-and you get switch-core's raw JSON API responses — it never serves the-dashboard's static assets, in dev or otherwise. In a standalone or Helm-deployment the dashboard is served by yet another process (the `gateway`-image, a separate container), so this is a permanent split, not a dev-mode-shortcut: switch-core is the API, something else is always the UI.+and you get switch-core's raw JSON API responses.++That is a development default, not how a deployed server works. switch-core+serves the dashboard itself, on its own port beside the API, whenever+`GATEWAY_UI_DIR` names a built dashboard — and the server image sets it, so a+deployed server has one address for everything. To get the same in dev, build+the dashboard once (`cd gateway && npm run build`) and run with+`GATEWAY_UI_DIR=gateway/dist`; Vite stays the way to work on the dashboard+itself, because it reloads as you edit. The separate `gateway` image (an nginx+container serving the same build and forwarding `/gateway` to switch-core)+still works in standalone and Helm deployments, but nothing needs it any more.The Vite dev server proxies every `/gateway/*` request to`http://127.0.0.1:8000` (see `gateway/vite.config.ts`), so from the browser's@@ -139,7 +145,7 @@ any CORS configuration: as far as the browser can tell, it never left| URL | What's there | Started by || --- | --- | --- || `http://localhost:5173` | The operator dashboard (Vite dev server). Open this in a browser. | `just gateway-dev` |-| `http://localhost:8000` | switch-core: the Agent Bridge API, the MCP server, and the gateway management API under `/gateway/*`. JSON, not a UI. | `just run` |+| `http://localhost:8000` | switch-core: the Agent Bridge API, the MCP server, and the gateway management API under `/gateway/*`. Also the dashboard when `GATEWAY_UI_DIR` points at a build; otherwise JSON, not a UI. | `just run` || `http://localhost:8081` | switch-core's collaboration callback listener — where Mattermost delivers a button press. Bound only once a bridge asks to be called back, so it is often not there at all. | `just run` || `http://localhost:8065` | Mattermost, seeded as the local collaboration bridge. | `just up` || `http://localhost:5432` | PostgreSQL. | `just up` |@@ -151,45 +157,31 @@ dashboard, such as the OIDC login redirect — it should match wherever## Connecting Switch Console to your local server-Switch Console (the desktop app) talks to a Switch server over two-addresses: a **Gateway URL** and an **API URL** — see [Add a-server](../official/getting-started/add-a-server.md) for what each field-means in general. They are not the same address in local dev, and getting-either one wrong fails in a way that points somewhere else:--- **API URL** is `http://localhost:8000` — switch-core directly. This is the- address Console writes into each connected agent's own config as the- endpoint it registers against and talks to (the Agent Bridge / MCP- surface), so it always names switch-core itself.-- **Gateway URL** is `http://localhost:5173` — the Vite dev server, **not**- `:8000`. Console uses this address for everything session-cookie-based:- its own calls into `/gateway/*` (signing in, listing agents and rooms),- the **Open** button under "Full admin interface" (which opens this exact- URL in your browser), and the periodic check that decides whether the- server shows as reachable. `just gateway-dev` has to be running for any of- that to work — Vite's `/gateway` proxy is what makes `:5173` stand in for- switch-core's session-authenticated surface, the same way it does for the- browser dashboard above.--Setting the Gateway URL to `:8000` looks reasonable, since switch-core does-answer `/gateway/*` on that port directly, but it hits the thing this page-already warned about: switch-core never serves the dashboard's static-assets. The reachability check still passes — `/gateway/*` genuinely-answers on `:8000` — so the only symptom is the **Open** button loading a-bare JSON response instead of the admin UI; nothing on the server list looks-wrong.--The opposite mistake is quieter and easier to hit by accident: forget to-start `just gateway-dev`, and there is nothing at `:5173` to answer the-Gateway URL check, so Console reports the **whole server** as unreachable —-even though switch-core (`just run`) is healthy and the API URL is-answering fine. The symptom points at the backend; the actual cause is the-frontend dev server not running.+Switch Console (the desktop app) connects to a Switch server by one address:+switch-core's. In local dev that is **`http://localhost:8000`**. Console+writes it into each connected agent's own config as the endpoint it+registers against (the Agent Bridge / MCP surface), calls the gateway+management API under `/gateway/*` on it (signing in, listing agents and+rooms, the reachability check), and opens dashboard pages on it — the+**Open** button under "Full admin interface", and links to rooms and agents.++Those dashboard pages are the one thing that needs more than `just run`:+switch-core serves them only when `GATEWAY_UI_DIR` names a built dashboard+(see above). Without it, everything else works and the **Open** button loads+a bare JSON response instead of the admin UI. Either run with+`GATEWAY_UI_DIR=gateway/dist` after building the dashboard, or open the Vite+dev server at `localhost:5173` in a browser yourself.++If you paste `http://localhost:5173` by mistake, Console refuses it when you+save, because it answers with a web page rather than the API.In Switch Console, add a server, choose **Connect to an existing server**,-and enter `http://localhost:5173` as the Gateway URL and-`http://localhost:8000` as the API URL — with `just gateway-dev` already-running.+and enter `http://localhost:8000`.++A server saved by an older Console with two addresses keeps working: its API+address became its one address, and the old Gateway URL is kept, out of+sight, for opening dashboard pages until the server serves its own dashboard+and the old address stops answering.## A local Switch Cloud@@ -214,7 +206,10 @@ just local-cloud-console # the Console, with Switch Cloud at http://localhost:80`http://localhost:8000`, so pasting one into the Console's "Paste yourinvite 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.+ it, so they open switch-core's JSON rather than the dashboard unless+ switch-core is serving it: build it (`just gateway-build`) and run+ `GATEWAY_UI_DIR=gateway/dist just local-cloud`, and they open the dashboard+ on `:8000`, as they do on a deployed Cloud.- **Joining by domain** is offered only for the domain of the admin's ownaddress: `switch.local` for the default admin. Give test accountsaddresses there.diff --git a/gateway/vite.config.ts b/gateway/vite.config.tsindex 968d05af6..487f8c33e 100644--- a/gateway/vite.config.ts+++ b/gateway/vite.config.ts@@ -8,7 +8,10 @@ export default defineConfig({proxy: {"/gateway": {target: "http://127.0.0.1:8000",- changeOrigin: true,+ // Keep the browser's Host, as the gateway container's nginx does:+ // switch-core starts a sign-in on the callback's host when the request+ // names another, so a rewritten Host costs every sign-in a redirect.+ changeOrigin: false,},},},