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
Revert the Console workspaces series (#516–#521, CHOO-2702) (#551)
Louis Amaudruzcbf6ec4c6bac
diff --git a/console/.gitignore b/console/.gitignoreindex 234ec9fc2..a8e608708 100644--- a/console/.gitignore+++ b/console/.gitignore@@ -115,5 +115,4 @@ apps/*/tooling/node-deps/node_modules/# Vitest / Browser testing.vitest-attachments/-.vitest/**/__screenshots__/diff --git a/console/agents/architecture/data-model.md b/console/agents/architecture/data-model.mdindex 2fd1788bc..e071bffc5 100644--- a/console/agents/architecture/data-model.md+++ b/console/agents/architecture/data-model.md@@ -23,8 +23,7 @@ The schema is defined in `apps/switch-console-desktop/src/main/db/schema.ts`.| **session** | `conversation` | One instantiation/run of an agent. The unit shown under an agent in the sidebar. || **message** | `message` | A message in a session (was keyed by `conversationId`, now `sessionId`). || *(removed)* | `session` (worktree-era) | The upstream parallel-run grouping. Removed — Switch Console runs every session in the location's directory, so the grouping layer is gone. |-| *(removed)* | `workspace` | The upstream execution-location abstraction (worktree / SSH / BYOI remote). Removed — see below. Switch Console has a `workspaces` table again, but it names something unrelated: a tenant on a Switch server. |-| **workspace** | *(none)* — new | A tenant on a Switch server, and what the window is scoped to. An agent belongs to one; every gateway call is made in its name. The table is `workspaces`. |+| *(removed)* | `workspace` | The upstream execution-location abstraction (worktree / SSH / BYOI remote). Removed — see below. |### Tables with no upstream equivalent@@ -33,7 +32,6 @@ These carry the Switch- and remote-specific state that upstream had no concept o| Table | What it is ||---|---|| `switch_servers` | A Switch server Switch Console talks to, managed or external. |-| `workspaces` | A tenant on one of those servers. Registering a server creates its first, tenant-less and named after the server. Agents reference it, and the active selection (`kv`, `activeWorkspaceId`) names one. || `remote_hosts` | An SSH host (keyed by its `~/.ssh/config` alias) that can run agents. || `remote_host_reachability` | The last observed reachability of a host. Separate from the host record so a probe result never masquerades as configuration — see the reachability note below. || `remote_host_setup_plans` | A host's onboarding plan (CHOO-1809). See "Remote host setup". |@@ -54,11 +52,6 @@ location (a working directory, local or on an SSH host)A location that lives on an SSH host references a `remote_hosts` row; that host carriesits own reachability and setup-plan rows alongside, not inside, the location hierarchy.-An agent also references the workspace it belongs to, which is not part of this-hierarchy: a location is where an agent runs, a workspace is who it runs as. One-directory can hold agents belonging to different workspaces, and a workspace's-agents can be spread across directories and hosts.-A session's room connection is a row keyed by `session_id` with`ON DELETE CASCADE`, so it cannot outlive the session (or the agent above it).It was previously a JSON blob in `app_settings`, which referenced nothing and so@@ -67,14 +60,12 @@ agents whose Switch server had been destroyed.## What we deliberately dropped from upstream, and why-- **The upstream workspace abstraction.** (Not to be confused with Switch- Console's own `workspaces` table above, which reuses the name for a tenant on- a Switch server and has nothing to do with this.) Upstream modelled+- **The `workspaces` table and the workspace abstraction.** Upstream modelled*where* a session runs (git worktree, project-SSH, BYOI remote). Switch Console hadalready gutted this before the rework — `workspace-config` reached v3 with thenote *"Switch Console has no git worktrees, branches, PRs, or BYOI: every sessionruns in the project root directory."* A workspace was therefore just "the- project directory" plus lifecycle scripts. We dropped it (and+ project directory" plus lifecycle scripts. We dropped the table (and`project.repositoryWorkspaceId` / `session.workspaceId`) and keep lifecyclescripts / fs access as a service hung off the location's directory.diff --git a/console/apps/switch-console-desktop/drizzle/0051_workspaces.sql b/console/apps/switch-console-desktop/drizzle/0051_workspaces.sqldeleted file mode 100644index 9ecb019bf..000000000--- a/console/apps/switch-console-desktop/drizzle/0051_workspaces.sql+++ /dev/null@@ -1,71 +0,0 @@--- Workspaces: what the window is scoped to, one level below a server.------ Each existing server gets exactly one workspace, and that workspace REUSES--- THE SERVER'S ID. That is what makes the upgrade invisible: every server id--- already persisted elsewhere — agents.server_id, the active-server kv value,--- and the opaque navigation snapshots under `view-state:` — stays valid when--- read as a workspace id, so nothing has to be rewritten or reconciled. New--- workspaces discovered from a gateway get fresh ids.------ tenant_id stays NULL for these rows: no gateway has been asked yet, and the--- upgrade must not depend on one being reachable. The first reconcile matches--- each row to a tenant, keeping the id so the agents pointing at it still do.-CREATE TABLE `workspaces` (- `id` text PRIMARY KEY NOT NULL,- `server_id` text NOT NULL,- `name` text NOT NULL,- `tenant_id` text,- `slug` text,- `role` text,- `created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,- `updated_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,- FOREIGN KEY (`server_id`) REFERENCES `switch_servers`(`id`) ON UPDATE no action ON DELETE cascade-);---> statement-breakpoint-CREATE INDEX `idx_workspaces_server_id` ON `workspaces` (`server_id`);--> statement-breakpoint-CREATE UNIQUE INDEX `idx_workspaces_server_tenant` ON `workspaces` (`server_id`,`tenant_id`);--> statement-breakpoint-CREATE UNIQUE INDEX `idx_workspaces_server_placeholder` ON `workspaces` (`server_id`) WHERE `tenant_id` IS NULL;--> statement-breakpoint-INSERT INTO `workspaces` (`id`, `server_id`, `name`, `tenant_id`, `slug`, `role`)- SELECT `id`, `id`, `name`, NULL, NULL, NULL FROM `switch_servers`;---> statement-breakpoint--- Re-point agents at workspaces via the SQLite table-recreation dance rather--- than DROP COLUMN: `server_id` carries a foreign key, and SQLite refuses to--- drop a column named in one. Runs with foreign_keys=OFF inside the migration--- transaction, so dropping and renaming does not disturb the sessions FK, which--- tracks the table name. The workspace id equals the old server id, so the--- carry-over is a straight copy — except that `server_id` was added by--- ALTER TABLE ADD COLUMN, which in SQLite cannot carry an ON DELETE clause, so--- its set-null was never enforced by the engine and a row may point at a server--- that is gone. Copying such a value would seed the new, real foreign key with a--- violation that foreign_keys=OFF lets straight through, so it is dropped to--- NULL here — the same "unlinked" state the app already handles.-CREATE TABLE `__new_agents` (- `id` text PRIMARY KEY NOT NULL,- `location_id` text NOT NULL,- `name` text NOT NULL,- `provider_id` text NOT NULL,- `switch_agent_id` text,- `api_endpoint` text,- `workspace_id` text,- `status` text,- `auto_approve` integer DEFAULT false NOT NULL,- `owner_name` text,- `provider_config` text,- `created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,- `updated_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,- FOREIGN KEY (`location_id`) REFERENCES `locations`(`id`) ON UPDATE no action ON DELETE no action,- FOREIGN KEY (`workspace_id`) REFERENCES `workspaces`(`id`) ON UPDATE no action ON DELETE set null-);--> statement-breakpoint-INSERT INTO `__new_agents` (`id`, `location_id`, `name`, `provider_id`, `switch_agent_id`, `api_endpoint`, `workspace_id`, `status`, `auto_approve`, `owner_name`, `provider_config`, `created_at`, `updated_at`)- SELECT `id`, `location_id`, `name`, `provider_id`, `switch_agent_id`, `api_endpoint`,- CASE WHEN `server_id` IN (SELECT `id` FROM `workspaces`) THEN `server_id` END,- `status`, `auto_approve`, `owner_name`, `provider_config`, `created_at`, `updated_at` FROM `agents`;---> statement-breakpoint-DROP TABLE `agents`;--> statement-breakpoint-ALTER TABLE `__new_agents` RENAME TO `agents`;--> statement-breakpoint-CREATE INDEX `idx_agents_location_id` ON `agents` (`location_id`);--> statement-breakpoint-CREATE INDEX `idx_agents_workspace_id` ON `agents` (`workspace_id`);--> statement-breakpoint-INSERT INTO `kv` (`key`, `value`)- SELECT 'activeWorkspaceId', `value` FROM `kv` WHERE `key` = 'activeSwitchServerId';---> statement-breakpoint-DELETE FROM `kv` WHERE `key` = 'activeSwitchServerId';diff --git a/console/apps/switch-console-desktop/drizzle/meta/0051_snapshot.json b/console/apps/switch-console-desktop/drizzle/meta/0051_snapshot.jsondeleted file mode 100644index 5f301abe2..000000000--- a/console/apps/switch-console-desktop/drizzle/meta/0051_snapshot.json+++ /dev/null@@ -1,978 +0,0 @@-{- "version": "6",- "dialect": "sqlite",- "id": "a44f0db7-1021-46dc-90e6-810d28551f3a",- "prevId": "9bf29a0b-5aea-41b1-8394-0475326b97f7",- "tables": {- "agents": {- "name": "agents",- "columns": {- "id": {- "name": "id",- "type": "text",- "primaryKey": true,- "notNull": true,- "autoincrement": false- },- "location_id": {- "name": "location_id",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false- },- "name": {- "name": "name",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false- },- "provider_id": {- "name": "provider_id",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false- },- "switch_agent_id": {- "name": "switch_agent_id",- "type": "text",- "primaryKey": false,- "notNull": false,- "autoincrement": false- },- "api_endpoint": {- "name": "api_endpoint",- "type": "text",- "primaryKey": false,- "notNull": false,- "autoincrement": false- },- "workspace_id": {- "name": "workspace_id",- "type": "text",- "primaryKey": false,- "notNull": false,- "autoincrement": false- },- "status": {- "name": "status",- "type": "text",- "primaryKey": false,- "notNull": false,- "autoincrement": false- },- "auto_approve": {- "name": "auto_approve",- "type": "integer",- "primaryKey": false,- "notNull": true,- "autoincrement": false,- "default": false- },- "owner_name": {- "name": "owner_name",- "type": "text",- "primaryKey": false,- "notNull": false,- "autoincrement": false- },- "provider_config": {- "name": "provider_config",- "type": "text",- "primaryKey": false,- "notNull": false,- "autoincrement": false- },- "created_at": {- "name": "created_at",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false,- "default": "CURRENT_TIMESTAMP"- },- "updated_at": {- "name": "updated_at",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false,- "default": "CURRENT_TIMESTAMP"- }- },- "indexes": {- "idx_agents_location_id": {- "name": "idx_agents_location_id",- "columns": ["location_id"],- "isUnique": false- },- "idx_agents_workspace_id": {- "name": "idx_agents_workspace_id",- "columns": ["workspace_id"],- "isUnique": false- }- },- "foreignKeys": {- "agents_location_id_locations_id_fk": {- "name": "agents_location_id_locations_id_fk",- "tableFrom": "agents",- "tableTo": "locations",- "columnsFrom": ["location_id"],- "columnsTo": ["id"],- "onDelete": "no action",- "onUpdate": "no action"- },- "agents_workspace_id_workspaces_id_fk": {- "name": "agents_workspace_id_workspaces_id_fk",- "tableFrom": "agents",- "tableTo": "workspaces",- "columnsFrom": ["workspace_id"],- "columnsTo": ["id"],- "onDelete": "set null",- "onUpdate": "no action"- }- },- "compositePrimaryKeys": {},- "uniqueConstraints": {},- "checkConstraints": {}- },- "app_secrets": {- "name": "app_secrets",- "columns": {- "key": {- "name": "key",- "type": "text",- "primaryKey": true,- "notNull": true,- "autoincrement": false- },- "secret": {- "name": "secret",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false- }- },- "indexes": {- "idx_app_secrets_key": {- "name": "idx_app_secrets_key",- "columns": ["key"],- "isUnique": true- }- },- "foreignKeys": {},- "compositePrimaryKeys": {},- "uniqueConstraints": {},- "checkConstraints": {}- },- "app_settings": {- "name": "app_settings",- "columns": {- "key": {- "name": "key",- "type": "text",- "primaryKey": true,- "notNull": true,- "autoincrement": false- },- "value": {- "name": "value",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false- },- "updated_at": {- "name": "updated_at",- "type": "integer",- "primaryKey": false,- "notNull": true,- "autoincrement": false,- "default": "CURRENT_TIMESTAMP"- }- },- "indexes": {- "idx_app_settings_key": {- "name": "idx_app_settings_key",- "columns": ["key"],- "isUnique": true- }- },- "foreignKeys": {},- "compositePrimaryKeys": {},- "uniqueConstraints": {},- "checkConstraints": {}- },- "kv": {- "name": "kv",- "columns": {- "key": {- "name": "key",- "type": "text",- "primaryKey": true,- "notNull": true,- "autoincrement": false- },- "value": {- "name": "value",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false- },- "updated_at": {- "name": "updated_at",- "type": "integer",- "primaryKey": false,- "notNull": true,- "autoincrement": false,- "default": "CURRENT_TIMESTAMP"- }- },- "indexes": {- "idx_kv_key": {- "name": "idx_kv_key",- "columns": ["key"],- "isUnique": true- }- },- "foreignKeys": {},- "compositePrimaryKeys": {},- "uniqueConstraints": {},- "checkConstraints": {}- },- "location_settings": {- "name": "location_settings",- "columns": {- "location_id": {- "name": "location_id",- "type": "text",- "primaryKey": true,- "notNull": true,- "autoincrement": false- },- "base_settings_json": {- "name": "base_settings_json",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false,- "default": "'{}'"- },- "shareable_settings_json": {- "name": "shareable_settings_json",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false,- "default": "'{}'"- },- "legacy_config_migrated_at": {- "name": "legacy_config_migrated_at",- "type": "text",- "primaryKey": false,- "notNull": false,- "autoincrement": false- },- "created_at": {- "name": "created_at",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false,- "default": "CURRENT_TIMESTAMP"- },- "updated_at": {- "name": "updated_at",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false,- "default": "CURRENT_TIMESTAMP"- }- },- "indexes": {},- "foreignKeys": {- "location_settings_location_id_locations_id_fk": {- "name": "location_settings_location_id_locations_id_fk",- "tableFrom": "location_settings",- "tableTo": "locations",- "columnsFrom": ["location_id"],- "columnsTo": ["id"],- "onDelete": "cascade",- "onUpdate": "no action"- }- },- "compositePrimaryKeys": {},- "uniqueConstraints": {},- "checkConstraints": {}- },- "locations": {- "name": "locations",- "columns": {- "id": {- "name": "id",- "type": "text",- "primaryKey": true,- "notNull": true,- "autoincrement": false- },- "name": {- "name": "name",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false- },- "ssh_host": {- "name": "ssh_host",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false,- "default": "''"- },- "dir": {- "name": "dir",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false- },- "created_at": {- "name": "created_at",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false,- "default": "CURRENT_TIMESTAMP"- },- "updated_at": {- "name": "updated_at",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false,- "default": "CURRENT_TIMESTAMP"- }- },- "indexes": {- "idx_locations_host_dir": {- "name": "idx_locations_host_dir",- "columns": ["ssh_host", "dir"],- "isUnique": true- }- },- "foreignKeys": {},- "compositePrimaryKeys": {},- "uniqueConstraints": {},- "checkConstraints": {}- },- "messages": {- "name": "messages",- "columns": {- "id": {- "name": "id",- "type": "text",- "primaryKey": true,- "notNull": true,- "autoincrement": false- },- "session_id": {- "name": "session_id",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false- },- "content": {- "name": "content",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false- },- "sender": {- "name": "sender",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false- },- "timestamp": {- "name": "timestamp",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false,- "default": "CURRENT_TIMESTAMP"- },- "metadata": {- "name": "metadata",- "type": "text",- "primaryKey": false,- "notNull": false,- "autoincrement": false- }- },- "indexes": {- "idx_messages_session_id": {- "name": "idx_messages_session_id",- "columns": ["session_id"],- "isUnique": false- },- "idx_messages_timestamp": {- "name": "idx_messages_timestamp",- "columns": ["timestamp"],- "isUnique": false- }- },- "foreignKeys": {- "messages_session_id_sessions_id_fk": {- "name": "messages_session_id_sessions_id_fk",- "tableFrom": "messages",- "tableTo": "sessions",- "columnsFrom": ["session_id"],- "columnsTo": ["id"],- "onDelete": "cascade",- "onUpdate": "no action"- }- },- "compositePrimaryKeys": {},- "uniqueConstraints": {},- "checkConstraints": {}- },- "remote_host_reachability": {- "name": "remote_host_reachability",- "columns": {- "ssh_host": {- "name": "ssh_host",- "type": "text",- "primaryKey": true,- "notNull": true,- "autoincrement": false- },- "status": {- "name": "status",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false,- "default": "'unknown'"- },- "last_error": {- "name": "last_error",- "type": "text",- "primaryKey": false,- "notNull": false,- "autoincrement": false- },- "last_checked_at": {- "name": "last_checked_at",- "type": "text",- "primaryKey": false,- "notNull": false,- "autoincrement": false- },- "last_reachable_at": {- "name": "last_reachable_at",- "type": "text",- "primaryKey": false,- "notNull": false,- "autoincrement": false- },- "consecutive_failures": {- "name": "consecutive_failures",- "type": "integer",- "primaryKey": false,- "notNull": true,- "autoincrement": false,- "default": 0- },- "updated_at": {- "name": "updated_at",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false,- "default": "CURRENT_TIMESTAMP"- }- },- "indexes": {},- "foreignKeys": {},- "compositePrimaryKeys": {},- "uniqueConstraints": {},- "checkConstraints": {}- },- "remote_host_setup_plans": {- "name": "remote_host_setup_plans",- "columns": {- "ssh_host": {- "name": "ssh_host",- "type": "text",- "primaryKey": true,- "notNull": true,- "autoincrement": false- },- "status": {- "name": "status",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false,- "default": "'idle'"- },- "steps": {- "name": "steps",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false- },- "current_step_id": {- "name": "current_step_id",- "type": "text",- "primaryKey": false,- "notNull": false,- "autoincrement": false- },- "created_at": {- "name": "created_at",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false,- "default": "CURRENT_TIMESTAMP"- },- "updated_at": {- "name": "updated_at",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false,- "default": "CURRENT_TIMESTAMP"- }- },- "indexes": {},- "foreignKeys": {},- "compositePrimaryKeys": {},- "uniqueConstraints": {},- "checkConstraints": {}- },- "remote_hosts": {- "name": "remote_hosts",- "columns": {- "ssh_host": {- "name": "ssh_host",- "type": "text",- "primaryKey": true,- "notNull": true,- "autoincrement": false- },- "name": {- "name": "name",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false- },- "created_at": {- "name": "created_at",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false,- "default": "CURRENT_TIMESTAMP"- },- "updated_at": {- "name": "updated_at",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false,- "default": "CURRENT_TIMESTAMP"- }- },- "indexes": {},- "foreignKeys": {},- "compositePrimaryKeys": {},- "uniqueConstraints": {},- "checkConstraints": {}- },- "session_room_connections": {- "name": "session_room_connections",- "columns": {- "session_id": {- "name": "session_id",- "type": "text",- "primaryKey": true,- "notNull": true,- "autoincrement": false- },- "room_id": {- "name": "room_id",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false- },- "room_name": {- "name": "room_name",- "type": "text",- "primaryKey": false,- "notNull": false,- "autoincrement": false- },- "switch_agent_id": {- "name": "switch_agent_id",- "type": "text",- "primaryKey": false,- "notNull": false,- "autoincrement": false- },- "updated_at": {- "name": "updated_at",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false,- "default": "CURRENT_TIMESTAMP"- }- },- "indexes": {},- "foreignKeys": {- "session_room_connections_session_id_sessions_id_fk": {- "name": "session_room_connections_session_id_sessions_id_fk",- "tableFrom": "session_room_connections",- "tableTo": "sessions",- "columnsFrom": ["session_id"],- "columnsTo": ["id"],- "onDelete": "cascade",- "onUpdate": "no action"- }- },- "compositePrimaryKeys": {},- "uniqueConstraints": {},- "checkConstraints": {}- },- "sessions": {- "name": "sessions",- "columns": {- "id": {- "name": "id",- "type": "text",- "primaryKey": true,- "notNull": true,- "autoincrement": false- },- "agent_id": {- "name": "agent_id",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false- },- "title": {- "name": "title",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false- },- "config": {- "name": "config",- "type": "text",- "primaryKey": false,- "notNull": false,- "autoincrement": false- },- "status": {- "name": "status",- "type": "text",- "primaryKey": false,- "notNull": false,- "autoincrement": false- },- "agent_status": {- "name": "agent_status",- "type": "text",- "primaryKey": false,- "notNull": false,- "autoincrement": false- },- "agent_status_seen": {- "name": "agent_status_seen",- "type": "integer",- "primaryKey": false,- "notNull": false,- "autoincrement": false,- "default": 1- },- "is_initial_session": {- "name": "is_initial_session",- "type": "integer",- "primaryKey": false,- "notNull": false,- "autoincrement": false- },- "is_pinned": {- "name": "is_pinned",- "type": "integer",- "primaryKey": false,- "notNull": true,- "autoincrement": false,- "default": 0- },- "archived_at": {- "name": "archived_at",- "type": "text",- "primaryKey": false,- "notNull": false,- "autoincrement": false- },- "last_interacted_at": {- "name": "last_interacted_at",- "type": "text",- "primaryKey": false,- "notNull": false,- "autoincrement": false- },- "status_changed_at": {- "name": "status_changed_at",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false,- "default": "CURRENT_TIMESTAMP"- },- "created_at": {- "name": "created_at",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false,- "default": "CURRENT_TIMESTAMP"- },- "updated_at": {- "name": "updated_at",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false,- "default": "CURRENT_TIMESTAMP"- }- },- "indexes": {- "idx_sessions_agent_id": {- "name": "idx_sessions_agent_id",- "columns": ["agent_id"],- "isUnique": false- }- },- "foreignKeys": {- "sessions_agent_id_agents_id_fk": {- "name": "sessions_agent_id_agents_id_fk",- "tableFrom": "sessions",- "tableTo": "agents",- "columnsFrom": ["agent_id"],- "columnsTo": ["id"],- "onDelete": "cascade",- "onUpdate": "no action"- }- },- "compositePrimaryKeys": {},- "uniqueConstraints": {},- "checkConstraints": {}- },- "switch_servers": {- "name": "switch_servers",- "columns": {- "id": {- "name": "id",- "type": "text",- "primaryKey": true,- "notNull": true,- "autoincrement": false- },- "name": {- "name": "name",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false- },- "gateway_url": {- "name": "gateway_url",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false- },- "api_url": {- "name": "api_url",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false- },- "managed": {- "name": "managed",- "type": "integer",- "primaryKey": false,- "notNull": true,- "autoincrement": false,- "default": false- },- "management_kind": {- "name": "management_kind",- "type": "text",- "primaryKey": false,- "notNull": false,- "autoincrement": false- },- "ssh_host": {- "name": "ssh_host",- "type": "text",- "primaryKey": false,- "notNull": false,- "autoincrement": false- },- "created_at": {- "name": "created_at",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false,- "default": "CURRENT_TIMESTAMP"- },- "updated_at": {- "name": "updated_at",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false,- "default": "CURRENT_TIMESTAMP"- }- },- "indexes": {- "idx_switch_servers_gateway_url": {- "name": "idx_switch_servers_gateway_url",- "columns": ["gateway_url"],- "isUnique": true- }- },- "foreignKeys": {},- "compositePrimaryKeys": {},- "uniqueConstraints": {},- "checkConstraints": {}- },- "workspaces": {- "name": "workspaces",- "columns": {- "id": {- "name": "id",- "type": "text",- "primaryKey": true,- "notNull": true,- "autoincrement": false- },- "server_id": {- "name": "server_id",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false- },- "name": {- "name": "name",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false- },- "tenant_id": {- "name": "tenant_id",- "type": "text",- "primaryKey": false,- "notNull": false,- "autoincrement": false- },- "slug": {- "name": "slug",- "type": "text",- "primaryKey": false,- "notNull": false,- "autoincrement": false- },- "role": {- "name": "role",- "type": "text",- "primaryKey": false,- "notNull": false,- "autoincrement": false- },- "created_at": {- "name": "created_at",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false,- "default": "CURRENT_TIMESTAMP"- },- "updated_at": {- "name": "updated_at",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false,- "default": "CURRENT_TIMESTAMP"- }- },- "indexes": {- "idx_workspaces_server_id": {- "name": "idx_workspaces_server_id",- "columns": ["server_id"],- "isUnique": false- },- "idx_workspaces_server_tenant": {- "name": "idx_workspaces_server_tenant",- "columns": ["server_id", "tenant_id"],- "isUnique": true- },- "idx_workspaces_server_placeholder": {- "name": "idx_workspaces_server_placeholder",- "columns": ["server_id"],- "isUnique": true,- "where": "`tenant_id` IS NULL"- }- },- "foreignKeys": {- "workspaces_server_id_switch_servers_id_fk": {- "name": "workspaces_server_id_switch_servers_id_fk",- "tableFrom": "workspaces",- "tableTo": "switch_servers",- "columnsFrom": ["server_id"],- "columnsTo": ["id"],- "onDelete": "cascade",- "onUpdate": "no action"- }- },- "compositePrimaryKeys": {},- "uniqueConstraints": {},- "checkConstraints": {}- }- },- "views": {},- "enums": {},- "_meta": {- "schemas": {},- "tables": {},- "columns": {}- },- "internal": {- "indexes": {}- }-}diff --git a/console/apps/switch-console-desktop/drizzle/meta/_journal.json b/console/apps/switch-console-desktop/drizzle/meta/_journal.jsonindex cb8a8591c..dd2dfb96e 100644--- a/console/apps/switch-console-desktop/drizzle/meta/_journal.json+++ b/console/apps/switch-console-desktop/drizzle/meta/_journal.json@@ -358,13 +358,6 @@"when": 1790248865722,"tag": "0050_drop_session_shell_id","breakpoints": true- },- {- "idx": 51,- "version": "6",- "when": 1790300000000,- "tag": "0051_workspaces",- "breakpoints": true}]}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.tsindex 44f2de0e1..d8fb24b63 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.ts@@ -28,7 +28,7 @@ function fakeFs(seed: Record<string, string> = {}): PluginFs {const h = vi.hoisted(() => {const writeDefinition = vi.fn(async () => {});// A faithful-enough stand-in for a repo-agents provider: the config sync- // renders the definition and writes it through the workdir fs, so the mock+ // renders the definition and writes it through the workspace fs, so the mock// has to answer where it goes and what it looks like.const repoAgents = {writeDefinition,@@ -40,11 +40,11 @@ const h = vi.hoisted(() => {readDefinition: async () => null,};const state: {- workdir: PluginFs | null;+ workspace: PluginFs | null;repoAgents: object | null;nameTaken: boolean;} = {- workdir: null,+ workspace: null,repoAgents,nameTaken: false,};@@ -67,17 +67,14 @@ vi.mock('@main/core/providers/plugin-registry', () => ({}));vi.mock('./register-agent-identity', () => ({ registerAgentIdentity: h.registerAgentIdentity }));vi.mock('./createAgent', () => ({ createAgent: h.createAgent }));-vi.mock('./agent-workdir-fs', () => ({- resolveWorkdirFsFor: vi.fn(async () => ({- fs: h.state.workdir as PluginFs,+vi.mock('./agent-workspace-fs', () => ({+ resolveWorkspaceFsFor: vi.fn(async () => ({+ fs: h.state.workspace as PluginFs,close: vi.fn(),})),}));vi.mock('@main/core/switch-servers/servers-store', () => ({- getServer: vi.fn(async () => mockServer),-}));-vi.mock('@main/core/workspaces/workspace-session', () => ({- withWorkspaceSession: (_workspaceId: string, fn: (server: unknown) => unknown) => fn(mockServer),+ getServer: vi.fn(async () => ({ id: 'srv-1', apiUrl: 'https://switch.example.com' })),}));vi.mock('@main/core/locations/store', () => ({ensureLocation: vi.fn(async () => ({ id: 'loc-1' })),@@ -107,11 +104,6 @@ vi.mock('@main/db/client', () => ({}));vi.mock('@main/db/schema', () => ({ agents: { id: 'id', switchAgentId: 'switchAgentId' } }));vi.mock('drizzle-orm', () => ({ eq: vi.fn() }));-vi.mock('@main/core/workspaces/workspaces-store', () => ({- requireWorkspaceForServer: vi.fn(async (serverId: string) => ({ id: `ws-${serverId}` })),-}));--const mockServer = vi.hoisted(() => ({ id: 'srv-1', apiUrl: 'https://switch.example.com' }));const { addAgent } = await import('./add-agent');const { trackEvent } = await import('@main/core/telemetry/telemetry-service');@@ -146,7 +138,7 @@ describe('addAgent', () => {vi.clearAllMocks();h.state.nameTaken = false;h.state.repoAgents = h.repoAgents;- h.state.workdir = fakeFs();+ h.state.workspace = fakeFs();h.registerAgentIdentity.mockResolvedValue({ kind: 'created', id: 'sw-1', apiKey: 'tok-123' });// `clearAllMocks` resets call records but not implementations: without a// default, whichever test last set one decides the answer for the rest.@@ -192,7 +184,7 @@ describe('addAgent', () => {// unconditional it got no credentials on disk at all, so its sessions// authenticated to Switch as whatever was in settings.local.json.h.state.repoAgents = null;- const fs = h.state.workdir as PluginFs;+ const fs = h.state.workspace as PluginFs;const result = await addAgent(params());@@ -206,7 +198,7 @@ describe('addAgent', () => {});it('writes both credentials and an on-disk definition for a repo-agents provider', async () => {- const fs = h.state.workdir as PluginFs;+ const fs = h.state.workspace as PluginFs;await addAgent(params({ providerId: 'claude', name: 'cc-hoot' }));@@ -217,7 +209,7 @@ describe('addAgent', () => {});it('records the agent’s instructions in its committed config file', async () => {- const fs = h.state.workdir as PluginFs;+ const fs = h.state.workspace as PluginFs;await addAgent(params({ providerId: 'claude', name: 'cc-hoot', instructions: 'Be careful.' }));@@ -228,7 +220,7 @@ describe('addAgent', () => {});it('git-ignores the credentials directory so the token never enters VCS', async () => {- const fs = h.state.workdir as PluginFs;+ const fs = h.state.workspace as PluginFs;await addAgent(params());expect(await fs.read('.switch/agents/.gitignore')).toBe('*\n');});@@ -247,9 +239,9 @@ describe('addAgent', () => {);});- it('writes nothing to the workdir when registration fails', async () => {+ it('writes nothing to the workspace when registration fails', async () => {h.registerAgentIdentity.mockResolvedValue({ kind: 'name-conflict' } as never);- const fs = h.state.workdir as PluginFs;+ const fs = h.state.workspace as PluginFs;expect((await addAgent(params())).kind).toBe('name-conflict');expect(await fs.read(agentSettingsRelativePath('codex-hoot'))).toBeNull();@@ -268,7 +260,7 @@ describe('addAgent', () => {SWITCH_AGENT_ID: 'their-agent',},});- h.state.workdir = fakeFs({ [agentSettingsRelativePath('codex-hoot')]: theirs });+ h.state.workspace = fakeFs({ [agentSettingsRelativePath('codex-hoot')]: theirs });const result = await addAgent(params());@@ -278,9 +270,9 @@ describe('addAgent', () => {});expect(h.registerAgentIdentity).not.toHaveBeenCalled();expect(h.createAgent).not.toHaveBeenCalled();- expect(await (h.state.workdir as PluginFs).read(agentSettingsRelativePath('codex-hoot'))).toBe(- theirs- );+ expect(+ await (h.state.workspace as PluginFs).read(agentSettingsRelativePath('codex-hoot'))+ ).toBe(theirs);});it('refuses when same-server credentials exist but the agent is unknown to this install (CHOO-2560)', async () => {@@ -295,7 +287,7 @@ describe('addAgent', () => {SWITCH_AGENT_ID: 'colleague-agent',},});- h.state.workdir = fakeFs({ [agentSettingsRelativePath('codex-hoot')]: colleague });+ h.state.workspace = fakeFs({ [agentSettingsRelativePath('codex-hoot')]: colleague });const result = await addAgent(params());@@ -303,9 +295,9 @@ describe('addAgent', () => {expect(h.registerAgentIdentity).not.toHaveBeenCalled();expect(h.createAgent).not.toHaveBeenCalled();// The colleague's file is intact.- expect(await (h.state.workdir as PluginFs).read(agentSettingsRelativePath('codex-hoot'))).toBe(- colleague- );+ expect(+ await (h.state.workspace as PluginFs).read(agentSettingsRelativePath('codex-hoot'))+ ).toBe(colleague);});it('refuses a name already taken in the location, without minting an identity', async () => {diff --git a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.ts b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.tsindex fb44dc57d..81c4eed19 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@@ -10,8 +10,6 @@ import { agentTypeOf } from '@main/core/telemetry/agent-type';import type { TelemetryAgentCreateFailure } from '@main/core/telemetry/events';import { entryPointOf } from '@main/core/telemetry/narrow';import { trackEvent } from '@main/core/telemetry/telemetry-service';-import { withWorkspaceSession } from '@main/core/workspaces/workspace-session';-import { requireWorkspaceForServer } from '@main/core/workspaces/workspaces-store';import { db } from '@main/db/client';import { agents as agentsTable } from '@main/db/schema';import { log } from '@main/lib/logger';@@ -33,7 +31,7 @@ import { syncAgentConfig } from './agent-config-sync';import { foreignCredentialsOwner, sameEndpointAgentId } from './agent-credentials-slot';import { agentEvents } from './agent-events';import { agentNameTaken } from './agent-name-taken';-import { resolveWorkdirFsFor } from './agent-workdir-fs';+import { resolveWorkspaceFsFor } from './agent-workspace-fs';import { createAgent } from './createAgent';import { knownAgentTypeForProvider } from './known-agent-type';import { registerAgentIdentity } from './register-agent-identity';@@ -193,7 +191,6 @@ async function runAddAgent(params: AddAgentParams): Promise<AddAgentResult> {message: `No Switch server with id ${params.serverId}`,});}- const targetWorkspace = await requireWorkspaceForServer(params.serverId);// Before minting an identity: the gateway's uniqueness check is scoped to the// Switch server, so it cannot see a name already taken in this directory. Two@@ -259,28 +256,26 @@ async function runAddAgent(params: AddAgentParams): Promise<AddAgentResult> {}}- const registered = await withWorkspaceSession(targetWorkspace.id, (target) =>- registerAgentIdentity(target, {- name: params.name,- description: params.description,- displayName: params.displayName,- repoDir: params.dir,- autoSession: params.autoSession,- agentType: knownAgentTypeForProvider(params.providerId),- iconUrl: params.iconUrl ?? agentAvatarUrlForName(params.name),- })- );+ const registered = await registerAgentIdentity(server, {+ name: params.name,+ description: params.description,+ displayName: params.displayName,+ repoDir: params.dir,+ autoSession: params.autoSession,+ agentType: knownAgentTypeForProvider(params.providerId),+ iconUrl: params.iconUrl ?? agentAvatarUrlForName(params.name),+ });if (registered.kind !== 'created') return reportFailedCreate(params, registered);const behavior = getPlugin(params.providerId).behavior.repoAgents;- const workdir = await resolveWorkdirFsFor(params.sshHost, params.dir);+ const workspace = await resolveWorkspaceFsFor(params.sshHost, params.dir);try {// Writing the per-agent Switch credentials is unconditional core behavior for// every provider, keyed by the agent's `name` — the single key-space every// reader (launch path, auto-session watcher, notification poller) uses// (CHOO-1440). Providers with repo-agent definitions (Claude) layer their// on-disk definition on top; that's the only provider-specific extra.- await writeNeutralAgentSettingsFs(workdir.fs, {+ await writeNeutralAgentSettingsFs(workspace.fs, {slug: params.name,apiEndpoint: server.apiUrl,apiToken: registered.apiKey,@@ -289,19 +284,19 @@ async function runAddAgent(params: AddAgentParams): Promise<AddAgentResult> {});// The config file is the agent's configuration; the provider's own file is// generated from it, here and on every later edit.- await writeAgentConfigFile(workdir.fs, params.name, {+ await writeAgentConfigFile(workspace.fs, params.name, {instructions: params.instructions,settings: params.definitionAttributes,...(params.templateOrigin ? { template: params.templateOrigin } : {}),});await syncAgentConfig({- workdirFs: workdir.fs,+ workspaceFs: workspace.fs,repoAgents: behavior ?? null,name: params.name,description: params.description,});} finally {- workdir.close();+ workspace.close();}const location = await ensureLocation({@@ -317,7 +312,7 @@ async function runAddAgent(params: AddAgentParams): Promise<AddAgentResult> {providerId: params.providerId,switchAgentId: registered.id,apiEndpoint: server.apiUrl,- workspaceId: targetWorkspace.id,+ serverId: params.serverId,autoApprove: params.autoApprove,providerConfig: params.providerConfig ?? null,});diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-config-file.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-config-file.tsindex 3368c75e0..4c3b06e1d 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-config-file.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-config-file.ts@@ -62,28 +62,14 @@ export type AgentTemplateOrigin = {name: string;source: 'bundled' | 'server';serverId?: string;- /**- * The workspace the template was read from.- *- * A template registry belongs to a workspace, not to the server hosting it,- * so the server alone does not say where to look again once an account holds- * several on one. Absent on an origin written before this was recorded.- */- workspaceId?: string;};function parseTemplateOrigin(value: unknown): AgentTemplateOrigin | undefined {if (!isPlainObject(value)) return undefined;- const { id, name, source, serverId, workspaceId } = value;+ const { id, name, source, serverId } = value;if (typeof id !== 'string' || typeof name !== 'string') return undefined;if (source !== 'bundled' && source !== 'server') return undefined;- return {- id,- name,- source,- ...(typeof serverId === 'string' ? { serverId } : {}),- ...(typeof workspaceId === 'string' ? { workspaceId } : {}),- };+ return { id, name, source, ...(typeof serverId === 'string' ? { serverId } : {}) };}/**diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-config-sync.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-config-sync.test.tsindex f8921fd2e..8066db2c1 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-config-sync.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-config-sync.test.ts@@ -25,7 +25,7 @@ const claudeRepoAgents = getPlugin('claude').behavior.repoAgents ?? null;function sync(pluginFs = createPluginFs(dir)) {return syncAgentConfig({- workdirFs: pluginFs,+ workspaceFs: pluginFs,repoAgents: claudeRepoAgents,name: NAME,description: DESCRIPTION,@@ -42,7 +42,7 @@ describe('syncAgentConfig', () => {await writeAgentConfigFile(pluginFs, NAME, { instructions: 'be terse' });const result = await syncAgentConfig({- workdirFs: pluginFs,+ workspaceFs: pluginFs,repoAgents: null,name: NAME,description: DESCRIPTION,diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-config-sync.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-config-sync.tsindex 7425750c2..bff18ec81 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-config-sync.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-config-sync.ts@@ -37,7 +37,7 @@ export type AgentConfigSyncResult = {};export async function syncAgentConfig(params: {- workdirFs: PluginFs;+ workspaceFs: PluginFs;/** Null for a provider with no repository definitions (Codex, OpenCode). */repoAgents: IRepoAgentsBehavior | null;/** The agent's name, which is both its config-file key and its definition stem. */@@ -45,16 +45,16 @@ export async function syncAgentConfig(params: {/** The agent's description, which the definition carries in its frontmatter. */description: string;}): Promise<AgentConfigSyncResult> {- const { workdirFs, repoAgents, name, description } = params;+ const { workspaceFs, repoAgents, name, description } = params;- const config = (await readAgentConfigFile(workdirFs, name)) ?? {};+ const config = (await readAgentConfigFile(workspaceFs, name)) ?? {};if (!repoAgents) return { config, action: 'not-applicable' };const definitionPath = repoAgents.definitionPath(name);const generated = repoAgents.renderDefinition(definitionAttributes({ config, name, description }));- const current = await workdirFs.read(definitionPath);+ const current = await workspaceFs.read(definitionPath);const action = decideArtifactSync({current,@@ -65,16 +65,16 @@ export async function syncAgentConfig(params: {if (action === 'in-sync') return { config, action };if (action === 'adopt') {- const adopted = await adoptDefinition({ workdirFs, repoAgents, name, config });+ const adopted = await adoptDefinition({ workspaceFs, repoAgents, name, config });return { config: adopted, action: 'adopted' };}- await workdirFs.write(definitionPath, generated);+ await workspaceFs.write(definitionPath, generated);const written: AgentConfigFile = {...config,rendered: { ...config.rendered, [definitionPath]: fingerprintArtifact(generated) },};- await writeAgentConfigFile(workdirFs, name, written);+ await writeAgentConfigFile(workspaceFs, name, written);return { config: written, action: 'written' };}@@ -88,14 +88,14 @@ export async function syncAgentConfig(params: {* meaningful instead of reporting a hand edit forever.*/async function adoptDefinition(params: {- workdirFs: PluginFs;+ workspaceFs: PluginFs;repoAgents: IRepoAgentsBehavior;name: string;config: AgentConfigFile;}): Promise<AgentConfigFile> {- const { workdirFs, repoAgents, name, config } = params;+ const { workspaceFs, repoAgents, name, config } = params;- const attributes = await repoAgents.readDefinition(workdirFs, name);+ const attributes = await repoAgents.readDefinition(workspaceFs, name);if (attributes === null) {throw new Error(`Agent ${name} has a definition that could not be read back.`);}@@ -115,13 +115,13 @@ async function adoptDefinition(params: {description: typeof description === 'string' ? description : '',}));- await workdirFs.write(definitionPath, generated);+ await workspaceFs.write(definitionPath, generated);const result: AgentConfigFile = {...adopted,rendered: { ...config.rendered, [definitionPath]: fingerprintArtifact(generated) },};- await writeAgentConfigFile(workdirFs, name, result);+ await writeAgentConfigFile(workspaceFs, name, result);return result;}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-config.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-config.test.tsindex 7b447dbc7..e8a5c332d 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-config.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-config.test.ts@@ -42,8 +42,8 @@ vi.mock('./getAgentById', () => ({vi.mock('./agent-location', () => ({getAgentLocation: async () => ({ id: 'loc-1', dir: '/repo', sshHost: 'vm-1' }),}));-vi.mock('./agent-workdir-fs', () => ({- resolveWorkdirFsFor: async () => ({ fs: fakeFs(), close: () => {} }),+vi.mock('./agent-workspace-fs', () => ({+ resolveWorkspaceFsFor: async () => ({ fs: fakeFs(), close: () => {} }),}));vi.mock('./setAgentProviderConfig', () => ({setAgentProviderConfig: (params: unknown) => setAgentProviderConfig(params),diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-config.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-config.tsindex bead9516f..c1c37ccb3 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-config.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-config.ts@@ -5,7 +5,7 @@ import type { Agent } from '@shared/core/agents/agents';import type { AgentConfigFile } from './agent-config-file';import { writeAgentConfigFile, type AgentTemplateOrigin } from './agent-config-file';import { syncAgentConfig } from './agent-config-sync';-import { withAgentWorkdir } from './agent-launch-config';+import { withAgentWorkspace } from './agent-launch-config';import { getAgentById } from './getAgentById';import { setAgentProviderConfig } from './setAgentProviderConfig';@@ -31,7 +31,7 @@ import { setAgentProviderConfig } from './setAgentProviderConfig';* that is not what the agent will actually launch with.*/export async function readAgentConfig(agentId: string): Promise<AgentConfigFile> {- return withAgentWorkdir(agentId, (agent, fs) => reconcile(agent, fs));+ return withAgentWorkspace(agentId, (agent, fs) => reconcile(agent, fs));}/**@@ -46,7 +46,7 @@ export async function writeAgentConfig(params: {agentId: string;config: AgentConfigFile;}): Promise<AgentConfigFile> {- return withAgentWorkdir(params.agentId, async (agent, fs) => {+ return withAgentWorkspace(params.agentId, async (agent, fs) => {await writeAgentConfigFile(fs, agent.name, params.config);return reconcile(agent, fs);});@@ -92,7 +92,7 @@ export async function setAgentSettings(params: {}/**- * Read, change, write — in one workdir session.+ * Read, change, write — in one workspace session.** Not read-then-write through the public helpers: over SSH that opens the* working directory twice, and it would reconcile twice for one edit.@@ -101,7 +101,7 @@ async function updateAgentConfig(agentId: string,change: (config: AgentConfigFile) => AgentConfigFile): Promise<AgentConfigFile> {- const config = await withAgentWorkdir(agentId, async (agent, fs) => {+ const config = await withAgentWorkspace(agentId, async (agent, fs) => {const current = await reconcile(agent, fs);await writeAgentConfigFile(fs, agent.name, change(current));return reconcile(agent, fs);@@ -158,7 +158,7 @@ async function reconcile(agent: Agent, fs: PluginFs): Promise<AgentConfigFile> {const description = typeof existing?.description === 'string' ? existing.description : '';const { config } = await syncAgentConfig({- workdirFs: fs,+ workspaceFs: fs,repoAgents,name: agent.name,description,diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-credentials-slot.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-credentials-slot.tsindex 1fcf30ba1..81bafcd68 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-credentials-slot.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-credentials-slot.ts@@ -1,4 +1,4 @@-import { resolveWorkdirFsFor } from './agent-workdir-fs';+import { resolveWorkspaceFsFor } from './agent-workspace-fs';import { agentSettingsRelativePath } from './switch-settings-paths';import { existingAgentIdInSlot, foreignCredentialsOwnerFs } from './write-switch-settings';@@ -22,11 +22,11 @@ export async function foreignCredentialsOwner(slug: string,apiEndpoint: string): Promise<string | null> {- const workdir = await resolveWorkdirFsFor(sshHost, dir);+ const workspace = await resolveWorkspaceFsFor(sshHost, dir);try {- return await foreignCredentialsOwnerFs(workdir.fs, slug, apiEndpoint);+ return await foreignCredentialsOwnerFs(workspace.fs, slug, apiEndpoint);} finally {- workdir.close();+ workspace.close();}}@@ -46,11 +46,11 @@ export async function sameEndpointAgentId(slug: string,apiEndpoint: string): Promise<string | null> {- const workdir = await resolveWorkdirFsFor(sshHost, dir);+ const workspace = await resolveWorkspaceFsFor(sshHost, dir);try {- const existingRaw = await workdir.fs.read(agentSettingsRelativePath(slug));+ const existingRaw = await workspace.fs.read(agentSettingsRelativePath(slug));return existingAgentIdInSlot(existingRaw, apiEndpoint);} finally {- workdir.close();+ workspace.close();}}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-definition.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-definition.tsindex 4d72c54a3..255f3c594 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-definition.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-definition.ts@@ -1,7 +1,7 @@import type { RepoAgentAttributes } from '@switch-console/core/agents/plugins';import { getPlugin } from '@main/core/providers/plugin-registry';import { getAgentLocation } from './agent-location';-import { resolveWorkdirFsFor } from './agent-workdir-fs';+import { resolveWorkspaceFsFor } from './agent-workspace-fs';import { getAgentById } from './getAgentById';/**@@ -19,11 +19,11 @@ export async function readAgentDefinition(agentId: string): Promise<RepoAgentAttif (!behavior || !agent.name) return null;const location = await getAgentLocation(agent);- const workdir = await resolveWorkdirFsFor(location.sshHost, location.dir);+ const workspace = await resolveWorkspaceFsFor(location.sshHost, location.dir);try {- return await behavior.readDefinition(workdir.fs, agent.name);+ return await behavior.readDefinition(workspace.fs, agent.name);} finally {- workdir.close();+ workspace.close();}}@@ -47,16 +47,16 @@ export async function updateAgentDefinition(params: {}const location = await getAgentLocation(agent);- const workdir = await resolveWorkdirFsFor(location.sshHost, location.dir);+ const workspace = await resolveWorkspaceFsFor(location.sshHost, location.dir);try {- const current = await behavior.readDefinition(workdir.fs, agent.name);+ const current = await behavior.readDefinition(workspace.fs, agent.name);const description = typeof current?.description === 'string' ? current.description : '';- await behavior.writeDefinition(workdir.fs, {+ await behavior.writeDefinition(workspace.fs, {...params.attributes,name: agent.name,description,});} finally {- workdir.close();+ workspace.close();}}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-launch-config.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-launch-config.tsindex 21ac9ed6a..1fe040bba 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-launch-config.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-launch-config.ts@@ -3,7 +3,7 @@ import type { Agent } from '@shared/core/agents/agents';import type { AgentConfigFile } from './agent-config-file';import { readAgentConfigFile } from './agent-config-file';import { getAgentLocation } from './agent-location';-import { resolveWorkdirFsFor } from './agent-workdir-fs';+import { resolveWorkspaceFsFor } from './agent-workspace-fs';import { getAgentById } from './getAgentById';/**@@ -18,7 +18,7 @@ import { getAgentById } from './getAgentById';/** Read launch settings from the execution host; transport failures must stop launch. */export async function readAgentConfigForLaunch(agentId: string): Promise<AgentConfigFile> {- return withAgentWorkdir(+ return withAgentWorkspace(agentId,async (agent, fs) => (await readAgentConfigFile(fs, agent.name)) ?? {});@@ -46,7 +46,7 @@ export async function agentLaunchSpecialization(}/** Run `run` against the agent's working directory, local or over SFTP. */-export async function withAgentWorkdir<T>(+export async function withAgentWorkspace<T>(agentId: string,run: (agent: Agent, fs: PluginFs) => Promise<T>): Promise<T> {@@ -54,10 +54,10 @@ export async function withAgentWorkdir<T>(if (!agent) throw new Error(`No agent with id ${agentId}`);const location = await getAgentLocation(agent);- const workdir = await resolveWorkdirFsFor(location.sshHost, location.dir);+ const workspace = await resolveWorkspaceFsFor(location.sshHost, location.dir);try {- return await run(agent, workdir.fs);+ return await run(agent, workspace.fs);} finally {- workdir.close();+ workspace.close();}}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-workdir-fs.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-workspace-fs.tssimilarity index 90%rename from console/apps/switch-console-desktop/src/main/core/agents/agent-workdir-fs.tsrename to console/apps/switch-console-desktop/src/main/core/agents/agent-workspace-fs.tsindex a0c9e2002..0697b8af9 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-workdir-fs.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-workspace-fs.ts@@ -12,7 +12,7 @@ import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';* Callers MUST invoke `close()` in a `finally` — a leaked SFTP channel* eventually exhausts the host's MaxSessions.*/-export type WorkdirFs = {+export type WorkspaceFs = {/** FS rooted at the working dir — local disk or the remote repo dir. */fs: PluginFs;/** FS for user-scoped (`~/.claude`) definitions; empty for remote agents. */@@ -34,12 +34,15 @@ const EMPTY_PLUGIN_FS: PluginFs = {};/**- * Open a {@link WorkdirFs} for a working directory identified by run location+ * Open a {@link WorkspaceFs} for a working directory identified by run location* (ssh host + dir) rather than an existing agent row — used at create/onboard* time before a row exists. Local dirs resolve on disk; remote dirs open an* SFTP channel to the host.*/-export async function resolveWorkdirFsFor(sshHost: string | null, dir: string): Promise<WorkdirFs> {+export async function resolveWorkspaceFsFor(+ sshHost: string | null,+ dir: string+): Promise<WorkspaceFs> {if (sshHost === null) {return { fs: createPluginFs(dir), homeFs: createPluginFs(homedir()), close: () => {} };}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/assignAgentServer.ts b/console/apps/switch-console-desktop/src/main/core/agents/assignAgentServer.tsindex cd7b884cc..d070f69de 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/assignAgentServer.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/assignAgentServer.ts@@ -1,6 +1,5 @@import { agentExistsOnServer, GatewayError } from '@main/core/switch-servers/gateway-client';-import { withWorkspaceSession } from '@main/core/workspaces/workspace-session';-import { requireWorkspaceForServer } from '@main/core/workspaces/workspaces-store';+import { getServer } from '@main/core/switch-servers/servers-store';import type { AgentVerifyResult } from '@shared/core/switch-servers/switch-servers';import { getAgentById } from './getAgentById';import { updateAgent } from './updateAgent';@@ -23,19 +22,14 @@ export async function assignAgentServer(params: {if (!agent.switchAgentId) {throw new Error(`Agent ${params.agentId} has no Switch agent id to verify`);}- // Resolved before the call, not after it: the workspace the agent would be- // written into is the one the question has to be asked of, or a `found` here- // means found somewhere else.- const workspace = await requireWorkspaceForServer(params.serverId);- const switchAgentId = agent.switchAgentId;+ const server = await getServer(params.serverId);+ if (!server) {+ throw new Error(`No Switch server with id ${params.serverId}`);+ }let result: AgentVerifyResult;try {- result = (await withWorkspaceSession(workspace.id, (server) =>- agentExistsOnServer(server, switchAgentId)- ))- ? 'found'- : 'not-found';+ result = (await agentExistsOnServer(server, agent.switchAgentId)) ? 'found' : 'not-found';} catch (cause) {if (cause instanceof GatewayError && cause.kind === 'unauthorized') {return 'unauthenticated';@@ -44,7 +38,7 @@ export async function assignAgentServer(params: {}if (result === 'found') {- await updateAgent({ agentId: params.agentId, workspaceId: workspace.id });+ await updateAgent({ agentId: params.agentId, serverId: params.serverId });}return result;}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.test.tsindex 469fb15bb..bf6e13a6a 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@@ -10,8 +10,8 @@ function readOnlyFs(seed: Record<string, string>): PluginFs {const files = new Map<string, string>(Object.entries(seed));return {read: (p) => Promise.resolve(files.get(p) ?? null),- write: (p) => Promise.reject(new Error(`attach wrote to the workdir: ${p}`)),- delete: (p) => Promise.reject(new Error(`attach deleted from the workdir: ${p}`)),+ write: (p) => Promise.reject(new Error(`attach wrote to the workspace: ${p}`)),+ delete: (p) => Promise.reject(new Error(`attach deleted from the workspace: ${p}`)),exists: (p) => Promise.resolve(files.has(p)),list: (dir) => {const prefix = `${dir}/`;@@ -44,12 +44,12 @@ const h = vi.hoisted(() => {}}const state: {- workdir: PluginFs | null;+ workspace: PluginFs | null;/** Agent-row names already in the directory, per Switch server. */- agentNamesByWorkspace: Record<string, string[]>;+ agentNamesByServer: Record<string, string[]>;existsOnServer: boolean;existsThrows: Error | null;- } = { workdir: null, agentNamesByWorkspace: {}, existsOnServer: true, existsThrows: null };+ } = { workspace: null, agentNamesByServer: {}, existsOnServer: true, existsThrows: null };return {state,GatewayError,@@ -69,25 +69,13 @@ vi.mock('@main/core/locations/store', () => ({ensureLocation: vi.fn(async () => ({ id: 'loc-1' })),}));vi.mock('./getAgents', () => ({- getLocationAgentsInWorkspace: vi.fn(async (_locationId: string, workspaceId: string) =>- (h.state.agentNamesByWorkspace[workspaceId] ?? []).map((name) => ({ name }))+ getLocationAgentsOnServer: vi.fn(async (_locationId: string, serverId: string) =>+ (h.state.agentNamesByServer[serverId] ?? []).map((name) => ({ name }))),}));-vi.mock('@main/core/workspaces/workspaces-store', () => ({- requireWorkspaceForServer: vi.fn(async (serverId: string) => ({ id: `ws-${serverId}` })),-}));--const mockServer = vi.hoisted(() => ({- id: 'srv-1',- name: 'Switch',- apiUrl: 'https://switch.example.com',-}));-vi.mock('@main/core/workspaces/workspace-session', () => ({- withWorkspaceSession: (_workspaceId: string, fn: (server: unknown) => unknown) => fn(mockServer),-}));-vi.mock('./agent-workdir-fs', () => ({- resolveWorkdirFsFor: vi.fn(async () => ({- fs: h.state.workdir as PluginFs,+vi.mock('./agent-workspace-fs', () => ({+ resolveWorkspaceFsFor: vi.fn(async () => ({+ fs: h.state.workspace as PluginFs,homeFs: null,close: vi.fn(),})),@@ -100,7 +88,11 @@ vi.mock('@main/core/switch-servers/gateway-client', () => ({GatewayError: h.GatewayError,}));vi.mock('@main/core/switch-servers/servers-store', () => ({- getServer: vi.fn(async () => mockServer),+ getServer: vi.fn(async () => ({+ id: 'srv-1',+ name: 'Switch',+ apiUrl: 'https://switch.example.com',+ })),}));vi.mock('./createAgent', () => ({ createAgent: h.createAgent }));vi.mock('@main/core/locations/path-utils', () => ({ checkIsValidDirectory: () => true }));@@ -123,10 +115,10 @@ function params(agents: Array<{ name: string; providerId: 'codex' | 'claude' }>)describe('attachConfiguredAgents', () => {beforeEach(() => {vi.clearAllMocks();- h.state.agentNamesByWorkspace = {};+ h.state.agentNamesByServer = {};h.state.existsOnServer = true;h.state.existsThrows = null;- h.state.workdir = readOnlyFs({ '.switch/agents/theirs.json': creds('sw-theirs') });+ h.state.workspace = readOnlyFs({ '.switch/agents/theirs.json': creds('sw-theirs') });});it('adopts the existing Switch identity instead of minting a new one', async () => {@@ -145,7 +137,7 @@ describe('attachConfiguredAgents', () => {});it('writes nothing to the working directory', async () => {- // The workdir belongs to whichever install set the agent up. Any write+ // The workspace belongs to whichever install set the agent up. Any write// here rejects, so this passing means attach touched none of their state.await expect(attachConfiguredAgents(params([{ name: 'theirs', providerId: 'codex' }]))@@ -183,7 +175,7 @@ describe('attachConfiguredAgents', () => {});it('skips an agent this Switch Console already has', async () => {- h.state.agentNamesByWorkspace = { 'ws-srv-1': ['theirs'] };+ h.state.agentNamesByServer = { 'srv-1': ['theirs'] };const result = await attachConfiguredAgents(params([{ name: 'theirs', providerId: 'codex' }]));@@ -193,13 +185,13 @@ describe('attachConfiguredAgents', () => {it('attaches an agent already attached to a different server (CHOO-2044)', async () => {// Same directory, same name, other server — a separate agent, not a duplicate.- h.state.agentNamesByWorkspace = { 'ws-srv-other': ['theirs'] };+ h.state.agentNamesByServer = { 'srv-other': ['theirs'] };const result = await attachConfiguredAgents(params([{ name: 'theirs', providerId: 'codex' }]));expect(result.success).toBe(true);expect(h.createAgent).toHaveBeenCalledWith(- expect.objectContaining({ name: 'theirs', workspaceId: 'ws-srv-1' })+ expect.objectContaining({ name: 'theirs', serverId: 'srv-1' }));});@@ -207,7 +199,7 @@ describe('attachConfiguredAgents', () => {// One Switch server can be reachable at two URLs. The launch path reads the// endpoint from the same file as the token, so the directory's value is what// the session will really use — surfaced, never corrected.- h.state.workdir = readOnlyFs({+ h.state.workspace = readOnlyFs({'.switch/agents/theirs.json': creds('sw-theirs', 'https://switch.internal:8443'),});diff --git a/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.ts b/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.tsindex c7a43a9fe..a56bb053a 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@@ -6,8 +6,6 @@ import { checkIsValidDirectory } from '@main/core/locations/path-utils';import { ensureLocation } from '@main/core/locations/store';import { agentExistsOnServer, GatewayError } from '@main/core/switch-servers/gateway-client';import { getServer } from '@main/core/switch-servers/servers-store';-import { withWorkspaceSession } from '@main/core/workspaces/workspace-session';-import { requireWorkspaceForServer } from '@main/core/workspaces/workspaces-store';import { log } from '@main/lib/logger';import type { Agent } from '@shared/core/agents/agents';import type { OnboardAgentError } from '@shared/core/agents/onboarding';@@ -49,7 +47,7 @@ export type AttachConfiguredAgentsResult = Result<Agent[], OnboardAgentError>;* provider config — the directory is another install's state and this operation* treats it as read-only. That is possible because the API token is never needed* here: it stays where it already is, and the launch path reads it from disk when- * a session spawns. This module deliberately imports no workdir writer, so the+ * a session spawns. This module deliberately imports no workspace writer, so the* guarantee is structural rather than a matter of care.** An identity that no longer exists on the chosen server fails the attach loudly@@ -72,7 +70,6 @@ export async function attachConfiguredAgents(const server = await getServer(params.serverId);if (!server) throw new Error(`No Switch server with id ${params.serverId}`);- const targetWorkspace = await requireWorkspaceForServer(params.serverId);const discovered = new Map((@@ -119,10 +116,7 @@ export async function attachConfiguredAgents(if (!found) continue;try {- const exists = await withWorkspaceSession(targetWorkspace.id, (target) =>- agentExistsOnServer(target, found.switchAgentId)- );- if (!exists) {+ if (!(await agentExistsOnServer(server, found.switchAgentId))) {return err({type: 'switch-agent-not-on-server',dir: params.dir,@@ -164,7 +158,7 @@ export async function attachConfiguredAgents(providerId,switchAgentId: found.switchAgentId,apiEndpoint: found.apiEndpoint,- workspaceId: targetWorkspace.id,+ serverId: params.serverId,autoApprove: params.sshHost !== null,ownerName: ownerName ?? null,});diff --git a/console/apps/switch-console-desktop/src/main/core/agents/controller.ts b/console/apps/switch-console-desktop/src/main/core/agents/controller.tsindex 7da7b134a..952451f5c 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/controller.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/controller.ts@@ -82,7 +82,7 @@ export const agentsController = createRPCController({onboardAgent: (params: OnboardAgentParams) => onboardAgent(params),discoverLoadableAgentsOnHost: (params: DiscoverLoadableAgentsParams) =>discoverLoadableAgentsOnHost(params),- discoverLoadableAgentsInDir: (params: { sshHost: string; dir: string; workspaceId: string }) =>+ discoverLoadableAgentsInDir: (params: { sshHost: string; dir: string; serverId: string }) =>discoverLoadableAgentsInDir(params),attachConfiguredAgents: (params: AttachConfiguredAgentsParams) => attachConfiguredAgents(params),removeLoadableAgentConfig: (params: RemoveLoadableAgentConfigParams) =>diff --git a/console/apps/switch-console-desktop/src/main/core/agents/createAgent.ts b/console/apps/switch-console-desktop/src/main/core/agents/createAgent.tsindex f2ade07ab..d6a28b0c3 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/createAgent.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/createAgent.ts@@ -2,7 +2,7 @@ import { sql } from 'drizzle-orm';import { db } from '@main/db/client';import { agents } from '@main/db/schema';import type { Agent, CreateAgentParams } from '@shared/core/agents/agents';-import { mapAgentRow } from './utils';+import { mapAgentRowToAgent } from './utils';/*** Insert an agent row. Main-process internal, and deliberately not an RPC@@ -21,7 +21,7 @@ export async function createAgent(params: CreateAgentParams): Promise<Agent> {providerId: params.providerId,switchAgentId: params.switchAgentId,apiEndpoint: params.apiEndpoint,- workspaceId: params.workspaceId,+ serverId: params.serverId,autoApprove: params.autoApprove,ownerName: params.ownerName ?? null,providerConfig: params.providerConfig ?? null,@@ -29,5 +29,5 @@ export async function createAgent(params: CreateAgentParams): Promise<Agent> {}).returning();- return mapAgentRow(row);+ return mapAgentRowToAgent(row);}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.test.tsindex 78d8ef6cc..a0c85a369 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.test.ts@@ -49,8 +49,8 @@ vi.mock('@main/core/sdk-host/shared-watcher', () => ({vi.mock('@main/core/providers/plugin-registry', () => ({getPlugin: () => ({ behavior: { repoAgents: h.state.repoAgents } }),}));-vi.mock('./agent-workdir-fs', () => ({- resolveWorkdirFsFor: vi.fn(async () => ({ fs: h.state.fs, close: vi.fn() })),+vi.mock('./agent-workspace-fs', () => ({+ resolveWorkspaceFsFor: vi.fn(async () => ({ fs: h.state.fs, close: vi.fn() })),}));vi.mock('./agent-location', () => ({getAgentLocation: vi.fn(async () => ({ sshHost: h.state.sshHost, dir: '/repo' })),@@ -85,10 +85,7 @@ vi.mock('@main/core/switch-servers/gateway-client', () => ({}},}));-vi.mock('@main/core/workspaces/workspace-session', () => ({- withWorkspaceSession: (_workspaceId: string, fn: (server: { id: string }) => unknown) =>- fn({ id: 'srv-1' }),-}));+vi.mock('@main/core/switch-servers/servers-store', () => ({ getServer: vi.fn() }));vi.mock('@main/core/view-state/view-state-service', () => ({viewStateService: { del: vi.fn(async () => {}) },}));@@ -336,9 +333,10 @@ describe('deleteAgent', () => {providerId: 'claude',locationId: 'loc',serverId: 'srv-1',- workspaceId: 'ws-1',switchAgentId: 'sw-1',};+ const { getServer } = await import('@main/core/switch-servers/servers-store');+ vi.mocked(getServer).mockResolvedValue({ id: 'srv-1' } as never);await expect(deleteAgent('agent-1', {@@ -361,7 +359,6 @@ describe('deleteAgent', () => {providerId: 'claude',locationId: 'loc',serverId: null,- workspaceId: null,switchAgentId: null,};diff --git a/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.ts b/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.tsindex c0dc01e0f..15378d295 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.ts@@ -11,6 +11,7 @@ import {deleteAgent as gatewayDeleteAgent,GatewayError,} from '@main/core/switch-servers/gateway-client';+import { getServer } from '@main/core/switch-servers/servers-store';import { agentTypeOf } from '@main/core/telemetry/agent-type';import type {TelemetryAgentRemoveFailure,@@ -20,7 +21,6 @@ import type {import { agentRemoveTriggerOf } from '@main/core/telemetry/narrow';import { trackEvent } from '@main/core/telemetry/telemetry-service';import { viewStateService } from '@main/core/view-state/view-state-service';-import { withWorkspaceSession } from '@main/core/workspaces/workspace-session';import { db } from '@main/db/client';import { agents, sessions } from '@main/db/schema';import { log } from '@main/lib/logger';@@ -29,7 +29,7 @@ import type { Location } from '@shared/core/locations/locations';import { sessionRuntimeManager } from '../sessions/session-runtime-manager';import { agentEvents } from './agent-events';import { getAgentLocation } from './agent-location';-import { resolveWorkdirFsFor } from './agent-workdir-fs';+import { resolveWorkspaceFsFor } from './agent-workspace-fs';import { getAgentById } from './getAgentById';import { stopRemoteWatcher } from './remote-watcher';import { removeAgentLaunchProfile } from './remove-launch-profile';@@ -101,14 +101,17 @@ function locationKindOfRow(location: Location | null): TelemetryLocationKind {* rather than leaving the row gone but the Switch identity orphaned.*/async function deleteAgentInSwitch(agent: Agent): Promise<void> {- const { workspaceId, switchAgentId } = agent;- if (!workspaceId || !switchAgentId) {+ if (!agent.serverId || !agent.switchAgentId) {throw new AgentNotLinkedToSwitchError(- `Agent ${agent.id} is not linked to a Switch workspace, so it cannot be deleted in Switch.`+ `Agent ${agent.id} is not linked to a Switch server, so it cannot be deleted in Switch.`);}+ const server = await getServer(agent.serverId);+ if (!server) {+ throw new AgentNotLinkedToSwitchError(`No Switch server with id ${agent.serverId}`);+ }- await withWorkspaceSession(workspaceId, (server) => gatewayDeleteAgent(server, switchAgentId));+ await gatewayDeleteAgent(server, agent.switchAgentId);}/**@@ -123,7 +126,7 @@ async function deleteAgentInSwitch(agent: Agent): Promise<void> {* (visibly) rather than thrown — the credentials being torn down are already dead.*/async function removeProvisionedFiles(agent: Agent, location: Location): Promise<void> {- const ctx = await resolveWorkdirFsFor(location.sshHost, location.dir);+ const ctx = await resolveWorkspaceFsFor(location.sshHost, location.dir);try {const behavior = getPlugin(agent.providerId).behavior.repoAgents;if (behavior && agent.name) {diff --git a/console/apps/switch-console-desktop/src/main/core/agents/discover-configured-agents.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/discover-configured-agents.test.tsindex 2fff3599b..e00083211 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/discover-configured-agents.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/discover-configured-agents.test.ts@@ -50,17 +50,12 @@ function launchSpec(providerId: string) {const h = vi.hoisted(() => {const state: {- workdir: PluginFs | null;+ workspace: PluginFs | null;location: { id: string } | undefined;/** Agent-row names already in the directory, per Switch server. */- agentNamesByWorkspace: Record<string, string[]>;+ agentNamesByServer: Record<string, string[]>;claudeDefinitions: Array<{ name: string; description: string | null }>;- } = {- workdir: null,- location: { id: 'loc-1' },- agentNamesByWorkspace: {},- claudeDefinitions: [],- };+ } = { workspace: null, location: { id: 'loc-1' }, agentNamesByServer: {}, claudeDefinitions: [] };return { state, warn: vi.fn() };});@@ -68,16 +63,13 @@ vi.mock('@main/core/locations/store', () => ({getLocationByHostDir: vi.fn(async () => h.state.location),}));vi.mock('./getAgents', () => ({- getLocationAgentsInWorkspace: vi.fn(async (_locationId: string, workspaceId: string) =>- (h.state.agentNamesByWorkspace[workspaceId] ?? []).map((name) => ({ name }))+ getLocationAgentsOnServer: vi.fn(async (_locationId: string, serverId: string) =>+ (h.state.agentNamesByServer[serverId] ?? []).map((name) => ({ name }))),}));-vi.mock('@main/core/workspaces/workspaces-store', () => ({- requireWorkspaceForServer: vi.fn(async (serverId: string) => ({ id: `ws-${serverId}` })),-}));-vi.mock('./agent-workdir-fs', () => ({- resolveWorkdirFsFor: vi.fn(async () => ({- fs: h.state.workdir as PluginFs,+vi.mock('./agent-workspace-fs', () => ({+ resolveWorkspaceFsFor: vi.fn(async () => ({+ fs: h.state.workspace as PluginFs,homeFs: null,close: vi.fn(),})),@@ -104,16 +96,16 @@ describe('discoverConfiguredAgents', () => {beforeEach(() => {vi.clearAllMocks();h.state.location = { id: 'loc-1' };- h.state.agentNamesByWorkspace = {};+ h.state.agentNamesByServer = {};h.state.claudeDefinitions = [];- h.state.workdir = fakeFs();+ h.state.workspace = fakeFs();});it('finds a Codex agent from credentials alone', async () => {// The gap this feature closes: Codex has no repo-agent definitions, so the// definition-based scan sees nothing. The provider-neutral credentials file// is written for every provider, so it finds the agent anyway.- h.state.workdir = fakeFs({+ h.state.workspace = fakeFs({'.switch/agents/.gitignore': '*\n','.switch/agents/codex-hoot.json': creds('sw-codex'),'.switchdash/agents/codex-hoot/agent-launch-spec.json': launchSpec('codex'),@@ -133,7 +125,7 @@ describe('discoverConfiguredAgents', () => {it('never surfaces the API token', async () => {// Attaching must not need the secret: it stays on disk for the launch path.- h.state.workdir = fakeFs({+ h.state.workspace = fakeFs({'.switch/agents/hoot.json': creds('sw-1', 'https://switch.example.com', 'tok-do-not-leak'),});@@ -142,7 +134,7 @@ describe('discoverConfiguredAgents', () => {it('falls back to the owning provider definition, then to unknown', async () => {h.state.claudeDefinitions = [{ name: 'cc-hoot', description: null }];- h.state.workdir = fakeFs({+ h.state.workspace = fakeFs({'.switch/agents/cc-hoot.json': creds('sw-cc'),'.switch/agents/mystery.json': creds('sw-my'),});@@ -160,7 +152,7 @@ describe('discoverConfiguredAgents', () => {it('uses the provider definition and ignores obsolete sidecar launch specs', async () => {h.state.claudeDefinitions = [{ name: 'hoot', description: null }];- h.state.workdir = fakeFs({+ h.state.workspace = fakeFs({'.switch/agents/hoot.json': creds('sw-1'),'.switchdash/agents/hoot/agent-launch-spec.json': launchSpec('codex'),});@@ -169,8 +161,8 @@ describe('discoverConfiguredAgents', () => {});it('marks agents this Switch Console already has a row for', async () => {- h.state.agentNamesByWorkspace = { 'ws-srv-a': ['mine'] };- h.state.workdir = fakeFs({+ h.state.agentNamesByServer = { 'srv-a': ['mine'] };+ h.state.workspace = fakeFs({'.switch/agents/mine.json': creds('sw-mine'),'.switch/agents/theirs.json': creds('sw-theirs'),});@@ -184,8 +176,8 @@ describe('discoverConfiguredAgents', () => {// The directory is a place on disk, not one server's territory. An agent row// for server A says nothing about server B, and treating it as "already got// this" is what silently emptied the onboarding list.- h.state.agentNamesByWorkspace = { 'ws-srv-a': ['shared'] };- h.state.workdir = fakeFs({ '.switch/agents/shared.json': creds('sw-shared') });+ h.state.agentNamesByServer = { 'srv-a': ['shared'] };+ h.state.workspace = fakeFs({ '.switch/agents/shared.json': creds('sw-shared') });expect((await scan('srv-a'))[0]).toMatchObject({ name: 'shared', alreadyAgent: true });expect((await scan('srv-b'))[0]).toMatchObject({ name: 'shared', alreadyAgent: false });@@ -197,13 +189,13 @@ describe('discoverConfiguredAgents', () => {it('reports nothing for an unknown location rather than failing', async () => {h.state.location = undefined;- h.state.workdir = fakeFs({ '.switch/agents/hoot.json': creds('sw-1') });+ h.state.workspace = fakeFs({ '.switch/agents/hoot.json': creds('sw-1') });expect((await scan())[0]).toMatchObject({ name: 'hoot', alreadyAgent: false });});it('skips unusable credentials files instead of inventing an identity', async () => {- h.state.workdir = fakeFs({+ h.state.workspace = fakeFs({'.switch/agents/broken.json': '{ not json','.switch/agents/no-id.json': JSON.stringify({ env: { SWITCH_API_ENDPOINT: 'https://x' } }),'.switch/agents/good.json': creds('sw-good'),@@ -214,7 +206,7 @@ describe('discoverConfiguredAgents', () => {});it('ignores non-JSON entries such as the .gitignore', async () => {- h.state.workdir = fakeFs({+ h.state.workspace = fakeFs({'.switch/agents/.gitignore': '*\n','.switch/agents/hoot.json': creds('sw-1'),});diff --git a/console/apps/switch-console-desktop/src/main/core/agents/discover-configured-agents.ts b/console/apps/switch-console-desktop/src/main/core/agents/discover-configured-agents.tsindex fa38097ae..0682e4ac7 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/discover-configured-agents.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/discover-configured-agents.ts@@ -1,14 +1,13 @@import type { PluginFs } from '@switch-console/core/agents/plugins';import { getLocationByHostDir } from '@main/core/locations/store';import { listPlugins } from '@main/core/providers/plugin-registry';-import { requireWorkspaceForServer } from '@main/core/workspaces/workspaces-store';import { log } from '@main/lib/logger';import {isValidProviderId,type AgentProviderId,} from '@shared/core/providers/agent-provider-registry';-import { resolveWorkdirFsFor } from './agent-workdir-fs';-import { getLocationAgentsInWorkspace } from './getAgents';+import { resolveWorkspaceFsFor } from './agent-workspace-fs';+import { getLocationAgentsOnServer } from './getAgents';import { SWITCH_AGENTS_DIR_RELATIVE } from './switch-settings-paths';/** How an agent's provider was inferred, so the UI can say whether to trust it. */@@ -74,13 +73,13 @@ function parseCredentialIdentity(raw: string | null, name: string): CredentialId* concept at all. Built once per scan: each provider answers with its own* discovery rather than this module hardcoding any provider's on-disk layout.*/-async function definitionOwners(workdirFs: PluginFs): Promise<Map<string, AgentProviderId>> {+async function definitionOwners(workspaceFs: PluginFs): Promise<Map<string, AgentProviderId>> {const owners = new Map<string, AgentProviderId>();for (const plugin of listPlugins()) {const behavior = plugin.behavior.repoAgents;if (!behavior) continue;try {- for (const def of await behavior.discoverDefinitions(workdirFs)) {+ for (const def of await behavior.discoverDefinitions(workspaceFs)) {if (!owners.has(def.name) && isValidProviderId(plugin.metadata.id)) {owners.set(def.name, plugin.metadata.id);}@@ -123,29 +122,26 @@ export async function discoverConfiguredAgents(params: {* attached here already and still be attachable to another (CHOO-2044). */serverId: string;}): Promise<DiscoveredConfiguredAgent[]> {- const targetWorkspace = await requireWorkspaceForServer(params.serverId);const location = await getLocationByHostDir(params.sshHost, params.dir);const existing = location- ? new Set(- (await getLocationAgentsInWorkspace(location.id, targetWorkspace.id)).map((a) => a.name)- )+ ? new Set((await getLocationAgentsOnServer(location.id, params.serverId)).map((a) => a.name)): new Set<string>();- const workdir = await resolveWorkdirFsFor(params.sshHost, params.dir);+ const workspace = await resolveWorkspaceFsFor(params.sshHost, params.dir);try {- const names = (await workdir.fs.list(SWITCH_AGENTS_DIR_RELATIVE))+ const names = (await workspace.fs.list(SWITCH_AGENTS_DIR_RELATIVE)).filter((entry) => entry.endsWith('.json')).map((entry) => entry.slice(0, -'.json'.length)).filter((name) => name.length > 0).sort((a, b) => a.localeCompare(b));if (names.length === 0) return [];- const owners = await definitionOwners(workdir.fs);+ const owners = await definitionOwners(workspace.fs);const discovered: DiscoveredConfiguredAgent[] = [];for (const name of names) {const identity = parseCredentialIdentity(- await workdir.fs.read(`${SWITCH_AGENTS_DIR_RELATIVE}/${name}.json`),+ await workspace.fs.read(`${SWITCH_AGENTS_DIR_RELATIVE}/${name}.json`),name);if (!identity) continue;@@ -164,6 +160,6 @@ export async function discoverConfiguredAgents(params: {}return discovered;} finally {- workdir.close();+ workspace.close();}}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/discover-loadable-agents.ts b/console/apps/switch-console-desktop/src/main/core/agents/discover-loadable-agents.tsindex c622c1803..b43e7a13b 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/discover-loadable-agents.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/discover-loadable-agents.ts@@ -2,7 +2,7 @@ import { SshExecutionContext } from '@main/core/execution-context/ssh-execution-import { sshConnectionIdForHost } from '@main/core/locations/location-transport';import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';import { fetchAgents, fetchMe } from '@main/core/switch-servers/gateway-client';-import { withWorkspaceSession, workspaceServer } from '@main/core/workspaces/workspace-session';+import { getServer } from '@main/core/switch-servers/servers-store';import { log } from '@main/lib/logger';import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';import { sameApiEndpoint } from '@shared/core/switch-servers/switch-servers';@@ -41,7 +41,7 @@ export type LoadableAgent = {export type DiscoverLoadableAgentsParams = {sshHost: string;- workspaceId: string;+ serverId: string;/** When true, run a depth-limited `find` over `$HOME` in addition to the* cheap server-assisted discovery. Off by default — the walk can be slow* on large VMs. */@@ -68,22 +68,17 @@ export type DiscoverLoadableAgentsResult = {export async function discoverLoadableAgentsOnHost(params: DiscoverLoadableAgentsParams): Promise<DiscoverLoadableAgentsResult> {- const server = await workspaceServer(params.workspaceId);+ const server = await getServer(params.serverId);+ if (!server) throw new Error(`No Switch server with id ${params.serverId}`);// Key: "dir\0name" → LoadableAgent. Server entries inserted first win.const seen = new Map<string, LoadableAgent>();// --- Source 1: Server-assisted discovery ---try {- // Leased together: `GET /agents` answers for the selected tenant, and the- // owner marks below are only meaningful against the same one. The on-host- // scans that follow are SSH and need no session, so the lease ends here- // rather than being held across them.- const { remoteAgents, me } = await withWorkspaceSession(params.workspaceId, async () => ({- remoteAgents: await fetchAgents(server),- // Marks rows the signed-in user owns; an auth failure degrades to not-owner.- me: await fetchMe(server).catch(() => null),- }));+ const remoteAgents = await fetchAgents(server);+ // Marks rows the signed-in user owns; an auth failure degrades to not-owner.+ const me = await fetchMe(server).catch(() => null);// Collect distinct repo_dirs from agents whose known_agent_options carry one.type ServerAgentInfo = {@@ -114,7 +109,7 @@ export async function discoverLoadableAgentsOnHost(const discovered = await discoverConfiguredAgents({sshHost: params.sshHost,dir,- serverId: server.id,+ serverId: params.serverId,});for (const agent of discovered) {const key = `${dir}\0${agent.name}`;@@ -145,7 +140,7 @@ export async function discoverLoadableAgentsOnHost(}} catch (error) {log.warn('discoverLoadableAgentsOnHost: server-assisted discovery failed', {- workspaceId: params.workspaceId,+ serverId: params.serverId,error: error instanceof Error ? error.message : String(error),});}@@ -159,7 +154,7 @@ export async function discoverLoadableAgentsOnHost(const discovered = await discoverConfiguredAgents({sshHost: params.sshHost,dir,- serverId: server.id,+ serverId: params.serverId,});for (const agent of discovered) {const key = `${dir}\0${agent.name}`;@@ -255,16 +250,15 @@ async function findSwitchAgentDirsOnHost(sshHost: string): Promise<string[]> {export async function discoverLoadableAgentsInDir(params: {sshHost: string;dir: string;- workspaceId: string;+ serverId: string;}): Promise<{ agents: LoadableAgent[]; serverApiUrl: string }> {- // The server only, with no lease: this path makes no gateway call — the scan- // is on-host and the server is here for its API URL.- const server = await workspaceServer(params.workspaceId);+ const server = await getServer(params.serverId);+ if (!server) throw new Error(`No Switch server with id ${params.serverId}`);const discovered = await discoverConfiguredAgents({sshHost: params.sshHost,dir: params.dir,- serverId: server.id,+ serverId: params.serverId,});const agents = discovered.map((agent) => ({diff --git a/console/apps/switch-console-desktop/src/main/core/agents/discover-location-agents.ts b/console/apps/switch-console-desktop/src/main/core/agents/discover-location-agents.tsindex 899f059f1..a15565afe 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/discover-location-agents.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/discover-location-agents.ts@@ -1,9 +1,8 @@import { getLocationByHostDir } from '@main/core/locations/store';import { getPlugin } from '@main/core/providers/plugin-registry';-import { requireWorkspaceForServer } from '@main/core/workspaces/workspaces-store';import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';-import { resolveWorkdirFsFor } from './agent-workdir-fs';-import { getLocationAgentsInWorkspace } from './getAgents';+import { resolveWorkspaceFsFor } from './agent-workspace-fs';+import { getLocationAgentsOnServer } from './getAgents';export type DiscoveredLocationAgent = {/** The definition/launch name (`.claude/agents/<name>.md` stem, `--agent <name>`). */@@ -47,18 +46,15 @@ export async function discoverLocationAgents(params: {const behavior = getPlugin(params.providerId).behavior.repoAgents;if (!behavior) return [];- const targetWorkspace = await requireWorkspaceForServer(params.serverId);const location = await getLocationByHostDir(params.sshHost, params.dir);const existing = location- ? new Set(- (await getLocationAgentsInWorkspace(location.id, targetWorkspace.id)).map((a) => a.name)- )+ ? new Set((await getLocationAgentsOnServer(location.id, params.serverId)).map((a) => a.name)): new Set<string>();- const workdir = await resolveWorkdirFsFor(params.sshHost, params.dir);+ const workspace = await resolveWorkspaceFsFor(params.sshHost, params.dir);try {- const definitions = await behavior.discoverDefinitions(workdir.fs);- const local = await behavior.discoverLocal(workdir.fs, workdir.homeFs);+ const definitions = await behavior.discoverDefinitions(workspace.fs);+ const local = await behavior.discoverLocal(workspace.fs, workspace.homeFs);const credentialled = new Map(local.filter((l) => l.switchAgentId !== null).map((l) => [l.name, l.apiEndpoint]));@@ -71,6 +67,6 @@ export async function discoverLocationAgents(params: {alreadyAgent: existing.has(def.name),}));} finally {- workdir.close();+ workspace.close();}}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/getAgentById.ts b/console/apps/switch-console-desktop/src/main/core/agents/getAgentById.tsindex 334f898e4..9aeab349b 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/getAgentById.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/getAgentById.ts@@ -2,10 +2,10 @@ import { eq } from 'drizzle-orm';import { db } from '@main/db/client';import { agents } from '@main/db/schema';import type { Agent } from '@shared/core/agents/agents';-import { mapAgentRow } from './utils';+import { mapAgentRowToAgent } from './utils';export async function getAgentById(agentId: string): Promise<Agent | undefined> {const [row] = await db.select().from(agents).where(eq(agents.id, agentId)).limit(1);if (!row) return undefined;- return mapAgentRow(row);+ return mapAgentRowToAgent(row);}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/getAgents.ts b/console/apps/switch-console-desktop/src/main/core/agents/getAgents.tsindex ef3e64ca6..51edb0773 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/getAgents.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/getAgents.ts@@ -1,45 +1,37 @@import { and, desc, eq } from 'drizzle-orm';import { db } from '@main/db/client';-import { agents, workspaces } from '@main/db/schema';+import { agents } from '@main/db/schema';import type { Agent } from '@shared/core/agents/agents';import { mapAgentRowToAgent } from './utils';-/**- * Agents with the server hosting each one's workspace. Left-joined, because an- * unlinked agent has no workspace and still has to be listed.- */-function agentsWithServer() {- return db- .select({ agent: agents, serverId: workspaces.serverId })- .from(agents)- .leftJoin(workspaces, eq(agents.workspaceId, workspaces.id));-}-export async function getAgents(locationId?: string): Promise<Agent[]> {- const query = agentsWithServer();const rows = locationId- ? await query.where(eq(agents.locationId, locationId)).orderBy(desc(agents.updatedAt))- : await query.orderBy(desc(agents.updatedAt));- return rows.map((row) => mapAgentRowToAgent(row.agent, row.serverId));+ ? await db+ .select()+ .from(agents)+ .where(eq(agents.locationId, locationId))+ .orderBy(desc(agents.updatedAt))+ : await db.select().from(agents).orderBy(desc(agents.updatedAt));+ return rows.map(mapAgentRowToAgent);}/**- * A directory's agents that belong to one workspace.+ * A directory's agents that belong to one Switch server.*- * A directory is a place on disk, not a workspace's territory: the same folder- * can hold agents belonging to several. Anything answering "do I already have- * this agent" must therefore ask per workspace — asking per directory reports- * an agent in workspace A as already onboarded when the target is workspace B,- * and the candidate is silently dropped (CHOO-2044). Per workspace rather than- * per server because an agent's name is unique per tenant on the gateway, so- * two workspaces on one server can each hold a different agent of that name.+ * A directory is a place on disk, not a server's territory: the same folder can+ * hold agents registered against several servers. Anything answering "do I+ * already have this agent" must therefore ask per server — asking per directory+ * reports an agent on server A as already onboarded when the target is server B,+ * and the candidate is silently dropped (CHOO-2044).*/-export async function getLocationAgentsInWorkspace(+export async function getLocationAgentsOnServer(locationId: string,- workspaceId: string+ serverId: string): Promise<Agent[]> {- const rows = await agentsWithServer()- .where(and(eq(agents.locationId, locationId), eq(agents.workspaceId, workspaceId)))+ const rows = await db+ .select()+ .from(agents)+ .where(and(eq(agents.locationId, locationId), eq(agents.serverId, serverId))).orderBy(desc(agents.updatedAt));- return rows.map((row) => mapAgentRowToAgent(row.agent, row.serverId));+ return rows.map(mapAgentRowToAgent);}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/migrate-agent-storage.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/migrate-agent-storage.test.tsindex d2ba105c7..eb7780a03 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/migrate-agent-storage.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/migrate-agent-storage.test.ts@@ -40,7 +40,7 @@ function credsJson(agentId: string): string {}// Shared mock state + spies. Hoisted so the vi.mock factories (which are lifted-// above imports) can reference them. `agents`/`workdir` are set per test.+// above imports) can reference them. `agents`/`workspace` are set per test.// `repoAgents` is the behavior `getPlugin` returns — set it to null in a test to// simulate a provider without repo-agent definitions (e.g. Codex).const h = vi.hoisted(() => {@@ -65,11 +65,11 @@ const h = vi.hoisted(() => {};const state: {agents: Array<Record<string, unknown>>;- workdir: PluginFs | null;+ workspace: PluginFs | null;repoAgents: object | null;} = {agents: [],- workdir: null,+ workspace: null,repoAgents: defaultRepoAgents,};return {@@ -91,10 +91,10 @@ vi.mock('@main/core/providers/plugin-registry', () => ({vi.mock('@main/core/locations/store', () => ({getLocationById: vi.fn(async () => ({ id: 'loc', sshHost: null, dir: '/repo' })),}));-vi.mock('./agent-workdir-fs', () => ({- resolveWorkdirFsFor: vi.fn(async () => ({- fs: h.state.workdir,- homeFs: h.state.workdir,+vi.mock('./agent-workspace-fs', () => ({+ resolveWorkspaceFsFor: vi.fn(async () => ({+ fs: h.state.workspace,+ homeFs: h.state.workspace,close: () => {},})),}));@@ -134,7 +134,7 @@ describe('migrateAgentStorage', () => {'.switch/agents/agent-id-1.json': credsJson('sw-1'),'.claude/agents/cc-hoot-main.md': '# def',});- h.state.workdir = ws;+ h.state.workspace = ws;await migrateAgentStorage();@@ -152,7 +152,7 @@ describe('migrateAgentStorage', () => {h.state.agents = [{ ...baseAgent, providerId: 'codex', name: 'codex-hoot' }];h.state.repoAgents = null;const ws = fakeFs({ '.switch/agents/agent-id-1.json': credsJson('sw-1') });- h.state.workdir = ws;+ h.state.workspace = ws;await migrateAgentStorage();@@ -172,7 +172,7 @@ describe('migrateAgentStorage', () => {'.claude/settings.local.json': credsJson('sw-1'),'.claude/agents/cc-hoot-main.md': '# def',});- h.state.workdir = ws;+ h.state.workspace = ws;await migrateAgentStorage();@@ -195,7 +195,7 @@ describe('migrateAgentStorage', () => {h.state.repoAgents = null;const ws = fakeFs({ '.claude/settings.local.json': credsJson('sw-CLAUDE-MAIN') });const read = vi.spyOn(ws, 'read');- h.state.workdir = ws;+ h.state.workspace = ws;await migrateAgentStorage();@@ -212,7 +212,7 @@ describe('migrateAgentStorage', () => {];h.state.repoAgents = null;const ws = fakeFs({ '.claude/settings.local.json': credsJson('sw-CLAUDE-MAIN') });- h.state.workdir = ws;+ h.state.workspace = ws;await migrateAgentStorage();@@ -226,7 +226,7 @@ describe('migrateAgentStorage', () => {'.claude/settings.local.json': credsJson('sw-other'),'.claude/agents/cc-hoot-main.md': '# def',});- h.state.workdir = ws;+ h.state.workspace = ws;await migrateAgentStorage();@@ -248,7 +248,7 @@ describe('migrateAgentStorage', () => {h.state.agents = [{ ...baseAgent, providerId: 'codex', name: 'codex-hoot' }];h.state.repoAgents = null;const ws = fakeFs({ '.switch/agents/agent-id-1.json': credsJson('sw-other') });- h.state.workdir = ws;+ h.state.workspace = ws;await migrateAgentStorage();@@ -269,7 +269,7 @@ describe('migrateAgentStorage', () => {'.claude/agents/cc-hoot-main.md': '# def',};const ws = fakeFs({ ...seed });- h.state.workdir = ws;+ h.state.workspace = ws;await migrateAgentStorage();@@ -281,33 +281,33 @@ describe('migrateAgentStorage', () => {it('writes no credentials when none exist anywhere (unrecoverable token)', async () => {const ws = fakeFs({ '.claude/agents/cc-hoot-main.md': '# def' });- h.state.workdir = ws;+ h.state.workspace = ws;await migrateAgentStorage();expect(await ws.exists('.switch/agents/cc-hoot-main.json')).toBe(false);});- it('skips the whole pass (no workdir opened) once the current generation is latched', async () => {+ it('skips the whole pass (no workspace opened) once the current generation is latched', async () => {h.completedGeneration.mockResolvedValueOnce(2);- const resolveWorkdirFsFor = (await import('./agent-workdir-fs')).resolveWorkdirFsFor;+ const resolveWorkspaceFsFor = (await import('./agent-workspace-fs')).resolveWorkspaceFsFor;await migrateAgentStorage();- expect(resolveWorkdirFsFor).not.toHaveBeenCalled();+ expect(resolveWorkspaceFsFor).not.toHaveBeenCalled();expect(h.markComplete).not.toHaveBeenCalled();});- it('re-running for generation 2 opens no workdir for a provider generation 1 already did', async () => {+ it('re-running for generation 2 opens no workspace for a provider generation 1 already did', async () => {// Generation 2 only broadened the credential step to providers WITHOUT a- // behavior, so re-opening a Claude agent's workdir — an SSH connect and an+ // behavior, so re-opening a Claude agent's workspace — an SSH connect and an// SFTP channel for a remote one — could not change anything.h.completedGeneration.mockResolvedValueOnce(1);- const resolveWorkdirFsFor = (await import('./agent-workdir-fs')).resolveWorkdirFsFor;+ const resolveWorkspaceFsFor = (await import('./agent-workspace-fs')).resolveWorkspaceFsFor;await migrateAgentStorage();- expect(resolveWorkdirFsFor).not.toHaveBeenCalled();+ expect(resolveWorkspaceFsFor).not.toHaveBeenCalled();expect(h.markComplete).toHaveBeenCalledTimes(1);});@@ -316,7 +316,7 @@ describe('migrateAgentStorage', () => {h.state.agents = [{ ...baseAgent, providerId: 'codex', name: 'codex-hoot' }];h.state.repoAgents = null;const ws = fakeFs({ '.switch/agents/agent-id-1.json': credsJson('sw-1') });- h.state.workdir = ws;+ h.state.workspace = ws;await migrateAgentStorage();@@ -324,7 +324,7 @@ describe('migrateAgentStorage', () => {});it('latches the marker after a clean pass', async () => {- h.state.workdir = fakeFs({+ h.state.workspace = fakeFs({'.switch/agents/cc-hoot-main.json': credsJson('sw-1'),'.claude/agents/cc-hoot-main.md': '# def',});@@ -335,7 +335,7 @@ describe('migrateAgentStorage', () => {});it('does not latch the marker when an agent migration throws', async () => {- h.state.workdir = fakeFs({+ h.state.workspace = fakeFs({'.switch/agents/cc-hoot-main.json': credsJson('sw-1'),'.claude/agents/cc-hoot-main.md': '# def',});diff --git a/console/apps/switch-console-desktop/src/main/core/agents/migrate-agent-storage.ts b/console/apps/switch-console-desktop/src/main/core/agents/migrate-agent-storage.tsindex 9ca238177..51a370cdc 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/migrate-agent-storage.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/migrate-agent-storage.ts@@ -11,7 +11,7 @@ import {completedAgentStorageMigrationGeneration,markAgentStorageMigrationComplete,} from './agent-storage-migration-marker';-import { resolveWorkdirFsFor } from './agent-workdir-fs';+import { resolveWorkspaceFsFor } from './agent-workspace-fs';import { getAgents } from './getAgents';import { agentSettingsRelativePath, SWITCH_SETTINGS_RELATIVE_PATH } from './switch-settings-paths';import { writeNeutralAgentSettingsFs } from './write-switch-settings';@@ -32,7 +32,7 @@ import { writeNeutralAgentSettingsFs } from './write-switch-settings';*/export async function migrateAgentStorage(): Promise<void> {// Once a full pass has migrated every agent, never re-run: the steady-state- // migration re-opens each agent's workdir filesystem (an SSH/SFTP round trip+ // migration re-opens each agent's workspace filesystem (an SSH/SFTP round trip// per remote agent) on every boot for no benefit.const completed = await completedAgentStorageMigrationGeneration();if (completed >= AGENT_STORAGE_MIGRATION_GENERATION) return;@@ -65,7 +65,7 @@ export async function migrateAgentStorage(): Promise<void> {** `completedGeneration` is the generation this install already finished, so a* re-run can skip agents the new generation cannot change — the check happens- * before the workdir filesystem is opened, which for a remote agent is an SSH+ * before the workspace filesystem is opened, which for a remote agent is an SSH* connect and an SFTP channel.*/async function migrateOne(agent: Agent, completedGeneration: number): Promise<boolean> {@@ -78,13 +78,13 @@ async function migrateOne(agent: Agent, completedGeneration: number): Promise<bo// Generation 2 only broadened step 1 to providers WITHOUT a behavior; for one// that has it, every step is what generation 1 already ran. Skipping here is- // what keeps the generation bump from re-opening a workdir per Claude agent.+ // what keeps the generation bump from re-opening a workspace per Claude agent.if (completedGeneration >= 1 && behavior) return false;const location = await getLocationById(agent.locationId);if (!location) return false;- const workdir = await resolveWorkdirFsFor(location.sshHost, location.dir);+ const workspace = await resolveWorkspaceFsFor(location.sshHost, location.dir);try {// The agent's identity is its single `name` (CHOO-1440): the creds/definition// stem on disk. It is authoritative — earlier migrations, and the 0041 SQL@@ -111,13 +111,13 @@ async function migrateOne(agent: Agent, completedGeneration: number): Promise<bo// to recover it — nothing can reconstruct it from the gateway.const idKeyedRelPath = agentSettingsRelativePath(agent.id);const namedRelPath = agentSettingsRelativePath(name);- const neutral = name === agent.id ? null : await workdir.fs.read(namedRelPath);+ const neutral = name === agent.id ? null : await workspace.fs.read(namedRelPath);if (neutral === null) {const recovered =- parseSwitchAgentCredentials(await workdir.fs.read(idKeyedRelPath), log) ??- (behavior ? toCreds(await behavior.readLaunchEnv(workdir.fs, name)) : null) ??+ parseSwitchAgentCredentials(await workspace.fs.read(idKeyedRelPath), log) ??+ (behavior ? toCreds(await behavior.readLaunchEnv(workspace.fs, name)) : null) ??(behavior- ? parseSwitchAgentCredentials(await workdir.fs.read(SWITCH_SETTINGS_RELATIVE_PATH), log)+ ? parseSwitchAgentCredentials(await workspace.fs.read(SWITCH_SETTINGS_RELATIVE_PATH), log): null);if (recovered && !belongsToAgent(agent, recovered)) {log.warn('migrateAgentStorage: recovered credentials name a different Switch agent', {@@ -128,7 +128,7 @@ async function migrateOne(agent: Agent, completedGeneration: number): Promise<bofoundSwitchAgentId: recovered.agentId,});} else if (recovered) {- await writeNeutralAgentSettingsFs(workdir.fs, {+ await writeNeutralAgentSettingsFs(workspace.fs, {slug: name,apiEndpoint: recovered.apiEndpoint,apiToken: recovered.token,@@ -141,9 +141,9 @@ async function migrateOne(agent: Agent, completedGeneration: number): Promise<bo// Remove the stale ID-keyed neutral file once the name-keyed one is in place:// an incomplete leftover there otherwise shadows the real creds in the// session preflight (which scans both), and a complete one is now redundant.- if (name !== agent.id && (await workdir.fs.read(namedRelPath)) !== null) {- if ((await workdir.fs.read(idKeyedRelPath)) !== null) {- await workdir.fs.delete(idKeyedRelPath);+ if (name !== agent.id && (await workspace.fs.read(namedRelPath)) !== null) {+ if ((await workspace.fs.read(idKeyedRelPath)) !== null) {+ await workspace.fs.delete(idKeyedRelPath);changed = true;}}@@ -151,14 +151,14 @@ async function migrateOne(agent: Agent, completedGeneration: number): Promise<bo// 2. Definition: ensure the provider has an on-disk definition for this agent// so it runs as a named repository-defined agent. Behavior providers only —// a provider without definitions (Codex) has nothing to write here.- if (behavior && (await behavior.readDefinition(workdir.fs, name)) === null) {- await behavior.writeDefinition(workdir.fs, { name, description });+ if (behavior && (await behavior.readDefinition(workspace.fs, name)) === null) {+ await behavior.writeDefinition(workspace.fs, { name, description });changed = true;}return changed;} finally {- workdir.close();+ workspace.close();}}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/onboard-agent.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/onboard-agent.test.tsindex 144156fc5..fde36e2f4 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@@ -44,12 +44,6 @@ vi.mock('@main/core/switch-rooms/switch-credentials', () => ({vi.mock('@main/core/switch-servers/servers-store', () => ({getServer: vi.fn(async () => h.server),}));-vi.mock('@main/core/workspaces/workspaces-store', () => ({- requireWorkspaceForServer: vi.fn(async (serverId: string) => ({ id: `ws-${serverId}` })),-}));-vi.mock('@main/core/workspaces/workspace-session', () => ({- withWorkspaceSession: (_workspaceId: string, fn: (server: unknown) => unknown) => fn(h.server),-}));vi.mock('@main/core/switch-servers/gateway-client', () => {class GatewayError extends Error {constructor(readonly kind: string) {diff --git a/console/apps/switch-console-desktop/src/main/core/agents/onboard-agent.ts b/console/apps/switch-console-desktop/src/main/core/agents/onboard-agent.tsindex adb5c392c..8aa129be6 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/onboard-agent.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/onboard-agent.ts@@ -9,8 +9,6 @@ import { getServer } from '@main/core/switch-servers/servers-store';import { agentTypeOf } from '@main/core/telemetry/agent-type';import type { TelemetryAgentCreateFailure } from '@main/core/telemetry/events';import { trackEvent } from '@main/core/telemetry/telemetry-service';-import { withWorkspaceSession } from '@main/core/workspaces/workspace-session';-import { requireWorkspaceForServer } from '@main/core/workspaces/workspaces-store';import { log } from '@main/lib/logger';import type {OnboardAgentError,@@ -86,32 +84,33 @@ async function verifyAgentOnServer(agentId: string,dir: string): Promise<OnboardAgentError | null> {- const workspace = await requireWorkspaceForServer(serverId);- return withWorkspaceSession(workspace.id, async (server) => {- try {- const exists = await agentExistsOnServer(server, agentId);- if (!exists) {- return {- type: 'switch-agent-not-on-server',- dir,- serverId: server.id,- serverName: server.name,- agentId,- };- }- return null;- } catch (cause) {- if (cause instanceof GatewayError && cause.kind === 'unauthorized') {- return {- type: 'switch-server-unauthenticated',- dir,- serverId: server.id,- serverName: server.name,- };- }- throw cause;+ const server = await getServer(serverId);+ if (!server) {+ throw new Error(`No Switch server with id ${serverId}`);+ }+ try {+ const exists = await agentExistsOnServer(server, agentId);+ if (!exists) {+ return {+ type: 'switch-agent-not-on-server',+ dir,+ serverId: server.id,+ serverName: server.name,+ agentId,+ };}- });+ return null;+ } catch (cause) {+ if (cause instanceof GatewayError && cause.kind === 'unauthorized') {+ return {+ type: 'switch-server-unauthenticated',+ dir,+ serverId: server.id,+ serverName: server.name,+ };+ }+ throw cause;+ }}/**@@ -186,8 +185,6 @@ export async function onboardAgent(params: OnboardAgentParams): Promise<OnboardA}}- const targetWorkspace = await requireWorkspaceForServer(params.serverId);-const location = await ensureLocation({ sshHost, dir: params.dir, name: params.name });const agent = await createAgent({@@ -197,7 +194,7 @@ export async function onboardAgent(params: OnboardAgentParams): Promise<OnboardAproviderId: params.providerId,switchAgentId: switchAgent.agentId,apiEndpoint: switchAgent.apiEndpoint,- workspaceId: targetWorkspace.id,+ serverId: params.serverId,// Honor an explicit choice from the add-agent modal; otherwise default by// run location — remote agents run unattended on their VM with no operator// to answer permission prompts, so default them to bypass, local off.diff --git a/console/apps/switch-console-desktop/src/main/core/agents/onboard-location-agents.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/onboard-location-agents.test.tsindex c70ca5c4b..3c8e2304a 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/onboard-location-agents.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/onboard-location-agents.test.ts@@ -9,7 +9,7 @@ const h = vi.hoisted(() => {}const state: {/** Agent-row names already in the directory, per Switch server. */- agentNamesByWorkspace: Record<string, string[]>;+ agentNamesByServer: Record<string, string[]>;definitions: Array<{name: string;description: string | null;@@ -20,7 +20,7 @@ const h = vi.hoisted(() => {local: Array<{ name: string; switchAgentId: string | null; apiEndpoint: string | null }>;/** Switch agent ids the target server admits to having. */idsOnServer: string[];- } = { agentNamesByWorkspace: {}, definitions: [], local: [], idsOnServer: [] };+ } = { agentNamesByServer: {}, definitions: [], local: [], idsOnServer: [] };return {state,GatewayError,@@ -44,24 +44,12 @@ vi.mock('@main/core/locations/store', () => ({ensureLocation: vi.fn(async () => ({ id: 'loc-1' })),}));vi.mock('./getAgents', () => ({- getLocationAgentsInWorkspace: vi.fn(async (_locationId: string, workspaceId: string) =>- (h.state.agentNamesByWorkspace[workspaceId] ?? []).map((name) => ({ name }))+ getLocationAgentsOnServer: vi.fn(async (_locationId: string, serverId: string) =>+ (h.state.agentNamesByServer[serverId] ?? []).map((name) => ({ name }))),}));-vi.mock('@main/core/workspaces/workspaces-store', () => ({- requireWorkspaceForServer: vi.fn(async (serverId: string) => ({ id: `ws-${serverId}` })),-}));--const mockServer = vi.hoisted(() => ({- id: 'srv-b',- name: 'Server B',- apiUrl: 'https://b.example.com',-}));-vi.mock('@main/core/workspaces/workspace-session', () => ({- withWorkspaceSession: (_workspaceId: string, fn: (server: unknown) => unknown) => fn(mockServer),-}));-vi.mock('./agent-workdir-fs', () => ({- resolveWorkdirFsFor: vi.fn(async () => ({+vi.mock('./agent-workspace-fs', () => ({+ resolveWorkspaceFsFor: vi.fn(async () => ({fs: {} as PluginFs,homeFs: {} as PluginFs,close: vi.fn(),@@ -82,7 +70,11 @@ vi.mock('@main/core/switch-servers/gateway-client', () => ({GatewayError: h.GatewayError,}));vi.mock('@main/core/switch-servers/servers-store', () => ({- getServer: vi.fn(async () => mockServer),+ getServer: vi.fn(async () => ({+ id: 'srv-b',+ name: 'Server B',+ apiUrl: 'https://b.example.com',+ })),findServerByEndpoint: vi.fn(async (endpoint: string) =>endpoint === 'https://a.example.com'? { id: 'srv-a', name: 'Server A', apiUrl: 'https://a.example.com' }@@ -123,7 +115,7 @@ function definition(name: string, registered: boolean) {describe('onboardLocationAgents identity resolution', () => {beforeEach(() => {vi.clearAllMocks();- h.state.agentNamesByWorkspace = {};+ h.state.agentNamesByServer = {};h.state.definitions = [];h.state.local = [];h.state.idsOnServer = [];@@ -182,11 +174,7 @@ describe('onboardLocationAgents identity resolution', () => {it('imports an identity the target server does have', async () => {h.state.definitions = [definition('mine', true)];h.state.local = [- {- name: 'mine',- switchAgentId: 'sw-on-b',- apiEndpoint: 'https://b.example.com',- },+ { name: 'mine', switchAgentId: 'sw-on-b', apiEndpoint: 'https://b.example.com' },];h.state.idsOnServer = ['sw-on-b'];@@ -196,7 +184,7 @@ describe('onboardLocationAgents identity resolution', () => {expect(h.registerAgentIdentity).not.toHaveBeenCalled();expect(h.writeNeutralAgentSettings).not.toHaveBeenCalled();expect(h.createAgent).toHaveBeenCalledWith(- expect.objectContaining({ name: 'mine', switchAgentId: 'sw-on-b', workspaceId: 'ws-srv-b' })+ expect.objectContaining({ name: 'mine', switchAgentId: 'sw-on-b', serverId: 'srv-b' }));});@@ -234,7 +222,7 @@ describe('onboardLocationAgents identity resolution', () => {it('offers a definition already onboarded onto another server', async () => {// Same directory, same name, different server — a separate agent.- h.state.agentNamesByWorkspace = { 'ws-srv-a': ['shared'] };+ h.state.agentNamesByServer = { 'srv-a': ['shared'] };h.state.definitions = [definition('shared', false)];h.state.local = [{ name: 'shared', switchAgentId: null, apiEndpoint: null }];@@ -242,7 +230,7 @@ describe('onboardLocationAgents identity resolution', () => {expect(result.success).toBe(true);expect(h.createAgent).toHaveBeenCalledWith(- expect.objectContaining({ name: 'shared', workspaceId: 'ws-srv-b' })+ expect.objectContaining({ name: 'shared', serverId: 'srv-b' }));});});diff --git a/console/apps/switch-console-desktop/src/main/core/agents/onboard-location-agents.ts b/console/apps/switch-console-desktop/src/main/core/agents/onboard-location-agents.tsindex c9337fa9a..e7a5d0218 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/onboard-location-agents.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/onboard-location-agents.ts@@ -8,8 +8,6 @@ import { ensureLocation } from '@main/core/locations/store';import { getPlugin } from '@main/core/providers/plugin-registry';import { agentExistsOnServer, GatewayError } from '@main/core/switch-servers/gateway-client';import { findServerByEndpoint, getServer } from '@main/core/switch-servers/servers-store';-import { withWorkspaceSession } from '@main/core/workspaces/workspace-session';-import { requireWorkspaceForServer } from '@main/core/workspaces/workspaces-store';import { log } from '@main/lib/logger';import { agentAvatarUrlForName } from '@shared/core/agents/agent-avatar';import type { Agent } from '@shared/core/agents/agents';@@ -18,9 +16,9 @@ import type { AgentProviderId } from '@shared/core/providers/agent-provider-regiimport type { SwitchServer } from '@shared/core/switch-servers/switch-servers';import { basenameFromAnyPath } from '@shared/path-name';import { agentEvents } from './agent-events';-import { resolveWorkdirFsFor, type WorkdirFs } from './agent-workdir-fs';+import { resolveWorkspaceFsFor, type WorkspaceFs } from './agent-workspace-fs';import { createAgent } from './createAgent';-import { getLocationAgentsInWorkspace } from './getAgents';+import { getLocationAgentsOnServer } from './getAgents';import { registerAgentIdentity } from './register-agent-identity';import { reconcileAgentAutoSessionFromGateway } from './setAgentAutoSession';import { writeNeutralAgentSettingsFs } from './write-switch-settings';@@ -86,24 +84,18 @@ async function resolveIdentity(description: string | null,ctx: {server: SwitchServer;- /** The workspace the agents are being onboarded into; every gateway call here is scoped to it. */- workspaceId: string;- workdir: WorkdirFs;+ workspace: WorkspaceFs;credsByName: Map<string, { switchAgentId: string | null; apiEndpoint: string | null }>;dir: string;}): Promise<{ ok: true; identity: ResolvedIdentity } | { ok: false; error: OnboardAgentError }> {const creds = ctx.credsByName.get(name);if (creds?.switchAgentId && creds.apiEndpoint) {- const switchAgentId = creds.switchAgentId;try {- const exists = await withWorkspaceSession(ctx.workspaceId, (target) =>- agentExistsOnServer(target, switchAgentId)- );- if (exists) {+ if (await agentExistsOnServer(ctx.server, creds.switchAgentId)) {return {ok: true,- identity: { switchAgentId, apiEndpoint: creds.apiEndpoint },+ identity: { switchAgentId: creds.switchAgentId, apiEndpoint: creds.apiEndpoint },};}} catch (cause) {@@ -132,22 +124,20 @@ async function resolveIdentity(// No usable credentials — adopt: mint a fresh identity and write its creds,// keeping the existing definition file untouched.- const registered = await withWorkspaceSession(ctx.workspaceId, (target) =>- registerAgentIdentity(target, {- name,- description: description ?? `Claude Code agent ${name}`,- repoDir: ctx.dir,- autoSession: true,- // This path onboards `.claude/agents/*.md` definitions, so the identity is a- // Claude Code one by construction.- agentType: knownAgentTypeForProvider('claude'),- // Nobody is at a form to choose one, so it starts with the avatar its name- // generates — the same picture it would be shown with anyway.- iconUrl: agentAvatarUrlForName(name),- // The definition file carries no human label, so there is none to adopt.- displayName: null,- })- );+ const registered = await registerAgentIdentity(ctx.server, {+ name,+ description: description ?? `Claude Code agent ${name}`,+ repoDir: ctx.dir,+ autoSession: true,+ // This path onboards `.claude/agents/*.md` definitions, so the identity is a+ // Claude Code one by construction.+ agentType: knownAgentTypeForProvider('claude'),+ // Nobody is at a form to choose one, so it starts with the avatar its name+ // generates — the same picture it would be shown with anyway.+ iconUrl: agentAvatarUrlForName(name),+ // The definition file carries no human label, so there is none to adopt.+ displayName: null,+ });if (registered.kind !== 'created') {const message = 'message' in registered ? registered.message : '';return {@@ -156,7 +146,7 @@ async function resolveIdentity(};}- await writeNeutralAgentSettingsFs(ctx.workdir.fs, {+ await writeNeutralAgentSettingsFs(ctx.workspace.fs, {slug: name,apiEndpoint: ctx.server.apiUrl,apiToken: registered.apiKey,@@ -206,16 +196,15 @@ export async function onboardLocationAgents(name: params.locationName ?? basenameFromAnyPath(params.dir) ?? params.providerId,});- const targetWorkspace = await requireWorkspaceForServer(params.serverId);const existing = new Set(- (await getLocationAgentsInWorkspace(location.id, targetWorkspace.id)).map((a) => a.name)+ (await getLocationAgentsOnServer(location.id, params.serverId)).map((a) => a.name));- const workdir = await resolveWorkdirFsFor(params.sshHost, params.dir);+ const workspace = await resolveWorkspaceFsFor(params.sshHost, params.dir);const created: Agent[] = [];try {- const definitions = await behavior.discoverDefinitions(workdir.fs);- const local = await behavior.discoverLocal(workdir.fs, workdir.homeFs);+ const definitions = await behavior.discoverDefinitions(workspace.fs);+ const local = await behavior.discoverLocal(workspace.fs, workspace.homeFs);const credsByName = new Map(local.map((l) => [l.name, l]));// Onboardable = a definition that can join Switch and isn't already a row.@@ -245,8 +234,7 @@ export async function onboardLocationAgents(for (const def of selected) {const resolved = await resolveIdentity(def.name, def.description, {server,- workspaceId: targetWorkspace.id,- workdir,+ workspace,credsByName,dir: params.dir,});@@ -259,7 +247,7 @@ export async function onboardLocationAgents(providerId: params.providerId,switchAgentId: resolved.identity.switchAgentId,apiEndpoint: resolved.identity.apiEndpoint,- workspaceId: targetWorkspace.id,+ serverId: params.serverId,autoApprove: params.sshHost !== null,});existing.add(def.name);@@ -273,7 +261,7 @@ export async function onboardLocationAgents(});}} finally {- workdir.close();+ workspace.close();}if (created.length === 0) {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..39b884bd7 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/propagate-server-api-url.db.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/propagate-server-api-url.db.test.ts@@ -5,7 +5,7 @@ import { openFixture } from '@tooling/utils/db';import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { AppDb } from '@main/db/client';-import { agents, locations, switchServers, workspaces } from '@main/db/schema';+import { agents, locations, switchServers } from '@main/db/schema';import { propagateServerApiUrl } from './propagate-server-api-url';import { agentSettingsRelativePath, SWITCH_SETTINGS_RELATIVE_PATH } from './switch-settings-paths';@@ -69,13 +69,6 @@ describe('propagateServerApiUrl', () => {apiUrl: 'https://other-api.example.com',},]);-- // Deliberately not the servers' ids: the cascade has to find agents through- // their workspace, and identical ids would hide it not doing so.- await fixture.db.insert(workspaces).values([- { id: 'ws-pilot', serverId: 'pilot', name: 'Pilot' },- { id: 'ws-other', serverId: 'other', name: 'Other' },- ]);});afterEach(async () => {@@ -103,7 +96,7 @@ describe('propagateServerApiUrl', () => {switchAgentId: 'switch-agent-1',providerId: 'claude',apiEndpoint: 'https://old-api.example.com',- workspaceId: 'ws-pilot',+ serverId: 'pilot',});const results = await propagateServerApiUrl('pilot', 'https://new-api.example.com');@@ -159,7 +152,7 @@ describe('propagateServerApiUrl', () => {locationId: 'named-location',name: 'named-agent',providerId,- workspaceId: 'ws-pilot',+ serverId: 'pilot',apiEndpoint: env.SWITCH_API_ENDPOINT,});expect(await propagateServerApiUrl('pilot', 'https://new-api.example.com')).toMatchObject([@@ -192,7 +185,7 @@ describe('propagateServerApiUrl', () => {locationId: 'broken-location',name: 'broken-agent',providerId: 'codex',- workspaceId: 'ws-pilot',+ serverId: 'pilot',});expect(await propagateServerApiUrl('pilot', 'https://new-api.example.com')).toMatchObject([{ agentId: 'broken-agent', outcome: 'failed', error: expect.stringContaining('invalid') },@@ -218,7 +211,7 @@ describe('propagateServerApiUrl', () => {locationId: 'shared-location',name: 'agent-a',providerId: 'codex',- workspaceId: 'ws-pilot',+ serverId: 'pilot',switchAgentId: 'agent-a-identity',},{@@ -226,7 +219,7 @@ describe('propagateServerApiUrl', () => {locationId: 'shared-location',name: 'agent-b',providerId: 'claude',- workspaceId: 'ws-other',+ serverId: 'other',switchAgentId: 'agent-b-identity',},]);@@ -246,7 +239,7 @@ describe('propagateServerApiUrl', () => {name: 'bare-agent',providerId: 'claude',apiEndpoint: null,- workspaceId: 'ws-pilot',+ serverId: 'pilot',});const results = await propagateServerApiUrl('pilot', 'https://new-api.example.com');@@ -279,7 +272,7 @@ describe('propagateServerApiUrl', () => {name: 'other-agent',providerId: 'claude',apiEndpoint: 'https://other-api.example.com',- workspaceId: 'ws-other',+ serverId: 'other',});const results = await propagateServerApiUrl('pilot', 'https://new-api.example.com');diff --git a/console/apps/switch-console-desktop/src/main/core/agents/propagate-server-api-url.ts b/console/apps/switch-console-desktop/src/main/core/agents/propagate-server-api-url.tsindex d98378ee8..0e8d166a1 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/propagate-server-api-url.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/propagate-server-api-url.ts@@ -6,7 +6,7 @@ import { FileSystemError, FileSystemErrorCodes } from '@main/core/fs/types';import { sshConnectionIdForHost } from '@main/core/locations/location-transport';import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';import { db } from '@main/db/client';-import { agents, workspaces } from '@main/db/schema';+import { agents } from '@main/db/schema';import { log } from '@main/lib/logger';import type { Agent } from '@shared/core/agents/agents';import type { AgentApiUrlPropagation } from '@shared/core/switch-servers/switch-servers';@@ -155,8 +155,7 @@ async function propagateToAgent(}/**- * Cascade a server's new API URL to every agent in any of its workspaces —- * the URL is the server's, so all of them move together. Rewrites each+ * Cascade a server's new API URL to every agent linked to it, rewriting each* agent's on-disk `SWITCH_API_ENDPOINT` (local dir or remote SSH host) and the* DB mirror. Agents keep their token; unprovisioned agents are skipped, not* clobbered. Returns a per-agent summary — failures are reported, never@@ -167,14 +166,10 @@ export async function propagateServerApiUrl(serverId: string,apiEndpoint: string): Promise<AgentApiUrlPropagation[]> {- const rows = await db- .select({ agent: agents })- .from(agents)- .innerJoin(workspaces, eq(agents.workspaceId, workspaces.id))- .where(eq(workspaces.serverId, serverId));+ const rows = await db.select().from(agents).where(eq(agents.serverId, serverId));const results: AgentApiUrlPropagation[] = [];for (const row of rows) {- results.push(await propagateToAgent(mapAgentRowToAgent(row.agent, serverId), apiEndpoint));+ results.push(await propagateToAgent(mapAgentRowToAgent(row), apiEndpoint));}return results;}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/remote-session-reconciler.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/remote-session-reconciler.test.tsindex 931a07e23..3e0492a85 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/remote-session-reconciler.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/remote-session-reconciler.test.ts@@ -7,6 +7,7 @@ import {const mocks = vi.hoisted(() => ({list: vi.fn(),+ server: vi.fn(async () => ({ id: 'server', gatewayUrl: 'https://example.test' })),snapshot: vi.fn(),room: vi.fn(),create: vi.fn(async () => ({ success: true })),@@ -24,14 +25,12 @@ vi.mock('./getAgentById', () => ({id: 'local',switchAgentId: 'agent',serverId: 'server',- workspaceId: 'workspace',providerId: 'codex',autoApprove: false,}),}));-vi.mock('@main/core/workspaces/workspace-session', () => ({- withWorkspaceSession: (_workspaceId: string, fn: (server: { id: string }) => Promise<unknown>) =>- fn({ id: 'server' }),+vi.mock('@main/core/switch-servers/servers-store', () => ({+ getServer: mocks.server,}));vi.mock('@main/core/switch-servers/gateway-client', () => ({fetchRoomDetail: mocks.room,diff --git a/console/apps/switch-console-desktop/src/main/core/agents/remote-session-reconciler.ts b/console/apps/switch-console-desktop/src/main/core/agents/remote-session-reconciler.tsindex 1a9d85b32..cc84c333a 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/remote-session-reconciler.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/remote-session-reconciler.ts@@ -6,7 +6,7 @@ import { sessionWasDeleted } from '@main/core/sessions/deleted-sessions';import { sessionService } from '@main/core/sessions/session-service';import { switchRoomService } from '@main/core/switch-rooms/switch-room-service';import { fetchRoomDetail } from '@main/core/switch-servers/gateway-client';-import { withWorkspaceSession } from '@main/core/workspaces/workspace-session';+import { getServer } from '@main/core/switch-servers/servers-store';import { db } from '@main/db/client';import { sessions } from '@main/db/schema';import { events } from '@main/lib/events';@@ -73,8 +73,9 @@ class RemoteSessionReconciler {this.stop(agentId);return;}- if (!agent.workspaceId) throw new Error('This linked agent has no workspace configured.');- const workspaceId = agent.workspaceId;+ if (!agent.serverId) throw new Error('This linked agent has no Switch server configured.');+ const server = await getServer(agent.serverId);+ if (!server) throw new Error('The session discovery server is missing.');const remote: unknown[] = await listHostSessions(agentId);const failures: string[] = [];const local = new Map(@@ -144,7 +145,7 @@ class RemoteSessionReconciler {id: session.sessionId,agentId,title: roomId- ? `Session for ${(await withWorkspaceSession(workspaceId, (server) => fetchRoomDetail(server, roomId))).name}`+ ? `Session for ${(await fetchRoomDetail(server, roomId)).name}`: 'Shared session',attach: false,startSource: 'adopted',diff --git a/console/apps/switch-console-desktop/src/main/core/agents/remove-launch-profile.ts b/console/apps/switch-console-desktop/src/main/core/agents/remove-launch-profile.tsindex b3b4dd2ee..42da7f49e 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/remove-launch-profile.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/remove-launch-profile.ts@@ -15,7 +15,7 @@ import { connectRemoteAgent } from './connect-remote-agent';** The profile lives in the home scope, not the working dir, so it is reached* through the same home filesystem that wrote it: local disk for a local agent,- * and the exec-backed remote home for a remote one (the repo-dir `WorkdirFs`+ * and the exec-backed remote home for a remote one (the repo-dir `WorkspaceFs`* used elsewhere in teardown deliberately has no writable home for remote* agents). Best-effort and isolated: a filesystem or connection failure is* logged, not thrown, so the rest of the agent's teardown still runs — but it isdiff --git a/console/apps/switch-console-desktop/src/main/core/agents/remove-loadable-agent-config.ts b/console/apps/switch-console-desktop/src/main/core/agents/remove-loadable-agent-config.tsindex 931491e8e..dafa03c4e 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/remove-loadable-agent-config.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/remove-loadable-agent-config.ts@@ -1,5 +1,5 @@import { log } from '@main/lib/logger';-import { resolveWorkdirFsFor } from './agent-workdir-fs';+import { resolveWorkspaceFsFor } from './agent-workspace-fs';import { agentSettingsRelativePath } from './switch-settings-paths';export type RemoveLoadableAgentConfigParams = {@@ -27,7 +27,7 @@ export async function removeLoadableAgentConfig(params: RemoveLoadableAgentConfigParams): Promise<RemoveLoadableAgentConfigResult> {const relPath = agentSettingsRelativePath(params.name);- const ctx = await resolveWorkdirFsFor(params.sshHost, params.dir);+ const ctx = await resolveWorkspaceFsFor(params.sshHost, params.dir);try {const existing = await ctx.fs.read(relPath);if (existing === null) return { removed: false, reason: 'not-found' };diff --git a/console/apps/switch-console-desktop/src/main/core/agents/renameAgent.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/renameAgent.test.tsindex 70483a665..373e53201 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/renameAgent.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/renameAgent.test.ts@@ -44,8 +44,8 @@ vi.mock('./agent-location', () => ({getAgentLocation: vi.fn(async () => ({ sshHost: null, dir: '/repo' })),getRemoteAgentLocation: vi.fn(async () => null),}));-vi.mock('./agent-workdir-fs', () => ({- resolveWorkdirFsFor: vi.fn(async () => ({ fs: h.state.fs, close: vi.fn() })),+vi.mock('./agent-workspace-fs', () => ({+ resolveWorkspaceFsFor: vi.fn(async () => ({ fs: h.state.fs, close: vi.fn() })),}));vi.mock('./getAgentById', () => ({getAgentById: vi.fn(async () => ({@@ -74,7 +74,6 @@ vi.mock('@main/db/client', () => ({vi.mock('@main/db/schema', () => ({ agents: {} }));vi.mock('./utils', () => ({mapAgentRowToAgent: (row: Record<string, unknown>) => row,- mapAgentRow: async (row: Record<string, unknown>) => row,}));const { renameAgent } = await import('./renameAgent');diff --git a/console/apps/switch-console-desktop/src/main/core/agents/renameAgent.ts b/console/apps/switch-console-desktop/src/main/core/agents/renameAgent.tsindex 51c9ce549..0e3b3122f 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/renameAgent.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/renameAgent.ts@@ -10,12 +10,12 @@ import type { Agent, RenameAgentParams } from '@shared/core/agents/agents';import { agentEvents } from './agent-events';import { getAgentLocation } from './agent-location';import { agentNameTaken } from './agent-name-taken';-import { resolveWorkdirFsFor } from './agent-workdir-fs';+import { resolveWorkspaceFsFor } from './agent-workspace-fs';import { getAgentById } from './getAgentById';import { ensureRemoteWatcher } from './remote-watcher';import { removeAgentLaunchProfile } from './remove-launch-profile';import { agentSettingsRelativePath } from './switch-settings-paths';-import { mapAgentRow } from './utils';+import { mapAgentRowToAgent } from './utils';import { foreignCredentialsEndpoint } from './write-switch-settings';async function moveSidecarToNewName(_previous: Agent, renamed: Agent): Promise<void> {@@ -32,14 +32,14 @@ async function moveSidecarToNewName(_previous: Agent, renamed: Agent): Promise<v* is using.*/async function foreignCredentialsOwnerForMove(- workdirFs: PluginFs,+ workspaceFs: PluginFs,credsRaw: string,to: string): Promise<string | null> {const source = parseSwitchAgentCredentials(credsRaw, log);if (!source) return null;return foreignCredentialsEndpoint(- await workdirFs.read(agentSettingsRelativePath(to)),+ await workspaceFs.read(agentSettingsRelativePath(to)),source.apiEndpoint);}@@ -58,7 +58,7 @@ async function foreignCredentialsAtNewName(agent: Agent, to: string): Promise<stif ((agent.name ?? agent.id) === to) return null;try {const location = await getAgentLocation(agent);- const ctx = await resolveWorkdirFsFor(location.sshHost, location.dir);+ const ctx = await resolveWorkspaceFsFor(location.sshHost, location.dir);try {const creds = await ctx.fs.read(agentSettingsRelativePath(agent.name ?? agent.id));return creds === null ? null : await foreignCredentialsOwnerForMove(ctx.fs, creds, to);@@ -100,7 +100,7 @@ async function moveProvisionedFiles(previous: Agent, renamed: Agent): Promise<votry {const location = await getAgentLocation(previous);- const ctx = await resolveWorkdirFsFor(location.sshHost, location.dir);+ const ctx = await resolveWorkspaceFsFor(location.sshHost, location.dir);try {const creds = await ctx.fs.read(agentSettingsRelativePath(from));if (creds !== null) {@@ -134,7 +134,7 @@ async function moveProvisionedFiles(previous: Agent, renamed: Agent): Promise<vo// A launch profile (Codex) is keyed on the agent name, so the rename orphans// the old-named one; it is rewritten under the new name on the next launch,// so just drop the stale file. Reached through its own home filesystem (the- // repo-dir workdir fs above has no writable home for a remote agent).+ // repo-dir workspace fs above has no writable home for a remote agent).await removeAgentLaunchProfile(previous, location, from);} catch (error) {log.warn('renameAgent: failed to move the agent files to the new name', {@@ -187,7 +187,7 @@ export async function renameAgent(.returning();if (!row) return err({ type: 'agent-not-found' });- const renamed = await mapAgentRow(row);+ const renamed = mapAgentRowToAgent(row);if (previous.name !== renamed.name) {await moveProvisionedFiles(previous, renamed);await moveSidecarToNewName(previous, renamed);diff --git a/console/apps/switch-console-desktop/src/main/core/agents/reset-remote-agent.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/reset-remote-agent.test.tsindex 5b2ac49ac..88f646e30 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/reset-remote-agent.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/reset-remote-agent.test.ts@@ -10,11 +10,10 @@ const mocks = vi.hoisted(() => ({teardown: vi.fn(async () => ({ success: true })),}));vi.mock('./getAgentById', () => ({- getAgentById: async () => ({ id: 'local', workspaceId: 'workspace', switchAgentId: 'agent' }),+ getAgentById: async () => ({ id: 'local', serverId: 'server', switchAgentId: 'agent' }),}));-vi.mock('@main/core/workspaces/workspace-session', () => ({- withWorkspaceSession: (_workspaceId: string, fn: (server: { id: string }) => Promise<unknown>) =>- fn({ id: 'server' }),+vi.mock('@main/core/switch-servers/servers-store', () => ({+ getServer: async () => ({ id: 'server' }),}));vi.mock('@main/core/sdk-host/host-sessions', () => ({ listHostSessions: mocks.list }));vi.mock('@main/core/sdk-host/shared-agent-runtime', () => ({ stopSharedSession: mocks.stop }));diff --git a/console/apps/switch-console-desktop/src/main/core/agents/reset-remote-agent.ts b/console/apps/switch-console-desktop/src/main/core/agents/reset-remote-agent.tsindex aeebeb943..199b2d4de 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/reset-remote-agent.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/reset-remote-agent.ts@@ -6,6 +6,7 @@ import { manageAgentSidecar } from '@main/core/sdk-host/sidecar-management';import { sessionHooks } from '@main/core/sessions/session-hooks';import { sessionRuntimeManager } from '@main/core/sessions/session-runtime-manager';import { switchRoomService } from '@main/core/switch-rooms/switch-room-service';+import { getServer } from '@main/core/switch-servers/servers-store';import { viewStateService } from '@main/core/view-state/view-state-service';import { db } from '@main/db/client';import { sessions } from '@main/db/schema';@@ -18,8 +19,10 @@ import { startRemoteDiscovery } from './remote-watcher';export async function resetRemoteAgent(agentId: string): Promise<void> {const agent = await getAgentById(agentId);- if (!agent?.workspaceId || !agent.switchAgentId)+ if (!agent?.serverId || !agent.switchAgentId)throw new Error('The agent is not linked to Switch.');+ const server = await getServer(agent.serverId);+ if (!server) throw new Error('The agent’s Switch server is missing.');await configureSharedWatcher(agentId, { connected: false, spawning: false }, 'explicit');remoteSessionReconciler.stop(agentId);const remote = await listHostSessions(agentId);diff --git a/console/apps/switch-console-desktop/src/main/core/agents/resolve-servers.db.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/resolve-servers.db.test.tsnew file mode 100644index 000000000..1bf6f9f3f--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/agents/resolve-servers.db.test.ts@@ -0,0 +1,128 @@+import { openFixture } from '@tooling/utils/db';+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { AppDb } from '@main/db/client';+import { agents, locations, switchServers } from '@main/db/schema';+import { resolveAgentServers } from './resolve-servers';++const mocks = vi.hoisted(() => ({+ db: undefined as AppDb | undefined,+}));++vi.mock('@main/db/client', () => ({+ get db() {+ if (!mocks.db) throw new Error('Test database not initialized');+ return mocks.db;+ },+}));++// servers-store transitively constructs the encrypted-secrets singleton (which+// touches the real db at import). resolveAgentServers never reads cookies, so+// stub it out to keep this test to the agent↔server reconciliation path.+vi.mock('@main/core/secrets/encrypted-app-secrets-store', () => ({+ encryptedAppSecretsStore: {+ getSecret: vi.fn(),+ setSecret: vi.fn(),+ deleteSecret: vi.fn(),+ },+}));++async function serverIdOf(db: AppDb, agentId: string): Promise<string | null> {+ const [row] = await db+ .select({ serverId: agents.serverId })+ .from(agents)+ .where(eq(agents.id, agentId))+ .limit(1);+ return row?.serverId ?? null;+}++describe('resolveAgentServers', () => {+ let fixture: Awaited<ReturnType<typeof openFixture>>;++ beforeEach(async () => {+ fixture = await openFixture('empty');+ mocks.db = fixture.db;+ // Mirror production: the app's main connection does not enforce foreign+ // keys, so an agent can reference a server that has since been removed —+ // exactly the dangling state resolveAgentServers cleans up.+ fixture.sqlite.pragma('foreign_keys = OFF');++ await fixture.db+ .insert(locations)+ .values({ id: 'location-1', name: 'Location', sshHost: '', dir: '/repo/location-1' });+ await fixture.db.insert(switchServers).values([+ {+ id: 'pilot',+ name: 'Pilot',+ gatewayUrl: 'https://pilot-gateway.example.com',+ apiUrl: 'https://pilot-api.example.com',+ },+ {+ id: 'local',+ name: 'Local',+ gatewayUrl: 'http://localhost:8080',+ apiUrl: 'http://localhost:8081',+ },+ ]);+ });++ afterEach(() => {+ fixture.close();+ mocks.db = undefined;+ });++ it('keeps links to registered servers, unlinks dangling, leaves unassigned alone', async () => {+ await fixture.db.insert(agents).values([+ // Explicitly linked to a registered server -> kept (not re-derived).+ {+ id: 'agent-pilot',+ locationId: 'location-1',+ name: 'pilot',+ providerId: 'claude',+ apiEndpoint: 'https://pilot.example.com/agent-bridge',+ serverId: 'pilot',+ },+ // Linked to a server that is no longer registered -> unlinked.+ {+ id: 'agent-dangling',+ locationId: 'location-1',+ name: 'dangling',+ providerId: 'claude',+ apiEndpoint: 'https://gone.example.com',+ serverId: 'removed-server',+ },+ // Never assigned -> stays null.+ {+ id: 'agent-none',+ locationId: 'location-1',+ name: 'none',+ providerId: 'claude',+ apiEndpoint: null,+ serverId: null,+ },+ ]);++ await resolveAgentServers();++ expect(await serverIdOf(fixture.db, 'agent-pilot')).toBe('pilot');+ expect(await serverIdOf(fixture.db, 'agent-dangling')).toBeNull();+ expect(await serverIdOf(fixture.db, 'agent-none')).toBeNull();+ });++ it('does not re-link by endpoint origin (links are explicit, never inferred)', async () => {+ // Endpoint origin matches the local server, but serverId is null: the old+ // behavior would auto-link; the new behavior must leave it unassigned.+ await fixture.db.insert(agents).values({+ id: 'agent-origin-match',+ locationId: 'location-1',+ name: 'origin-match',+ providerId: 'claude',+ apiEndpoint: 'http://localhost:8080',+ serverId: null,+ });++ await resolveAgentServers();++ expect(await serverIdOf(fixture.db, 'agent-origin-match')).toBeNull();+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/agents/resolve-servers.ts b/console/apps/switch-console-desktop/src/main/core/agents/resolve-servers.tsnew file mode 100644index 000000000..962379f33--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/agents/resolve-servers.ts@@ -0,0 +1,42 @@+import { isNotNull, notInArray } from 'drizzle-orm';+import { listServers } from '@main/core/switch-servers/servers-store';+import { db } from '@main/db/client';+import { agents } from '@main/db/schema';+import { log } from '@main/lib/logger';++/**+ * Drop agent → server links that point at a server no longer in the registry,+ * so an agent never references a server that has been removed.+ *+ * Links are otherwise authoritative: an agent's `serverId` is chosen and+ * verified explicitly at onboarding (or via the assign-server action), not+ * inferred. This reconciliation only *unlinks* dangling references — it never+ * re-derives or re-assigns a server — so an explicit choice is never clobbered.+ * An agent left with a null `serverId` surfaces in the UI as "needs a server".+ *+ * Run at boot and whenever the server registry changes.+ */+export async function resolveAgentServers(): Promise<void> {+ const servers = await listServers();+ const registeredIds = servers.map((s) => s.id);++ // No registered servers → every linked agent is dangling. Otherwise unlink+ // only agents whose serverId is set and not among the registered ids.+ // (`NOT IN` already excludes null rows, so unassigned agents stay untouched.)+ const where =+ registeredIds.length === 0+ ? isNotNull(agents.serverId)+ : notInArray(agents.serverId, registeredIds);++ const result = await db+ .update(agents)+ .set({ serverId: null })+ .where(where)+ .returning({ id: agents.id });++ if (result.length > 0) {+ log.info('switch-agents: unlinked agents pointing at removed servers', {+ unlinked: result.length,+ });+ }+}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/setAgentAutoSession.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/setAgentAutoSession.test.tsindex adffb0acd..9d06c2d91 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/setAgentAutoSession.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/setAgentAutoSession.test.ts@@ -28,9 +28,8 @@ vi.mock('@main/core/switch-servers/gateway-client', () => ({setAutoSession: h.setAutoSession,GatewayError: class GatewayError extends Error {},}));-vi.mock('@main/core/workspaces/workspace-session', () => ({- withWorkspaceSession: (_id: string, fn: (server: { id: string }) => unknown) =>- fn({ id: 'server-1' }),+vi.mock('@main/core/switch-servers/servers-store', () => ({+ getServer: vi.fn(async () => ({ id: 'server-1' })),}));vi.mock('@main/lib/logger', () => ({ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));vi.mock('./agent-location', () => ({ getRemoteAgentLocation: async () => h.state.sshHost }));@@ -43,7 +42,7 @@ beforeEach(() => {vi.clearAllMocks();h.calls.length = 0;h.state.sshHost = null;- h.state.agent = { id: 'agent-1', workspaceId: 'workspace-1', switchAgentId: 'switch-1' };+ h.state.agent = { id: 'agent-1', serverId: 'server-1', switchAgentId: 'switch-1' };});it('makes the controller spawn-capable before claiming the profile that promises a session', async () => {diff --git a/console/apps/switch-console-desktop/src/main/core/agents/setAgentAutoSession.ts b/console/apps/switch-console-desktop/src/main/core/agents/setAgentAutoSession.tsindex 1d0f9dece..fc61c494d 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/setAgentAutoSession.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/setAgentAutoSession.ts@@ -8,7 +8,7 @@ import {GatewayError,setAutoSession,} from '@main/core/switch-servers/gateway-client';-import { withWorkspaceSession } from '@main/core/workspaces/workspace-session';+import { getServer } from '@main/core/switch-servers/servers-store';import { log } from '@main/lib/logger';import type { Agent } from '@shared/core/agents/agents';import { getRemoteAgentLocation } from './agent-location';@@ -54,19 +54,18 @@ async function applyLocalAutoSessionState(agent: Agent, enabled: boolean): Promiexport async function setAgentAutoSession(params: AgentAutoSessionParams): Promise<void> {const agent = await getAgentById(params.agentId);if (!agent) throw new Error(`No agent with id ${params.agentId}`);- const { workspaceId, switchAgentId } = agent;- if (!workspaceId || !switchAgentId) {- throw new Error('Agent is not linked to a Switch workspace; cannot set auto_session.');+ if (!agent.serverId || !agent.switchAgentId) {+ throw new Error('Agent is not linked to a Switch server; cannot set auto_session.');}+ const server = await getServer(agent.serverId);+ if (!server) throw new Error(`No Switch server with id ${agent.serverId}`);if (params.enabled) {await applyLocalAutoSessionState(agent, true);- await withWorkspaceSession(workspaceId, (server) =>- setAutoSession(server, switchAgentId, true)- );+ await setAutoSession(server, agent.switchAgentId, true);return;}- await withWorkspaceSession(workspaceId, (server) => setAutoSession(server, switchAgentId, false));+ await setAutoSession(server, agent.switchAgentId, false);await applyLocalAutoSessionState(agent, false);}@@ -76,17 +75,15 @@ export async function setAgentAutoSession(params: AgentAutoSessionParams): Promi* after an agent is created so a fresh agent registered with `auto_session: true`* starts watching immediately, without the operator having to toggle it off→on.* Returns whether auto_session is enabled. No-ops for agents not linked to a- * Switch workspace.+ * Switch server.*/export async function reconcileAgentAutoSessionFromGateway(agentId: string): Promise<boolean> {const agent = await getAgentById(agentId);- if (!agent) return false;- const { workspaceId, switchAgentId } = agent;- if (!workspaceId || !switchAgentId) return false;+ if (!agent?.serverId || !agent.switchAgentId) return false;+ const server = await getServer(agent.serverId);+ if (!server) return false;- const { connectionModel } = await withWorkspaceSession(workspaceId, (server) =>- fetchAgentOptions(server, switchAgentId)- );+ const { connectionModel } = await fetchAgentOptions(server, agent.switchAgentId);const enabled = connectionModel === 'auto_session';await applyLocalAutoSessionState(agent, enabled);return enabled;@@ -100,7 +97,7 @@ export async function reconcileAgentAutoSessionFromGateway(agentId: string): Pro*/export async function getAgentAutoSession(params: { agentId: string }): Promise<boolean> {const agent = await getAgentById(params.agentId);- if (!agent?.workspaceId || !agent.switchAgentId) return false;+ if (!agent?.serverId || !agent.switchAgentId) return false;try {return await reconcileAgentAutoSessionFromGateway(params.agentId);diff --git a/console/apps/switch-console-desktop/src/main/core/agents/stop-shared-agent-sessions.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/stop-shared-agent-sessions.test.tsindex 0cf2792ba..782f44938 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/stop-shared-agent-sessions.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/stop-shared-agent-sessions.test.ts@@ -16,9 +16,8 @@ vi.mock('@main/core/sdk-host/session-commands', () => ({submitSessionCommand: mocks.submit,sessionCommandStatus: mocks.status,}));-vi.mock('@main/core/workspaces/workspace-session', () => ({- withWorkspaceSession: (_workspaceId: string, fn: (server: { id: string }) => Promise<unknown>) =>- fn({ id: 'server' }),+vi.mock('@main/core/switch-servers/servers-store', () => ({+ getServer: async () => ({ id: 'server' }),}));const { stopSharedAgentSessions } = await import('./stop-shared-agent-sessions');const session = {@@ -41,7 +40,7 @@ const session = {attachmentMimeTypes: [],},};-const agent = { id: 'local-agent', workspaceId: 'workspace', switchAgentId: 'agent' } as Agent;+const agent = { id: 'local-agent', serverId: 'server', switchAgentId: 'agent' } as Agent;const receipt = {type: 'command.status',commandId: 'stop-epoch',@@ -91,8 +90,3 @@ it('does not stop other agents or retired sessions', async () => {await stopSharedAgentSessions(agent);expect(mocks.submit).not.toHaveBeenCalled();});--it('does nothing for an agent with no workspace to address', async () => {- await stopSharedAgentSessions({ ...agent, workspaceId: null } as Agent);- expect(mocks.list).not.toHaveBeenCalled();-});diff --git a/console/apps/switch-console-desktop/src/main/core/agents/stop-shared-agent-sessions.ts b/console/apps/switch-console-desktop/src/main/core/agents/stop-shared-agent-sessions.tsindex d6743f137..b308523cb 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/stop-shared-agent-sessions.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/stop-shared-agent-sessions.ts@@ -1,9 +1,12 @@import { listHostSessions } from '@main/core/sdk-host/host-sessions';import { stopSharedSession } from '@main/core/sdk-host/stop-shared-session';+import { getServer } from '@main/core/switch-servers/servers-store';import type { Agent } from '@shared/core/agents/agents';export async function stopSharedAgentSessions(agent: Agent): Promise<void> {- if (!agent.workspaceId || !agent.switchAgentId) return;+ if (!agent.serverId || !agent.switchAgentId) return;+ const server = await getServer(agent.serverId);+ if (!server) throw new Error('Cannot stop SDK sessions: the Switch server is missing.');const sessions = await listHostSessions(agent.id);for (const session of sessions.filter((session) =>diff --git a/console/apps/switch-console-desktop/src/main/core/agents/updateAgent.ts b/console/apps/switch-console-desktop/src/main/core/agents/updateAgent.tsindex 2285bb0af..89073bec4 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/updateAgent.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/updateAgent.ts@@ -4,14 +4,14 @@ import { agents } from '@main/db/schema';import type { AgentProviderConfig } from '@shared/core/agents/agent-provider-config';import type { Agent } from '@shared/core/agents/agents';import { agentEvents } from './agent-events';-import { mapAgentRow } from './utils';+import { mapAgentRowToAgent } from './utils';export type UpdateAgentParams = {agentId: string;status?: string | null;switchAgentId?: string | null;apiEndpoint?: string | null;- workspaceId?: string;+ serverId?: string;autoApprove?: boolean;/** Null clears the agent's specialization, putting it back on provider defaults. */providerConfig?: AgentProviderConfig | null;@@ -24,13 +24,13 @@ export async function updateAgent(params: UpdateAgentParams): Promise<Agent | unif (params.status !== undefined) set.status = params.status;if (params.switchAgentId !== undefined) set.switchAgentId = params.switchAgentId;if (params.apiEndpoint !== undefined) set.apiEndpoint = params.apiEndpoint;- if (params.workspaceId !== undefined) set.workspaceId = params.workspaceId;+ if (params.serverId !== undefined) set.serverId = params.serverId;if (params.autoApprove !== undefined) set.autoApprove = params.autoApprove;if (params.providerConfig !== undefined) set.providerConfig = params.providerConfig;const [row] = await db.update(agents).set(set).where(eq(agents.id, params.agentId)).returning();if (!row) return undefined;- const agent = await mapAgentRow(row);+ const agent = mapAgentRowToAgent(row);agentEvents._emit('agent:updated', agent);return agent;}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/utils.ts b/console/apps/switch-console-desktop/src/main/core/agents/utils.tsindex 7f8455a05..801b36b72 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/utils.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/utils.ts@@ -1,14 +1,8 @@-import { serverIdForWorkspace } from '@main/core/workspaces/workspaces-store';import type { AgentRow } from '@main/db/schema';import { noteAgentName } from '@main/lib/log-name-cache';import type { Agent } from '@shared/core/agents/agents';-/**- * `serverId` is the server hosting the agent's workspace. It is a join away- * from the row rather than on it, so the caller resolves it — the list reads- * join, the single-row reads use {@link mapAgentRow}.- */-export function mapAgentRowToAgent(row: AgentRow, serverId: string | null): Agent {+export function mapAgentRowToAgent(row: AgentRow): Agent {// Every read and write of an agent passes through here, so the log sink can// name an agent id without ever querying for it.noteAgentName(row.id, row.name);@@ -20,8 +14,7 @@ export function mapAgentRowToAgent(row: AgentRow, serverId: string | null): AgenproviderId: row.providerId,switchAgentId: row.switchAgentId ?? null,apiEndpoint: row.apiEndpoint ?? null,- workspaceId: row.workspaceId ?? null,- serverId,+ serverId: row.serverId ?? null,status: row.status ?? null,autoApprove: row.autoApprove,ownerName: row.ownerName ?? null,@@ -30,8 +23,3 @@ export function mapAgentRowToAgent(row: AgentRow, serverId: string | null): AgenupdatedAt: row.updatedAt,};}--/** {@link mapAgentRowToAgent} for one row, looking its server up. */-export async function mapAgentRow(row: AgentRow): Promise<Agent> {- return mapAgentRowToAgent(row, await serverIdForWorkspace(row.workspaceId));-}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.test.tsindex d0fc69f1f..ecbfeb293 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.test.ts@@ -259,15 +259,19 @@ describe('writeNeutralAgentSettingsFs, against another install of Switch Consoleit('reports the owning server through foreignCredentialsOwnerFs, for a caller checking before it registers', async () => {await seed('shared-name', otherInstall);- const workdirFs = createPluginFs(dir);+ const workspaceFs = createPluginFs(dir);expect(- await foreignCredentialsOwnerFs(workdirFs, 'shared-name', 'https://switch.example.com')+ await foreignCredentialsOwnerFs(workspaceFs, 'shared-name', 'https://switch.example.com')).toBe('https://other-switch.example.com');expect(- await foreignCredentialsOwnerFs(workdirFs, 'shared-name', 'https://other-switch.example.com')+ await foreignCredentialsOwnerFs(+ workspaceFs,+ 'shared-name',+ 'https://other-switch.example.com'+ )).toBeNull();- expect(await foreignCredentialsOwnerFs(workdirFs, 'absent', 'https://switch.example.com')) //+ expect(await foreignCredentialsOwnerFs(workspaceFs, 'absent', 'https://switch.example.com')) //.toBeNull();});});diff --git a/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.ts b/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.tsindex 2f9b8d22e..1db3963d3 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.ts@@ -405,11 +405,11 @@ export class ExistingAgentCredentialsError extends Error {* below re-checks, so a path that skips this one still cannot clobber.*/export async function foreignCredentialsOwnerFs(- workdirFs: PluginFs,+ workspaceFs: PluginFs,slug: string,apiEndpoint: string): Promise<string | null> {- const existingRaw = await workdirFs.read(agentSettingsRelativePath(slug));+ const existingRaw = await workspaceFs.read(agentSettingsRelativePath(slug));return foreignCredentialsEndpoint(existingRaw, apiEndpoint);}@@ -474,11 +474,11 @@ export function existingAgentIdInSlot(* before the token reaches disk.*/export async function writeNeutralAgentSettingsFs(- workdirFs: PluginFs,+ workspaceFs: PluginFs,params: { slug: string; expectedAgentId?: string } & SwitchSettingsCredentials): Promise<void> {const relPath = agentSettingsRelativePath(params.slug);- const existingRaw = await workdirFs.read(relPath);+ const existingRaw = await workspaceFs.read(relPath);const existingEndpoint = foreignCredentialsEndpoint(existingRaw, params.apiEndpoint);if (existingEndpoint !== null) {throw new ForeignAgentCredentialsError({@@ -508,8 +508,8 @@ export async function writeNeutralAgentSettingsFs(});}- if (!(await workdirFs.exists(SWITCH_AGENTS_GITIGNORE_RELATIVE))) {- await workdirFs.write(SWITCH_AGENTS_GITIGNORE_RELATIVE, '*\n');+ if (!(await workspaceFs.exists(SWITCH_AGENTS_GITIGNORE_RELATIVE))) {+ await workspaceFs.write(SWITCH_AGENTS_GITIGNORE_RELATIVE, '*\n');}- await workdirFs.write(relPath, mergeAgentCredentials(existingRaw, params));+ await workspaceFs.write(relPath, mergeAgentCredentials(existingRaw, params));}diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline-matrix-migration.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline-matrix-migration.test.tsindex d566da845..296037cbf 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline-matrix-migration.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline-matrix-migration.test.ts@@ -60,13 +60,10 @@ vi.mock('@main/core/switch-servers/servers-store', () => ({ensureManagedServer: () => Promise.resolve({ id: 'srv-1' }),setActiveServerId: vi.fn(),}));-// Reads this install's own workspace rows, and through them the database client.-vi.mock('@main/core/workspaces/reconcile-workspaces', () => ({- reconcileServerWorkspaces: () => Promise.resolve(),-}));vi.mock('@main/core/switch-servers/auth', () => ({passwordLogin: () => Promise.resolve({ success: true }),}));+vi.mock('@main/core/agents/resolve-servers', () => ({ resolveAgentServers: vi.fn() }));vi.mock('./managed-upgrade', () => ({prepareUpgrade: prepareUpgradeMock,finishUpgrade: finishUpgradeMock,diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline.test.tsindex c791a56f1..f5e827c8e 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline.test.ts@@ -66,13 +66,10 @@ vi.mock('@main/core/switch-servers/servers-store', () => ({ensureManagedServer: () => Promise.resolve({ id: 'srv-1' }),setActiveServerId: setActiveServerIdMock,}));-// Reads this install's own workspace rows, and through them the database client.-vi.mock('@main/core/workspaces/reconcile-workspaces', () => ({- reconcileServerWorkspaces: () => Promise.resolve(),-}));vi.mock('@main/core/switch-servers/auth', () => ({passwordLogin: () => Promise.resolve({ success: true }),}));+vi.mock('@main/core/agents/resolve-servers', () => ({ resolveAgentServers: vi.fn() }));vi.mock('./managed-upgrade', () => ({prepareUpgrade: prepareUpgradeMock,finishUpgrade: finishUpgradeMock,diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline.tsindex dc0753f6b..0982bfa60 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline.ts@@ -1,6 +1,6 @@+import { resolveAgentServers } from '@main/core/agents/resolve-servers';import { passwordLogin } from '@main/core/switch-servers/auth';import { ensureManagedServer, setActiveServerId } from '@main/core/switch-servers/servers-store';-import { reconcileServerWorkspaces } from '@main/core/workspaces/reconcile-workspaces';import { log } from '@main/lib/logger';import { COMPATIBLE_SWITCH_VERSION, RELEASE_REPO_OWNER } from '@shared/app-identity';import {@@ -270,18 +270,9 @@ export async function startStack(opts: StartStackOptions): Promise<StartLocalSerlog.warn('managed-switch-server: auto sign-in failed; server will show a sign-in prompt', {error: login.error,});- } else {- // The user never sees a login form for a managed stack, so this is the only- // sign-in it will ever have — without matching the workspaces here, its- // placeholder one would stay unmatched until some later launch happened to.- await reconcileServerWorkspaces(server.id).catch((error: unknown) => {- log.warn('managed-switch-server: signed in, but could not read the account’s workspaces', {- server: server.id,- error: String(error),- });- });}+ await resolveAgentServers();if (upgrade) await finishUpgrade(host);return { kind: 'started', serverId: server.id, telemetryEnabled };}diff --git a/console/apps/switch-console-desktop/src/main/core/onboarding/controller.ts b/console/apps/switch-console-desktop/src/main/core/onboarding/controller.tsdeleted file mode 100644index 5bef6e6e8..000000000--- a/console/apps/switch-console-desktop/src/main/core/onboarding/controller.ts+++ /dev/null@@ -1,6 +0,0 @@-import { createRPCController } from '@shared/lib/ipc/rpc';-import { installIsEmpty } from './install-contents';--export const onboardingController = createRPCController({- installIsEmpty,-});diff --git a/console/apps/switch-console-desktop/src/main/core/onboarding/install-contents.ts b/console/apps/switch-console-desktop/src/main/core/onboarding/install-contents.tsdeleted file mode 100644index f59a08805..000000000--- a/console/apps/switch-console-desktop/src/main/core/onboarding/install-contents.ts+++ /dev/null@@ -1,27 +0,0 @@-import { db } from '@main/db/client';-import { agents, locations, switchServers } from '@main/db/schema';--/**- * Whether this install holds nothing of its own — the fresh-install question the- * shell asks before it puts the first-run page over the whole window.- *- * Deliberately not "has no Switch server". Agents, locations and the sessions- * running in them outlive a server on purpose: removing one says in as many- * words that its agents are kept and can be re-linked elsewhere. Reading an- * empty server list as a fresh install would answer that promise by replacing- * the window with a welcome page — permanently, across relaunches, with those- * sessions still running behind it.- *- * Answered here rather than assembled in the renderer because the counts are- * three rows the database already has, and the alternative is the shell waiting- * on stores that mount agents and open SSH connections to tell it whether to- * draw a sidebar at all.- */-export async function installIsEmpty(): Promise<boolean> {- const [server] = await db.select({ id: switchServers.id }).from(switchServers).limit(1);- if (server) return false;- const [location] = await db.select({ id: locations.id }).from(locations).limit(1);- if (location) return false;- const [agent] = await db.select({ id: agents.id }).from(agents).limit(1);- return agent === undefined;-}diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.test.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.test.tsindex ec7f2f1bf..b7a2dbe99 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.test.ts@@ -4,7 +4,7 @@ import { adoptSubagent } from './adopt-subagent';const mocks = vi.hoisted(() => ({local: vi.fn(),- session: vi.fn(),+ server: vi.fn(),remote: vi.fn(),create: vi.fn(),emit: vi.fn(),@@ -12,18 +12,16 @@ const mocks = vi.hoisted(() => ({}));vi.mock('@main/core/agents/agent-events', () => ({ agentEvents: { _emit: mocks.emit } }));vi.mock('@main/core/agents/createAgent', () => ({ createAgent: mocks.create }));-vi.mock('@main/core/agents/getAgents', () => ({ getLocationAgentsInWorkspace: mocks.local }));+vi.mock('@main/core/agents/getAgents', () => ({ getLocationAgentsOnServer: mocks.local }));vi.mock('@main/core/agents/remote-session-reconciler', () => ({remoteSessionReconciler: { start: mocks.start },}));vi.mock('@main/core/switch-servers/gateway-client', () => ({ fetchAgentDetail: mocks.remote }));-vi.mock('@main/core/workspaces/workspace-session', () => ({- withWorkspaceSession: mocks.session,-}));+vi.mock('@main/core/switch-servers/servers-store', () => ({ getServer: mocks.server }));const parent = {id: 'parent',locationId: 'location',- workspaceId: 'workspace',+ serverId: 'server',apiEndpoint: 'https://example.test/agent',providerId: 'claude',autoApprove: false,@@ -33,9 +31,7 @@ const parent = {beforeEach(() => {vi.resetAllMocks();mocks.local.mockResolvedValue([]);- mocks.session.mockImplementation(- (_workspaceId: string, fn: (server: { id: string }) => Promise<unknown>) => fn({ id: 'server' })- );+ mocks.server.mockResolvedValue({ id: 'server' });mocks.remote.mockResolvedValue({ id: 'child', ownerName: 'Owner' });mocks.create.mockImplementation(async (value) => ({ ...value, id: 'local-child' }));});@@ -48,7 +44,7 @@ it('adopts the child identity and discovers its sessions using its own credentianame: 'reviewer',switchAgentId: 'child',providerId: 'claude',- workspaceId: 'workspace',+ serverId: 'server',autoApprove: false,providerConfig: parent.providerConfig,})diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.tsindex de40a0d41..d0f6552ee 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.ts@@ -1,10 +1,10 @@import { randomUUID } from 'node:crypto';import { agentEvents } from '@main/core/agents/agent-events';import { createAgent } from '@main/core/agents/createAgent';-import { getLocationAgentsInWorkspace } from '@main/core/agents/getAgents';+import { getLocationAgentsOnServer } from '@main/core/agents/getAgents';import { remoteSessionReconciler } from '@main/core/agents/remote-session-reconciler';import { fetchAgentDetail } from '@main/core/switch-servers/gateway-client';-import { withWorkspaceSession } from '@main/core/workspaces/workspace-session';+import { getServer } from '@main/core/switch-servers/servers-store';import type { Agent } from '@shared/core/agents/agents';export async function adoptSubagent(@@ -12,8 +12,8 @@ export async function adoptSubagent(name: string,switchAgentId: string): Promise<void> {- if (!parent.workspaceId) throw new Error('The subagent’s Switch workspace is missing.');- const local = await getLocationAgentsInWorkspace(parent.locationId, parent.workspaceId);+ if (!parent.serverId) throw new Error('The subagent’s Switch server is missing.');+ const local = await getLocationAgentsOnServer(parent.locationId, parent.serverId);const existing = local.find((agent) => agent.switchAgentId === switchAgentId);if (existing) {if (existing.name !== name || existing.providerId !== parent.providerId)@@ -23,9 +23,9 @@ export async function adoptSubagent(}if (local.some((agent) => agent.name === name))throw new Error('This subagent name is already linked to a different Switch identity.');- const remote = await withWorkspaceSession(parent.workspaceId, (server) =>- fetchAgentDetail(server, switchAgentId)- );+ const server = await getServer(parent.serverId);+ if (!server) throw new Error('The subagent’s Switch server is missing.');+ const remote = await fetchAgentDetail(server, switchAgentId);if (remote.id !== switchAgentId)throw new Error('Switch returned a different subagent identity.');const agent = await createAgent({@@ -35,7 +35,7 @@ export async function adoptSubagent(providerId: parent.providerId,switchAgentId,apiEndpoint: parent.apiEndpoint,- workspaceId: parent.workspaceId,+ serverId: parent.serverId,autoApprove: parent.autoApprove,ownerName: remote.ownerName,providerConfig: parent.providerConfig,diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/controller.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/controller.tsindex a6df2edc4..a02061e52 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/controller.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/controller.ts@@ -29,10 +29,10 @@ export const sdkHostController = createRPCController({agentLogs: sharedAgentLogs,manageSidecar: async (agentId: string, action: 'update' | 'restart' | 'stop' | 'start') =>manageAgentSidecar(agentId, z.enum(['update', 'restart', 'stop', 'start']).parse(action)),- workspaceForAgent: async (agentId: string) => {+ serverForAgent: async (agentId: string) => {const agent = await getAgentById(agentId);- if (!agent?.workspaceId) throw new Error('This agent has no Switch workspace.');- return agent.workspaceId;+ if (!agent?.serverId) throw new Error('This agent has no Switch server.');+ return agent.serverId;},transcriptSource,transcriptOpen: (agentId: string, sessionId: string) => openTranscript(agentId, sessionId),diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/diagnostics.test.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/diagnostics.test.tsindex 151570f0b..8965944a7 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/diagnostics.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/diagnostics.test.ts@@ -5,11 +5,7 @@ vi.mock('@main/core/agent-runtime/impl/resolve-sidecar-bundle', () => ({resolveSharedHostBundlePath: () => import.meta.filename,}));vi.mock('@main/core/agents/getAgentById', () => ({- getAgentById: async () => ({- id: 'agent',- switchAgentId: 'remote-agent',- workspaceId: 'workspace',- }),+ getAgentById: async () => ({ id: 'agent', switchAgentId: 'remote-agent', serverId: 'server' }),}));vi.mock('@main/core/agents/agent-location', () => ({getAgentLocation: async () => ({ sshHost: 'host', dir: '/work' }),@@ -20,9 +16,8 @@ vi.mock('@main/core/agents/connect-remote-agent', () => ({vi.mock('@main/core/execution-context/local-execution-context', () => ({LocalExecutionContext: class {},}));-vi.mock('@main/core/workspaces/workspace-session', () => ({- withWorkspaceSession: (_workspaceId: string, fn: (server: { id: string }) => Promise<unknown>) =>- fn({ id: 'server' }),+vi.mock('@main/core/switch-servers/servers-store', () => ({+ getServer: async () => ({ id: 'server' }),}));vi.mock('./host-sessions', () => ({ listHostSessions: mocks.sessions }));const { sharedAgentDiagnostics, sharedAgentLogs } = await import('./diagnostics');diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/diagnostics.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/diagnostics.tsindex e0c0c1c0c..fec2b7801 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/diagnostics.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/diagnostics.ts@@ -6,6 +6,7 @@ import { getAgentLocation } from '@main/core/agents/agent-location';import { connectRemoteAgent } from '@main/core/agents/connect-remote-agent';import { getAgentById } from '@main/core/agents/getAgentById';import { LocalExecutionContext } from '@main/core/execution-context/local-execution-context';+import { getServer } from '@main/core/switch-servers/servers-store';import { redactSecrets } from '@main/lib/file-logger';import { listHostSessions } from './host-sessions';import { inspectWatchers } from './watcher-inspection';@@ -27,7 +28,7 @@ const watcherSchema = z.object({async function agentHost(agentId: string) {const agent = await getAgentById(agentId);- if (!agent?.workspaceId || !agent.switchAgentId)+ if (!agent?.serverId || !agent.switchAgentId)throw new Error('The agent is not linked to Switch.');const location = await getAgentLocation(agent);const ctx = location.sshHost@@ -38,6 +39,8 @@ async function agentHost(agentId: string) {export async function sharedAgentDiagnostics(agentId: string) {const { agent, location, ctx } = await agentHost(agentId);+ const server = await getServer(agent.serverId!);+ if (!server) throw new Error('The agent’s Switch server is missing.');const [host, bundle, remote] = await Promise.all([ctx.exec('node', ['-e', inspectWatchers, agent.switchAgentId!, 'status']),readFile(resolveSharedHostBundlePath()),diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.initial-prompt.test.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.initial-prompt.test.tsindex d4ecaf2cf..5876dbed3 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.initial-prompt.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.initial-prompt.test.ts@@ -35,7 +35,7 @@ vi.mock('@main/core/switch-rooms/session-room-store', () => ({getPersistedRoomConnection: mocks.persistedRoom,}));vi.mock('@main/core/agents/getAgentById', () => ({ getAgentById: mocks.agent }));-vi.mock('@main/core/workspaces/workspace-session', () => ({ workspaceServer: mocks.server }));+vi.mock('@main/core/switch-servers/servers-store', () => ({ getServer: mocks.server }));class FakeNotRecorded extends Error {}vi.mock('./session-commands', () => ({CommandNotRecordedError: FakeNotRecorded,@@ -108,7 +108,7 @@ beforeEach(() => {id: 'agent-1',name: 'scout',switchAgentId: 'remote-agent',- workspaceId: 'workspace-1',+ serverId: 'server-1',});mocks.server.mockResolvedValue({ id: 'server-1' });mocks.ready.mockResolvedValue(undefined);@@ -326,7 +326,7 @@ it('reports restart progress through host replacement and authentication until rrelease = resolve;}));- mocks.loadSession.mockResolvedValue({ workspaceId: 'workspace-1', row: { config: {} } });+ mocks.loadSession.mockResolvedValue({ serverId: 'server-1', row: { config: {} } });mocks.snapshot.mockResolvedValueOnce({session: { epoch: 'old', connectivity: 'online', status: 'ready' },diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.tsindex dafc9809d..6bfc96b51 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.ts@@ -39,10 +39,11 @@ import { controllerConnectionId } from '@main/core/switch-rooms/session-connectiimport { getPersistedRoomConnection } from '@main/core/switch-rooms/session-room-store';import { switchNotificationPoller } from '@main/core/switch-rooms/switch-notification-poller';import { switchRoomService } from '@main/core/switch-rooms/switch-room-service';-import { workspaceServer } from '@main/core/workspaces/workspace-session';+import { getServer } from '@main/core/switch-servers/servers-store';import { log } from '@main/lib/logger';import { makeHookSessionId } from '@shared/core/providers/hook-session-id';import type { Session } from '@shared/core/sessions/sessions';+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';import { JournalUnavailableError } from './host-journal';import { currentSnapshot } from './transcripts';@@ -64,7 +65,7 @@ function launchSettled(snapshot: Snapshot): boolean {}export class SharedAgentRuntime implements AgentRuntimeProvider {- private workspaceId: string | null = null;+ private server: SwitchServer | null = null;private starting: Promise<void> | null = null;private opened: Promise<void> | null = null;private startupError: string | null = null;@@ -134,11 +135,12 @@ export class SharedAgentRuntime implements AgentRuntimeProvider {): Promise<void> {this.startupStage = 'Preparing the session on its host…';const agent = await getAgentById(session.agentId);- if (!agent?.switchAgentId || !agent.workspaceId)- throw new Error('Link this agent to a Switch workspace before starting a session.');- this.workspaceId = agent.workspaceId;+ if (!agent?.switchAgentId || !agent.serverId)+ throw new Error('Link this agent to a Switch server before starting a session.');+ this.server = await getServer(agent.serverId);+ if (!this.server) throw new Error('The agent’s Switch server is missing.');this.startupStage = 'Waiting for the Switch server to be ready…';- await ensureServerSessionReady(await workspaceServer(agent.workspaceId));+ await ensureServerSessionReady(this.server);this.startupStage = 'Preparing the session on its host…';const intended = switchNotificationPoller.getSharedIntent(session.id, agent.switchAgentId);const config = await buildSharedHostConfig(session, this.params, this.transport);@@ -336,7 +338,7 @@ export class SharedAgentRuntime implements AgentRuntimeProvider {}async restart(session: Session): Promise<void> {- await this.resolveWorkspace();+ await this.resolveServer();if (this.starting) await this.starting;this.setStartupError(null);this.starting = this.open(session, undefined, true, true, () => {});@@ -361,12 +363,11 @@ export class SharedAgentRuntime implements AgentRuntimeProvider {if (!joined) throw new Error('The session is no longer recorded in Console.');await stopSharedSession(joined.row.agentId, this.params.sessionId);}- private async resolveWorkspace(): Promise<string> {- if (this.workspaceId) return this.workspaceId;+ private async resolveServer(): Promise<void> {+ if (this.server) return;const session = await loadSessionWithAgent(this.params.sessionId);- if (!session?.workspaceId) throw new Error('The session’s Switch workspace is missing.');- this.workspaceId = session.workspaceId;- return this.workspaceId;+ this.server = session?.serverId ? await getServer(session.serverId) : null;+ if (!this.server) throw new Error('The session’s Switch server is missing.');}}diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/stop-saved-session.test.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/stop-saved-session.test.tsindex b6a6b18de..9c881fff1 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/stop-saved-session.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/stop-saved-session.test.ts@@ -12,7 +12,7 @@ vi.mock('./local-host', () => ({ stopLocalSession: mocks.stopLocal }));beforeEach(() => {vi.resetAllMocks();- mocks.agent.mockResolvedValue({ switchAgentId: 'remote-agent', workspaceId: 'workspace' });+ mocks.agent.mockResolvedValue({ switchAgentId: 'remote-agent', serverId: 'server' });mocks.stop.mockResolvedValue(undefined);mocks.stopLocal.mockResolvedValue(undefined);});diff --git a/console/apps/switch-console-desktop/src/main/core/sessions/session-join.ts b/console/apps/switch-console-desktop/src/main/core/sessions/session-join.tsindex 716c94524..21ab50987 100644--- a/console/apps/switch-console-desktop/src/main/core/sessions/session-join.ts+++ b/console/apps/switch-console-desktop/src/main/core/sessions/session-join.ts@@ -1,6 +1,6 @@import { eq } from 'drizzle-orm';import { db } from '@main/db/client';-import { agents, sessions, type SessionRow, workspaces } from '@main/db/schema';+import { agents, sessions, type SessionRow } from '@main/db/schema';import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';export type SessionWithAgent = {@@ -10,13 +10,9 @@ export type SessionWithAgent = {/** The owning agent's `name` — the session's identity source. The creds slug* and `--agent` launch name derive from it, read live, not from a frozen tag. */name: string;- /** The workspace the owning agent belongs to; null for an agent not linked to- * Switch. This is what a call about the session is addressed with — a server- * can host several workspaces and answers for only the selected one. */- workspaceId: string | null;- /** The server hosting the agent's workspace; null once that server has been- * removed, which leaves the agent's endpoint and token pointing at something- * that no longer exists. */+ /** The registered Switch server the agent belongs to; null once that server+ * has been removed, which leaves the agent's endpoint and token pointing at+ * something that no longer exists. */serverId: string | null;};@@ -33,13 +29,10 @@ export async function loadSessionWithAgent(locationId: agents.locationId,providerId: agents.providerId,name: agents.name,- workspaceId: agents.workspaceId,- serverId: workspaces.serverId,+ serverId: agents.serverId,}).from(sessions).innerJoin(agents, eq(sessions.agentId, agents.id))- // Left: an unlinked agent has no workspace and its sessions still load.- .leftJoin(workspaces, eq(agents.workspaceId, workspaces.id)).where(eq(sessions.id, sessionId)).limit(1);if (!joined) return undefined;@@ -48,7 +41,6 @@ export async function loadSessionWithAgent(locationId: joined.locationId,providerId: joined.providerId,name: joined.name,- workspaceId: joined.workspaceId,serverId: joined.serverId,};}diff --git a/console/apps/switch-console-desktop/src/main/core/switch-rooms/switch-credentials.ts b/console/apps/switch-console-desktop/src/main/core/switch-rooms/switch-credentials.tsindex d3986f655..1e53e273f 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-rooms/switch-credentials.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-rooms/switch-credentials.ts@@ -102,12 +102,12 @@ export async function readAgentSwitchEnv(* the agent, so the miss is warned about here rather than at each call site.*/export async function readAgentSwitchEnvFromFs(- workdirFs: PluginFs,+ workspaceFs: PluginFs,slug: string,log: CredentialsLogger): Promise<Record<string, string>> {const relPath = agentSettingsRelativePath(slug);- const env = credentialsAsEnv(parseSwitchAgentCredentials(await workdirFs.read(relPath), log));+ const env = credentialsAsEnv(parseSwitchAgentCredentials(await workspaceFs.read(relPath), log));if (Object.keys(env).length === 0) {log.warn('readAgentSwitchEnvFromFs: no Switch identity for agent; session will not authenticate as it',diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/auth.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/auth.tsindex 0acdb6ec3..3db499561 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@@ -21,7 +21,7 @@ function gatewayUrl(server: SwitchServer, path: string): string {}/** Pull the `switch_auth` value out of the response's Set-Cookie headers. */-export function extractAuthCookie(setCookies: string[]): string | null {+function extractAuthCookie(setCookies: string[]): string | null {for (const raw of setCookies) {const [pair] = raw.split(';');const eq = pair.indexOf('=');diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.test.tsindex f285bbe7b..90aee30fa 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.test.ts@@ -55,25 +55,20 @@ function server(id: string): SwitchServer {}/**- * Set up a workspace's agent list and which of them this install manages- * locally. `managed` defaults to all of them — the ordinary case of a machine- * looking at its own agents.+ * Set up a server's agent list and which of them this install manages locally.+ * `managed` defaults to all of them — the ordinary case of a machine looking at+ * its own agents.*/function given(remote: RemoteAgentSummary[], managed?: string[]) {const ids = managed ?? remote.map((a) => a.id);fetchAgents.mockResolvedValue(remote);getAgents.mockResolvedValue(- ids.map((switchAgentId) => ({- id: `local-${switchAgentId}`,- switchAgentId,- workspaceId: 'ws-1',- }))+ ids.map((switchAgentId) => ({ id: `local-${switchAgentId}`, switchAgentId, serverId: 's-1' })));}-/** Re-imported per test: the module remembers which workspaces it has done,- * which is the behaviour under test in one case and interference in every- * other. */+/** Re-imported per test: the module remembers which servers it has done, which+ * is the behaviour under test in one case and interference in every other. */async function loadFresh() {vi.resetModules();return (await import('./backfill-agent-icons')).backfillAgentIcons;@@ -90,7 +85,7 @@ describe('backfillAgentIcons', () => {given([agent({ id: 'a-1', name: 'switch_worker' })]);const backfill = await loadFresh();- expect(await backfill('ws-1', server('s-1'))).toEqual({ kind: 'written', written: 1 });+ expect(await backfill(server('s-1'))).toEqual({ kind: 'written', written: 1 });expect(updateAgentIcon).toHaveBeenCalledWith(expect.anything(),'a-1',@@ -106,7 +101,7 @@ describe('backfillAgentIcons', () => {given([agent({ id: 'a-1', name: 'ancient', ownerId: null })]);const backfill = await loadFresh();- expect(await backfill('ws-1', server('s-1'))).toEqual({ kind: 'written', written: 1 });+ expect(await backfill(server('s-1'))).toEqual({ kind: 'written', written: 1 });expect(updateAgentIcon).toHaveBeenCalledOnce();});@@ -116,7 +111,7 @@ describe('backfillAgentIcons', () => {given([agent({ iconUrl: 'https://example.com/mine.png' })]);const backfill = await loadFresh();- expect(await backfill('ws-1', server('s-1'))).toEqual({ kind: 'written', written: 0 });+ expect(await backfill(server('s-1'))).toEqual({ kind: 'written', written: 0 });expect(updateAgentIcon).not.toHaveBeenCalled();});@@ -126,18 +121,18 @@ describe('backfillAgentIcons', () => {given([agent({ id: 'a-1' }), agent({ id: 'someone-elses' })], ['a-1']);const backfill = await loadFresh();- expect(await backfill('ws-1', server('s-1'))).toEqual({ kind: 'written', written: 1 });+ expect(await backfill(server('s-1'))).toEqual({ kind: 'written', written: 1 });expect(updateAgentIcon).toHaveBeenCalledWith(expect.anything(), 'a-1', expect.any(String));});- it('ignores a local agent belonging to a different workspace', async () => {+ it('ignores a local agent belonging to a different server', async () => {fetchAgents.mockResolvedValue([agent({ id: 'a-1' })]);getAgents.mockResolvedValue([- { id: 'local-1', switchAgentId: 'a-1', workspaceId: 'another-workspace' },+ { id: 'local-1', switchAgentId: 'a-1', serverId: 'another-server' },]);const backfill = await loadFresh();- expect(await backfill('ws-1', server('s-1'))).toEqual({ kind: 'written', written: 0 });+ expect(await backfill(server('s-1'))).toEqual({ kind: 'written', written: 0 });expect(updateAgentIcon).not.toHaveBeenCalled();});@@ -146,7 +141,7 @@ describe('backfillAgentIcons', () => {updateAgentIcon.mockRejectedValueOnce(new FakeGatewayError('http', 'forbidden', 403));const backfill = await loadFresh();- expect(await backfill('ws-1', server('s-1'))).toEqual({ kind: 'written', written: 0 });+ expect(await backfill(server('s-1'))).toEqual({ kind: 'written', written: 0 });});it('reports a server with no icon endpoint', async () => {@@ -157,7 +152,7 @@ describe('backfillAgentIcons', () => {updateAgentIcon.mockRejectedValue(new FakeGatewayError('http', 'not found', 404));const backfill = await loadFresh();- expect(await backfill('ws-1', server('s-1'))).toEqual({ kind: 'unsupported' });+ expect(await backfill(server('s-1'))).toEqual({ kind: 'unsupported' });});it('reports the agents that kept the old icon', async () => {@@ -165,21 +160,17 @@ describe('backfillAgentIcons', () => {updateAgentIcon.mockRejectedValueOnce(new Error('boom'));const backfill = await loadFresh();- expect(await backfill('ws-1', server('s-1'))).toEqual({- kind: 'partial',- written: 2,- failed: 1,- });+ expect(await backfill(server('s-1'))).toEqual({ kind: 'partial', written: 2, failed: 1 });expect(updateAgentIcon).toHaveBeenCalledTimes(3);});- it('asks the gateway once per workspace however often it is called', async () => {+ it('asks the gateway once per server however often it is called', async () => {given([agent({})]);const backfill = await loadFresh();- await backfill('ws-1', server('s-1'));- await backfill('ws-1', server('s-1'));- await backfill('ws-1', server('s-1'));+ await backfill(server('s-1'));+ await backfill(server('s-1'));+ await backfill(server('s-1'));expect(updateAgentIcon).toHaveBeenCalledTimes(1);expect(fetchAgents).toHaveBeenCalledTimes(1);@@ -189,7 +180,7 @@ describe('backfillAgentIcons', () => {// Two sidebar refreshes can land together on startup; without this each// would see no icons yet and write every agent twice.let release = (_: RemoteAgentSummary[]) => {};- getAgents.mockResolvedValue([{ id: 'local-1', switchAgentId: 'a-1', workspaceId: 'ws-1' }]);+ getAgents.mockResolvedValue([{ id: 'local-1', switchAgentId: 'a-1', serverId: 's-1' }]);fetchAgents.mockReturnValue(new Promise<RemoteAgentSummary[]>((resolve) => {release = resolve;@@ -197,8 +188,8 @@ describe('backfillAgentIcons', () => {);const backfill = await loadFresh();- const first = backfill('ws-1', server('s-1'));- const second = backfill('ws-1', server('s-1'));+ const first = backfill(server('s-1'));+ const second = backfill(server('s-1'));release([agent({ id: 'a-1' })]);await Promise.all([first, second]);@@ -212,45 +203,23 @@ describe('backfillAgentIcons', () => {fetchAgents.mockRejectedValueOnce(new Error('offline'));const backfill = await loadFresh();- await expect(backfill('ws-1', server('s-1'))).rejects.toThrow('offline');+ await expect(backfill(server('s-1'))).rejects.toThrow('offline');given([agent({})]);- expect(await backfill('ws-1', server('s-1'))).toEqual({ kind: 'written', written: 1 });+ expect(await backfill(server('s-1'))).toEqual({ kind: 'written', written: 1 });});- it('handles each workspace separately', async () => {+ it('handles each server separately', async () => {fetchAgents.mockResolvedValue([agent({ id: 'a-1' })]);getAgents.mockResolvedValue([- { id: 'local-1', switchAgentId: 'a-1', workspaceId: 'ws-1' },- { id: 'local-2', switchAgentId: 'a-1', workspaceId: 'ws-2' },+ { id: 'local-1', switchAgentId: 'a-1', serverId: 's-1' },+ { id: 'local-2', switchAgentId: 'a-1', serverId: 's-2' },]);const backfill = await loadFresh();- await backfill('ws-1', server('s-1'));- await backfill('ws-2', server('s-2'));+ await backfill(server('s-1'));+ await backfill(server('s-2'));expect(updateAgentIcon).toHaveBeenCalledTimes(2);});-- /**- * Two workspaces on one server are two different agent lists: `GET /agents`- * answers for whichever tenant the session has selected. Remembering the pass- * against the server would have the first workspace's result stand in for the- * second's — its agents never written, and its report describing a pass that- * never looked at them.- */- it('does a second workspace on the same server rather than reusing the first', async () => {- fetchAgents.mockResolvedValue([agent({ id: 'a-1' })]);- getAgents.mockResolvedValue([- { id: 'local-1', switchAgentId: 'a-1', workspaceId: 'ws-1' },- { id: 'local-2', switchAgentId: 'a-1', workspaceId: 'ws-2' },- ]);- const backfill = await loadFresh();-- await backfill('ws-1', server('s-1'));- await backfill('ws-2', server('s-1'));-- expect(fetchAgents).toHaveBeenCalledTimes(2);- expect(updateAgentIcon).toHaveBeenCalledTimes(2);- });});diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.tsindex fa6d64e26..3f6427268 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.ts@@ -29,51 +29,37 @@ import { fetchAgents, GatewayError, updateAgentIcon } from './gateway-client';* server — still show the lettered avatar. Nothing on screen would say why, so* the caller is handed what happened and tells the user.*/-export function backfillAgentIcons(- workspaceId: string,- server: SwitchServer-): Promise<AgentIconBackfill> {- const settled = completed.get(workspaceId);+export function backfillAgentIcons(server: SwitchServer): Promise<AgentIconBackfill> {+ const settled = completed.get(server.id);if (settled !== undefined) return Promise.resolve(settled);- const running = inFlight.get(workspaceId);+ const running = inFlight.get(server.id);if (running) return running;- const run = writeMissingIcons(workspaceId, server)+ const run = writeMissingIcons(server).then((outcome) => {- completed.set(workspaceId, outcome);+ completed.set(server.id, outcome);return outcome;})- .finally(() => inFlight.delete(workspaceId));+ .finally(() => inFlight.delete(server.id));- inFlight.set(workspaceId, run);+ inFlight.set(server.id, run);return run;}-/**- * Workspaces already done this run, and what happened to each. Kept so opening- * the agents page repeatedly does not re-ask the gateway; a workspace whose- * pass threw is deliberately absent, so the next refresh tries again.- *- * Per workspace and not per server: `GET /agents` answers for the tenant the- * session has selected, so one server's two workspaces are two different lists.- * Keying on the server would let the first workspace's pass stand in for the- * second's — the second's agents never written, and the first's outcome- * reported under the second's name.- */+/** Servers already done this run, and what happened to each. Kept so opening+ * the agents page repeatedly does not re-ask the gateway; a server that threw+ * is deliberately absent, so the next refresh tries again. */const completed = new Map<string, AgentIconBackfill>();const inFlight = new Map<string, Promise<AgentIconBackfill>>();-async function writeMissingIcons(- workspaceId: string,- server: SwitchServer-): Promise<AgentIconBackfill> {+async function writeMissingIcons(server: SwitchServer): Promise<AgentIconBackfill> {const [agents, local] = await Promise.all([fetchAgents(server), getAgents()]);- // `GET /agents` lists the whole workspace, most of which is nothing to do- // with this computer.+ // `GET /agents` lists the whole server, most of which is nothing to do with+ // this computer.const managed = new Set(local- .filter((agent) => agent.workspaceId === workspaceId && agent.switchAgentId !== null)+ .filter((agent) => agent.serverId === server.id && agent.switchAgentId !== null).map((agent) => agent.switchAgentId as string));const missing = agents.filter((agent) => agent.iconUrl === null && managed.has(agent.id));@@ -108,7 +94,6 @@ async function writeMissingIcons(if (written === 0 && notFound > 0 && notFound === missing.length) {log.warn('agent icon backfill: this server has no agent-icon endpoint', {event: 'agent_icon_backfill',- workspaceId,serverId: server.id,agents: missing.length,});@@ -118,7 +103,6 @@ async function writeMissingIcons(if (failures.length > 0) {log.warn('agent icon backfill: some agents kept the lettered avatar', {event: 'agent_icon_backfill',- workspaceId,serverId: server.id,written,failed: failures.length,@@ -129,7 +113,6 @@ async function writeMissingIcons(log.info('agent icon backfill: done', {event: 'agent_icon_backfill',- workspaceId,serverId: server.id,written,});diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.test.tsindex 106418c65..44875ad81 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.test.ts@@ -8,10 +8,12 @@ const managedServerHostBlocked = vi.hoisted(() => vi.fn((): unknown => null));const fetchAuthConfig = vi.hoisted(() => vi.fn());const trackEvent = vi.hoisted(() => vi.fn());const addServer = vi.hoisted(() => vi.fn());+const resolveAgentServers = vi.hoisted(() => vi.fn());const passwordLogin = vi.hoisted(() => vi.fn());-const reconcileServerWorkspaces = vi.hoisted(() => vi.fn());-const listWorkspacesForServer = vi.hoisted(() => vi.fn());-const createTenant = vi.hoisted(() => vi.fn());+const createRoomOnServer = vi.hoisted(() => vi.fn());+const deleteBridge = vi.hoisted(() => vi.fn());+const deleteRoom = vi.hoisted(() => vi.fn());+const fetchBridges = vi.hoisted(() => vi.fn());// Stubbed rather than reimplemented: what the tests below assert is that the// kind reaches the event, not how a row is read as one.const serverKindOf = vi.hoisted(() => vi.fn(() => 'remote_managed'));@@ -20,6 +22,7 @@ const serverKindOf = vi.hoisted(() => vi.fn(() => 'remote_managed'));// ssh / agent side effects at load.vi.mock('@main/core/agents/agent-defaults', () => ({ suggestAgentDefaults: vi.fn() }));vi.mock('@main/core/agents/propagate-server-api-url', () => ({ propagateServerApiUrl: vi.fn() }));+vi.mock('@main/core/agents/resolve-servers', () => ({ resolveAgentServers }));vi.mock('@main/core/agents/write-remote-switch-settings', () => ({writeRemoteSwitchSettings: vi.fn(),}));@@ -33,11 +36,6 @@ vi.mock('@main/core/managed-switch-server/managed-server-status', () => ({isManagedServerRunning,managedServerHostBlocked,}));-// Reads this install's own workspace rows, and through them the database client.-vi.mock('@main/core/workspaces/reconcile-workspaces', () => ({- reconcileServerWorkspaces,-}));-vi.mock('@main/core/workspaces/workspaces-store', () => ({ listWorkspacesForServer }));// Writes to the app's log file, which a test has no business creating.vi.mock('@main/lib/logger', () => ({log: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() },@@ -47,15 +45,18 @@ vi.mock('./auth', () => ({ oidcLogin: vi.fn(), passwordLogin }));vi.mock('./backfill-agent-icons', () => ({ backfillAgentIcons: vi.fn() }));// Reaches the encrypted secrets store, and through it the database client.vi.mock('./bundled-chat-sign-in', () => ({ bundledChatSignInFor: vi.fn() }));+vi.mock('./create-room', () => ({ createRoomOnServer }));vi.mock('./gateway-web', () => ({ openAuthenticatedGatewayPage: vi.fn() }));vi.mock('./gateway-client', () => ({fetchMe,agentExistsOnServer: vi.fn(),+ deleteBridge,+ deleteRoom,fetchAgentDetail: vi.fn(),fetchAgentRooms: vi.fn(),fetchAgents: vi.fn(),fetchAuthConfig,- createTenant,+ fetchBridges,fetchRoomRoles: vi.fn(),fetchRooms: vi.fn(),registerKnownAgent: vi.fn(),@@ -65,6 +66,7 @@ vi.mock('./servers-store', () => ({getServer,addServer,deleteSessionCookie: vi.fn(),+ getActiveServerId: vi.fn(),listServers: vi.fn(),removeServer: vi.fn(),renameServer: vi.fn(),@@ -153,6 +155,43 @@ describe('gateway calls on an unreachable host', () => {});});+describe('disconnecting a bridge', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ managedServerHostBlocked.mockReturnValue(null);+ getServer.mockResolvedValue(server({}));+ fetchBridges.mockResolvedValue([{ id: 'b1', type: 'slack' }]);+ });++ it('reports a disconnection the gateway carried out', async () => {+ deleteBridge.mockResolvedValue({ kind: 'deleted' });++ await switchServersController.deleteBridge({ serverId: 'srv', bridgeId: 'b1' });++ await vi.waitFor(() =>+ expect(trackEvent).toHaveBeenCalledWith('bridge_disconnected', {+ bridge_platform: 'slack',+ outcome: 'success',+ })+ );+ });++ it('reports a refusal as a failure rather than as a disconnection', async () => {+ // Admin-only, and the gateway hands back the refusal instead of throwing+ // it — so the await returns exactly as it does for a bridge that went.+ deleteBridge.mockResolvedValue({ kind: 'forbidden' });++ await switchServersController.deleteBridge({ serverId: 'srv', bridgeId: 'b1' });++ await vi.waitFor(() =>+ expect(trackEvent).toHaveBeenCalledWith('bridge_disconnected', {+ bridge_platform: 'slack',+ outcome: 'failure',+ })+ );+ });+});+describe('an action a server whose host has gone down cannot take', () => {const blocked = {sshHost: 'h',@@ -165,6 +204,45 @@ describe('an action a server whose host has gone down cannot take', () => {vi.clearAllMocks();getServer.mockResolvedValue(server({ managed: true, managementKind: 'remote', sshHost: 'h' }));managedServerHostBlocked.mockReturnValue(blocked);+ // What the gateway does on a host that cannot be reached: the platform is+ // then unknowable rather than absent.+ fetchBridges.mockRejectedValue(new Error('no route to host'));+ });++ it('reports the room it refused to create', async () => {+ await expect(+ switchServersController.createRoom({+ serverId: 'srv',+ name: 'Room',+ description: '',+ bridgeId: 'b1',+ agentIds: ['a1'],+ })+ ).rejects.toBeInstanceOf(HostUnreachableError);++ expect(createRoomOnServer).not.toHaveBeenCalled();+ await vi.waitFor(() =>+ expect(trackEvent).toHaveBeenCalledWith('room_created', {+ server_kind: 'remote_managed',+ bridge_platform: 'unknown',+ agent_count: 1,+ has_instructions: false,+ outcome: 'failure',+ failure_reason: 'unreachable',+ })+ );+ });++ it('reports the room it refused to delete', async () => {+ await expect(+ switchServersController.deleteRoom({ serverId: 'srv', roomId: 'r1' })+ ).rejects.toBeInstanceOf(HostUnreachableError);++ expect(deleteRoom).not.toHaveBeenCalled();+ expect(trackEvent).toHaveBeenCalledWith('room_deleted', {+ server_kind: 'remote_managed',+ outcome: 'failure',+ });});it('reports the sign-in that never left this machine', async () => {@@ -204,206 +282,21 @@ describe('an action a server whose host has gone down cannot take', () => {});});-/**- * Signing in is the first moment the gateway will say which workspaces the- * account belongs to — before it, the server's only workspace is the- * placeholder its registration created.- */-describe('reading the account’s workspaces once it is signed in', () => {- beforeEach(() => {- vi.clearAllMocks();- getServer.mockResolvedValue(server({}));- managedServerHostBlocked.mockReturnValue(null);- });-- it('matches the workspaces after a sign-in that succeeded', async () => {- passwordLogin.mockResolvedValue({ success: true, value: { id: 'u1' } });-- await switchServersController.passwordLogin({- serverId: 'srv',- email: '[email protected]',- password: 'hunter2',- });-- expect(reconcileServerWorkspaces).toHaveBeenCalledWith('srv');- });-- it('does not after one that failed', async () => {- passwordLogin.mockResolvedValue({ success: false, error: { kind: 'invalid_credentials' } });-- await switchServersController.passwordLogin({- serverId: 'srv',- email: '[email protected]',- password: 'hunter2',- });-- expect(reconcileServerWorkspaces).not.toHaveBeenCalled();- });-- // The sign-in itself worked; reporting it as a failure would send the user- // back to a form with nothing left to do.- it('still reports the sign-in when the workspaces cannot be read', async () => {- passwordLogin.mockResolvedValue({ success: true, value: { id: 'u1' } });- reconcileServerWorkspaces.mockRejectedValue(new Error('gateway too old'));-- const result = await switchServersController.passwordLogin({- serverId: 'srv',- email: '[email protected]',- password: 'hunter2',- });-- expect(result.success).toBe(true);- });-});--function workspaceRow(overrides: Record<string, unknown>) {- return {- id: 'ws',- serverId: 'srv',- name: 'W',- tenantId: 'tenant-1',- slug: 'w',- role: 'member',- createdAt: '',- updatedAt: '',- ...overrides,- };-}--describe('resolveWorkspaces', () => {- beforeEach(() => {- vi.clearAllMocks();- // Reset rather than cleared: an earlier test leaves a rejection standing on- // it, and `clearAllMocks` forgets the calls but keeps the behaviour.- reconcileServerWorkspaces.mockReset().mockResolvedValue(undefined);- getServer.mockResolvedValue(server({}));- managedServerHostBlocked.mockReturnValue(null);- });-- it('answers with the memberships the server confirmed', async () => {- listWorkspacesForServer.mockResolvedValue([- workspaceRow({ id: 'ws-1', tenantId: 't1' }),- workspaceRow({ id: 'ws-2', tenantId: 't2' }),- ]);-- const found = await switchServersController.resolveWorkspaces('srv');-- expect(reconcileServerWorkspaces).toHaveBeenCalledWith('srv');- expect(found.map((w) => w.id)).toEqual(['ws-1', 'ws-2']);- });-- // The placeholder a registration creates is not a membership, and offering it- // would scope the window to a workspace the gateway has never heard of.- it('leaves out the row that was never matched to a tenant', async () => {- listWorkspacesForServer.mockResolvedValue([- workspaceRow({ id: 'ws-1', tenantId: null, slug: null, role: null }),- ]);-- await expect(switchServersController.resolveWorkspaces('srv')).resolves.toEqual([]);- });-- /**- * The row is kept locally so its agents are not silently detached, but every- * call scoped to it is refused. Offering it puts the refusal after the click;- * worse, left as the only answer it is the one the caller enters without- * asking.- */- it('leaves out a membership the account has been removed from', async () => {- listWorkspacesForServer.mockResolvedValue([- workspaceRow({ id: 'ws-1', tenantId: 't1' }),- workspaceRow({ id: 'ws-gone', tenantId: 't2', role: null }),- ]);-- const found = await switchServersController.resolveWorkspaces('srv');-- expect(found.map((w) => w.id)).toEqual(['ws-1']);- });-- // "You belong to nothing" and "nobody could be asked" are different answers,- // and a caller that received the empty list for both would offer to create a- // second workspace to someone who already has one.- it('raises rather than answering empty when the server cannot be asked', async () => {- reconcileServerWorkspaces.mockRejectedValue(new Error('gateway unreachable'));-- await expect(switchServersController.resolveWorkspaces('srv')).rejects.toThrow(- 'gateway unreachable'- );- });-});--describe('createWorkspace', () => {- beforeEach(() => {- vi.clearAllMocks();- reconcileServerWorkspaces.mockReset().mockResolvedValue(undefined);- getServer.mockResolvedValue(server({}));- managedServerHostBlocked.mockReturnValue(null);- });-- it('returns the local row for the workspace the gateway minted', async () => {- createTenant.mockResolvedValue({ id: 't9', slug: 'acme', name: 'Acme', role: 'owner' });- listWorkspacesForServer.mockResolvedValue([- workspaceRow({ id: 'ws-1', tenantId: 't1' }),- workspaceRow({ id: 'ws-9', tenantId: 't9', name: 'Acme', role: 'owner' }),- ]);-- const created = await switchServersController.createWorkspace({- serverId: 'srv',- name: 'Acme',- });-- expect(createTenant).toHaveBeenCalledWith(expect.objectContaining({ id: 'srv' }), 'Acme');- expect(created.id).toBe('ws-9');- });-- /**- * The reconcile is what records the workspace, name included — so one that- * failed has recorded nothing. Answering anyway would hand back whichever row- * happened to be there, under a name the user did not type, and report a- * success the install has no trace of.- */- it('raises when the reconcile that records the workspace fails', async () => {- createTenant.mockResolvedValue({ id: 't9', slug: 'acme', name: 'Acme', role: 'owner' });- reconcileServerWorkspaces.mockRejectedValue(new Error('the gateway stopped answering'));-- await expect(- switchServersController.createWorkspace({ serverId: 'srv', name: 'Acme' })- ).rejects.toThrow('the gateway stopped answering');- expect(listWorkspacesForServer).not.toHaveBeenCalled();- });-- // The workspace exists on the server either way. Returning something else, or- // nothing, would leave the app scoped to a workspace that is not the one just- // made — so it says so instead.- it('raises when the new workspace did not land locally', async () => {- createTenant.mockResolvedValue({ id: 't9', slug: 'acme', name: 'Acme', role: 'owner' });- listWorkspacesForServer.mockResolvedValue([workspaceRow({ id: 'ws-1', tenantId: 't1' })]);-- await expect(- switchServersController.createWorkspace({ serverId: 'srv', name: 'Acme' })- ).rejects.toThrow('did not record it');- });-- it('does not ask a server whose host is down to create anything', async () => {- getServer.mockResolvedValue(server({ managed: true, managementKind: 'remote', sshHost: 'h' }));- managedServerHostBlocked.mockReturnValue({ sshHost: 'h', status: 'unreachable' });-- await expect(- switchServersController.createWorkspace({ serverId: 'srv', name: 'Acme' })- ).rejects.toThrow();- expect(createTenant).not.toHaveBeenCalled();- });-});-describe('adding a server by URL', () => {const params = { name: 'S', gatewayUrl: 'http://gateway', apiUrl: 'http://api' };beforeEach(() => {vi.clearAllMocks();+ resolveAgentServers.mockResolvedValue(undefined);});- it('reports the add that worked', async () => {+ it('keeps the add that worked when reconciling the agent links does not', async () => {+ // The row is in; unlinking agents from servers that are gone is bookkeeping+ // after the fact. Rejecting here would show the user a failure for a server+ // they now have, and a second press would register it twice.const added = server({ id: 'new' });addServer.mockResolvedValue(added);+ resolveAgentServers.mockRejectedValue(new Error('database is locked'));await expect(switchServersController.addServer(params)).resolves.toBe(added);expect(trackEvent).toHaveBeenCalledExactlyOnceWith('server_added', {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 95ff5cb1f..ff872e675 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts@@ -1,41 +1,174 @@import type { Result } from '@switch-console/shared';import { propagateServerApiUrl } from '@main/core/agents/propagate-server-api-url';+import { resolveAgentServers } from '@main/core/agents/resolve-servers';import { appService } from '@main/core/app/service';-import { isManagedServerRunning } from '@main/core/managed-switch-server/managed-server-status';-import type { TelemetryAuthMethod, TelemetrySignInFailure } from '@main/core/telemetry/events';+import {+ isManagedServerRunning,+ managedServerHostBlocked,+} from '@main/core/managed-switch-server/managed-server-status';+import { bridgePlatformOfType } from '@main/core/telemetry/bridge-platform';+import type {+ TelemetryAuthMethod,+ TelemetryBridgeFailure,+ TelemetryBridgePlatform,+ TelemetryOutcome,+ TelemetryRoomAgentsDirection,+ TelemetryRoomCreateFailure,+ TelemetryServerKind,+ TelemetrySignInFailure,+} from '@main/core/telemetry/events';+import { roomAgentsDirectionOf } from '@main/core/telemetry/narrow';import { trackEvent } from '@main/core/telemetry/telemetry-service';-import { reconcileServerWorkspaces } from '@main/core/workspaces/reconcile-workspaces';-import { listWorkspacesForServer } from '@main/core/workspaces/workspaces-store';import { log } from '@main/lib/logger';+import { HostUnreachableError } from '@shared/core/remote-hosts/reachability';import type {+ AddressingPolicy,AddServerParams,+ AgentVerifyResult,+ BridgeDirectorySearchResult,+ AgentIconBackfill,BundledChatSignIn,+ ClaimIdentityParams,+ ClaimIdentityResult,+ CreateBridgeParams,+ CreateBridgeResult,+ CreateRoomParams,+ CreateRoomResult,+ DeleteBridgeParams,+ DeleteBridgeResult,+ LinkedIdentity,PasswordLoginParams,+ RemoteAgentRoom,+ RemoteAgentSummary,+ RemoteBridge,+ RemoteBridgeType,+ RemoteExternalUser,+ RemoteRoomDetail,+ RemoteRoomGroup,+ RemoteRoomRole,+ RemoteRoomSummary,RenameServerParams,ServerConnectionStatus,SwitchAuthConfig,SwitchServer,+ UpdateBridgeParams,+ UpdateBridgeResult,+ UpdateRoomParams,UpdateServerParams,UpdateServerResult,} from '@shared/core/switch-servers/switch-servers';-import { isWithdrawnWorkspace, type Workspace } from '@shared/core/workspaces/workspaces';import { createRPCController } from '@shared/lib/ipc/rpc';import { type LoginError, oidcLogin, passwordLogin } from './auth';+import { backfillAgentIcons } from './backfill-agent-icons';+import { withResolvedHomeUrls } from './bridge-home-url';import { bundledChatSignInFor } from './bundled-chat-sign-in';-import { createTenant, fetchAuthConfig, fetchMe, GatewayError } from './gateway-client';+import { createBridgeOnServer } from './create-bridge';+import { createRoomOnServer } from './create-room';+import {+ addRoomAgents,+ agentExistsOnServer,+ deleteBridge,+ deleteRoom,+ fetchAddressingPolicy,+ fetchAgentRooms,+ fetchAgents,+ fetchAllExternalUsers,+ fetchAuthConfig,+ fetchBridges,+ fetchBridgeTypes,+ fetchMe,+ fetchMyIdentities,+ fetchRoomAgentIds,+ fetchRoomDetail,+ fetchRoomGroups,+ fetchRoomRoles,+ fetchRooms,+ createTemplate,+ deleteTemplate,+ updateTemplate,+ fetchTemplateDetail,+ fetchTemplates,+ GatewayError,+ ownsOwnerAddressedAgent,+ releaseBridgeIdentity,+ createRoomFromTemplate,+ exportRoomYaml,+ fetchTemplateSchema,+ removeRoomAgent,+ type StoredTemplateDetail,+ type StoredTemplateSummary,+ type TemplateVisibility,+ type ProvisionFromTemplateResult,+ updateAddressingPolicy,+ updateAgentIcon,+ updateRoom,+} from './gateway-client';import { openAuthenticatedGatewayPage } from './gateway-web';-import { hostUnreachable, requireReachableServer, requireServer } from './require-server';+import { claimIdentityOnServer, searchDirectoryOnServer } from './identities';import {addServer,deleteSessionCookie,+ getActiveServerId,getServer,listServers,removeServer,renameServer,- serverKindOf,setActiveServerId,updateServer,+ serverKindOf,} from './servers-store';+import { updateBridgeOnServer } from './update-bridge';++async function requireServer(serverId: string): Promise<SwitchServer> {+ const server = await getServer(serverId);+ if (!server) {+ throw new Error(`No Switch server with id ${serverId}`);+ }+ return server;+}++/**+ * The refusal a managed server's host being down produces, or null while it is+ * up.+ *+ * Returned rather than thrown so a path that reports its own outcome can count+ * the refusal before it propagates: the server is what an event describes+ * itself with, and a helper that throws leaves the caller holding nothing.+ */+function hostUnreachable(server: SwitchServer): HostUnreachableError | null {+ const blocked = managedServerHostBlocked(server);+ return blocked ? new HostUnreachableError(blocked) : null;+}++/**+ * Resolve a server and refuse to touch its gateway while the host it is managed+ * on is unreachable (CHOO-1780). `gatewayFetch` enforces the same rule at the+ * transport, so this is for the paths that reach the gateway some other way —+ * sign-in and the dashboard window — and for failing before the side effects a+ * write would otherwise start.+ */+async function requireReachableServer(serverId: string): Promise<SwitchServer> {+ const server = await requireServer(serverId);+ const unreachable = hostUnreachable(server);+ if (unreachable) throw unreachable;+ return server;+}++/** A bridge result's discriminant as a code. Never the message beside it. */+function bridgeFailureReason(kind: string): TelemetryBridgeFailure {+ switch (kind) {+ case 'created':+ return 'none';+ case 'unauthenticated':+ return 'unauthenticated';+ case 'forbidden':+ return 'forbidden';+ case 'invalid':+ return 'invalid';+ default:+ return 'error';+ }+}/** A sign-in's own error union, as a reportable code. Never its message. */const SIGN_IN_FAILURE: Record<LoginError['kind'], TelemetrySignInFailure> = {@@ -48,26 +181,6 @@ function signInFailureReason(result: Result<unknown, LoginError>): TelemetrySignreturn result.success ? 'none' : SIGN_IN_FAILURE[result.error.kind];}-/**- * Match the server's workspaces to the memberships the account turns out to- * have. Signing in is the first moment the gateway will answer that, and the- * renderer reloads its workspace list straight afterwards — so it is awaited,- * to be there when it does.- *- * Logged rather than raised: the sign-in itself succeeded, and reporting it as- * a failure would send the user back to a form that has nothing left to do.- */-async function adoptWorkspaces(server: SwitchServer): Promise<void> {- try {- await reconcileServerWorkspaces(server.id);- } catch (error) {- log.warn('workspaces: signed in, but could not read the account’s workspaces', {- server: server.id,- error: String(error),- });- }-}-/*** Reported by reason rather than by outcome: the two are the same fact, and a* sign-in that never left this machine — the server's host is down — has a@@ -86,6 +199,78 @@ function reportSignIn(});}+/** A room-create result's discriminant as a code. */+function roomCreateFailureReason(result: CreateRoomResult): TelemetryRoomCreateFailure {+ switch (result.kind) {+ case 'created':+ return 'none';+ case 'unauthenticated':+ return 'unauthenticated';+ case 'bridge-unavailable':+ return 'bridge_unavailable';+ case 'invalid':+ return 'invalid';+ default:+ return 'error';+ }+}++/**+ * Which platform a bridge id is on.+ *+ * A lookup rather than a field: these operations take a bridge id, and the type+ * either never appears (a delete) or appears only on success (a room). Best+ * effort — an unreachable server yields `unknown` rather than failing the+ * operation it is only describing.+ *+ * **Never awaited by a caller doing real work.** It asks the gateway, and making+ * someone wait on a network round trip so we can describe what they did would+ * put reporting in the path of the thing being reported. `reportWithBridge` is+ * how the answer is used once it arrives.+ */+function bridgePlatformOf(+ server: SwitchServer,+ bridgeId: string | null | undefined+): Promise<TelemetryBridgePlatform> {+ if (!bridgeId) return Promise.resolve('unknown');+ return fetchBridges(server)+ .then((bridges) => bridgePlatformOfType(bridges.find((b) => b.id === bridgeId)?.type))+ .catch((): TelemetryBridgePlatform => 'unknown');+}++/**+ * Report once the platform is known, without anyone waiting for it.+ *+ * The event arrives a moment after the action rather than with it, which costs+ * nothing: it carries its own timestamp, taken when the work happened.+ */+function reportWithBridge(+ platform: Promise<TelemetryBridgePlatform>,+ emit: (platform: TelemetryBridgePlatform) => void+): void {+ void platform.then(emit).catch(() => {});+}++/** The same, for a room create whose other properties are already known. */+function reportRoomCreated(+ server: SwitchServer,+ bridgeId: string | null | undefined,+ rest: {+ server_kind: TelemetryServerKind;+ agent_count: number;+ has_instructions: boolean;+ failure_reason: TelemetryRoomCreateFailure;+ }+): void {+ reportWithBridge(bridgePlatformOf(server, bridgeId), (bridge_platform) =>+ trackEvent('room_created', {+ ...rest,+ bridge_platform,+ outcome: rest.failure_reason === 'none' ? 'success' : 'failure',+ })+ );+}+export const switchServersController = createRPCController({listServers: (): Promise<SwitchServer[]> => listServers(),@@ -102,12 +287,23 @@ export const switchServersController = createRPCController({throw error;}trackEvent('server_added', { server_kind: 'external', outcome: 'success' });+ // The row has landed, so the server is added whatever happens next — this+ // reconciliation only unlinks agents pointing at servers that are gone.+ // Rejecting for it would tell the user their add failed while the store has+ // already reported it as done, and leave them to press Add again, which+ // registers the same server a second time rather than retrying the first.+ try {+ await resolveAgentServers();+ } catch (error) {+ log.warn('switch-servers: could not reconcile agent links after adding a server', { error });+ }return server;},updateServer: async (params: UpdateServerParams): Promise<UpdateServerResult> => {const previous = await requireServer(params.id);const server = await updateServer(params);+ await resolveAgentServers();// The API URL is what an agent's SWITCH_API_ENDPOINT points at. When it// changes, cascade it to every member agent's stored config so they don't@@ -125,66 +321,9 @@ export const switchServersController = createRPCController({removeServer: (serverId: string): Promise<void> => removeServer(serverId),- setActiveServer: (serverId: string): Promise<void> => setActiveServerId(serverId),-- /**- * Ask a server which workspaces this account belongs to, and return the local- * rows for them.- *- * Local rows rather than the gateway's answer directly, because what a caller- * does next is scope the window to one, and that is addressed by the row's- * id. Reconciling first is what guarantees there is a row for each.- *- * An empty list means the server answered and the account belongs to nothing- * — a real answer, and the one the first-run flow turns into "create your- * workspace". A server that cannot be asked raises instead, because the two- * are not the same and a caller that treated them alike would offer to create- * a second workspace to someone who already has one.- */- resolveWorkspaces: async (serverId: string): Promise<Workspace[]> => {- await reconcileServerWorkspaces(serverId);- const workspaces = await listWorkspacesForServer(serverId);- // A withdrawn membership is a row this install still holds for a workspace- // the account has been removed from. It is kept so its agents are not- // silently detached, but it is not somewhere to work: every call scoped to- // it is refused, and with exactly one of them the caller would take it- // without asking.- return workspaces.filter(- (workspace) => workspace.tenantId !== null && !isWithdrawnWorkspace(workspace)- );- },+ getActiveServerId: (): Promise<string | null> => getActiveServerId(),- /**- * Create a workspace on a server, owned by the signed-in user.- *- * Addressed by server rather than by workspace — the exception the split- * allows itself, because the thing being created is the workspace: there is- * no id to address it by until the gateway has minted one, and on a fresh- * install there is no other workspace to address it from either.- *- * Reconciling afterwards rather than inserting a row here keeps one- * implementation of "which local row is this membership": the new workspace- * may claim the tenant-less row a freshly registered server starts with, and- * deciding that twice is how the two answers come to differ. It is also what- * carries the typed name onto the row, since a matched workspace takes its- * name from the gateway — so a reconcile that fails here leaves the name to- * the next one rather than stranding it on the server forever, which is what- * a rename issued from this call site would have done.- */- createWorkspace: async (params: { serverId: string; name: string }): Promise<Workspace> => {- const server = await requireReachableServer(params.serverId);- const tenant = await createTenant(server, params.name);- await reconcileServerWorkspaces(params.serverId);-- const workspaces = await listWorkspacesForServer(params.serverId);- const created = workspaces.find((workspace) => workspace.tenantId === tenant.id);- if (!created) {- throw new Error(- `${server.name} created the workspace ${tenant.name}, but this install did not record it.`- );- }- return created;- },+ setActiveServer: (serverId: string): Promise<void> => setActiveServerId(serverId),getAuthConfig: async (serverId: string): Promise<SwitchAuthConfig> =>fetchAuthConfig(await requireReachableServer(serverId)),@@ -201,7 +340,6 @@ export const switchServersController = createRPCController({}const result = await passwordLogin(server, params.email, params.password);reportSignIn('password', server, signInFailureReason(result));- if (result.success) await adoptWorkspaces(server);return result;},@@ -214,7 +352,6 @@ export const switchServersController = createRPCController({}const result = await oidcLogin(server);reportSignIn('oidc', server, signInFailureReason(result));- if (result.success) await adoptWorkspaces(server);return result;},@@ -264,6 +401,20 @@ export const switchServersController = createRPCController({}},+ listRemoteAgents: async (serverId: string): Promise<RemoteAgentSummary[]> =>+ fetchAgents(await requireServer(serverId)),++ listRemoteRooms: async (serverId: string): Promise<RemoteRoomSummary[]> =>+ fetchRooms(await requireServer(serverId)),++ listRemoteBridges: async (serverId: string): Promise<RemoteBridge[]> => {+ const server = await requireReachableServer(serverId);+ return withResolvedHomeUrls(server, await fetchBridges(server));+ },++ listRemoteBridgeTypes: async (serverId: string): Promise<RemoteBridgeType[]> =>+ fetchBridgeTypes(await requireReachableServer(serverId)),+/*** The bundled chat's address and sign-in for a managed server (CHOO-1787).*@@ -273,4 +424,367 @@ export const switchServersController = createRPCController({*/getBundledChatSignIn: async (serverId: string): Promise<BundledChatSignIn> =>bundledChatSignInFor(await getServer(serverId)),++ /**+ * Attach a collaboration bridge to the chosen server (CHOO-1784).+ *+ * `params.connectionConfig` carries platform credentials. They cross the IPC+ * boundary once, on the way out, and are never written to Switch Console's disk+ * or returned to the renderer — the server stores them. Keep it that way: do+ * not log `params` here.+ */+ createBridge: async (params: CreateBridgeParams): Promise<CreateBridgeResult> => {+ const server = await requireReachableServer(params.serverId);+ const platform = bridgePlatformOfType(params.bridgeType);+ let result: CreateBridgeResult;+ try {+ result = await createBridgeOnServer(server, {+ bridgeType: params.bridgeType,+ displayName: params.displayName,+ connectionConfig: params.connectionConfig,+ setAsDefault: params.setAsDefault,+ channelCreationEnabled: params.channelCreationEnabled,+ });+ } catch (error) {+ trackEvent('bridge_connected', {+ bridge_platform: platform,+ outcome: 'failure',+ failure_reason: 'error',+ });+ throw error;+ }+ trackEvent('bridge_connected', {+ bridge_platform: platform,+ outcome: result.kind === 'created' ? 'success' : 'failure',+ failure_reason: bridgeFailureReason(result.kind),+ });+ return result;+ },++ /**+ * Edit a bridge's operator-controlled switches — today, only whether the+ * connection may create channels. Admin-only, like registering one; see+ * `updateBridgeOnServer` for the recoverable-failure mapping.+ */+ updateBridge: async (params: UpdateBridgeParams): Promise<UpdateBridgeResult> => {+ const server = await requireReachableServer(params.serverId);+ return updateBridgeOnServer(server, {+ bridgeId: params.bridgeId,+ channelCreationEnabled: params.channelCreationEnabled,+ });+ },++ /**+ * Disconnect a messaging app from the chosen server. Admin-only, and the+ * gateway deletes every Switch room on the bridge on the way — see+ * `deleteBridge`. The renderer owns the confirmation; by the time this runs+ * the rooms are being given up deliberately.+ */+ deleteBridge: async (params: DeleteBridgeParams): Promise<DeleteBridgeResult> => {+ const server = await requireReachableServer(params.serverId);+ // Started before the delete, because afterwards there is no bridge left to+ // read a platform from — but never waited on: see `reportWithBridge`.+ const platform = bridgePlatformOf(server, params.bridgeId);+ const result = await deleteBridge(server, params.bridgeId);+ reportWithBridge(platform, (bridge_platform) =>+ trackEvent('bridge_disconnected', {+ bridge_platform,+ outcome: result.kind === 'deleted' ? 'success' : 'failure',+ })+ );+ return result;+ },++ /**+ * Create a room on the chosen server, owned by the signed-in user. Room+ * provisioning stays server-side (`POST /gateway/rooms`); this only maps+ * recoverable failures onto a typed result the modal can act on.+ */+ createRoom: async (params: CreateRoomParams): Promise<CreateRoomResult> => {+ const server = await requireServer(params.serverId);+ const report = (failure_reason: TelemetryRoomCreateFailure) =>+ reportRoomCreated(server, params.bridgeId, {+ server_kind: serverKindOf(server),+ agent_count: params.agentIds.length,+ has_instructions: (params.instructions?.trim().length ?? 0) > 0,+ failure_reason,+ });++ const unreachable = hostUnreachable(server);+ if (unreachable) {+ report('unreachable');+ throw unreachable;+ }++ let result: CreateRoomResult;+ try {+ result = await createRoomOnServer(server, {+ name: params.name,+ description: params.description,+ instructions: params.instructions,+ bridgeId: params.bridgeId,+ agentIds: params.agentIds,+ });+ } catch (error) {+ report('error');+ throw error;+ }++ report(roomCreateFailureReason(result));+ return result;+ },++ createRoomFromTemplate: async (+ serverId: string,+ yamlText: string,+ inputs: Record<string, string | number | boolean>+ ): Promise<ProvisionFromTemplateResult> =>+ createRoomFromTemplate(await requireServer(serverId), yamlText, inputs),++ listTemplates: async (params: {+ serverId: string;+ kind?: string;+ /** Narrows to templates whose name or description contains it. */+ q?: string;+ }): Promise<StoredTemplateSummary[]> =>+ fetchTemplates(await requireServer(params.serverId), { kind: params.kind, q: params.q }),++ getTemplateDetail: async (params: {+ serverId: string;+ templateId: string;+ }): Promise<StoredTemplateDetail> =>+ fetchTemplateDetail(await requireServer(params.serverId), params.templateId),++ deleteTemplate: async (params: { serverId: string; templateId: string }): Promise<void> =>+ deleteTemplate(await requireServer(params.serverId), params.templateId),++ updateTemplate: async (params: {+ serverId: string;+ templateId: string;+ name?: string;+ description?: string;+ kind?: string;+ content?: string;+ readVisibility?: TemplateVisibility;+ writeVisibility?: TemplateVisibility;+ }): Promise<StoredTemplateDetail> => {+ const { serverId, templateId, ...changes } = params;+ return updateTemplate(await requireServer(serverId), templateId, changes);+ },++ saveTemplate: async (params: {+ serverId: string;+ name: string;+ description: string;+ kind: string;+ content: string;+ readVisibility?: TemplateVisibility;+ writeVisibility?: TemplateVisibility;+ }): Promise<StoredTemplateDetail> => {+ const { serverId, ...template } = params;+ return createTemplate(await requireServer(serverId), template);+ },++ fetchTemplateSchema: async (serverId: string): Promise<Record<string, unknown> | null> =>+ fetchTemplateSchema(await requireServer(serverId)),++ exportRoomYaml: async (params: { serverId: string; roomId: string }): Promise<string> =>+ exportRoomYaml(await requireServer(params.serverId), params.roomId),++ listAgentRooms: async (params: {+ serverId: string;+ agentId: string;+ }): Promise<RemoteAgentRoom[]> =>+ fetchAgentRooms(await requireServer(params.serverId), params.agentId),++ listRoomRoles: async (params: { serverId: string; roomId: string }): Promise<RemoteRoomRole[]> =>+ fetchRoomRoles(await requireServer(params.serverId), params.roomId),++ listRoomAgentIds: async (params: { serverId: string; roomId: string }): Promise<string[]> =>+ fetchRoomAgentIds(await requireServer(params.serverId), params.roomId),++ /** One room in full, for its configuration page. */+ getRoomDetail: async (params: { serverId: string; roomId: string }): Promise<RemoteRoomDetail> =>+ fetchRoomDetail(await requireServer(params.serverId), params.roomId),++ /**+ * Change a room's own settings. Failures propagate as-is — a user without+ * write access to the room needs the gateway's refusal, not a saved-looking+ * field holding a value the server never took.+ */+ updateRoom: async (params: UpdateRoomParams): Promise<RemoteRoomDetail> =>+ updateRoom(await requireReachableServer(params.serverId), params.roomId, {+ description: params.description,+ instructions: params.instructions,+ }),++ /**+ * Add agents to a room. Failures propagate as-is: the caller shows the+ * gateway's own words (e.g. an agent whose server-side client is not running,+ * which the gateway rejects) rather than a generic message.+ */+ addRoomAgents: async (params: {+ serverId: string;+ roomId: string;+ agentIds: string[];+ /**+ * Which screen this came from. The same call serves both, and the+ * one-agent-to-many-rooms screen loops it once per room — so without this,+ * adding an agent to five rooms is indistinguishable from five people each+ * adding one agent.+ */+ direction: TelemetryRoomAgentsDirection;+ }): Promise<void> => {+ await addRoomAgents(+ await requireReachableServer(params.serverId),+ params.roomId,+ params.agentIds+ );+ trackEvent('room_agents_added', {+ agent_count: params.agentIds.length,+ direction: roomAgentsDirectionOf(params.direction),+ });+ },++ /** Remove one agent from a room. Membership only — the agent is not deleted. */+ removeRoomAgent: async (params: {+ serverId: string;+ roomId: string;+ agentId: string;+ }): Promise<void> =>+ removeRoomAgent(await requireReachableServer(params.serverId), params.roomId, params.agentId),++ /** Delete a room and everything in it. The gateway enforces who may. */+ deleteRoom: async (params: { serverId: string; roomId: string }): Promise<void> => {+ const server = await requireServer(params.serverId);+ const report = (outcome: TelemetryOutcome) =>+ trackEvent('room_deleted', { server_kind: serverKindOf(server), outcome });++ // A host that has gone down refuses the deletion as surely as the gateway+ // can, and the event has an outcome precisely so a refusal is counted.+ const unreachable = hostUnreachable(server);+ if (unreachable) {+ report('failure');+ throw unreachable;+ }++ try {+ await deleteRoom(server, params.roomId);+ } catch (error) {+ report('failure');+ throw error;+ }+ report('success');+ },++ listRemoteRoomGroups: async (serverId: string): Promise<RemoteRoomGroup[]> =>+ fetchRoomGroups(await requireServer(serverId)),++ listRemoteExternalUsers: async (serverId: string): Promise<RemoteExternalUser[]> =>+ fetchAllExternalUsers(await requireServer(serverId)),++ /**+ * Search a bridge's own user directory so the signed-in user can find+ * themselves before they have ever posted in the workspace (CHOO-2137).+ */+ searchBridgeDirectory: async (params: {+ serverId: string;+ bridgeId: string;+ query: string;+ }): Promise<BridgeDirectorySearchResult> =>+ searchDirectoryOnServer(+ await requireReachableServer(params.serverId),+ params.bridgeId,+ params.query+ ),++ /** Claim a messaging-app account as the signed-in Switch user's own. */+ claimBridgeIdentity: async (params: ClaimIdentityParams): Promise<ClaimIdentityResult> => {+ const server = await requireReachableServer(params.serverId);+ const result = await claimIdentityOnServer(server, {+ bridgeId: params.bridgeId,+ externalUserId: params.externalUserId,+ username: params.username,+ });+ reportWithBridge(bridgePlatformOf(server, params.bridgeId), (bridge_platform) =>+ trackEvent('bridge_identity_claimed', {+ bridge_platform,+ outcome: result.kind === 'claimed' ? 'success' : 'failure',+ })+ );+ return result;+ },++ /** Give up a claim on a messaging-app account, leaving any other user's claim+ * on it in place. `userId` is whose claim to drop — null for the signed-in+ * user, which is the only one this app offers. Failures propagate: unclaiming+ * is a deliberate act, and reporting success for one that did not happen+ * would leave the user thinking an agent is no longer reachable by them when+ * it still is. */+ releaseBridgeIdentity: async (params: {+ serverId: string;+ bridgeId: string;+ identityId: string;+ userId: string | null;+ }): Promise<void> =>+ releaseBridgeIdentity(+ await requireReachableServer(params.serverId),+ params.bridgeId,+ params.identityId,+ params.userId+ ),++ /** The messaging accounts the signed-in user has claimed on this server. */+ listMyIdentities: async (serverId: string): Promise<LinkedIdentity[]> =>+ fetchMyIdentities(await requireServer(serverId)),++ /** Whether the signed-in user owns an agent here that is set to answer its+ * owner, which is what makes an unlinked messaging account worth warning+ * about. One agent-list read, so callers need not ration it. */+ ownsOwnerAddressedAgent: async (serverId: string): Promise<boolean> =>+ ownsOwnerAddressedAgent(await requireServer(serverId)),++ getAddressingPolicy: async (params: {+ serverId: string;+ agentId: string;+ }): Promise<AddressingPolicy | null> =>+ fetchAddressingPolicy(await requireServer(params.serverId), params.agentId),++ updateAddressingPolicy: async (params: {+ serverId: string;+ agentId: string;+ policy: AddressingPolicy | null;+ }): Promise<void> =>+ updateAddressingPolicy(await requireServer(params.serverId), params.agentId, params.policy),++ /** Give this user's icon-less agents the avatar their name generates. Runs+ * once per server per app run; reports what happened so the caller can say+ * when the icons did not reach the server. */+ backfillAgentIcons: async (serverId: string): Promise<AgentIconBackfill> =>+ backfillAgentIcons(await requireServer(serverId)),++ /** Set or clear an agent's icon. Returns the agent as the server now holds+ * it, so the caller refreshes from the stored value rather than the one it+ * hoped for. */+ updateAgentIcon: async (params: {+ serverId: string;+ agentId: string;+ iconUrl: string | null;+ }): Promise<RemoteAgentSummary> =>+ updateAgentIcon(await requireServer(params.serverId), params.agentId, params.iconUrl),++ verifyAgent: async (params: {+ serverId: string;+ agentId: string;+ }): Promise<AgentVerifyResult> => {+ const server = await requireServer(params.serverId);+ try {+ return (await agentExistsOnServer(server, params.agentId)) ? 'found' : 'not-found';+ } catch (cause) {+ if (cause instanceof GatewayError && cause.kind === 'unauthorized') {+ return 'unauthenticated';+ }+ throw cause;+ }+ },});diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.tsindex 4226079fd..8b34fab8f 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.ts@@ -18,7 +18,7 @@ import type {*/export async function createBridgeOnServer(server: SwitchServer,- params: Omit<CreateBridgeParams, 'workspaceId'>+ params: Omit<CreateBridgeParams, 'serverId'>): Promise<CreateBridgeResult> {try {const bridge = await createBridge(server, {diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/create-room.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/create-room.tsindex 276f7c679..c1bc0b288 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/create-room.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/create-room.ts@@ -33,7 +33,7 @@ function isBridgeFailure(detail: string): boolean {*/export async function createRoomOnServer(server: SwitchServer,- params: Omit<CreateRoomParams, 'workspaceId'>+ params: Omit<CreateRoomParams, 'serverId'>): Promise<CreateRoomResult> {try {const room = await createRoom(server, {diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/delete-server-agents.db.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/delete-server-agents.db.test.tsindex d4a78cab5..12c9aa201 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/delete-server-agents.db.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/delete-server-agents.db.test.ts@@ -2,7 +2,7 @@ import { openFixture } from '@tooling/utils/db';import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { AppDb } from '@main/db/client';-import { agents, locations, switchServers, workspaces } from '@main/db/schema';+import { agents, locations, switchServers } from '@main/db/schema';const mocks = vi.hoisted(() => ({db: undefined as AppDb | undefined,@@ -44,11 +44,6 @@ describe('deleteAgentsForServer', () => {gatewayUrl: `https://${id}.example.com`,apiUrl: `https://api-${id}.example.com`,});- // Deliberately not the server's id: the query has to reach the server- // through the workspace, and identical ids would hide it not doing so.- await fixture.db- .insert(workspaces)- .values({ id: `ws-${id}`, serverId: id, name: `Workspace ${id}` });}});@@ -58,13 +53,9 @@ describe('deleteAgentsForServer', () => {});async function seedAgent(id: string, serverId: string | null): Promise<void> {- await fixture.db.insert(agents).values({- id,- locationId: 'loc-1',- name: id,- providerId: 'claude',- workspaceId: serverId ? `ws-${serverId}` : null,- });+ await fixture.db+ .insert(agents)+ .values({ id, locationId: 'loc-1', name: id, providerId: 'claude', serverId });}it('deletes only the agents belonging to the given server', async () => {@@ -130,7 +121,7 @@ describe('deleteAgentsForServer', () => {const remaining = await fixture.db.select({ id: agents.id }).from(agents)- .where(eq(agents.workspaceId, 'ws-other-1'));+ .where(eq(agents.serverId, 'other-1'));expect(remaining).toEqual([{ id: 'agent-other' }]);});});diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/delete-server-agents.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/delete-server-agents.tsindex 2f0a08cf5..6fd47dbde 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/delete-server-agents.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/delete-server-agents.ts@@ -1,11 +1,11 @@import { eq } from 'drizzle-orm';import { deleteAgent } from '@main/core/agents/deleteAgent';import { db } from '@main/db/client';-import { agents, workspaces } from '@main/db/schema';+import { agents } from '@main/db/schema';import { log } from '@main/lib/logger';/**- * Delete every agent in every workspace of a managed Switch server, as part of+ * Delete every agent that belongs to a managed Switch server, as part of* destroying that server's stack.** Wiping a managed stack destroys the server-side identity behind each of its@@ -33,8 +33,7 @@ export async function deleteAgentsForServer(const rows = await db.select({ id: agents.id, name: agents.name }).from(agents)- .innerJoin(workspaces, eq(agents.workspaceId, workspaces.id))- .where(eq(workspaces.serverId, serverId));+ .where(eq(agents.serverId, serverId));const deleted: string[] = [];const failed: { agentId: string; error: string }[] = [];diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.tsindex 9a5c71e2f..e12000267 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@@ -3,7 +3,6 @@ import {managedServerHostBlocked,managedServerStoppedPhase,} from '@main/core/managed-switch-server/managed-server-status';-import { assertedTenant } from '@main/core/workspaces/asserted-tenant';import { ManagedServerStoppedError } from '@shared/core/managed-switch-server/managed-switch-server';import { HostUnreachableError } from '@shared/core/remote-hosts/reachability';import { policyNamesOwner } from '@shared/core/switch-servers/owner-policy';@@ -27,9 +26,8 @@ import type {SwitchServerDeclaration,SwitchUser,} from '@shared/core/switch-servers/switch-servers';-import type { WorkspaceRole } from '@shared/core/workspaces/workspaces';-import { extractAuthCookie, reauthenticateManagedServer, refreshSession } from './auth';-import { getSessionCookie, setSessionCookie } from './servers-store';+import { reauthenticateManagedServer, refreshSession } from './auth';+import { getSessionCookie } from './servers-store';/** The gateway management API is mounted under `/gateway` on the server. */function gatewayUrl(server: SwitchServer, path: string): string {@@ -60,30 +58,6 @@ function decodeJwtExpMs(jwt: string): number | null {}}-/**- * Read the `tenant_id` claim out of a JWT without verifying it. Returns null- * for a malformed token, and for a session that has selected no tenant — the- * gateway mints the claim as null until `/tenants/{id}/switch` is called.- *- * Unverified is the right level here: the claim only ever *selects* which- * workspace a call is scoped to, and the gateway re-checks membership against- * a live row on every request, so nothing this reads can grant access. It is- * read to know whether the selection already matches the workspace being- * addressed, or whether a switch has to happen first.- */-export function decodeJwtTenantId(jwt: string): string | null {- const parts = jwt.split('.');- if (parts.length !== 3) return null;- try {- const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8')) as {- tenant_id?: unknown;- };- return typeof payload.tenant_id === 'string' ? payload.tenant_id : null;- } catch {- return null;- }-}-/** Dedupe concurrent renewals per server so a burst of authenticated calls* triggers at most one refresh round-trip (and one cookie write). */const inflightRefresh = new Map<string, Promise<string | null>>();@@ -165,42 +139,12 @@ async function resolveAuthCookie(server: SwitchServer): Promise<string> {return renewIfExpiring(server, stored);}if (server.managed) {- const minted = await silentLogin(server);+ const minted = await reauthenticateManagedServer(server);if (minted) return minted;}throw new GatewayError('unauthorized', 'Not signed in to this Switch server.');}-/**- * Servers whose silent re-login is putting a tenant back, so the switch it makes- * does not try to re-login its way out of its own 401.- */-const restoringTenant = new Set<string>();--/**- * Log a managed server back in silently, and re-select the workspace the calls- * in flight on it were addressing.- *- * A login cookie names no tenant. Handed back on its own it would answer the- * rest of a workspace-scoped call with the account's default workspace —- * succeeding, and looking exactly like the answer that was asked for.- */-async function silentLogin(server: SwitchServer): Promise<string | null> {- const minted = await reauthenticateManagedServer(server);- if (!minted) return null;- const tenantId = assertedTenant(server.id);- if (tenantId === null || restoringTenant.has(server.id)) return minted;- restoringTenant.add(server.id);- try {- await switchTenant(server, tenantId);- } finally {- restoringTenant.delete(server.id);- }- // `switchTenant` stores the scoped cookie; the minted one it replaced would- // send this very call to the wrong workspace.- return (await getSessionCookie(server.id)) ?? minted;-}-async function gatewayFetch(server: SwitchServer,path: string,@@ -255,7 +199,7 @@ async function gatewayFetch(// We hold its admin creds, so re-login and retry the call once rather than// bouncing the user to a sign-in screen for a password they never saw.if (response.status === 401 && options.authenticated && server.managed) {- const renewed = await silentLogin(server);+ const renewed = await reauthenticateManagedServer(server);if (renewed) {response = await sendOnce(renewed);}@@ -333,76 +277,6 @@ export async function fetchMe(server: SwitchServer): Promise<SwitchUser> {return mapUser((await res.json()) as UserResponseJson);}-/** A tenant the signed-in user belongs to, as `GET /tenants` reports it. */-export type RemoteTenant = {- id: string;- slug: string;- name: string;- role: WorkspaceRole;-};--function mapRole(raw: unknown): WorkspaceRole {- if (raw === 'owner' || raw === 'admin' || raw === 'member') return raw;- throw new GatewayError('http', `Switch server reported an unknown workspace role: ${raw}`);-}--/**- * The tenants the signed-in user belongs to. Answered without a tenant being- * selected on the session, which is what makes it the entry point: a user with- * several memberships has none selected until they pick one.- */-export async function fetchTenants(server: SwitchServer): Promise<RemoteTenant[]> {- const res = await gatewayFetch(server, '/tenants', { authenticated: true });- const json = (await res.json()) as Array<{- id: string;- slug: string;- name: string;- role: string;- }>;- return json.map((t) => ({ id: t.id, slug: t.slug, name: t.name, role: mapRole(t.role) }));-}--/**- * Create a workspace on this server, owned by the signed-in user.- *- * The gateway derives the slug from the name and refuses a name whose slug is- * already taken, so the caller shows that refusal rather than retrying under a- * name the user did not choose.- */-export async function createTenant(server: SwitchServer, name: string): Promise<RemoteTenant> {- const res = await gatewayFetch(server, '/tenants', {- authenticated: true,- method: 'POST',- body: { name },- });- const json = (await res.json()) as { id: string; slug: string; name: string; role: string };- return { id: json.id, slug: json.slug, name: json.name, role: mapRole(json.role) };-}--/**- * Select a tenant for this server's session, persisting the re-minted cookie.- *- * One session holds one selected tenant, so this is what makes a call scoped to- * a particular workspace rather than to whichever one was picked last. The- * gateway verifies membership before it mints, so a refusal here is a real- * answer — it is raised rather than swallowed, because the alternative is- * issuing the caller's next request against somebody else's workspace.- */-export async function switchTenant(server: SwitchServer, tenantId: string): Promise<void> {- const res = await gatewayFetch(server, `/tenants/${encodeURIComponent(tenantId)}/switch`, {- authenticated: true,- method: 'POST',- });- const cookie = extractAuthCookie(res.headers.getSetCookie());- if (!cookie) {- throw new GatewayError(- 'http',- `${server.name} accepted the workspace selection but returned no session cookie.`- );- }- await setSessionCookie(server.id, cookie);-}-/** Options for `registerKnownAgent`, matching the gateway's* `RegisterKnownAgentRequest.options`. The gateway validates these against the* options schema of the `agent_type` being registered and ignores keys that typediff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/identities.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/identities.tsindex dd231daeb..920157230 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/identities.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/identities.ts@@ -68,7 +68,7 @@ export async function searchDirectoryOnServer(*/export async function claimIdentityOnServer(server: SwitchServer,- params: Omit<ClaimIdentityParams, 'workspaceId'>+ params: Omit<ClaimIdentityParams, 'serverId'>): Promise<ClaimIdentityResult> {try {const claimed = await claimBridgeIdentity(server, params.bridgeId, {diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/require-server.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/require-server.tsdeleted file mode 100644index ed42d6b84..000000000--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/require-server.ts+++ /dev/null@@ -1,39 +0,0 @@-import { managedServerHostBlocked } from '@main/core/managed-switch-server/managed-server-status';-import { HostUnreachableError } from '@shared/core/remote-hosts/reachability';-import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';-import { getServer } from './servers-store';--export async function requireServer(serverId: string): Promise<SwitchServer> {- const server = await getServer(serverId);- if (!server) {- throw new Error(`No Switch server with id ${serverId}`);- }- return server;-}--/**- * The refusal a managed server's host being down produces, or null while it is- * up.- *- * Returned rather than thrown so a path that reports its own outcome can count- * the refusal before it propagates: the server is what an event describes- * itself with, and a helper that throws leaves the caller holding nothing.- */-export function hostUnreachable(server: SwitchServer): HostUnreachableError | null {- const blocked = managedServerHostBlocked(server);- return blocked ? new HostUnreachableError(blocked) : null;-}--/**- * Resolve a server and refuse to touch its gateway while the host it is managed- * on is unreachable (CHOO-1780). `gatewayFetch` enforces the same rule at the- * transport, so this is for the paths that reach the gateway some other way —- * sign-in and the dashboard window — and for failing before the side effects a- * write would otherwise start.- */-export async function requireReachableServer(serverId: string): Promise<SwitchServer> {- const server = await requireServer(serverId);- const unreachable = hostUnreachable(server);- if (unreachable) throw unreachable;- return server;-}diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/servers-store.db.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/servers-store.db.test.tsindex fe5a08288..2102d693d 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/servers-store.db.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/servers-store.db.test.ts@@ -2,7 +2,7 @@ import { openFixture } from '@tooling/utils/db';import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { AppDb } from '@main/db/client';-import { agents, kv, locations, switchServers, workspaces } from '@main/db/schema';+import { agents, kv, locations, switchServers } from '@main/db/schema';const mocks = vi.hoisted(() => ({db: undefined as AppDb | undefined,@@ -37,9 +37,8 @@ vi.mock('@main/core/telemetry/telemetry-service', () => ({}));// Imported after the mocks so the module binds to the mocked db + secrets store.-const { addServer, ensureManagedServer, removeServer, renameServer, setActiveServerId } =+const { addServer, ensureManagedServer, removeServer, renameServer } =await import('./servers-store');-const { getActiveWorkspaceId } = await import('@main/core/workspaces/workspaces-store');describe('servers-store: rename & delete', () => {let fixture: Awaited<ReturnType<typeof openFixture>>;@@ -226,10 +225,6 @@ describe('servers-store: rename & delete', () => {});it('unlinks the server’s agents (keeps them), deletes the row, and clears the active pointer', async () => {- // The unlink is two foreign keys deep — the server's workspaces cascade,- // and their agents are set null — so this one test needs the engine to be- // enforcing them.- fixture.sqlite.pragma('foreign_keys = ON');await fixture.db.insert(locations).values({ id: 'loc-1', name: 'Loc', sshHost: '', dir: '/repo/loc-1' });@@ -239,163 +234,28 @@ describe('servers-store: rename & delete', () => {gatewayUrl: 'https://gw.example.com',apiUrl: 'https://api.example.com',});- await fixture.db.insert(workspaces).values({ id: 'ws-1', serverId: 'srv-1', name: 'Server' });await fixture.db.insert(agents).values([- {- id: 'agent-1',- locationId: 'loc-1',- name: 'A',- providerId: 'claude',- workspaceId: 'ws-1',- },- {- id: 'agent-2',- locationId: 'loc-1',- name: 'B',- providerId: 'claude',- workspaceId: 'ws-1',- },+ { id: 'agent-1', locationId: 'loc-1', name: 'A', providerId: 'claude', serverId: 'srv-1' },+ { id: 'agent-2', locationId: 'loc-1', name: 'B', providerId: 'claude', serverId: 'srv-1' },]);- await fixture.db.insert(kv).values({ key: 'activeWorkspaceId', value: 'ws-1' });+ await fixture.db.insert(kv).values({ key: 'activeSwitchServerId', value: 'srv-1' });await removeServer('srv-1');const remainingServers = await fixture.db.select().from(switchServers);expect(remainingServers).toHaveLength(0);- const remainingWorkspaces = await fixture.db.select().from(workspaces);- expect(remainingWorkspaces).toHaveLength(0);-const remainingAgents = await fixture.db.select().from(agents);expect(remainingAgents).toHaveLength(2);- expect(remainingAgents.every((a) => a.workspaceId === null)).toBe(true);+ expect(remainingAgents.every((a) => a.serverId === null)).toBe(true);const [activePointer] = await fixture.db.select().from(kv)- .where(eq(kv.key, 'activeWorkspaceId'));+ .where(eq(kv.key, 'activeSwitchServerId'));expect(activePointer).toBeUndefined();expect(secretMocks.deleteSecret).toHaveBeenCalledWith('switch-server-cookie:srv-1');});});});--describe('selecting a server', () => {- let fixture: Awaited<ReturnType<typeof openFixture>>;-- beforeEach(async () => {- fixture = await openFixture('empty');- mocks.db = fixture.db;- fixture.sqlite.pragma('foreign_keys = OFF');- await fixture.db.insert(switchServers).values({- id: 'srv-1',- name: 'Local dev',- gatewayUrl: 'https://srv-1.example.com',- apiUrl: 'https://api-srv-1.example.com',- });- });-- afterEach(() => {- fixture.close();- mocks.db = undefined;- });-- async function seedWorkspace(- id: string,- tenantId: string | null,- role: 'owner' | 'member' | null = 'member'- ): Promise<void> {- await fixture.db.insert(workspaces).values({ id, serverId: 'srv-1', name: id, tenantId, role });- }-- it('selects the one workspace a server has', async () => {- await seedWorkspace('ws-1', 't-1');-- await setActiveServerId('srv-1');-- expect(await getActiveWorkspaceId()).toBe('ws-1');- });-- /**- * Refusing would fail the managed stack start this runs inside, taking a- * healthy server down over a question about which of its workspaces to show.- */- it('picks one rather than refusing when the account has several there', async () => {- await seedWorkspace('ws-1', 't-1');- await seedWorkspace('ws-2', 't-2');-- await setActiveServerId('srv-1');-- expect(await getActiveWorkspaceId()).toBe('ws-1');- });-- // Re-selecting the server the user is already in must not move them to- // another of its workspaces; a managed stack start does exactly that.- it('leaves the selection alone when it is already on that server', async () => {- await seedWorkspace('ws-1', 't-1');- await seedWorkspace('ws-2', 't-2');- await setActiveServerId('srv-1');- await fixture.db.update(kv).set({ value: 'ws-2' }).where(eq(kv.key, 'activeWorkspaceId'));-- await setActiveServerId('srv-1');-- const [pointer] = await fixture.db.select().from(kv).where(eq(kv.key, 'activeWorkspaceId'));- expect(pointer!.value).toBe('ws-2');- });-- /**- * The oldest row is the one a withdrawn membership is most likely to be —- * the server's original workspace, whose membership was the first to be- * given up. Landing on it would scope the window to something the gateway- * refuses every call for.- */- it('skips a workspace this account is no longer a member of', async () => {- await seedWorkspace('ws-1', 't-gone', null);- await seedWorkspace('ws-2', 't-2');-- await setActiveServerId('srv-1');-- expect(await getActiveWorkspaceId()).toBe('ws-2');- });-- /**- * The row the server was registered with, before the gateway was asked which- * workspaces the account has. It names no tenant, so a call scoped to it- * selects none and the gateway answers with whichever workspace the session- * last selected — under this one's name. On an upgraded install it is also- * the oldest row, and holds every agent.- */- it('skips a placeholder the reconcile could not match', async () => {- await seedWorkspace('ws-1', null, null);- await seedWorkspace('ws-2', 't-2');-- await setActiveServerId('srv-1');-- expect(await getActiveWorkspaceId()).toBe('ws-2');- });-- // Every server's first workspace starts out like this and is matched to a- // membership afterwards; on its own there is nothing to confuse it with.- it('selects a lone workspace that has no tenant yet', async () => {- await seedWorkspace('ws-1', null, null);-- await setActiveServerId('srv-1');-- expect(await getActiveWorkspaceId()).toBe('ws-1');- });-- // Nothing else to fall back to, and refusing here takes a healthy managed- // stack start down; the seam says why on the first call instead.- it('still picks one when every workspace on the server is withdrawn', async () => {- await seedWorkspace('ws-1', 't-gone', null);-- await setActiveServerId('srv-1');-- expect(await getActiveWorkspaceId()).toBe('ws-1');- });-- it('refuses a server with no workspace at all', async () => {- await expect(setActiveServerId('srv-1')).rejects.toThrow('no workspace');- });-});diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/servers-store.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/servers-store.tsindex adf83d194..9c027fa26 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/servers-store.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/servers-store.ts@@ -3,18 +3,8 @@ import { and, desc, eq, isNull, ne, or, sql } from 'drizzle-orm';import { encryptedAppSecretsStore } from '@main/core/secrets/encrypted-app-secrets-store';import type { TelemetryEventMap } from '@main/core/telemetry/events';import { trackEvent } from '@main/core/telemetry/telemetry-service';-import { forgetServerSession } from '@main/core/workspaces/workspace-session';-import {- clearActiveWorkspaceOnServer,- ensureServerWorkspace,- getActiveWorkspaceId,- insertServerWorkspace,- listWorkspacesForServer,- renameServerWorkspaces,- setActiveWorkspaceId,-} from '@main/core/workspaces/workspaces-store';import { db } from '@main/db/client';-import { type SwitchServerRow, switchServers } from '@main/db/schema';+import { agents, kv, type SwitchServerRow, switchServers } from '@main/db/schema';import {urlOrigin,type AddServerParams,@@ -23,10 +13,9 @@ import {type SwitchServer,type UpdateServerParams,} from '@shared/core/switch-servers/switch-servers';-import { workspaceUnavailability } from '@shared/core/workspaces/workspaces';-// Keyed to the server, not the workspace: one gateway session cookie covers-// every workspace on a server.+const ACTIVE_SERVER_KV_KEY = 'activeSwitchServerId';+function cookieSecretKey(serverId: string): string {return `switch-server-cookie:${serverId}`;}@@ -153,9 +142,7 @@ export async function ensureManagedServer(}).where(eq(switchServers.id, existing.id)).returning();- const server = mapRow(row);- await ensureServerWorkspace(server);- return server;+ return mapRow(row);}const [row] = await db.insert(switchServers)@@ -170,15 +157,13 @@ export async function ensureManagedServer(updatedAt: sql`CURRENT_TIMESTAMP`,}).returning();- const server = mapRow(row);- await ensureServerWorkspace(server);// Only the insert: this function also runs on every restart of a stack that// already exists, and that is not a server being added.trackEvent('server_added', {server_kind: ref.kind === 'remote' ? 'remote_managed' : 'local',outcome: 'success',});- return server;+ return mapRow(row);}async function getServerByGatewayUrl(gatewayUrl: string): Promise<SwitchServer | null> {@@ -191,28 +176,22 @@ async function getServerByGatewayUrl(gatewayUrl: string): Promise<SwitchServer |}export async function addServer(params: AddServerParams): Promise<SwitchServer> {- const server = db.transaction((tx) => {- const [row] = tx- .insert(switchServers)- .values({- id: randomUUID(),- name: params.name.trim(),- gatewayUrl: normaliseUrl(params.gatewayUrl),- apiUrl: normaliseUrl(params.apiUrl),- updatedAt: sql`CURRENT_TIMESTAMP`,- })- .returning()- .all();- const inserted = mapRow(row!);- insertServerWorkspace(tx, inserted);- return inserted;- });+ const [row] = await db+ .insert(switchServers)+ .values({+ id: randomUUID(),+ name: params.name.trim(),+ gatewayUrl: normaliseUrl(params.gatewayUrl),+ apiUrl: normaliseUrl(params.apiUrl),+ updatedAt: sql`CURRENT_TIMESTAMP`,+ })+ .returning();// Not reported here, unlike the managed insert above: registering a URL is a// discrete action with one caller, so the controller reports both of its// outcomes together and a single Add cannot produce two events. The managed// kinds have no such single owner — two services call that path and so does// every restart — which is why it is reported at the insert instead.- return server;+ return mapRow(row);}export async function updateServer(params: UpdateServerParams): Promise<SwitchServer> {@@ -229,7 +208,6 @@ export async function updateServer(params: UpdateServerParams): Promise<SwitchSeif (!row) {throw new Error(`No Switch server with id ${params.id}`);}- await renameServerWorkspaces(params.id, params.name.trim());return mapRow(row);}@@ -242,7 +220,6 @@ export async function renameServer(params: RenameServerParams): Promise<SwitchSeif (!row) {throw new Error(`No Switch server with id ${params.id}`);}- await renameServerWorkspaces(params.id, params.name.trim());return mapRow(row);}@@ -252,12 +229,13 @@ export async function removeServer(id: string): Promise<void> {const server = await getServer(id).catch(() => null);await deleteSessionCookie(id);- // Before the delete, while the server's workspaces are still readable.- await clearActiveWorkspaceOnServer(id);- // Deleting the server takes its workspaces with it and unlinks their agents,- // both by foreign key: workspaces cascade, agents are set null.+ // Unlink agents explicitly: SQLite's ALTER TABLE ADD COLUMN can't carry an+ // ON DELETE clause, so the FK's set-null isn't enforced by the engine.+ await db.update(agents).set({ serverId: null }).where(eq(agents.serverId, id));await db.delete(switchServers).where(eq(switchServers.id, id));- forgetServerSession(id);+ if ((await getActiveServerId()) === id) {+ await db.delete(kv).where(eq(kv.key, ACTIVE_SERVER_KV_KEY));+ }// Removing an already-absent server is not a server being removed.if (server) trackEvent('server_removed', { server_kind: serverKindOf(server) });@@ -271,36 +249,23 @@ export function serverKindOf(return server.managementKind === 'remote' ? 'remote_managed' : 'local';}-/**- * Select a server by selecting one of its workspaces.- *- * Picks the first when the account turns out to belong to several on that- * server, rather than refusing the way the paths that attach an agent do. The- * risks are not the same: showing the wrong workspace is visible and one click- * from being corrected, while attaching an agent to it is neither. Refusing- * here would instead fail the managed stack start this runs inside, taking a- * healthy server down over a question about which of its workspaces to show.- *- * "First" means the first that can actually be opened, where there is one: a- * withdrawn membership and an unmatched placeholder are both refused by the- * gateway, and landing on either is not a wrong guess a click corrects. Where- * there is no such workspace it still picks, for the same reason it does not- * refuse a choice between several — the seam says why on the first call.- */+export async function getActiveServerId(): Promise<string | null> {+ const [row] = await db.select().from(kv).where(eq(kv.key, ACTIVE_SERVER_KV_KEY)).limit(1);+ return row?.value ?? null;+}+export async function setActiveServerId(id: string): Promise<void> {const server = await getServer(id);- if (!server) throw new Error(`No Switch server with id ${id}`);- const found = await listWorkspacesForServer(id);- if (found.length === 0) throw new Error(`Switch server ${id} has no workspace`);- const active = await getActiveWorkspaceId();- if (found.some((candidate) => candidate.id === active)) return;- // The rows are oldest first, and the oldest is exactly the one a withdrawn- // membership or an unmatched placeholder is most likely to be — the row the- // server was registered with, before the gateway was ever asked.- const openable = found.find(- (candidate) => workspaceUnavailability(candidate, found.length) === null- );- await setActiveWorkspaceId((openable ?? found[0]!).id);+ if (!server) {+ throw new Error(`No Switch server with id ${id}`);+ }+ await db+ .insert(kv)+ .values({ key: ACTIVE_SERVER_KV_KEY, value: id, updatedAt: sql`CURRENT_TIMESTAMP` })+ .onConflictDoUpdate({+ target: kv.key,+ set: { value: id, updatedAt: sql`CURRENT_TIMESTAMP` },+ });}// ---------------------------------------------------------------------------diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/update-bridge.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/update-bridge.tsindex d1e3fa08a..9b3e03d35 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/update-bridge.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/update-bridge.ts@@ -15,7 +15,7 @@ import type {*/export async function updateBridgeOnServer(server: SwitchServer,- params: Omit<UpdateBridgeParams, 'workspaceId'>+ params: Omit<UpdateBridgeParams, 'serverId'>): Promise<UpdateBridgeResult> {try {const bridge = await updateBridge(server, params.bridgeId, {diff --git a/console/apps/switch-console-desktop/src/main/core/telemetry/catalogue.test.ts b/console/apps/switch-console-desktop/src/main/core/telemetry/catalogue.test.tsindex ac0975a66..9fd7600dd 100644--- a/console/apps/switch-console-desktop/src/main/core/telemetry/catalogue.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/telemetry/catalogue.test.ts@@ -46,8 +46,7 @@ function sampleFor(property: string): string | number | boolean {property === 'connected_to_room' ||property === 'delete_in_switch' ||property === 'resolved' ||- property === 'cold_start' ||- property === 'first_run'+ property === 'cold_start') {return true;}diff --git a/console/apps/switch-console-desktop/src/main/core/telemetry/events.ts b/console/apps/switch-console-desktop/src/main/core/telemetry/events.tsindex 23bcadd3c..a8b03b05f 100644--- a/console/apps/switch-console-desktop/src/main/core/telemetry/events.ts+++ b/console/apps/switch-console-desktop/src/main/core/telemetry/events.ts@@ -651,7 +651,7 @@ export const TELEMETRY_EVENT_PROPERTIES = {onboarding_step_started: ['step_id'],onboarding_checklist_dismissed: [],onboarding_completed: [],- add_server_step: ['step', 'choice', 'first_run'],+ add_server_step: ['step', 'choice'],renderer_crashed: [],telemetry_consent_changed: ['source'],session_attached: ['agent_type', 'outcome'],diff --git a/console/apps/switch-console-desktop/src/main/core/telemetry/renderer-events.ts b/console/apps/switch-console-desktop/src/main/core/telemetry/renderer-events.tsindex abfb66ec2..844be6f70 100644--- a/console/apps/switch-console-desktop/src/main/core/telemetry/renderer-events.ts+++ b/console/apps/switch-console-desktop/src/main/core/telemetry/renderer-events.ts@@ -53,7 +53,6 @@ const RENDERER_TELEMETRY_SCHEMAS = {add_server_step: z.object({step: z.enum(ADD_SERVER_STEPS),choice: z.enum(ADD_SERVER_CHOICES),- first_run: z.boolean(),}),renderer_crashed: z.object({}),} as const satisfies {diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/asserted-tenant.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/asserted-tenant.tsdeleted file mode 100644index 5843c48bd..000000000--- a/console/apps/switch-console-desktop/src/main/core/workspaces/asserted-tenant.ts+++ /dev/null@@ -1,36 +0,0 @@-/**- * Which tenant a server's session is currently selecting on behalf of the calls- * holding a lease on it.- *- * The session seam owns this; it lives in a module of its own so the gateway- * client can read it without importing the seam that switches tenants through- * the gateway client.- *- * Every lease outstanding on a server at one moment names the same tenant — a- * switch waits for every lease to be given up first — so there is one answer per- * server rather than one per call.- */-const asserted = new Map<string, string>();--/** Record the tenant `serverId`'s first outstanding lease was taken against. */-export function setAssertedTenant(serverId: string, tenantId: string): void {- asserted.set(serverId, tenantId);-}--/** Forget it once nothing is leasing the server. */-export function clearAssertedTenant(serverId: string): void {- asserted.delete(serverId);-}--/**- * The tenant that has to hold for the calls in flight on `serverId`, or null- * when nothing is leasing it or the lease named no tenant.- *- * Read by anything that replaces the session cookie underneath those calls: a- * cookie minted by a fresh login selects no tenant, and handing it back- * unchanged would answer the rest of the lease with the account's default- * workspace while the caller still believes it is addressing the one it named.- */-export function assertedTenant(serverId: string): string | null {- return asserted.get(serverId) ?? null;-}diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.test.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.test.tsdeleted file mode 100644index e6b84d82b..000000000--- a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.test.ts+++ /dev/null@@ -1,261 +0,0 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';-import { HostUnreachableError } from '@shared/core/remote-hosts/reachability';--const managedServerHostBlocked = vi.hoisted(() => vi.fn((): unknown => null));-const trackEvent = vi.hoisted(() => vi.fn());-const createRoomOnServer = vi.hoisted(() => vi.fn());-const deleteBridge = vi.hoisted(() => vi.fn());-const deleteRoom = vi.hoisted(() => vi.fn());-const fetchBridges = vi.hoisted(() => vi.fn());-const getServer = vi.hoisted(() => vi.fn());-const getSessionCookie = vi.hoisted(() => vi.fn());-const requireWorkspace = vi.hoisted(() => vi.fn());-const listWorkspacesForServer = vi.hoisted(() => vi.fn(async () => [{ id: 'ws' }]));-const switchTenant = vi.hoisted(() => vi.fn());-// Stubbed rather than reimplemented: what the tests below assert is that the-// kind reaches the event, not how a row is read as one.-const serverKindOf = vi.hoisted(() => vi.fn(() => 'remote_managed'));--// Stub the modules the controller imports that would otherwise pull electron /-// ssh / agent side effects at load.-vi.mock('@main/core/agents/agent-credentials-slot', () => ({ foreignCredentialsOwner: vi.fn() }));-vi.mock('@main/core/agents/agent-workdir-fs', () => ({ resolveWorkdirFsFor: vi.fn() }));-vi.mock('@main/core/agents/known-agent-type', () => ({ knownAgentTypeForProvider: vi.fn() }));-vi.mock('@main/core/agents/register-agent-identity', () => ({ registerAgentIdentity: vi.fn() }));-vi.mock('@main/core/agents/write-remote-switch-settings', () => ({- writeRemoteSwitchSettings: vi.fn(),-}));-vi.mock('@main/core/agents/write-switch-settings', () => ({- writeNeutralAgentSettingsFs: vi.fn(),- writeSwitchSettings: vi.fn(),-}));-vi.mock('@main/core/fs/impl/ssh-fs', () => ({ SshFileSystem: vi.fn() }));-vi.mock('@main/core/locations/location-transport', () => ({ sshConnectionIdForHost: vi.fn() }));-vi.mock('@main/core/ssh/connect/connect-agent-ssh', () => ({ ensureSshConnected: vi.fn() }));-vi.mock('@main/core/telemetry/telemetry-service', () => ({ trackEvent }));-vi.mock('@main/core/managed-switch-server/managed-server-status', () => ({- isManagedServerRunning: vi.fn(() => true),- managedServerHostBlocked,-}));-// Writes to the app's log file, which a test has no business creating.-vi.mock('@main/lib/logger', () => ({- log: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() },-}));-// Reads this install's own agent rows, and through them the database client.-vi.mock('@main/core/switch-servers/backfill-agent-icons', () => ({ backfillAgentIcons: vi.fn() }));-vi.mock('@main/core/switch-servers/bridge-home-url', () => ({ withResolvedHomeUrls: vi.fn() }));-vi.mock('@main/core/switch-servers/create-bridge', () => ({ createBridgeOnServer: vi.fn() }));-vi.mock('@main/core/switch-servers/create-room', () => ({ createRoomOnServer }));-vi.mock('@main/core/switch-servers/identities', () => ({- claimIdentityOnServer: vi.fn(),- searchDirectoryOnServer: vi.fn(),-}));-vi.mock('@main/core/switch-servers/update-bridge', () => ({ updateBridgeOnServer: vi.fn() }));-vi.mock('@main/core/switch-servers/gateway-client', () => ({- addRoomAgents: vi.fn(),- agentExistsOnServer: vi.fn(),- createRoomFromTemplate: vi.fn(),- decodeJwtTenantId: vi.fn(() => null),- deleteBridge,- deleteRoom,- fetchAddressingPolicy: vi.fn(),- fetchAgentDetail: vi.fn(),- fetchAgentRooms: vi.fn(),- fetchAgents: vi.fn(),- fetchAllExternalUsers: vi.fn(),- fetchBridges,- fetchBridgeTypes: vi.fn(),- fetchMyIdentities: vi.fn(),- fetchRoomAgentIds: vi.fn(),- fetchRoomDetail: vi.fn(),- fetchRoomGroups: vi.fn(),- fetchRoomRoles: vi.fn(),- fetchRooms: vi.fn(),- fetchTemplateSchema: vi.fn(),- GatewayError: class GatewayError extends Error {},- ownsOwnerAddressedAgent: vi.fn(),- releaseBridgeIdentity: vi.fn(),- removeRoomAgent: vi.fn(),- switchTenant,- updateAddressingPolicy: vi.fn(),- updateAgentIcon: vi.fn(),- updateRoom: vi.fn(),-}));-vi.mock('@main/core/switch-servers/servers-store', () => ({- getServer,- getSessionCookie,- serverKindOf,-}));-vi.mock('./workspaces-store', () => ({- getActiveWorkspaceId: vi.fn(),- listWorkspaces: vi.fn(),- listWorkspacesForServer,- requireWorkspace,- setActiveWorkspaceId: vi.fn(),-}));--const { workspacesController } = await import('./controller');--function server(overrides: Record<string, unknown>) {- return {- id: 'srv',- name: 'S',- gatewayUrl: 'http://localhost:3300',- apiUrl: 'http://localhost:8000',- managed: false,- managementKind: null,- sshHost: null,- createdAt: '',- updatedAt: '',- ...overrides,- };-}--/** The workspace every call below names, on the server the test set up. */-function workspace(tenantId: string | null = null) {- return { id: 'ws', serverId: 'srv', name: 'S', tenantId, createdAt: '', updatedAt: '' };-}--describe('disconnecting a bridge', () => {- beforeEach(() => {- vi.clearAllMocks();- managedServerHostBlocked.mockReturnValue(null);- getServer.mockResolvedValue(server({}));- requireWorkspace.mockResolvedValue(workspace());- fetchBridges.mockResolvedValue([{ id: 'b1', type: 'slack' }]);- });-- it('reports a disconnection the gateway carried out', async () => {- deleteBridge.mockResolvedValue({ kind: 'deleted' });-- await workspacesController.deleteBridge({ workspaceId: 'ws', bridgeId: 'b1' });-- await vi.waitFor(() =>- expect(trackEvent).toHaveBeenCalledWith('bridge_disconnected', {- bridge_platform: 'slack',- outcome: 'success',- })- );- });-- it('reports a refusal as a failure rather than as a disconnection', async () => {- // Admin-only, and the gateway hands back the refusal instead of throwing- // it — so the await returns exactly as it does for a bridge that went.- deleteBridge.mockResolvedValue({ kind: 'forbidden' });-- await workspacesController.deleteBridge({ workspaceId: 'ws', bridgeId: 'b1' });-- await vi.waitFor(() =>- expect(trackEvent).toHaveBeenCalledWith('bridge_disconnected', {- bridge_platform: 'slack',- outcome: 'failure',- })- );- });-});--describe('an action a workspace whose host has gone down cannot take', () => {- const blocked = {- sshHost: 'h',- status: 'unreachable',- lastError: 'no route to host',- lastCheckedAt: null,- };-- beforeEach(() => {- vi.clearAllMocks();- getServer.mockResolvedValue(server({ managed: true, managementKind: 'remote', sshHost: 'h' }));- requireWorkspace.mockResolvedValue(workspace());- managedServerHostBlocked.mockReturnValue(blocked);- // What the gateway does on a host that cannot be reached: the platform is- // then unknowable rather than absent.- fetchBridges.mockRejectedValue(new Error('no route to host'));- });-- it('reports the room it refused to create', async () => {- await expect(- workspacesController.createRoom({- workspaceId: 'ws',- name: 'Room',- description: '',- bridgeId: 'b1',- agentIds: ['a1'],- })- ).rejects.toBeInstanceOf(HostUnreachableError);-- expect(createRoomOnServer).not.toHaveBeenCalled();- await vi.waitFor(() =>- expect(trackEvent).toHaveBeenCalledWith('room_created', {- server_kind: 'remote_managed',- bridge_platform: 'unknown',- agent_count: 1,- has_instructions: false,- outcome: 'failure',- failure_reason: 'unreachable',- })- );- });-- it('reports the room it refused to delete', async () => {- await expect(- workspacesController.deleteRoom({ workspaceId: 'ws', roomId: 'r1' })- ).rejects.toBeInstanceOf(HostUnreachableError);-- expect(deleteRoom).not.toHaveBeenCalled();- expect(trackEvent).toHaveBeenCalledWith('room_deleted', {- server_kind: 'remote_managed',- outcome: 'failure',- });- });-});--/**- * The seam's whole point: a call names a workspace, and the session it goes out- * on must be selecting that workspace's tenant. A read that answered from the- * previously selected tenant would succeed and look right.- */-describe('selecting the workspace’s tenant before the call', () => {- beforeEach(() => {- vi.clearAllMocks();- managedServerHostBlocked.mockReturnValue(null);- getServer.mockResolvedValue(server({}));- fetchBridges.mockResolvedValue([]);- });-- it('switches when the session is selecting another tenant', async () => {- requireWorkspace.mockResolvedValue(workspace('tenant-b'));- getSessionCookie.mockResolvedValue('cookie-for-tenant-a');-- await workspacesController.listBridges('ws');-- expect(switchTenant).toHaveBeenCalledWith(expect.objectContaining({ id: 'srv' }), 'tenant-b');- });-- it('does not switch when the session already selects it', async () => {- const { decodeJwtTenantId } = await import('@main/core/switch-servers/gateway-client');- vi.mocked(decodeJwtTenantId).mockReturnValue('tenant-b');- requireWorkspace.mockResolvedValue(workspace('tenant-b'));- getSessionCookie.mockResolvedValue('cookie-for-tenant-b');-- await workspacesController.listBridges('ws');-- expect(switchTenant).not.toHaveBeenCalled();- });-- it('asserts nothing for a workspace with no tenant, where its server has only the one', async () => {- requireWorkspace.mockResolvedValue(workspace(null));-- await workspacesController.listBridges('ws');-- expect(switchTenant).not.toHaveBeenCalled();- expect(getSessionCookie).not.toHaveBeenCalled();- });-- it('refuses a workspace with no tenant where its server has several', async () => {- requireWorkspace.mockResolvedValue(workspace(null));- listWorkspacesForServer.mockResolvedValueOnce([{ id: 'ws' }, { id: 'ws-2' }]);-- await expect(workspacesController.listBridges('ws')).rejects.toThrow('has not been matched');- expect(fetchBridges).not.toHaveBeenCalled();- });-});diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.tsdeleted file mode 100644index 12a137eaf..000000000--- a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts+++ /dev/null@@ -1,615 +0,0 @@-import { backfillAgentIcons } from '@main/core/switch-servers/backfill-agent-icons';-import { withResolvedHomeUrls } from '@main/core/switch-servers/bridge-home-url';-import { createBridgeOnServer } from '@main/core/switch-servers/create-bridge';-import { createRoomOnServer } from '@main/core/switch-servers/create-room';-import {- addRoomAgents,- agentExistsOnServer,- createRoomFromTemplate,- createTemplate,- deleteBridge,- deleteRoom,- deleteTemplate,- exportRoomYaml,- fetchAddressingPolicy,- fetchAgentRooms,- fetchAgents,- fetchAllExternalUsers,- fetchBridges,- fetchBridgeTypes,- fetchMyIdentities,- fetchRoomAgentIds,- fetchRoomDetail,- fetchRoomGroups,- fetchRoomRoles,- fetchRooms,- fetchTemplateDetail,- fetchTemplates,- fetchTemplateSchema,- GatewayError,- ownsOwnerAddressedAgent,- releaseBridgeIdentity,- removeRoomAgent,- type StoredTemplateDetail,- type StoredTemplateSummary,- type ProvisionFromTemplateResult,- type TemplateVisibility,- updateAddressingPolicy,- updateAgentIcon,- updateRoom,- updateTemplate,-} from '@main/core/switch-servers/gateway-client';-import {- claimIdentityOnServer,- searchDirectoryOnServer,-} from '@main/core/switch-servers/identities';-import { hostUnreachable } from '@main/core/switch-servers/require-server';-import { serverKindOf } from '@main/core/switch-servers/servers-store';-import { updateBridgeOnServer } from '@main/core/switch-servers/update-bridge';-import { bridgePlatformOfType } from '@main/core/telemetry/bridge-platform';-import type {- TelemetryBridgeFailure,- TelemetryBridgePlatform,- TelemetryOutcome,- TelemetryRoomAgentsDirection,- TelemetryRoomCreateFailure,- TelemetryServerKind,-} from '@main/core/telemetry/events';-import { roomAgentsDirectionOf } from '@main/core/telemetry/narrow';-import { trackEvent } from '@main/core/telemetry/telemetry-service';-import type {- AddressingPolicy,- AgentIconBackfill,- AgentVerifyResult,- BridgeDirectorySearchResult,- ClaimIdentityParams,- ClaimIdentityResult,- CreateBridgeParams,- CreateBridgeResult,- CreateRoomParams,- CreateRoomResult,- DeleteBridgeParams,- DeleteBridgeResult,- LinkedIdentity,- RemoteAgentRoom,- RemoteAgentSummary,- RemoteBridge,- RemoteBridgeType,- RemoteExternalUser,- RemoteRoomDetail,- RemoteRoomGroup,- RemoteRoomRole,- RemoteRoomSummary,- SwitchServer,- UpdateBridgeParams,- UpdateBridgeResult,- UpdateRoomParams,-} from '@shared/core/switch-servers/switch-servers';-import type { Workspace } from '@shared/core/workspaces/workspaces';-import { createRPCController } from '@shared/lib/ipc/rpc';-import {- withReachableWorkspaceSession,- withWorkspaceSession,- workspaceServer,-} from './workspace-session';-import { getActiveWorkspaceId, listWorkspaces, setActiveWorkspaceId } from './workspaces-store';--/** A bridge result's discriminant as a code. Never the message beside it. */-function bridgeFailureReason(kind: string): TelemetryBridgeFailure {- switch (kind) {- case 'created':- return 'none';- case 'unauthenticated':- return 'unauthenticated';- case 'forbidden':- return 'forbidden';- case 'invalid':- return 'invalid';- default:- return 'error';- }-}--/** A room-create result's discriminant as a code. */-function roomCreateFailureReason(result: CreateRoomResult): TelemetryRoomCreateFailure {- switch (result.kind) {- case 'created':- return 'none';- case 'unauthenticated':- return 'unauthenticated';- case 'bridge-unavailable':- return 'bridge_unavailable';- case 'invalid':- return 'invalid';- default:- return 'error';- }-}--/**- * Which platform a bridge id is on.- *- * A lookup rather than a field: these operations take a bridge id, and the type- * either never appears (a delete) or appears only on success (a room). Best- * effort — an unreachable server yields `unknown` rather than failing the- * operation it is only describing.- *- * **Never awaited by a caller doing real work.** It asks the gateway, and making- * someone wait on a network round trip so we can describe what they did would- * put reporting in the path of the thing being reported. `reportWithBridge` is- * how the answer is used once it arrives.- *- * It takes its own lease, so it must be started outside one: unawaited inside- * another call's lease it would be left addressing whatever workspace the- * session had moved on to. Where the answer is only readable before the work —- * a delete — read it in that call's lease with- * {@link bridgePlatformOnServer} instead.- */-function bridgePlatformOf(- workspaceId: string,- bridgeId: string | null | undefined-): Promise<TelemetryBridgePlatform> {- if (!bridgeId) return Promise.resolve('unknown');- return withWorkspaceSession(workspaceId, fetchBridges)- .then((bridges) => bridgePlatformOfType(bridges.find((b) => b.id === bridgeId)?.type))- .catch((): TelemetryBridgePlatform => 'unknown');-}--/** {@link bridgePlatformOf} against a server already leased by the caller. */-function bridgePlatformOnServer(- server: SwitchServer,- bridgeId: string | null | undefined-): Promise<TelemetryBridgePlatform> {- if (!bridgeId) return Promise.resolve('unknown');- return fetchBridges(server)- .then((bridges) => bridgePlatformOfType(bridges.find((b) => b.id === bridgeId)?.type))- .catch((): TelemetryBridgePlatform => 'unknown');-}--/**- * Report once the platform is known, without anyone waiting for it.- *- * The event arrives a moment after the action rather than with it, which costs- * nothing: it carries its own timestamp, taken when the work happened.- */-function reportWithBridge(- platform: Promise<TelemetryBridgePlatform>,- emit: (platform: TelemetryBridgePlatform) => void-): void {- void platform.then(emit).catch(() => {});-}--/** The same, for a room create whose other properties are already known. */-function reportRoomCreated(- workspaceId: string,- bridgeId: string | null | undefined,- rest: {- server_kind: TelemetryServerKind;- agent_count: number;- has_instructions: boolean;- failure_reason: TelemetryRoomCreateFailure;- }-): void {- reportWithBridge(bridgePlatformOf(workspaceId, bridgeId), (bridge_platform) =>- trackEvent('room_created', {- ...rest,- bridge_platform,- outcome: rest.failure_reason === 'none' ? 'success' : 'failure',- })- );-}--/**- * Everything that reads or writes what a workspace owns — its rooms, agents,- * bridges and identities.- *- * Every one of these is addressed by workspace rather than by server, because- * that is what the data belongs to: a server can host several workspaces, and- * the same call against the same server means a different thing in each. The- * server is resolved from the workspace, and the session's selected tenant is- * made to match it, inside `withWorkspaceSession` — see there for why that is- * the seam and not a courtesy at each call site.- *- * Registering a server, signing in to one and asking whether it can be reached- * are not workspace-scoped and stay in `switch-servers/controller.ts`.- */-export const workspacesController = createRPCController({- list: (): Promise<Workspace[]> => listWorkspaces(),-- getActiveId: (): Promise<string | null> => getActiveWorkspaceId(),-- setActive: (workspaceId: string): Promise<void> => setActiveWorkspaceId(workspaceId),-- listAgents: (workspaceId: string): Promise<RemoteAgentSummary[]> =>- withWorkspaceSession(workspaceId, fetchAgents),-- listRooms: (workspaceId: string): Promise<RemoteRoomSummary[]> =>- withWorkspaceSession(workspaceId, fetchRooms),-- listBridges: (workspaceId: string): Promise<RemoteBridge[]> =>- withReachableWorkspaceSession(workspaceId, async (server) =>- withResolvedHomeUrls(server, await fetchBridges(server))- ),-- listBridgeTypes: (workspaceId: string): Promise<RemoteBridgeType[]> =>- withReachableWorkspaceSession(workspaceId, fetchBridgeTypes),-- /**- * Attach a collaboration bridge to the chosen workspace (CHOO-1784).- *- * `params.connectionConfig` carries platform credentials. They cross the IPC- * boundary once, on the way out, and are never written to Switch Console's disk- * or returned to the renderer — the server stores them. Keep it that way: do- * not log `params` here.- */- createBridge: (params: CreateBridgeParams): Promise<CreateBridgeResult> =>- withReachableWorkspaceSession(params.workspaceId, async (server) => {- const platform = bridgePlatformOfType(params.bridgeType);- let result: CreateBridgeResult;- try {- result = await createBridgeOnServer(server, {- bridgeType: params.bridgeType,- displayName: params.displayName,- connectionConfig: params.connectionConfig,- setAsDefault: params.setAsDefault,- channelCreationEnabled: params.channelCreationEnabled,- });- } catch (error) {- trackEvent('bridge_connected', {- bridge_platform: platform,- outcome: 'failure',- failure_reason: 'error',- });- throw error;- }- trackEvent('bridge_connected', {- bridge_platform: platform,- outcome: result.kind === 'created' ? 'success' : 'failure',- failure_reason: bridgeFailureReason(result.kind),- });- return result;- }),-- /**- * Edit a bridge's operator-controlled switches — today, only whether the- * connection may create channels. Admin-only, like registering one; see- * `updateBridgeOnServer` for the recoverable-failure mapping.- */- updateBridge: (params: UpdateBridgeParams): Promise<UpdateBridgeResult> =>- withReachableWorkspaceSession(params.workspaceId, (server) =>- updateBridgeOnServer(server, {- bridgeId: params.bridgeId,- channelCreationEnabled: params.channelCreationEnabled,- })- ),-- /**- * Disconnect a messaging app from the chosen workspace. Admin-only, and the- * gateway deletes every Switch room on the bridge on the way — see- * `deleteBridge`. The renderer owns the confirmation; by the time this runs- * the rooms are being given up deliberately.- */- deleteBridge: (params: DeleteBridgeParams): Promise<DeleteBridgeResult> =>- withReachableWorkspaceSession(params.workspaceId, async (server) => {- // Read before the delete, because afterwards there is no bridge left to- // read a platform from — and awaited, unlike every other report: left to- // resolve on its own it would outlive the lease that scopes it to this- // workspace. A disconnect is a confirmed, destructive action, not a hot- // path, so it can afford the round trip.- const platform = await bridgePlatformOnServer(server, params.bridgeId);- const result = await deleteBridge(server, params.bridgeId);- trackEvent('bridge_disconnected', {- bridge_platform: platform,- outcome: result.kind === 'deleted' ? 'success' : 'failure',- });- return result;- }),-- /**- * Create a room in the chosen workspace, owned by the signed-in user. Room- * provisioning stays server-side (`POST /gateway/rooms`); this only maps- * recoverable failures onto a typed result the modal can act on.- */- createRoom: async (params: CreateRoomParams): Promise<CreateRoomResult> => {- // A host that has gone down is counted before it is raised, which is why- // this is here rather than left to the session seam.- const known = await workspaceServer(params.workspaceId);-- // Every report is made out here, after the lease rather than inside it: the- // platform lookup behind it takes a lease of its own, and one started from- // within this call's would be left addressing whichever workspace the- // session had moved on to by the time it ran.- const report = (failure_reason: TelemetryRoomCreateFailure) =>- reportRoomCreated(params.workspaceId, params.bridgeId, {- server_kind: serverKindOf(known),- agent_count: params.agentIds.length,- has_instructions: (params.instructions?.trim().length ?? 0) > 0,- failure_reason,- });-- const unreachable = hostUnreachable(known);- if (unreachable) {- report('unreachable');- throw unreachable;- }-- let result: CreateRoomResult;- try {- result = await withWorkspaceSession(params.workspaceId, (server) =>- createRoomOnServer(server, {- name: params.name,- description: params.description,- instructions: params.instructions,- bridgeId: params.bridgeId,- agentIds: params.agentIds,- })- );- } catch (error) {- report('error');- throw error;- }-- report(roomCreateFailureReason(result));- return result;- },-- createRoomFromTemplate: (- workspaceId: string,- yamlText: string,- inputs: Record<string, string | number | boolean>- ): Promise<ProvisionFromTemplateResult> =>- withWorkspaceSession(workspaceId, (server) => createRoomFromTemplate(server, yamlText, inputs)),-- fetchTemplateSchema: (workspaceId: string): Promise<Record<string, unknown> | null> =>- withWorkspaceSession(workspaceId, fetchTemplateSchema),-- listTemplates: (params: {- workspaceId: string;- kind?: string;- q?: string;- }): Promise<StoredTemplateSummary[]> =>- withWorkspaceSession(params.workspaceId, (server) =>- fetchTemplates(server, { kind: params.kind, q: params.q })- ),-- getTemplateDetail: (params: {- workspaceId: string;- templateId: string;- }): Promise<StoredTemplateDetail> =>- withWorkspaceSession(params.workspaceId, (server) =>- fetchTemplateDetail(server, params.templateId)- ),-- deleteTemplate: (params: { workspaceId: string; templateId: string }): Promise<void> =>- withWorkspaceSession(params.workspaceId, (server) => deleteTemplate(server, params.templateId)),-- saveTemplate: (params: {- workspaceId: string;- name: string;- description: string;- kind: string;- content: string;- readVisibility?: TemplateVisibility;- writeVisibility?: TemplateVisibility;- }): Promise<StoredTemplateDetail> => {- const { workspaceId, ...template } = params;- return withWorkspaceSession(workspaceId, (server) => createTemplate(server, template));- },-- updateTemplate: (params: {- workspaceId: string;- templateId: string;- name?: string;- description?: string;- kind?: string;- content?: string;- readVisibility?: TemplateVisibility;- writeVisibility?: TemplateVisibility;- }): Promise<StoredTemplateDetail> => {- const { workspaceId, templateId, ...changes } = params;- return withWorkspaceSession(workspaceId, (server) =>- updateTemplate(server, templateId, changes)- );- },-- exportRoomYaml: (params: { workspaceId: string; roomId: string }): Promise<string> =>- withWorkspaceSession(params.workspaceId, (server) => exportRoomYaml(server, params.roomId)),-- listAgentRooms: (params: { workspaceId: string; agentId: string }): Promise<RemoteAgentRoom[]> =>- withWorkspaceSession(params.workspaceId, (server) => fetchAgentRooms(server, params.agentId)),-- listRoomRoles: (params: { workspaceId: string; roomId: string }): Promise<RemoteRoomRole[]> =>- withWorkspaceSession(params.workspaceId, (server) => fetchRoomRoles(server, params.roomId)),-- listRoomAgentIds: (params: { workspaceId: string; roomId: string }): Promise<string[]> =>- withWorkspaceSession(params.workspaceId, (server) => fetchRoomAgentIds(server, params.roomId)),-- /** One room in full, for its configuration page. */- getRoomDetail: (params: { workspaceId: string; roomId: string }): Promise<RemoteRoomDetail> =>- withWorkspaceSession(params.workspaceId, (server) => fetchRoomDetail(server, params.roomId)),-- /**- * Change a room's own settings. Failures propagate as-is — a user without- * write access to the room needs the gateway's refusal, not a saved-looking- * field holding a value the server never took.- */- updateRoom: (params: UpdateRoomParams): Promise<RemoteRoomDetail> =>- withReachableWorkspaceSession(params.workspaceId, (server) =>- updateRoom(server, params.roomId, {- description: params.description,- instructions: params.instructions,- })- ),-- /**- * Add agents to a room. Failures propagate as-is: the caller shows the- * gateway's own words (e.g. an agent whose server-side client is not running,- * which the gateway rejects) rather than a generic message.- */- addRoomAgents: (params: {- workspaceId: string;- roomId: string;- agentIds: string[];- /**- * Which screen this came from. The same call serves both, and the- * one-agent-to-many-rooms screen loops it once per room — so without this,- * adding an agent to five rooms is indistinguishable from five people each- * adding one agent.- */- direction: TelemetryRoomAgentsDirection;- }): Promise<void> =>- withReachableWorkspaceSession(params.workspaceId, async (server) => {- await addRoomAgents(server, params.roomId, params.agentIds);- trackEvent('room_agents_added', {- agent_count: params.agentIds.length,- direction: roomAgentsDirectionOf(params.direction),- });- }),-- /** Remove one agent from a room. Membership only — the agent is not deleted. */- removeRoomAgent: (params: {- workspaceId: string;- roomId: string;- agentId: string;- }): Promise<void> =>- withReachableWorkspaceSession(params.workspaceId, (server) =>- removeRoomAgent(server, params.roomId, params.agentId)- ),-- /** Delete a room and everything in it. The gateway enforces who may. */- deleteRoom: async (params: { workspaceId: string; roomId: string }): Promise<void> => {- const known = await workspaceServer(params.workspaceId);- const report = (outcome: TelemetryOutcome) =>- trackEvent('room_deleted', { server_kind: serverKindOf(known), outcome });-- // A host that has gone down refuses the deletion as surely as the gateway- // can, and the event has an outcome precisely so a refusal is counted.- const unreachable = hostUnreachable(known);- if (unreachable) {- report('failure');- throw unreachable;- }-- await withWorkspaceSession(params.workspaceId, async (server) => {- try {- await deleteRoom(server, params.roomId);- } catch (error) {- report('failure');- throw error;- }- report('success');- });- },-- listRoomGroups: (workspaceId: string): Promise<RemoteRoomGroup[]> =>- withWorkspaceSession(workspaceId, fetchRoomGroups),-- listExternalUsers: (workspaceId: string): Promise<RemoteExternalUser[]> =>- withWorkspaceSession(workspaceId, fetchAllExternalUsers),-- /**- * Search a bridge's own user directory so the signed-in user can find- * themselves before they have ever posted in the chat workspace (CHOO-2137).- */- searchBridgeDirectory: (params: {- workspaceId: string;- bridgeId: string;- query: string;- }): Promise<BridgeDirectorySearchResult> =>- withReachableWorkspaceSession(params.workspaceId, (server) =>- searchDirectoryOnServer(server, params.bridgeId, params.query)- ),-- /** Claim a messaging-app account as the signed-in Switch user's own. */- claimBridgeIdentity: async (params: ClaimIdentityParams): Promise<ClaimIdentityResult> => {- const result = await withReachableWorkspaceSession(params.workspaceId, (server) =>- claimIdentityOnServer(server, {- bridgeId: params.bridgeId,- externalUserId: params.externalUserId,- username: params.username,- })- );- // Reported after the lease, not inside it: the platform lookup takes a lease- // of its own, and the bridge is still there to read afterwards.- reportWithBridge(bridgePlatformOf(params.workspaceId, params.bridgeId), (bridge_platform) =>- trackEvent('bridge_identity_claimed', {- bridge_platform,- outcome: result.kind === 'claimed' ? 'success' : 'failure',- })- );- return result;- },-- /** Give up a claim on a messaging-app account, leaving any other user's claim- * on it in place. `userId` is whose claim to drop — null for the signed-in- * user, which is the only one this app offers. Failures propagate: unclaiming- * is a deliberate act, and reporting success for one that did not happen- * would leave the user thinking an agent is no longer reachable by them when- * it still is. */- releaseBridgeIdentity: (params: {- workspaceId: string;- bridgeId: string;- identityId: string;- userId: string | null;- }): Promise<void> =>- withReachableWorkspaceSession(params.workspaceId, (server) =>- releaseBridgeIdentity(server, params.bridgeId, params.identityId, params.userId)- ),-- /** The messaging accounts the signed-in user has claimed in this workspace. */- listMyIdentities: (workspaceId: string): Promise<LinkedIdentity[]> =>- withWorkspaceSession(workspaceId, fetchMyIdentities),-- /** Whether the signed-in user owns an agent here that is set to answer its- * owner, which is what makes an unlinked messaging account worth warning- * about. One agent-list read, so callers need not ration it. */- ownsOwnerAddressedAgent: (workspaceId: string): Promise<boolean> =>- withWorkspaceSession(workspaceId, ownsOwnerAddressedAgent),-- getAddressingPolicy: (params: {- workspaceId: string;- agentId: string;- }): Promise<AddressingPolicy | null> =>- withWorkspaceSession(params.workspaceId, (server) =>- fetchAddressingPolicy(server, params.agentId)- ),-- updateAddressingPolicy: (params: {- workspaceId: string;- agentId: string;- policy: AddressingPolicy | null;- }): Promise<void> =>- withWorkspaceSession(params.workspaceId, (server) =>- updateAddressingPolicy(server, params.agentId, params.policy)- ),-- /** Give this user's icon-less agents the avatar their name generates. Runs- * once per workspace per app run; reports what happened so the caller can say- * when the icons did not reach the server. */- backfillAgentIcons: (workspaceId: string): Promise<AgentIconBackfill> =>- withWorkspaceSession(workspaceId, (server) => backfillAgentIcons(workspaceId, server)),-- /** Set or clear an agent's icon. Returns the agent as the server now holds- * it, so the caller refreshes from the stored value rather than the one it- * hoped for. */- updateAgentIcon: (params: {- workspaceId: string;- agentId: string;- iconUrl: string | null;- }): Promise<RemoteAgentSummary> =>- withWorkspaceSession(params.workspaceId, (server) =>- updateAgentIcon(server, params.agentId, params.iconUrl)- ),-- verifyAgent: (params: { workspaceId: string; agentId: string }): Promise<AgentVerifyResult> =>- withWorkspaceSession(params.workspaceId, async (server) => {- try {- return (await agentExistsOnServer(server, params.agentId)) ? 'found' : 'not-found';- } catch (cause) {- if (cause instanceof GatewayError && cause.kind === 'unauthorized') {- return 'unauthenticated';- }- throw cause;- }- }),-});diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.db.test.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.db.test.tsdeleted file mode 100644index 4a74aa61b..000000000--- a/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.db.test.ts+++ /dev/null@@ -1,447 +0,0 @@-import { openFixture } from '@tooling/utils/db';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import type { AppDb } from '@main/db/client';-import { agents, locations, switchServers } from '@main/db/schema';-import { workspacesChangedChannel } from '@shared/core/workspaces/workspaceEvents';-import { isWithdrawnWorkspace } from '@shared/core/workspaces/workspaces';--const mocks = vi.hoisted(() => ({- db: undefined as AppDb | undefined,-}));--const fetchTenants = vi.hoisted(() => vi.fn());-const decodeJwtTenantId = vi.hoisted(() => vi.fn((_jwt: string): string | null => null));-const getSessionCookie = vi.hoisted(() => vi.fn(async (): Promise<string | null> => null));-const listServers = vi.hoisted(() => vi.fn(async (): Promise<{ id: string }[]> => []));-const warn = vi.hoisted(() => vi.fn());-const emit = vi.hoisted(() => vi.fn());--vi.mock('@main/db/client', () => ({- get db() {- if (!mocks.db) throw new Error('Test database not initialized');- return mocks.db;- },-}));-vi.mock('@main/core/managed-switch-server/managed-server-status', () => ({- isManagedServerRunning: () => true,-}));-vi.mock('@main/core/switch-servers/gateway-client', () => ({ decodeJwtTenantId, fetchTenants }));-vi.mock('@main/core/switch-servers/require-server', () => ({- requireServer: async (id: string) => ({ id, name: id }),-}));-vi.mock('@main/lib/events', () => ({ events: { emit } }));-vi.mock('@main/lib/logger', () => {- const logger = { debug: vi.fn(), info: vi.fn(), warn, error: vi.fn(), child: () => logger };- return { log: logger };-});--// Mocked whole rather than in part: the module builds the encrypted secrets-// store at import, which a test has no key for.-vi.mock('@main/core/switch-servers/servers-store', () => ({ getSessionCookie, listServers }));--const { reconcileAllWorkspaces, reconcileServerWorkspaces } =- await import('./reconcile-workspaces');-const { createTenantWorkspace, ensureServerWorkspace, listWorkspacesForServer } =- await import('./workspaces-store');--function tenant(id: string, name: string, role = 'member') {- return { id, slug: id, name, role };-}--describe('reconcile-workspaces', () => {- let fixture: Awaited<ReturnType<typeof openFixture>>;-- beforeEach(async () => {- vi.clearAllMocks();- decodeJwtTenantId.mockReturnValue(null);- getSessionCookie.mockResolvedValue(null);- fixture = await openFixture('empty');- mocks.db = fixture.db;- fixture.sqlite.pragma('foreign_keys = ON');- await fixture.db.insert(switchServers).values({- id: 'srv-1',- name: 'Local dev',- gatewayUrl: 'https://srv-1.example.com',- apiUrl: 'https://api-srv-1.example.com',- });- listServers.mockResolvedValue([{ id: 'srv-1' }]);- });-- afterEach(() => {- fixture.close();- mocks.db = undefined;- });-- /** An agent in a workspace, which is the one thing that makes it unguessable. */- async function attachAgent(workspaceId: string): Promise<void> {- await fixture.db- .insert(locations)- .values({ id: 'loc-1', name: 'repo', dir: '/repo' })- .onConflictDoNothing();- await fixture.db.insert(agents).values({- id: `agent-${workspaceId}`,- locationId: 'loc-1',- name: 'a',- providerId: 'claude',- workspaceId,- });- }-- /**- * The case every install upgrading into tenancy is in: one workspace carrying- * every agent, and one membership it turns out to be.- */- it('claims the server’s existing workspace for its sole membership', async () => {- const before = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });- fetchTenants.mockResolvedValue([tenant('t-1', 'Default', 'owner')]);-- await reconcileServerWorkspaces('srv-1');-- const found = await listWorkspacesForServer('srv-1');- expect(found).toHaveLength(1);- // Same row: the agents, the active selection and the saved navigation all- // name this id, and a replacement would detach every one of them.- expect(found[0]!.id).toBe(before.id);- expect(found[0]!.tenantId).toBe('t-1');- expect(found[0]!.role).toBe('owner');- });-- /**- * A row is named after its server only until it is matched. After that the- * workspace is a tenant, the gateway is the only place it can be named or- * renamed, and nothing in this app offers to name one — so a local label kept- * here is one neither side can ever correct.- */- it('takes the gateway’s name for a workspace it has matched', async () => {- await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });- fetchTenants.mockResolvedValue([tenant('t-1', 'Default')]);-- await reconcileServerWorkspaces('srv-1');-- expect((await listWorkspacesForServer('srv-1'))[0]!.name).toBe('Default');- });-- /**- * Also how a name typed into the create form survives the round trip that- * records it failing. The workspace exists on the gateway under that name and- * the local row does not have it yet; the next reconcile is what closes the- * gap, so the name is late rather than lost.- */- it('carries a later rename on the gateway onto the row it already matched', async () => {- await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });- fetchTenants.mockResolvedValue([tenant('t-1', 'Default')]);- await reconcileServerWorkspaces('srv-1');-- fetchTenants.mockResolvedValue([tenant('t-1', 'Acme Robotics')]);- await reconcileServerWorkspaces('srv-1');-- expect((await listWorkspacesForServer('srv-1'))[0]!.name).toBe('Acme Robotics');- });-- it('adds a workspace for a membership this install has no row for', async () => {- await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });- getSessionCookie.mockResolvedValue('cookie');- decodeJwtTenantId.mockReturnValue('t-1');- fetchTenants.mockResolvedValue([tenant('t-1', 'Default'), tenant('t-2', 'Research')]);-- await reconcileServerWorkspaces('srv-1');-- const found = await listWorkspacesForServer('srv-1');- expect(found).toHaveLength(2);- expect(found.find((w) => w.tenantId === 't-1')!.name).toBe('Default');- expect(found.find((w) => w.tenantId === 't-2')!.name).toBe('Research');- });-- /**- * What every multi-membership sign-in used to produce: the gateway refuses a- * scoped call from a session with several memberships and no selection, so- * this server has never answered one and its row holds nothing. Left behind- * while a row was added per membership, it appeared in the switcher as a- * workspace belonging to no membership at all.- */- it('gives the registration row a membership rather than leaving it belonging to none', async () => {- const before = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });- fetchTenants.mockResolvedValue([tenant('t-1', 'Default')]);-- await reconcileServerWorkspaces('srv-1');-- const found = await listWorkspacesForServer('srv-1');- expect(found).toHaveLength(1);- // The same row, so the active selection and the saved navigation still name- // something that exists.- expect(found[0]!.id).toBe(before.id);- expect(found[0]!.tenantId).toBe('t-1');- });-- /**- * Which membership inherits the id the agents, the active selection and the- * saved navigation point at is not something to decide by coin toss. Every- * membership gets its own row instead, and the placeholder nothing was ever- * put in is dropped — the same list, arrived at the same way every time.- */- it('refuses to pick one of several memberships for the registration row', async () => {- const before = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });- fetchTenants.mockResolvedValue([tenant('t-1', 'Default'), tenant('t-2', 'Research')]);-- await reconcileServerWorkspaces('srv-1');-- const found = await listWorkspacesForServer('srv-1');- expect(found).toHaveLength(2);- expect(found.some((w) => w.id === before.id)).toBe(false);- expect(found.map((w) => w.name).toSorted()).toEqual(['Default', 'Research']);- });-- /**- * The cookie says which membership this row's calls have been reaching, so- * there is nothing to guess and the row keeps its agents and its id.- */- it('adopts the membership the session already resolves to', async () => {- const before = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });- getSessionCookie.mockResolvedValue('cookie');- decodeJwtTenantId.mockReturnValue('t-2');- fetchTenants.mockResolvedValue([tenant('t-1', 'Default'), tenant('t-2', 'Research')]);-- await reconcileServerWorkspaces('srv-1');-- const found = await listWorkspacesForServer('srv-1');- expect(found).toHaveLength(2);- expect(found.find((w) => w.id === before.id)!.tenantId).toBe('t-2');- });-- /**- * The one case that cannot be answered: agents were registered through this- * row, so it stands for wherever they live, and naming it the wrong- * membership would move them somewhere the user cannot see.- */- it('refuses to guess which membership a workspace with agents holds', async () => {- const before = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });- await attachAgent(before.id);- fetchTenants.mockResolvedValue([tenant('t-1', 'Default'), tenant('t-2', 'Research')]);-- await reconcileServerWorkspaces('srv-1');-- const found = await listWorkspacesForServer('srv-1');- expect(found.find((w) => w.id === before.id)!.tenantId).toBeNull();- // Both memberships are still recorded — only the question of which one the- // existing row holds is left open.- expect(found).toHaveLength(3);- expect(found.some((w) => w.tenantId === 't-1')).toBe(true);- expect(found.some((w) => w.tenantId === 't-2')).toBe(true);- expect(warn).toHaveBeenCalled();- });-- /**- * The repair the short-circuit used to make impossible: once every membership- * has a row, the leftover registration row could never be revisited, and no- * later boot or sign-in could clear it.- */- it('drops an empty registration row left over once every membership has one', async () => {- const before = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });- await createTenantWorkspace('srv-1', {- id: 't-1',- slug: 't-1',- name: 'Default',- role: 'owner',- });- await createTenantWorkspace('srv-1', {- id: 't-2',- slug: 't-2',- name: 'Research',- role: 'member',- });- fetchTenants.mockResolvedValue([tenant('t-1', 'Default'), tenant('t-2', 'Research')]);-- await reconcileServerWorkspaces('srv-1');-- const found = await listWorkspacesForServer('srv-1');- expect(found).toHaveLength(2);- expect(found.some((w) => w.id === before.id)).toBe(false);- });-- /**- * The boot sweep runs behind an open window that read its list before it- * started, and nothing else tells that window the list moved. Without this a- * membership gained or lost between launches stays invisible for the whole- * session, and the row dropped above goes on being offered in the switcher- * after it has gone.- */- it('announces the change so an open window re-reads the list', async () => {- await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });- fetchTenants.mockResolvedValue([tenant('t-1', 'Default')]);-- await reconcileServerWorkspaces('srv-1');-- expect(emit).toHaveBeenCalledWith(workspacesChangedChannel, undefined);- });-- /**- * The boot sweep is not awaited, so a sign-in lands in the middle of it. Read- * together, both passes see a membership with no row and both create one; the- * unique index then turns the loser into an error that abandons the rest of- * its pass, leaving the tenants it had not reached yet unmatched.- */- it('runs two passes on one server one after the other', async () => {- await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });- getSessionCookie.mockResolvedValue('cookie');- decodeJwtTenantId.mockReturnValue('t-1');- fetchTenants.mockResolvedValue([- tenant('t-1', 'Default'),- tenant('t-2', 'Research'),- tenant('t-3', 'Ops'),- ]);-- await Promise.all([reconcileServerWorkspaces('srv-1'), reconcileServerWorkspaces('srv-1')]);-- const found = await listWorkspacesForServer('srv-1');- expect(found).toHaveLength(3);- expect(found.map((w) => w.tenantId).toSorted((a, b) => a!.localeCompare(b!))).toEqual([- 't-1',- 't-2',- 't-3',- ]);- });-- it('carries a role change on a workspace it already matched', async () => {- const existing = await createTenantWorkspace('srv-1', {- id: 't-1',- slug: 't-1',- name: 'Research',- role: 'member',- });- fetchTenants.mockResolvedValue([tenant('t-1', 'Research', 'admin')]);-- await reconcileServerWorkspaces('srv-1');-- const found = await listWorkspacesForServer('srv-1');- expect(found).toHaveLength(1);- expect(found[0]!.id).toBe(existing.id);- expect(found[0]!.role).toBe('admin');- });-- /**- * Deleting it would silently detach that workspace's agents. Kept, so the- * next call scoped to it fails and says why — and said out loud now.- */- it('keeps a workspace whose membership has been withdrawn, and says so', async () => {- await createTenantWorkspace('srv-1', {- id: 't-gone',- slug: 't-gone',- name: 'Research',- role: 'member',- });- fetchTenants.mockResolvedValue([tenant('t-1', 'Default')]);-- await reconcileServerWorkspaces('srv-1');-- const found = await listWorkspacesForServer('srv-1');- const gone = found.find((w) => w.tenantId === 't-gone');- expect(gone).toBeDefined();- // The role is what the switcher reads to say so before the click, rather- // than leaving the log file as the only place it is said.- expect(gone!.role).toBeNull();- expect(isWithdrawnWorkspace(gone!)).toBe(true);- expect(warn).toHaveBeenCalledWith(expect.stringContaining('no longer a member'), {- server: 'srv-1',- workspace: expect.any(String),- });- });-- it('restores the role when a withdrawn membership is granted again', async () => {- await createTenantWorkspace('srv-1', {- id: 't-back',- slug: 't-back',- name: 'Research',- role: 'admin',- });- fetchTenants.mockResolvedValue([tenant('t-1', 'Default')]);- await reconcileServerWorkspaces('srv-1');-- fetchTenants.mockResolvedValue([tenant('t-1', 'Default'), tenant('t-back', 'Research')]);- await reconcileServerWorkspaces('srv-1');-- const back = (await listWorkspacesForServer('srv-1')).find((w) => w.tenantId === 't-back');- expect(isWithdrawnWorkspace(back!)).toBe(false);- });-- // An account in no workspace at all is a server the user cannot use; saying- // nothing and deleting the local row would look like it had never been set up.- it('leaves the rows alone when the gateway reports no membership', async () => {- const before = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });- fetchTenants.mockResolvedValue([]);-- await reconcileServerWorkspaces('srv-1');-- const found = await listWorkspacesForServer('srv-1');- expect(found).toEqual([before]);- expect(warn).toHaveBeenCalled();- });-- /**- * The short-circuit for "no memberships" used to return before the withdrawal- * pass, so the one case where every row has been withdrawn was the one case- * that never marked any. The switcher and the first-run picker went on- * offering them, and the refusal only arrived after the click.- */- it('marks every row withdrawn when the account is left in no workspace', async () => {- const held = await createTenantWorkspace('srv-1', {- id: 't-gone',- slug: 't-gone',- name: 'Research',- role: 'member',- });- fetchTenants.mockResolvedValue([]);-- await reconcileServerWorkspaces('srv-1');-- const found = await listWorkspacesForServer('srv-1');- expect(found.find((w) => w.id === held.id)!.role).toBeNull();- expect(found.find((w) => w.id === held.id)!.tenantId).toBe('t-gone');- });-- it('is idempotent across launches', async () => {- const before = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });- fetchTenants.mockResolvedValue([tenant('t-1', 'Default')]);-- await reconcileServerWorkspaces('srv-1');- await reconcileServerWorkspaces('srv-1');-- const found = await listWorkspacesForServer('srv-1');- expect(found).toHaveLength(1);- expect(found[0]!.id).toBe(before.id);- });-- describe('the boot sweep', () => {- // Asking costs a round trip that can only be refused, and the answer would- // be thrown away.- it('skips a server this install is not signed in to', async () => {- await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });-- await reconcileAllWorkspaces();-- expect(fetchTenants).not.toHaveBeenCalled();- });-- // One server being down must not stop the rest from being reconciled.- it('carries on past a server that cannot be reached', async () => {- await fixture.db.insert(switchServers).values({- id: 'srv-2',- name: 'Staging',- gatewayUrl: 'https://srv-2.example.com',- apiUrl: 'https://api-srv-2.example.com',- });- await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });- await ensureServerWorkspace({ id: 'srv-2', name: 'Staging' });- listServers.mockResolvedValue([{ id: 'srv-1' }, { id: 'srv-2' }]);- getSessionCookie.mockResolvedValue('cookie');- fetchTenants- .mockRejectedValueOnce(new Error('no route to host'))- .mockResolvedValue([tenant('t-2', 'Default')]);-- await reconcileAllWorkspaces();-- expect((await listWorkspacesForServer('srv-1'))[0]!.tenantId).toBeNull();- expect((await listWorkspacesForServer('srv-2'))[0]!.tenantId).toBe('t-2');- expect(warn).toHaveBeenCalled();- });- });-});diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.tsdeleted file mode 100644index 4322263e0..000000000--- a/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.ts+++ /dev/null@@ -1,226 +0,0 @@-import { isManagedServerRunning } from '@main/core/managed-switch-server/managed-server-status';-import {- decodeJwtTenantId,- fetchTenants,- type RemoteTenant,-} from '@main/core/switch-servers/gateway-client';-import { requireServer } from '@main/core/switch-servers/require-server';-import { getSessionCookie, listServers } from '@main/core/switch-servers/servers-store';-import { events } from '@main/lib/events';-import { log } from '@main/lib/logger';-import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';-import { workspacesChangedChannel } from '@shared/core/workspaces/workspaceEvents';-import type { Workspace } from '@shared/core/workspaces/workspaces';-import {- clearWorkspaceRole,- createTenantWorkspace,- discardEmptyWorkspace,- listWorkspacesForServer,- setWorkspaceTenant,- workspaceHasAgents,-} from './workspaces-store';--/**- * The tenant this server's session resolves to — the one whose data every call- * made against it so far has actually reached.- *- * The gateway resolves a session to the tenant its cookie selects, or to the- * sole membership when nothing is selected; with several memberships and no- * selection it refuses the request instead of guessing. So a server that has- * ever answered has exactly one answer here, and when there is none nothing has- * been attached to a workspace yet and there is nothing to get wrong.- */-async function resolvedTenant(- server: SwitchServer,- tenants: RemoteTenant[]-): Promise<RemoteTenant | null> {- const cookie = await getSessionCookie(server.id);- const selected = cookie ? decodeJwtTenantId(cookie) : null;- // A claim naming a membership the account no longer holds answers nothing, so- // it falls through rather than standing in the way of the sole-membership- // answer below — which is what the gateway itself would resolve the next call- // to.- const claimed = selected ? tenants.find((tenant) => tenant.id === selected) : undefined;- if (claimed) return claimed;- return tenants.length === 1 ? tenants[0]! : null;-}--/**- * The membership to give the tenant-less row a server is registered with, or- * null when it cannot be told and must not be guessed.- *- * Every server starts with one such row, and until it is matched it belongs to- * nothing: a call scoped to it selects no tenant, so the gateway answers under- * whatever the session last selected — another workspace's rooms and agents,- * under this one's name, with no error anywhere. Leaving one behind while- * creating a row per membership is how that used to happen on every- * multi-membership sign-in.- */-async function tenantToAdopt(- server: SwitchServer,- unclaimed: Workspace,- tenants: RemoteTenant[],- unmatched: RemoteTenant[]-): Promise<RemoteTenant | null> {- // The one this row's calls have been reaching all along, when no other row- // holds it already.- const resolved = await resolvedTenant(server, tenants);- if (resolved && unmatched.some((tenant) => tenant.id === resolved.id)) return resolved;- // Only where there is nothing to choose between. Nothing was ever registered- // through the row, so there is no data to put anywhere, and a membership the- // user can see and switch away from beats a row belonging to none of them.- // With several it would be a coin toss deciding which membership inherits the- // id the saved navigation and the active selection point at; left unadopted,- // every membership gets its own row and the empty placeholder is dropped- // further down, which reaches the same list without the toss.- if (unmatched.length === 1 && !(await workspaceHasAgents(unclaimed.id))) return unmatched[0]!;- return null;-}--/**- * Mark the workspaces still held locally for a membership that has gone.- *- * The row is kept — deleting it would silently detach its agents — so the mark- * is what stops it reading as a workspace the user can still open. A log line- * alone would leave the switcher listing it exactly like the others, and the- * only sign would be the gateway refusing the call after the click.- */-async function markWithdrawnMemberships(- serverId: string,- local: Workspace[],- tenants: RemoteTenant[]-): Promise<void> {- for (const workspace of local) {- if (!workspace.tenantId) continue;- if (tenants.some((tenant) => tenant.id === workspace.tenantId)) continue;- log.warn(- 'workspaces: this account is no longer a member of a workspace held locally; calls scoped to it will be refused',- { server: serverId, workspace: workspace.id }- );- if (workspace.role !== null) await clearWorkspaceRole(workspace.id);- }-}--/**- * Match this install's workspaces for a server against the memberships the- * gateway reports.- *- * A server registers before anyone asks which workspaces its account belongs- * to, so its first row is created tenant-less and named after the server. This- * is what later gives that row its tenant — claiming it rather than replacing- * it, so the agents registered through it stay where they are — and adds a row- * for every other membership.- *- * A row whose membership has been withdrawn is kept, not deleted. Deleting it- * would silently detach that workspace's agents; leaving it means the next call- * scoped to it fails and says why.- */-export async function reconcileServerWorkspaces(serverId: string): Promise<void> {- // The boot sweep is not awaited and a sign-in can land in the middle of it.- // Two passes that both read the rows before either writes create the same- // tenant twice, and the unique index turns the loser into an error that- // abandons the rest of its pass — so they run one after the other instead.- const queued = (inFlight.get(serverId) ?? Promise.resolve())- .then(- () => reconcileOneServer(serverId),- () => reconcileOneServer(serverId)- )- // An open window read its list before this ran, and nothing else tells it- // the list moved. Without this a membership added or withdrawn between- // launches stays invisible for the session, and a placeholder dropped below- // goes on being offered in the switcher after the row it names has gone.- .then(() => {- events.emit(workspacesChangedChannel, undefined);- });- inFlight.set(- serverId,- queued.then(- () => {},- () => {}- )- );- return queued;-}--const inFlight = new Map<string, Promise<void>>();--async function reconcileOneServer(serverId: string): Promise<void> {- const server = await requireServer(serverId);- const tenants = await fetchTenants(server);- const local = await listWorkspacesForServer(serverId);- // Marked before the short-circuit below, not after it: an account that is in- // nothing has had every membership withdrawn, and that is precisely the case- // where a row still claiming one would go on being offered as somewhere to- // work.- await markWithdrawnMemberships(serverId, local, tenants);-- if (tenants.length === 0) {- log.warn('workspaces: the gateway reports no workspace membership for this account', {- server: serverId,- });- return;- }-- const claimed = new Map(- local- .filter((workspace) => workspace.tenantId)- .map((workspace) => [workspace.tenantId!, workspace])- );- for (const tenant of tenants) {- const workspace = claimed.get(tenant.id);- if (workspace) await setWorkspaceTenant(workspace.id, tenant);- }-- const unmatched = tenants.filter((tenant) => !claimed.has(tenant.id));- const unclaimed = local.find((workspace) => !workspace.tenantId) ?? null;- const adopting = unclaimed ? await tenantToAdopt(server, unclaimed, tenants, unmatched) : null;- if (unclaimed && adopting) await setWorkspaceTenant(unclaimed.id, adopting);-- for (const tenant of unmatched) {- if (tenant.id === adopting?.id) continue;- await createTenantWorkspace(serverId, tenant);- }-- if (!unclaimed || adopting) return;-- // Reached when every membership is held by another row and this one is left- // over. Empty, it is a placeholder the reconcile has overtaken and dropping- // it is the whole repair; holding agents, it is the only record of where they- // live and is kept, unmatched, so the next call scoped to it is refused and- // says why rather than answering as some other workspace.- if (await workspaceHasAgents(unclaimed.id)) {- log.warn(- 'workspaces: cannot tell which workspace this server’s existing agents belong to; leaving it unmatched, and calls scoped to it will be refused',- { server: serverId, workspace: unclaimed.id, memberships: tenants.length }- );- return;- }- await discardEmptyWorkspace(unclaimed.id);-}--/**- * Reconcile every server this install holds a session for.- *- * Run at boot and left unawaited: a workspace list that is one launch stale is- * cosmetic, and a server that is slow or down must not hold up the window. A- * managed server whose stack is not running is skipped rather than probed —- * its gateway port is not listening, so the attempt only produces a network- * error in the log (CHOO-1657).- */-export async function reconcileAllWorkspaces(): Promise<void> {- for (const server of await listServers()) {- // The cookie read is inside the guard with everything else: it opens the- // keychain, and a machine that refuses to unlock it would otherwise take- // the whole sweep down on the first server and skip the rest in silence.- try {- if (server.managed && !isManagedServerRunning(server)) continue;- if (!(await getSessionCookie(server.id))) continue;- await reconcileServerWorkspaces(server.id);- } catch (error: unknown) {- log.warn('workspaces: could not reconcile a server’s workspaces', {- server: server.id,- error: String(error),- });- }- }-}diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/workspace-session.test.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/workspace-session.test.tsdeleted file mode 100644index a11e13d03..000000000--- a/console/apps/switch-console-desktop/src/main/core/workspaces/workspace-session.test.ts+++ /dev/null@@ -1,289 +0,0 @@-/**- * The seam every tenant-owned gateway call goes through.- *- * What it has to get right is not visible in any one call: a Switch session- * selects one tenant at a time, so the guarantee is about what happens when- * calls for two workspaces on the same server overlap. If a switch can land- * between another call reading the cookie and sending it, that call quietly- * answers with the wrong workspace's data and nothing anywhere reports an- * error. These tests drive that overlap deliberately, since it is not a state- * the app reaches on demand.- */-import { beforeEach, describe, expect, it, vi } from 'vitest';--const decodeJwtTenantId = vi.hoisted(() => vi.fn<(jwt: string) => string | null>());-const switchTenant = vi.hoisted(() =>- vi.fn<(server: unknown, tenantId: string) => Promise<void>>()-);-const getSessionCookie = vi.hoisted(() => vi.fn<(serverId: string) => Promise<string | null>>());-const requireWorkspace = vi.hoisted(() => vi.fn());-const listWorkspacesForServer = vi.hoisted(() => vi.fn());-const hostUnreachable = vi.hoisted(() => vi.fn((): unknown => null));--vi.mock('@main/core/switch-servers/gateway-client', () => ({ decodeJwtTenantId, switchTenant }));-vi.mock('@main/core/switch-servers/servers-store', () => ({ getSessionCookie }));-vi.mock('@main/core/switch-servers/require-server', () => ({- hostUnreachable,- requireServer: async (serverId: string) => ({ id: serverId, name: serverId }),-}));-vi.mock('./workspaces-store', () => ({ requireWorkspace, listWorkspacesForServer }));--import { assertedTenant } from './asserted-tenant';-import {- forgetServerSession,- withReachableWorkspaceSession,- withWorkspaceSession,-} from './workspace-session';--const SERVER = 'srv-1';--/**- * The tenant the server's session currently selects, as the cookie would carry- * it.- *- * Modelled rather than stubbed away: the seam decides whether to switch by- * reading the cookie back, so a `switchTenant` that left it unchanged would- * make every call look like a switch and hide the very interleaving these tests- * are about.- */-let selected: string | null = null;--/** The rows the seam resolves, keyed by workspace id. */-const rows = new Map<string, { id: string; serverId: string; tenantId: string | null }>();--function workspace(id: string, tenantId: string | null) {- const row = { id, serverId: SERVER, tenantId };- rows.set(id, row);- return row;-}--/** A promise plus the handles to settle it, so a call can be held mid-flight. */-function deferred<T>() {- let resolve!: (value: T) => void;- let reject!: (cause: unknown) => void;- const promise = new Promise<T>((res, rej) => {- resolve = res;- reject = rej;- });- return { promise, resolve, reject };-}--/**- * Let everything that can proceed proceed, so "still pending" means blocked- * rather than merely not got to yet. A macrotask boundary, since the admission- * queue is several promise hops deep.- */-async function settle(): Promise<void> {- for (let i = 0; i < 4; i++) await new Promise((resolve) => setTimeout(resolve, 0));-}--beforeEach(() => {- rows.clear();- forgetServerSession(SERVER);- // A session that has selected nothing, as it is straight after signing in.- selected = null;- switchTenant.mockReset().mockImplementation(async (_server: unknown, tenantId: string) => {- selected = tenantId;- });- hostUnreachable.mockReset().mockReturnValue(null);- getSessionCookie.mockReset().mockImplementation(async () => `cookie:${selected ?? 'none'}`);- decodeJwtTenantId.mockReset().mockImplementation((jwt: string) => {- const tenant = jwt.slice('cookie:'.length);- return tenant === 'none' ? null : tenant;- });- requireWorkspace.mockReset().mockImplementation(async (id: string) => {- const row = rows.get(id);- if (!row) throw new Error(`no workspace ${id}`);- return row;- });- listWorkspacesForServer.mockReset().mockImplementation(async () => [...rows.values()]);-});--describe('withWorkspaceSession', () => {- it('selects the workspace’s tenant before the call goes out', async () => {- workspace('ws-a', 'tenant-a');- const order: string[] = [];- switchTenant.mockImplementation(async () => void order.push('switch'));-- await withWorkspaceSession('ws-a', async (server) => {- order.push(`call:${server.id}`);- });-- expect(order).toEqual(['switch', `call:${SERVER}`]);- expect(switchTenant).toHaveBeenCalledWith(expect.objectContaining({ id: SERVER }), 'tenant-a');- });-- it('does not switch when the session already selects that tenant', async () => {- workspace('ws-a', 'tenant-a');- selected = 'tenant-a';-- await withWorkspaceSession('ws-a', async () => {});-- expect(switchTenant).not.toHaveBeenCalled();- });-- /**- * The row a server is registered with, before any gateway has been asked.- * There is no id to select and nothing to confuse it with, so the call goes- * out as it did before workspaces existed.- */- it('asks a tenant-less workspace’s server without selecting anything', async () => {- workspace('ws-only', null);-- await withWorkspaceSession('ws-only', async () => {});-- expect(switchTenant).not.toHaveBeenCalled();- });-- /**- * The same row on a server that turns out to hold several. The call would- * still succeed — the gateway answers for whatever the session last selected- * — and would answer with another workspace's rooms and agents under this- * one's name. There is no way to tell which is meant, so it is refused rather- * than guessed.- */- it('refuses a tenant-less workspace on a server holding several', async () => {- workspace('ws-stale', null);- workspace('ws-b', 'tenant-b');- const ran = vi.fn();-- await expect(withWorkspaceSession('ws-stale', ran)).rejects.toThrow(- /has not been matched to one of the 2/- );- expect(ran).not.toHaveBeenCalled();- expect(switchTenant).not.toHaveBeenCalled();- });-- it('runs calls on the same tenant at the same time', async () => {- workspace('ws-a', 'tenant-a');- const first = deferred<void>();- const inFlight: string[] = [];-- const a = withWorkspaceSession('ws-a', async () => {- inFlight.push('a');- await first.promise;- });- const b = withWorkspaceSession('ws-a', async () => void inFlight.push('b'));- await settle();-- // Serialising here would be a correctness-free cost: they name one tenant,- // so there is no switch between them to be straddled.- expect(inFlight).toEqual(['a', 'b']);- expect(switchTenant).toHaveBeenCalledTimes(1);-- first.resolve();- await Promise.all([a, b]);- });-- /**- * The whole point of the lease. `switchTenant` replaces the selection for- * every call on that server at once, so letting it run while another- * workspace's call is outstanding would answer that call from the new tenant- * — the exact silent wrong answer the seam exists to make impossible.- */- it('holds a switch back until the calls it would disturb are done', async () => {- workspace('ws-a', 'tenant-a');- workspace('ws-b', 'tenant-b');- const holding = deferred<void>();- const ranB = vi.fn();-- const a = withWorkspaceSession('ws-a', async () => {- await holding.promise;- });- await settle();- const b = withWorkspaceSession('ws-b', ranB);- await settle();-- expect(switchTenant).toHaveBeenCalledTimes(1);- expect(ranB).not.toHaveBeenCalled();-- holding.resolve();- await a;- await b;-- expect(switchTenant).toHaveBeenNthCalledWith(2, expect.anything(), 'tenant-b');- expect(ranB).toHaveBeenCalled();- });-- it('gives the lease up when the call throws, so the next switch is not stuck', async () => {- workspace('ws-a', 'tenant-a');- workspace('ws-b', 'tenant-b');-- await expect(- withWorkspaceSession('ws-a', async () => {- throw new Error('the gateway said no');- })- ).rejects.toThrow('the gateway said no');-- await withWorkspaceSession('ws-b', async () => {});-- expect(switchTenant).toHaveBeenNthCalledWith(2, expect.anything(), 'tenant-b');- });-- /**- * Read by anything that replaces the cookie underneath a call in flight: a- * cookie minted by a fresh login selects no tenant, and handing it back- * unchanged would finish the lease against the account's default workspace.- */- it('publishes the tenant the calls in flight are relying on, and forgets it after', async () => {- workspace('ws-a', 'tenant-a');- const holding = deferred<void>();-- const call = withWorkspaceSession('ws-a', async () => {- await holding.promise;- });- await settle();-- expect(assertedTenant(SERVER)).toBe('tenant-a');-- holding.resolve();- await call;-- expect(assertedTenant(SERVER)).toBeNull();- });-- it('wakes a switch queued behind a server that has been removed', async () => {- workspace('ws-a', 'tenant-a');- workspace('ws-b', 'tenant-b');- const holding = deferred<void>();-- const a = withWorkspaceSession('ws-a', async () => {- await holding.promise;- });- await settle();- const b = withWorkspaceSession('ws-b', async () => {});- await settle();-- // The lease is never given up: the call belongs to a server that is gone.- forgetServerSession(SERVER);- await expect(b).resolves.toBeUndefined();-- holding.resolve();- await a;- });-});--describe('withReachableWorkspaceSession', () => {- it('refuses before touching the session when the managed host is down', async () => {- workspace('ws-a', 'tenant-a');- hostUnreachable.mockReturnValue(new Error('build-box is not reachable'));- const ran = vi.fn();-- await expect(withReachableWorkspaceSession('ws-a', ran)).rejects.toThrow('not reachable');-- // No switch means no side effect to undo, and the next call to a reachable- // server does not find the session selecting a tenant nobody asked for.- expect(switchTenant).not.toHaveBeenCalled();- expect(ran).not.toHaveBeenCalled();- expect(assertedTenant(SERVER)).toBeNull();- });-- it('selects the tenant and runs while the host is up', async () => {- workspace('ws-a', 'tenant-a');-- await expect(withReachableWorkspaceSession('ws-a', async () => 'answered')).resolves.toBe(- 'answered'- );- expect(switchTenant).toHaveBeenCalledWith(expect.anything(), 'tenant-a');- });-});diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/workspace-session.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/workspace-session.tsdeleted file mode 100644index 73b302c86..000000000--- a/console/apps/switch-console-desktop/src/main/core/workspaces/workspace-session.ts+++ /dev/null@@ -1,196 +0,0 @@-import { decodeJwtTenantId, switchTenant } from '@main/core/switch-servers/gateway-client';-import { hostUnreachable, requireServer } from '@main/core/switch-servers/require-server';-import { getSessionCookie } from '@main/core/switch-servers/servers-store';-import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';-import { isUnmatchedWorkspace, type Workspace } from '@shared/core/workspaces/workspaces';-import { clearAssertedTenant, setAssertedTenant } from './asserted-tenant';-import { listWorkspacesForServer, requireWorkspace } from './workspaces-store';--/**- * Calls in flight on a server's current tenant selection, and the queue that- * changes it.- *- * A server session selects one tenant at a time, so a workspace-scoped call is- * only addressing the workspace it names while that selection matches. Calls- * that share the selection run in parallel and hold a lease; changing the- * selection waits for every lease to be given up, so a switch can never land- * between another call reading the cookie and sending it.- */-type ServerSession = {- leases: number;- /** Resolvers waiting for `leases` to reach zero. */- idle: Array<() => void>;-};--const sessions = new Map<string, ServerSession>();--/** Serialises the decision to switch, per server — never the calls themselves. */-const admissions = new Map<string, Promise<unknown>>();--function sessionFor(serverId: string): ServerSession {- let session = sessions.get(serverId);- if (!session) {- session = { leases: 0, idle: [] };- sessions.set(serverId, session);- }- return session;-}--function release(serverId: string, session: ServerSession): void {- session.leases -= 1;- if (session.leases > 0) return;- for (const resolve of session.idle.splice(0)) resolve();- clearAssertedTenant(serverId);-}--/**- * Drop everything held for a server that no longer exists.- *- * Nothing prunes these as calls finish — an entry is the server's, not a call's- * — so a removal is the one moment they can go. Left behind, a lease that leaked- * would be inherited by whatever next holds the id, and a switch waiting for it- * to be given up would wait for a call that ended with the server.- */-export function forgetServerSession(serverId: string): void {- const session = sessions.get(serverId);- // Waiters first: a switch queued behind a server that has just gone would- // otherwise never be woken at all.- if (session) for (const resolve of session.idle.splice(0)) resolve();- sessions.delete(serverId);- admissions.delete(serverId);- clearAssertedTenant(serverId);-}--function whenIdle(session: ServerSession): Promise<void> {- if (session.leases === 0) return Promise.resolve();- return new Promise<void>((resolve) => session.idle.push(resolve));-}--function admit<T>(serverId: string, task: () => Promise<T>): Promise<T> {- const queued = (admissions.get(serverId) ?? Promise.resolve()).then(task, task);- admissions.set(- serverId,- queued.then(- () => {},- () => {}- )- );- return queued;-}--/**- * Take a lease on `server`'s session with `tenantId` selected, switching the- * selection first if it is something else.- *- * The caller must release the lease. Never call this from inside a leased call- * on the same server: a switch waits for outstanding leases, and a call waiting- * on its own would wait forever.- */-async function acquire(server: SwitchServer, tenantId: string | null): Promise<ServerSession> {- const session = sessionFor(server.id);- await admit(server.id, async () => {- if (tenantId !== null) {- const cookie = await getSessionCookie(server.id);- if (!cookie || decodeJwtTenantId(cookie) !== tenantId) {- await whenIdle(session);- await switchTenant(server, tenantId);- }- setAssertedTenant(server.id, tenantId);- }- session.leases += 1;- });- return session;-}--/**- * The workspace, refusing one that names no tenant on a server holding several.- *- * A row without a tenant asserts nothing, so the call goes out under whatever- * the session last selected and the gateway answers for that — another- * workspace's rooms and agents, under this one's name, with no error anywhere.- * Refusing costs nothing where a server holds one workspace: there is nothing- * to confuse it with, and the gateway resolves the account's sole membership to- * exactly that row.- */-async function requireAddressableWorkspace(workspaceId: string): Promise<Workspace> {- const workspace = await requireWorkspace(workspaceId);- if (workspace.tenantId) return workspace;- const onServer = await listWorkspacesForServer(workspace.serverId);- if (isUnmatchedWorkspace(workspace, onServer.length)) {- throw new Error(- // Not "sign in again": signing in re-runs the reconcile, which is what- // left the row unmatched in the first place and would do so again. The- // row only survives because it holds agents, so the way out is to open- // one of the workspaces the account does belong to and add those agents- // there.- `This workspace has not been matched to one of the ${onServer.length} this account belongs to on its Switch server, so there is no way to tell which one to ask. Switch to one of the others on this server; the agents left here have to be added again in the workspace they belong to.`- );- }- return workspace;-}--/**- * The server hosting a workspace, with no session work done.- *- * For the callers that have to know which server they are about to address- * before they address it — the ones that report their own outcome, and so must- * be able to count a refusal the session seam would otherwise raise past them.- */-export async function workspaceServer(workspaceId: string): Promise<SwitchServer> {- const workspace = await requireWorkspace(workspaceId);- return requireServer(workspace.serverId);-}--/**- * Run `fn` against the server hosting `workspaceId`, with that workspace's- * tenant selected on the session.- *- * This is the seam every call that reads or writes tenant-owned data goes- * through — rooms, agents, bridges, identities. Without it the renderer showing- * one workspace while the session still selects another is invisible: every- * call succeeds and answers with the other workspace's data. Making the- * selection part of resolving the workspace makes that impossible rather than- * something a bug report eventually surfaces.- *- * A workspace that has not been matched to a tenant yet asserts nothing — there- * is no id to select, and the call goes out against whatever the session- * resolves. That is the right answer only while the server holds one workspace,- * which is why the rest are refused; see `requireAddressableWorkspace`. It still- * takes a lease, so it cannot straddle another workspace's switch.- */-export async function withWorkspaceSession<T>(- workspaceId: string,- fn: (server: SwitchServer) => Promise<T>-): Promise<T> {- const workspace = await requireAddressableWorkspace(workspaceId);- const server = await requireServer(workspace.serverId);- const session = await acquire(server, workspace.tenantId);- try {- return await fn(server);- } finally {- release(server.id, session);- }-}--/**- * {@link withWorkspaceSession}, refusing to touch the gateway while the host- * the server is managed on is unreachable (CHOO-1780).- *- * Checked before the session is acquired, so an unreachable host costs no- * switch and starts no side effect it cannot finish.- */-export async function withReachableWorkspaceSession<T>(- workspaceId: string,- fn: (server: SwitchServer) => Promise<T>-): Promise<T> {- const workspace = await requireAddressableWorkspace(workspaceId);- const server = await requireServer(workspace.serverId);- const unreachable = hostUnreachable(server);- if (unreachable) throw unreachable;- const session = await acquire(server, workspace.tenantId);- try {- return await fn(server);- } finally {- release(server.id, session);- }-}diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/workspaces-store.db.test.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/workspaces-store.db.test.tsdeleted file mode 100644index 0abc22d39..000000000--- a/console/apps/switch-console-desktop/src/main/core/workspaces/workspaces-store.db.test.ts+++ /dev/null@@ -1,220 +0,0 @@-import { openFixture } from '@tooling/utils/db';-import { eq } from 'drizzle-orm';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import type { AppDb } from '@main/db/client';-import { kv, switchServers, workspaces } from '@main/db/schema';--const mocks = vi.hoisted(() => ({- db: undefined as AppDb | undefined,-}));--vi.mock('@main/db/client', () => ({- get db() {- if (!mocks.db) throw new Error('Test database not initialized');- return mocks.db;- },-}));--const {- clearActiveWorkspaceOnServer,- ensureServerWorkspace,- getActiveWorkspaceId,- listWorkspacesForServer,- renameServerWorkspaces,- requireWorkspaceForServer,- requireWorkspace,- serverIdForWorkspace,- setActiveWorkspaceId,-} = await import('./workspaces-store');--describe('workspaces-store', () => {- let fixture: Awaited<ReturnType<typeof openFixture>>;-- beforeEach(async () => {- fixture = await openFixture('empty');- mocks.db = fixture.db;- fixture.sqlite.pragma('foreign_keys = ON');- });-- afterEach(() => {- fixture.close();- mocks.db = undefined;- });-- async function seedServer(id: string, name: string): Promise<void> {- await fixture.db.insert(switchServers).values({- id,- name,- gatewayUrl: `https://${id}.example.com`,- apiUrl: `https://api-${id}.example.com`,- });- }-- describe('ensureServerWorkspace', () => {- it('gives a newly registered server one workspace, named after it', async () => {- await seedServer('srv-1', 'Local dev');-- const workspace = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });-- expect(workspace.serverId).toBe('srv-1');- expect(workspace.name).toBe('Local dev');- expect(workspace.tenantId).toBeNull();- expect(workspace.slug).toBeNull();- expect(workspace.role).toBeNull();- });-- // The managed-server paths run again on every restart of a stack that- // already exists, and a second workspace would silently split its agents.- it('returns the existing workspace instead of adding a second', async () => {- await seedServer('srv-1', 'Local dev');- const first = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });-- const again = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });-- expect(again.id).toBe(first.id);- expect(await listWorkspacesForServer('srv-1')).toHaveLength(1);- });-- /**- * The table's other unique index is on (server_id, tenant_id), and SQLite- * treats NULLs as distinct, so it lets a second tenant-less row through.- * Reconcile repairs the one unmatched row it finds; a second would be left- * behind belonging to no membership, and every call scoped to it refused.- */- it('refuses a second tenant-less workspace on the same server', async () => {- await seedServer('srv-1', 'Local dev');- await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });-- await expect(- fixture.db.insert(workspaces).values({ id: 'ws-2', serverId: 'srv-1', name: 'Local dev' })- ).rejects.toThrow(/UNIQUE/);- });- });-- describe('requireWorkspaceForServer', () => {- it('returns the one workspace a server has', async () => {- await seedServer('srv-1', 'Local dev');- const created = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });-- expect((await requireWorkspaceForServer('srv-1')).id).toBe(created.id);- });-- it('raises for a server whose registration left it with none', async () => {- await seedServer('srv-1', 'Local dev');-- await expect(requireWorkspaceForServer('srv-1')).rejects.toThrow('has no workspace');- });-- // These callers run from screens showing the active workspace, so acting- // anywhere else would act somewhere the user is not looking.- it('takes the active one when a server has several', async () => {- await seedServer('srv-1', 'Cloud');- await fixture.db.insert(workspaces).values([- { id: 'ws-a', serverId: 'srv-1', name: 'A', tenantId: 'tenant-a' },- { id: 'ws-b', serverId: 'srv-1', name: 'B', tenantId: 'tenant-b' },- ]);- await setActiveWorkspaceId('ws-b');-- expect((await requireWorkspaceForServer('srv-1')).id).toBe('ws-b');- });-- // Picking one would attach the agent to a workspace the user never chose,- // and nothing would show them until it had already happened.- it('raises when a server has several and the active one is elsewhere', async () => {- await seedServer('srv-1', 'Cloud');- await seedServer('srv-2', 'Local dev');- await fixture.db.insert(workspaces).values([- { id: 'ws-a', serverId: 'srv-1', name: 'A', tenantId: 'tenant-a' },- { id: 'ws-b', serverId: 'srv-1', name: 'B', tenantId: 'tenant-b' },- { id: 'ws-c', serverId: 'srv-2', name: 'C', tenantId: 'tenant-c' },- ]);- await setActiveWorkspaceId('ws-c');-- await expect(requireWorkspaceForServer('srv-1')).rejects.toThrow('must name one');- });- });-- describe('renameServerWorkspaces', () => {- it('carries the new server name onto the workspace that took its name from it', async () => {- await seedServer('srv-1', 'Old name');- await ensureServerWorkspace({ id: 'srv-1', name: 'Old name' });-- await renameServerWorkspaces('srv-1', 'New name');-- expect((await listWorkspacesForServer('srv-1'))[0]!.name).toBe('New name');- });-- // Once matched to a tenant the name is the gateway's, not the server's.- it('leaves a tenant-bound workspace’s own name alone', async () => {- await seedServer('srv-1', 'Old name');- await fixture.db- .insert(workspaces)- .values({ id: 'ws-a', serverId: 'srv-1', name: 'Platform', tenantId: 'tenant-a' });-- await renameServerWorkspaces('srv-1', 'New name');-- expect((await listWorkspacesForServer('srv-1'))[0]!.name).toBe('Platform');- });- });-- describe('serverIdForWorkspace', () => {- it('finds the server hosting a workspace', async () => {- await seedServer('srv-1', 'Local dev');- const created = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });-- expect(await serverIdForWorkspace(created.id)).toBe('srv-1');- });-- it('answers null for an agent with no workspace', async () => {- expect(await serverIdForWorkspace(null)).toBeNull();- });- });-- describe('the active selection', () => {- it('round-trips a workspace id', async () => {- await seedServer('srv-1', 'Local dev');- const created = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });-- await setActiveWorkspaceId(created.id);-- expect(await getActiveWorkspaceId()).toBe(created.id);- });-- it('refuses to select a workspace that does not exist', async () => {- await expect(setActiveWorkspaceId('ws-missing')).rejects.toThrow('No workspace with id');- });-- // The selection is a plain kv value; nothing cascades to it when the- // server, and with it the workspace, is deleted.- it('is cleared when the server holding the selected workspace goes', async () => {- await seedServer('srv-1', 'Local dev');- const created = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });- await setActiveWorkspaceId(created.id);-- await clearActiveWorkspaceOnServer('srv-1');-- expect(await getActiveWorkspaceId()).toBeNull();- expect(await fixture.db.select().from(kv).where(eq(kv.key, 'activeWorkspaceId'))).toEqual([]);- });-- it('survives another server being removed', async () => {- await seedServer('srv-1', 'Local dev');- await seedServer('srv-2', 'Cloud');- const created = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });- await ensureServerWorkspace({ id: 'srv-2', name: 'Cloud' });- await setActiveWorkspaceId(created.id);-- await clearActiveWorkspaceOnServer('srv-2');-- expect(await getActiveWorkspaceId()).toBe(created.id);- });- });-- describe('requireWorkspace', () => {- it('names the id it could not find', async () => {- await expect(requireWorkspace('ws-missing')).rejects.toThrow(- 'No workspace with id ws-missing'- );- });- });-});diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/workspaces-store.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/workspaces-store.tsdeleted file mode 100644index 98686313f..000000000--- a/console/apps/switch-console-desktop/src/main/core/workspaces/workspaces-store.ts+++ /dev/null@@ -1,307 +0,0 @@-import { randomUUID } from 'node:crypto';-import { and, asc, eq, isNull, sql } from 'drizzle-orm';-import { db, type DrizzleTx } from '@main/db/client';-import { agents, kv, type WorkspaceRow, workspaces } from '@main/db/schema';-import type { Workspace, WorkspaceRole } from '@shared/core/workspaces/workspaces';--const ACTIVE_WORKSPACE_KV_KEY = 'activeWorkspaceId';--function mapRow(row: WorkspaceRow): Workspace {- return {- id: row.id,- serverId: row.serverId,- name: row.name,- tenantId: row.tenantId ?? null,- slug: row.slug ?? null,- role: row.role ?? null,- createdAt: row.createdAt,- updatedAt: row.updatedAt,- };-}--// `createdAt` is a one-second-granularity timestamp and a reconcile writes a-// server's rows in one loop, so ties are the norm rather than the exception. The-// id breaks them, because callers that take the first row — the one the window-// falls back to — must land on the same one every launch.-const workspaceOrder = [asc(workspaces.createdAt), asc(workspaces.id)];--export async function listWorkspaces(): Promise<Workspace[]> {- const rows = await db- .select()- .from(workspaces)- .orderBy(...workspaceOrder);- return rows.map(mapRow);-}--export async function listWorkspacesForServer(serverId: string): Promise<Workspace[]> {- const rows = await db- .select()- .from(workspaces)- .where(eq(workspaces.serverId, serverId))- .orderBy(...workspaceOrder);- return rows.map(mapRow);-}--export async function getWorkspace(id: string): Promise<Workspace | null> {- const [row] = await db.select().from(workspaces).where(eq(workspaces.id, id)).limit(1);- return row ? mapRow(row) : null;-}--export async function requireWorkspace(id: string): Promise<Workspace> {- const workspace = await getWorkspace(id);- if (!workspace) throw new Error(`No workspace with id ${id}`);- return workspace;-}--/**- * The workspace to act in on a server, for a caller that knows only the server- * — onboarding an agent, attaching one, discovering what a directory holds.- *- * Most servers carry exactly one workspace, and then there is nothing to- * choose. Where there are several, the answer is the one the window is scoped- * to: these callers are all driven from screens showing that workspace, so- * anything else would act somewhere the user is not looking.- *- * Raises rather than picking when neither applies. A server with no workspace- * is a registration that half-succeeded; a server with several, none of them- * the active one, means the caller is the one that has to say which — and- * attaching an agent to the wrong workspace is not something the user would see- * until it had already happened.- */-export async function requireWorkspaceForServer(serverId: string): Promise<Workspace> {- const found = await listWorkspacesForServer(serverId);- if (found.length === 1) return found[0]!;- if (found.length === 0) throw new Error(`Switch server ${serverId} has no workspace`);-- const activeId = await getActiveWorkspaceId();- const active = found.find((workspace) => workspace.id === activeId);- if (active) return active;- throw new Error(- `Switch server ${serverId} has ${found.length} workspaces and none of them is the active one; the caller must name one`- );-}--/**- * Give a newly registered server its workspace, reusing the one it already has.- *- * Registering a server is what creates its first workspace — the gateway is- * only asked which tenants the user belongs to afterwards, and the app has to- * be usable before that answer arrives. The row starts tenant-less and named- * after the server; a reconcile matches it to a tenant rather than replacing- * it, so the agents pointing at it stay pointed at it.- *- * Idempotent, because the managed-server paths run again on every restart of a- * stack that already exists. The read and the insert share one transaction, so- * two of those restarts overlapping cannot each find no row and each create- * one; the partial unique index on the table is the backstop for anything that- * writes outside this function.- */-export async function ensureServerWorkspace(server: {- id: string;- name: string;-}): Promise<Workspace> {- return db.transaction((tx) => {- const [existing] = tx- .select()- .from(workspaces)- .where(eq(workspaces.serverId, server.id))- .orderBy(...workspaceOrder)- .limit(1)- .all();- return existing ? mapRow(existing) : insertServerWorkspace(tx, server);- });-}--/**- * The insert half of `ensureServerWorkspace`, so a caller registering a server- * can create both rows in one transaction.- *- * A server row without a workspace cannot be used for anything — every path- * that reaches a gateway resolves a workspace first — and nothing outside- * registration creates one, so the two rows have to arrive together or not at- * all.- */-export function insertServerWorkspace(- tx: DrizzleTx,- server: { id: string; name: string }-): Workspace {- const [row] = tx- .insert(workspaces)- .values({- id: randomUUID(),- serverId: server.id,- name: server.name,- updatedAt: sql`CURRENT_TIMESTAMP`,- })- .returning()- .all();- return mapRow(row!);-}--/**- * Match a workspace row to the tenant it holds, and keep what the gateway owns- * about that tenant up to date.- *- * An update rather than a replacement, because the row's id is what the agents,- * the active selection and the saved navigation all point at — a new row for- * the same workspace would detach every one of them.- *- * The name comes over with the rest. A matched workspace is a tenant, the- * gateway is where it is named and renamed, and nothing in this app offers to- * name one — so the alternative is a local label that can never be corrected- * from either side. The row a server is registered with is named after the- * server only for as long as it belongs to no tenant.- */-export async function setWorkspaceTenant(- workspaceId: string,- tenant: { id: string; slug: string; name: string; role: WorkspaceRole }-): Promise<void> {- await db- .update(workspaces)- .set({- tenantId: tenant.id,- slug: tenant.slug,- name: tenant.name,- role: tenant.role,- updatedAt: sql`CURRENT_TIMESTAMP`,- })- .where(eq(workspaces.id, workspaceId));-}--/**- * Record that the account is no longer a member of a workspace it still holds a- * row for.- *- * The tenant id stays, because it is what the row's agents were registered- * against and what a restored membership would match it back to; only the role- * goes, since the gateway no longer reports one. A row naming a tenant with no- * role is what the switcher reads as withdrawn.- */-export async function clearWorkspaceRole(workspaceId: string): Promise<void> {- await db- .update(workspaces)- .set({ role: null, updatedAt: sql`CURRENT_TIMESTAMP` })- .where(eq(workspaces.id, workspaceId));-}--/**- * Whether any agent still belongs to a workspace.- *- * Asked of the tenant-less row a server is registered with, to tell a- * placeholder nothing was ever put in from the record of where a set of agents- * lives. The first can be given a membership or dropped; the second cannot be- * guessed at, because moving it would move those agents somewhere the user has- * no way to see.- */-export async function workspaceHasAgents(workspaceId: string): Promise<boolean> {- const [row] = await db- .select({ id: agents.id })- .from(agents)- .where(eq(agents.workspaceId, workspaceId))- .limit(1);- return row !== undefined;-}--/**- * Drop a workspace nothing points at, moving the active selection off it first.- *- * Only ever the placeholder row a server is registered with, and only once a- * reconcile has found that every membership the account holds is already held- * by another row — leaving it would put a workspace in the switcher that- * belongs to no membership at all. The caller checks it is empty first; the- * selection is a plain `kv` value that no foreign key reaches, so it has to be- * moved here rather than left pointing at a row that has gone.- */-export async function discardEmptyWorkspace(workspaceId: string): Promise<void> {- const workspace = await requireWorkspace(workspaceId);- const sibling = (await listWorkspacesForServer(workspace.serverId)).find(- (candidate) => candidate.id !== workspaceId- );- if (!sibling) throw new Error(`Workspace ${workspaceId} is the only one on its Switch server`);- if ((await getActiveWorkspaceId()) === workspaceId) await setActiveWorkspaceId(sibling.id);- await db.delete(workspaces).where(eq(workspaces.id, workspaceId));-}--/** Record a workspace the user belongs to that this install has no row for. */-export async function createTenantWorkspace(- serverId: string,- tenant: { id: string; slug: string; name: string; role: WorkspaceRole }-): Promise<Workspace> {- const [row] = await db- .insert(workspaces)- .values({- id: randomUUID(),- serverId,- name: tenant.name,- tenantId: tenant.id,- slug: tenant.slug,- role: tenant.role,- updatedAt: sql`CURRENT_TIMESTAMP`,- })- .returning();- return mapRow(row!);-}--/**- * Carry a server rename onto the workspaces that take their name from it.- *- * A tenant-less workspace has no name of its own — it was created named after- * its server and nothing else has supplied one. Once matched to a tenant the- * name is the gateway's, and a server rename must not overwrite it.- */-export async function renameServerWorkspaces(serverId: string, name: string): Promise<void> {- await db- .update(workspaces)- .set({ name, updatedAt: sql`CURRENT_TIMESTAMP` })- .where(and(eq(workspaces.serverId, serverId), isNull(workspaces.tenantId)));-}--/**- * The server hosting a workspace, or null when there is no workspace to ask- * about — an agent that has not been attached to one.- *- * A workspace id that names no row is a different thing entirely, and raises:- * the agents' foreign key means it cannot happen, so if it does the caller is- * holding an id from somewhere the database does not know about, and answering- * "no server" would send it on to fail somewhere further away.- */-export async function serverIdForWorkspace(workspaceId: string | null): Promise<string | null> {- if (!workspaceId) return null;- const [row] = await db- .select({ serverId: workspaces.serverId })- .from(workspaces)- .where(eq(workspaces.id, workspaceId))- .limit(1);- if (!row) throw new Error(`No workspace with id ${workspaceId}`);- return row.serverId;-}--export async function getActiveWorkspaceId(): Promise<string | null> {- const [row] = await db.select().from(kv).where(eq(kv.key, ACTIVE_WORKSPACE_KV_KEY)).limit(1);- return row?.value ?? null;-}--export async function setActiveWorkspaceId(id: string): Promise<void> {- await requireWorkspace(id);- await db- .insert(kv)- .values({ key: ACTIVE_WORKSPACE_KV_KEY, value: id, updatedAt: sql`CURRENT_TIMESTAMP` })- .onConflictDoUpdate({- target: kv.key,- set: { value: id, updatedAt: sql`CURRENT_TIMESTAMP` },- });-}--/**- * Drop the active selection if it names one of a server's workspaces.- *- * Removing a server takes its workspaces with it (the foreign key cascades),- * and the selection is a plain `kv` value that nothing cascades to — so it has- * to be cleared here, while the workspaces are still readable.- */-export async function clearActiveWorkspaceOnServer(serverId: string): Promise<void> {- const active = await getActiveWorkspaceId();- if (!active) return;- const onServer = (await listWorkspacesForServer(serverId)).some((w) => w.id === active);- if (onServer) await db.delete(kv).where(eq(kv.key, ACTIVE_WORKSPACE_KV_KEY));-}diff --git a/console/apps/switch-console-desktop/src/main/db/schema.ts b/console/apps/switch-console-desktop/src/main/db/schema.tsindex d88ef167d..05e3586f2 100644--- a/console/apps/switch-console-desktop/src/main/db/schema.ts+++ b/console/apps/switch-console-desktop/src/main/db/schema.ts@@ -4,18 +4,14 @@ import { versionedJsonColumn } from '@main/db/versioned-column';import { agentProviderConfig } from '@shared/core/agents/agent-provider-config';import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';import { sessionConfig } from '@shared/core/sessions/session-config';-import type { WorkspaceRole } from '@shared/core/workspaces/workspaces';// ---------------------------------------------------------------------------// Data model (Switch Console rework — diverges from upstream; see// agents/architecture/data-model.md for the full map)://-// switch_servers — a registered Switch gateway-// └─ workspaces — what the window is scoped to; one active at a time-//// locations — a working directory on a host (this machine or an SSH host)// └─ agents — a Switch agent identity (one provider each; many per-// │ location; belongs to one workspace)+// │ location)// └─ sessions — an instantiation/run of an agent (was "conversation";// │ one session == one terminal, folded in)// └─ messages@@ -86,11 +82,10 @@ export const appSettings = sqliteTable(/*** A Switch server: a gateway Switch Console can connect to. Switch Console is* multi-server — many gateways (a local dev one, a deployed pilot one) can be- * registered. What the window is scoped to is a workspace on one of them, not- * the server itself, so the active selection names a workspace (`kv`,- * `activeWorkspaceId`) and the server is read from it. The session JWT minted- * by the gateway is NOT stored here — it lives in the encrypted secrets store- * keyed by server id — so this table holds only non-secret connection+ * registered, and the UI works against one "active" server at a time (the+ * active id is tracked in `kv` under `activeSwitchServerId`). The session JWT+ * minted by the gateway is NOT stored here — it lives in the encrypted secrets+ * store keyed by server id — so this table holds only non-secret connection* metadata.*/export const switchServers = sqliteTable(@@ -130,66 +125,6 @@ export const switchServers = sqliteTable(}));-/**- * A workspace: the unit everything in the window is scoped to. A server hosts- * one or more of them, and exactly one workspace is active at a time (tracked- * in `kv` under `activeWorkspaceId`). Switching workspace swaps the whole- * window — agents, rooms, sidebar — the way switching server used to.- *- * `tenantId` is the workspace's id on the gateway. It is null only until the- * gateway has been asked: a workspace is created locally the moment a server is- * registered, because the app has to be usable before the answer arrives, and- * the upgrade to workspaces created one per already-registered server the same- * way. Every deployed Switch server has tenancy — the backend migration that- * introduced it puts every existing user in a tenant — so a tenant-less row is- * a workspace that has not reconciled yet, not a server without tenants.- *- * Reconcile therefore has to *match* that row to a tenant rather than insert- * the real workspace beside it: the row's id is what every agent points at, and- * the (server, tenant) unique index cannot catch a duplicate here because- * SQLite treats NULLs as distinct.- *- * `slug` is the gateway's handle for the workspace; null alongside a null- * `tenantId`.- */-export const workspaces = sqliteTable(- 'workspaces',- {- id: text('id').primaryKey(),- serverId: text('server_id')- .notNull()- .references(() => switchServers.id, { onDelete: 'cascade' }),- name: text('name').notNull(),- /** The workspace's id on the gateway; null when the server has no tenancy. */- tenantId: text('tenant_id'),- /** The gateway's slug for the workspace; null when it has no tenancy. */- slug: text('slug'),- /**- * The caller's role in the workspace as the gateway last reported it- * (`owner` / `admin` / `member`). Null for a tenant-less workspace, where- * the notion does not apply.- */- role: text('role').$type<WorkspaceRole>(),- createdAt: text('created_at')- .notNull()- .default(sql`CURRENT_TIMESTAMP`),- updatedAt: text('updated_at')- .notNull()- .default(sql`CURRENT_TIMESTAMP`),- },- (table) => ({- serverIdIdx: index('idx_workspaces_server_id').on(table.serverId),- serverTenantIdx: uniqueIndex('idx_workspaces_server_tenant').on(table.serverId, table.tenantId),- // A server has at most one unreconciled row. The index above cannot say so,- // because SQLite treats NULLs as distinct, so two registrations racing on- // the same server would each insert a placeholder and reconcile would only- // ever repair the first one it found.- serverPlaceholderIdx: uniqueIndex('idx_workspaces_server_placeholder')- .on(table.serverId)- .where(sql`tenant_id IS NULL`),- })-);-/*** A Switch agent: an agent identity bound to a single provider, living at a* location. Many agents may share a location (e.g. a Claude Code and a Codex@@ -197,10 +132,11 @@ export const workspaces = sqliteTable(* the location dir is configured as a Switch agent (detected from* `.claude/settings.local.json`); they are null for a plain local agent.*- * `workspaceId` binds the agent to the one workspace it belongs to, chosen and- * verified at onboarding rather than inferred. It is nullable: an agent whose- * workspace is gone is shown as "unlinked" rather than guessed, and removing a- * server sets its workspaces' agents to null instead of deleting them.+ * `serverId` binds the agent to the one registered Switch server it belongs to.+ * It is resolved by matching the detected `apiEndpoint` against the registered+ * servers' origins. It is nullable: an agent whose server is not (or no longer)+ * registered is shown as "unlinked" rather than guessed, and removing a server+ * sets its agents' `serverId` to null instead of deleting them.*/export const agents = sqliteTable('agents',@@ -217,7 +153,7 @@ export const agents = sqliteTable(providerId: text('provider_id').$type<AgentProviderId>().notNull(),switchAgentId: text('switch_agent_id'),apiEndpoint: text('api_endpoint'),- workspaceId: text('workspace_id').references(() => workspaces.id, { onDelete: 'set null' }),+ serverId: text('server_id').references(() => switchServers.id, { onDelete: 'set null' }),status: text('status'),// When set, Switch Console launches this agent's CLI with its auto-approve /// "bypass permissions" flag (e.g. `--dangerously-skip-permissions`).@@ -239,7 +175,7 @@ export const agents = sqliteTable(},(table) => ({locationIdIdx: index('idx_agents_location_id').on(table.locationId),- workspaceIdIdx: index('idx_agents_workspace_id').on(table.workspaceId),+ serverIdIdx: index('idx_agents_server_id').on(table.serverId),}));@@ -443,8 +379,6 @@ export type AppSecretRow = typeof appSecrets.$inferSelect;export type AppSecretInsert = typeof appSecrets.$inferInsert;export type SwitchServerRow = typeof switchServers.$inferSelect;export type SwitchServerInsert = typeof switchServers.$inferInsert;-export type WorkspaceRow = typeof workspaces.$inferSelect;-export type WorkspaceInsert = typeof workspaces.$inferInsert;export type RemoteHostRow = typeof remoteHosts.$inferSelect;export type RemoteHostInsert = typeof remoteHosts.$inferInsert;export type RemoteHostReachabilityRow = typeof remoteHostReachability.$inferSelect;diff --git a/console/apps/switch-console-desktop/src/main/db/tests/migrations/0051-workspaces.test.ts b/console/apps/switch-console-desktop/src/main/db/tests/migrations/0051-workspaces.test.tsdeleted file mode 100644index 34ca4f80d..000000000--- a/console/apps/switch-console-desktop/src/main/db/tests/migrations/0051-workspaces.test.ts+++ /dev/null@@ -1,356 +0,0 @@-/**- * Migration 0051 — introduces workspaces, the unit the window is scoped to, and- * moves agents from being owned by a server to being owned by a workspace.- *- * The upgrade has to be invisible: everyone currently has servers and no- * workspaces, so each server gets exactly one workspace reusing the server's id.- * That reuse is the whole backward-compatibility story — agent rows, the active- * selection in `kv`, and the opaque navigation snapshots all keep referring to- * the same string — so these tests pin it rather than just checking the table- * exists.- *- * The SQL is applied to a hand-built pre-0051 schema (the same approach as the- * 0047 test) because the committed fixtures have already been migrated past it.- */--import { readFileSync } from 'node:fs';-import path from 'node:path';-import { fileURLToPath } from 'node:url';-import Database from 'better-sqlite3';-import { afterEach, beforeEach, describe, expect, it } from 'vitest';--const MIGRATION_SQL = readFileSync(- path.resolve(- path.dirname(fileURLToPath(import.meta.url)),- '../../../../../drizzle/0051_workspaces.sql'- ),- 'utf8'-);--type WorkspaceRow = {- id: string;- server_id: string;- name: string;- tenant_id: string | null;- slug: string | null;- role: string | null;-};--describe('migration 0051: workspaces', () => {- let db: Database.Database;-- beforeEach(() => {- db = new Database(':memory:');- db.exec(`- CREATE TABLE switch_servers (- id TEXT PRIMARY KEY NOT NULL,- name TEXT NOT NULL,- gateway_url TEXT NOT NULL,- api_url TEXT NOT NULL,- managed INTEGER NOT NULL DEFAULT 0,- management_kind TEXT,- ssh_host TEXT,- created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,- updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP- );- CREATE TABLE locations (- id TEXT PRIMARY KEY NOT NULL,- name TEXT NOT NULL- );- INSERT INTO locations (id, name) VALUES ('loc-1', 'repo');- -- Mirrors the real pre-0051 agents DDL, foreign keys included. The- -- columns are not incidental: server_id carrying an FK is exactly why the- -- migration has to recreate the table instead of dropping the column.- CREATE TABLE agents (- id TEXT PRIMARY KEY NOT NULL,- location_id TEXT NOT NULL,- name TEXT NOT NULL,- provider_id TEXT NOT NULL,- switch_agent_id TEXT,- api_endpoint TEXT,- server_id TEXT,- status TEXT,- auto_approve INTEGER DEFAULT false NOT NULL,- owner_name TEXT,- provider_config TEXT,- created_at TEXT DEFAULT CURRENT_TIMESTAMP NOT NULL,- updated_at TEXT DEFAULT CURRENT_TIMESTAMP NOT NULL,- FOREIGN KEY (location_id) REFERENCES locations(id),- FOREIGN KEY (server_id) REFERENCES switch_servers(id) ON DELETE SET NULL- );- CREATE INDEX idx_agents_location_id ON agents (location_id);- CREATE INDEX idx_agents_server_id ON agents (server_id);- CREATE TABLE kv (- key TEXT PRIMARY KEY NOT NULL,- value TEXT NOT NULL,- updated_at INTEGER NOT NULL DEFAULT 0- );- `);- });-- afterEach(() => {- db.close();- });-- function seedServer(id: string, name: string): void {- db.prepare(- `INSERT INTO switch_servers (id, name, gateway_url, api_url) VALUES (?, ?, ?, ?)`- ).run(id, name, `https://${id}.example`, `https://${id}.example:8000`);- }-- function seedAgent(id: string, serverId: string | null): void {- db.prepare(- `INSERT INTO agents (id, location_id, name, provider_id, server_id) VALUES (?, 'loc-1', ?, 'claude', ?)`- ).run(id, id, serverId);- }-- function applyMigration(): void {- for (const stmt of MIGRATION_SQL.split('--> statement-breakpoint')) {- const trimmed = stmt.trim();- if (trimmed) db.exec(trimmed);- }- }-- function workspaces(): WorkspaceRow[] {- return db.prepare(`SELECT * FROM workspaces ORDER BY name`).all() as WorkspaceRow[];- }-- it('gives every existing server exactly one workspace, named after it', () => {- seedServer('srv-local', 'Local dev');- seedServer('srv-cloud', 'Switch Cloud');-- applyMigration();-- expect(workspaces().map((w) => [w.server_id, w.name])).toEqual([- ['srv-local', 'Local dev'],- ['srv-cloud', 'Switch Cloud'],- ]);- });-- it('reuses the server id as the workspace id, so persisted ids stay valid', () => {- seedServer('srv-local', 'Local dev');-- applyMigration();-- const [workspace] = workspaces();- expect(workspace!.id).toBe('srv-local');- });-- // No gateway is asked during the upgrade — it must not depend on one being- // reachable — so the tenant is filled in by the first reconcile, not here.- it('leaves the migrated workspaces tenant-less for the first reconcile to match', () => {- seedServer('srv-local', 'Local dev');-- applyMigration();-- const [workspace] = workspaces();- expect(workspace!.tenant_id).toBeNull();- expect(workspace!.slug).toBeNull();- expect(workspace!.role).toBeNull();- });-- it("moves each agent onto its server's workspace", () => {- seedServer('srv-local', 'Local dev');- seedServer('srv-cloud', 'Switch Cloud');- seedAgent('agent-a', 'srv-local');- seedAgent('agent-b', 'srv-cloud');-- applyMigration();-- const rows = db.prepare(`SELECT id, workspace_id FROM agents ORDER BY id`).all() as {- id: string;- workspace_id: string | null;- }[];- expect(rows).toEqual([- { id: 'agent-a', workspace_id: 'srv-local' },- { id: 'agent-b', workspace_id: 'srv-cloud' },- ]);- });-- it('keeps an unlinked agent unlinked rather than guessing a workspace for it', () => {- seedServer('srv-local', 'Local dev');- seedAgent('agent-unlinked', null);-- applyMigration();-- const row = db- .prepare(`SELECT workspace_id FROM agents WHERE id = ?`)- .get('agent-unlinked') as {- workspace_id: string | null;- };- expect(row.workspace_id).toBeNull();- });-- // The old server_id was added by ALTER TABLE ADD COLUMN, which in SQLite- // cannot carry ON DELETE, so its set-null was never enforced and a row can- // point at a server that is gone. Carrying that value over would seed the new,- // engine-enforced foreign key with a violation, and the migration runs with- // foreign_keys=OFF, so nothing would catch it until much later.- it('drops an agent’s link to a server that no longer exists', () => {- seedServer('srv-local', 'Local dev');- seedAgent('agent-a', 'srv-local');- // The dangling value has to be written with the constraint off, which is- // how it arises: the real column was added by ALTER TABLE, so the engine- // never enforced the clause this fixture's DDL can only state up front.- db.exec('PRAGMA foreign_keys = OFF');- db.prepare(`UPDATE agents SET server_id = 'srv-gone' WHERE id = 'agent-a'`).run();-- applyMigration();- db.exec('PRAGMA foreign_keys = ON');-- const row = db.prepare(`SELECT workspace_id FROM agents WHERE id = 'agent-a'`).get() as {- workspace_id: string | null;- };- expect(row.workspace_id).toBeNull();- expect(db.prepare(`PRAGMA foreign_key_check`).all()).toEqual([]);- });-- it('carries every other agent column through the table rebuild', () => {- seedServer('srv-local', 'Local dev');- db.prepare(- `INSERT INTO agents (id, location_id, name, provider_id, switch_agent_id, api_endpoint, server_id, status, auto_approve, owner_name, provider_config)- VALUES ('agent-a', 'loc-1', 'Worker', 'codex', 'switch-123', 'https://api.example', 'srv-local', 'live', 1, 'owner-1', '{"v":1}')`- ).run();-- applyMigration();-- const row = db.prepare(`SELECT * FROM agents WHERE id = 'agent-a'`).get() as Record<- string,- unknown- >;- expect(row).toMatchObject({- location_id: 'loc-1',- name: 'Worker',- provider_id: 'codex',- switch_agent_id: 'switch-123',- api_endpoint: 'https://api.example',- workspace_id: 'srv-local',- status: 'live',- auto_approve: 1,- owner_name: 'owner-1',- provider_config: '{"v":1}',- });- });-- it('keeps the location foreign key working after the rebuild', () => {- seedServer('srv-local', 'Local dev');- seedAgent('agent-a', 'srv-local');-- applyMigration();- db.exec('PRAGMA foreign_keys = ON');-- expect(() =>- db- .prepare(`INSERT INTO agents (id, location_id, name, provider_id) VALUES (?, ?, ?, ?)`)- .run('agent-b', 'loc-missing', 'B', 'claude')- ).toThrow(/FOREIGN KEY/);- });-- it('drops the old server column so nothing can keep reading it', () => {- seedServer('srv-local', 'Local dev');-- applyMigration();-- const columns = (db.prepare(`PRAGMA table_info('agents')`).all() as { name: string }[]).map(- (c) => c.name- );- expect(columns).toContain('workspace_id');- expect(columns).not.toContain('server_id');- });-- it('carries the active selection over, so the app opens where it was left', () => {- seedServer('srv-local', 'Local dev');- db.prepare(`INSERT INTO kv (key, value) VALUES ('activeSwitchServerId', 'srv-local')`).run();-- applyMigration();-- const active = db.prepare(`SELECT value FROM kv WHERE key = 'activeWorkspaceId'`).get() as- | { value: string }- | undefined;- expect(active?.value).toBe('srv-local');-- const stale = db.prepare(`SELECT value FROM kv WHERE key = 'activeSwitchServerId'`).get();- expect(stale).toBeUndefined();- });-- it('survives an install that had no active selection recorded', () => {- seedServer('srv-local', 'Local dev');-- applyMigration();-- const active = db.prepare(`SELECT value FROM kv WHERE key = 'activeWorkspaceId'`).get();- expect(active).toBeUndefined();- });-- it('survives a fresh install with no servers at all', () => {- applyMigration();-- expect(workspaces()).toEqual([]);- });-- it('removes a server’s workspaces with it', () => {- seedServer('srv-local', 'Local dev');- applyMigration();- db.exec('PRAGMA foreign_keys = ON');-- db.prepare(`DELETE FROM switch_servers WHERE id = ?`).run('srv-local');-- expect(workspaces()).toEqual([]);- });-- // Two foreign keys deep, and the one the old schema only claimed: the server's- // workspaces cascade away, and their agents are unlinked rather than deleted.- it('unlinks an agent when the server under its workspace is deleted', () => {- seedServer('srv-local', 'Local dev');- seedAgent('agent-a', 'srv-local');- applyMigration();- db.exec('PRAGMA foreign_keys = ON');-- db.prepare(`DELETE FROM switch_servers WHERE id = ?`).run('srv-local');-- const row = db.prepare(`SELECT workspace_id FROM agents WHERE id = 'agent-a'`).get() as {- workspace_id: string | null;- };- expect(row.workspace_id).toBeNull();- });-- it('lets two servers each keep a tenant-less workspace', () => {- seedServer('srv-a', 'A');- seedServer('srv-b', 'B');-- applyMigration();-- expect(workspaces()).toHaveLength(2);- });-- it('refuses two workspaces with the same tenant on one server', () => {- seedServer('srv-cloud', 'Switch Cloud');- applyMigration();-- const insert = (id: string, tenantId: string) =>- db- .prepare(`INSERT INTO workspaces (id, server_id, name, tenant_id) VALUES (?, ?, ?, ?)`)- .run(id, 'srv-cloud', id, tenantId);-- insert('ws-1', 'tenant-1');- expect(() => insert('ws-2', 'tenant-1')).toThrow(/UNIQUE/);- });-- it('allows the same tenant id on two different servers', () => {- seedServer('srv-a', 'A');- seedServer('srv-b', 'B');- applyMigration();-- db.prepare(`INSERT INTO workspaces (id, server_id, name, tenant_id) VALUES (?, ?, ?, ?)`).run(- 'ws-a',- 'srv-a',- 'Shared',- 'tenant-1'- );- expect(() =>- db- .prepare(`INSERT INTO workspaces (id, server_id, name, tenant_id) VALUES (?, ?, ?, ?)`)- .run('ws-b', 'srv-b', 'Shared', 'tenant-1')- ).not.toThrow();- });-});diff --git a/console/apps/switch-console-desktop/src/main/db/tests/migrations/journal-registration.test.ts b/console/apps/switch-console-desktop/src/main/db/tests/migrations/journal-registration.test.tsindex ab2311463..75ea22dd6 100644--- a/console/apps/switch-console-desktop/src/main/db/tests/migrations/journal-registration.test.ts+++ b/console/apps/switch-console-desktop/src/main/db/tests/migrations/journal-registration.test.ts@@ -25,10 +25,6 @@ const journalTags = journal.entries.map((entry) => entry.tag);const sqlTags = readdirSync(drizzleDir).filter((name) => name.endsWith('.sql')).map((name) => name.replace(/\.sql$/, ''));-const snapshotIndices = readdirSync(`${drizzleDir}/meta`)- .map((name) => /^(\d+)_snapshot\.json$/.exec(name))- .filter((match) => match !== null)- .map((match) => Number(match[1]));describe('migration journal registration', () => {it('finds the migration files at all, so the checks below are not vacuous', () => {@@ -46,23 +42,6 @@ describe('migration journal registration', () => {expect(missing).toEqual([]);});- /**- * A hand-written migration is easy to commit without one, and nothing at- * runtime notices: the runner reads the journal and the `.sql`, never `meta/`.- *- * drizzle-kit does, and it takes the *highest-numbered snapshot file* as the- * state to diff against rather than the last journal entry — a gap is not an- * error it reports. So the next `db:generate` diffs the schema against the- * last snapshot before the gap and re-emits everything since as one new- * migration. On any machine that already ran the missing one, that lands as- * `table workspaces already exists`, and it takes `db:fixtures` with it.- */- it('has a meta snapshot for every journal entry', () => {- const missing = journal.entries.filter((entry) => !snapshotIndices.includes(entry.idx));-- expect(missing.map((entry) => entry.tag)).toEqual([]);- });-it('numbers journal entries contiguously from zero', () => {// A gap means an entry was hand-edited out; a duplicate means two branches// claimed the same number and the merge kept both.diff --git a/console/apps/switch-console-desktop/src/main/index.ts b/console/apps/switch-console-desktop/src/main/index.tsindex 3e697c980..a21936552 100644--- a/console/apps/switch-console-desktop/src/main/index.ts+++ b/console/apps/switch-console-desktop/src/main/index.ts@@ -13,6 +13,7 @@ import { createMainWindow, getMainWindow } from './app/window';import { bridgeAgentEventsToRenderer } from './core/agents/agent-events-renderer-bridge';import { migrateAgentStorage } from './core/agents/migrate-agent-storage';import { initializeRemoteDiscovery, initializeRemoteWatchers } from './core/agents/remote-watcher';+import { resolveAgentServers } from './core/agents/resolve-servers';import { appService } from './core/app/service';import { controlService } from './core/control-api/control-service';import { localDependencyManager } from './core/dependencies/dependency-managers';@@ -35,7 +36,6 @@ import { registerTelemetryListeners } from './core/telemetry/telemetry-listenersimport { trackEvent } from './core/telemetry/telemetry-service';import { updateService } from './core/updates/update-service';import { viewStateService } from './core/view-state/view-state-service';-import { reconcileAllWorkspaces } from './core/workspaces/reconcile-workspaces';import { initializeDatabase } from './db/initialize';import { logAppExit, logAppStart, registerAppDiagnostics } from './lib/app-diagnostics';import {@@ -144,6 +144,12 @@ void app.whenReady().then(async () => {registerTelemetryListeners();trackEvent('app_launched', {});+ try {+ await resolveAgentServers();+ } catch (e) {+ log.warn('switch-agents: failed to reconcile agent → server links at boot', { error: e });+ }+// Kept off the boot path: this can open an SSH/SFTP connection per remote// agent, so awaiting it here delayed the window opening. Session relaunch below// waits on it (it needs each agent's definitionName); nothing else does.@@ -161,23 +167,10 @@ void app.whenReady().then(async () => {// Reflect a managed local Switch stack that survived the last quit, so the UI// shows it running without the user restarting it.- const localServerReady = localServerService.initialize();+ void localServerService.initialize();// Re-establish desktop-side forwards for remote-managed stacks that survived// the last quit, restoring their reachability from this machine.- const remoteServerReady = remoteServerService.initialize();-- // A server registered before its account's memberships were known carries one- // tenant-less workspace; this is what gives it its tenant, and what notices a- // membership added or withdrawn since the last launch. It runs after the two- // services above because they are what make a stack that survived the last- // quit report itself as running — before them every managed server still- // looks stopped and would be passed over. Unawaited: it talks to every- // signed-in server, and the window must not wait on any of them.- void Promise.allSettled([localServerReady, remoteServerReady])- .then(reconcileAllWorkspaces)- .catch((error: unknown) => {- log.error('Workspace reconcile could not run; every server was left as it was:', error);- });+ void remoteServerService.initialize();const dependenciesReady = localDependencyManager.probeAll().catch((e: unknown) => {log.error('Failed to probe dependencies:', e);diff --git a/console/apps/switch-console-desktop/src/main/rpc.ts b/console/apps/switch-console-desktop/src/main/rpc.tsindex 68a133597..4893c74dd 100644--- a/console/apps/switch-console-desktop/src/main/rpc.ts+++ b/console/apps/switch-console-desktop/src/main/rpc.ts@@ -7,7 +7,6 @@ import { filesController } from './core/fs/controller';import { locationsController } from './core/locations/controller';import { localSwitchServerController } from './core/managed-switch-server/controller';import { remoteSwitchServerController } from './core/managed-switch-server/remote-controller';-import { onboardingController } from './core/onboarding/controller';import { providersController } from './core/providers/controller';import { remoteHostsController } from './core/remote-hosts/controller';import { resourceMonitorController } from './core/resource-monitor/controller';@@ -21,7 +20,6 @@ import { switchServersController } from './core/switch-servers/controller';import { telemetryController } from './core/telemetry/controller';import { updateController } from './core/updates/controller';import { viewStateController } from './core/view-state/controller';-import { workspacesController } from './core/workspaces/controller';export const rpcRouter = createRPCRouter({sdkHost: sdkHostController,@@ -39,8 +37,6 @@ export const rpcRouter = createRPCRouter({switchRooms: switchRoomsController,switchServers: switchServersController,agentTypes: agentTypesController,- workspaces: workspacesController,- onboarding: onboardingController,localSwitchServer: localSwitchServerController,remoteSwitchServer: remoteSwitchServerController,remoteHosts: remoteHostsController,diff --git a/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts b/console/apps/switch-console-desktop/src/renderer/app/modal-registry.tsindex e3abd6080..b94ed44bb 100644--- a/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts+++ b/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts@@ -20,7 +20,6 @@ import { DeleteServerModal } from '@renderer/features/switch-servers/DeleteServeimport { DisconnectMessagingAppModal } from '@renderer/features/switch-servers/DisconnectMessagingAppModal';import { RenameServerModal } from '@renderer/features/switch-servers/RenameServerModal';import { SaveTemplateModal } from '@renderer/features/templates/save-template-modal';-import { CreateWorkspaceModal } from '@renderer/features/workspaces/create-workspace-modal';import { ConfirmActionDialog } from '@renderer/lib/components/confirm-action-dialog';import { ExternalLinkChoiceDialog } from '@renderer/lib/components/external-link-choice-dialog';import { UnsavedChangesDialog } from '@renderer/lib/components/unsaved-changes-dialog';@@ -66,10 +65,6 @@ export const modalRegistry = {}),deleteSessionModal: createModal(DeleteSessionModal, { size: 'sm' }),addServerModal: createModal(AddServerModal, { size: 'md', dismissOnOutsideClick: false }),- createWorkspaceModal: createModal(CreateWorkspaceModal, {- size: 'md',- dismissOnOutsideClick: false,- }),addHostModal: createModal(AddHostModal, { size: 'md', dismissOnOutsideClick: false }),assignServerModal: createModal(AssignServerModal, { size: 'sm', dismissOnOutsideClick: false }),renameServerModal: createModal(RenameServerModal, {diff --git a/console/apps/switch-console-desktop/src/renderer/app/shell-shape.test.ts b/console/apps/switch-console-desktop/src/renderer/app/shell-shape.test.tsdeleted file mode 100644index 204e09326..000000000--- a/console/apps/switch-console-desktop/src/renderer/app/shell-shape.test.ts+++ /dev/null@@ -1,89 +0,0 @@-import { describe, expect, it } from 'vitest';-import { shellShape } from './shell-shape';--/**- * The window has two shapes and what the install holds picks between them. Both- * wrong answers are bad in a way a layout bug is not: onboarding shown to- * someone who has an install hides it behind a first-run page, and the- * workspace shown on a fresh install is a sidebar listing nothing.- */--/**- * A loaded, empty, undisturbed install — the fresh-install case. Each test- * below names only what it changes about it.- */-function shape(differences: Partial<Parameters<typeof shellShape>[0]>) {- return shellShape({- loaded: true,- listError: null,- installIsEmpty: true,- viewWorksWithoutServer: false,- onboardingInProgress: false,- ...differences,- });-}--describe('what fills the window', () => {- it('waits rather than guessing before anything has been read', () => {- // The trap: an install with five servers looks exactly like a fresh one- // until the read comes back, because neither has answered yet.- expect(shape({ loaded: false, installIsEmpty: false })).toBe('loading');- });-- it('onboards only once the install is known to be empty', () => {- expect(shape({})).toBe('onboarding');- });-- /**- * "Something to show" is not "a server". Removing one says in as many words- * that its agents are kept and can be re-linked elsewhere, so an install left- * with agents and no server still has a window's worth of content — and the- * sessions in those agents are still running behind it.- */- it('shows the workspace as soon as there is anything to show', () => {- expect(shape({ installIsEmpty: false })).toBe('workspace');- });-- it('lets a view that needs no server out of the onboarding page', () => {- // Settings and the remote hosts are views, so only the workspace can draw- // them, and the onboarding page carries no chrome of its own. Holding the- // window on it would leave ⌘, and the Preferences menu item doing nothing.- expect(shape({ viewWorksWithoutServer: true })).toBe('workspace');- });-- /**- * Settings is where the logs and the database are, so a failed first read is- * precisely when it has to be reachable — and it needs nothing from the read- * to draw. Ordering this after the load gate would leave ⌘, and Preferences- * doing nothing in the one state that calls for them.- */- it('draws such a view even when nothing could be read', () => {- expect(shape({ loaded: false, viewWorksWithoutServer: true })).toBe('workspace');- expect(- shape({ loaded: false, listError: 'Could not load', viewWorksWithoutServer: true })- ).toBe('workspace');- });-- it('stays on the first-run pages once the flow has added the server', () => {- // The flow adds the server pages before it is done with it — signing in and- // linking accounts both come after. Going by the contents alone would throw- // the user out of the flow at the moment it half-succeeded.- expect(shape({ installIsEmpty: false, onboardingInProgress: true })).toBe('onboarding');- });-- it('still lets such a view out of a flow in progress', () => {- expect(shape({ onboardingInProgress: true, viewWorksWithoutServer: true })).toBe('workspace');- });-- it('says a first read failed instead of staying blank', () => {- // Otherwise the failure is indistinguishable from the blank first frame and- // the window just never fills.- expect(shape({ loaded: false, listError: 'Could not load' })).toBe('failed');- });-- it('keeps the workspace when a later read fails', () => {- // The list in hand is still the list; a failed refresh is not a reason to- // take the app away from someone using it.- expect(shape({ listError: 'Could not load', installIsEmpty: false })).toBe('workspace');- });-});diff --git a/console/apps/switch-console-desktop/src/renderer/app/shell-shape.ts b/console/apps/switch-console-desktop/src/renderer/app/shell-shape.tsdeleted file mode 100644index 5f9d0aec8..000000000--- a/console/apps/switch-console-desktop/src/renderer/app/shell-shape.ts+++ /dev/null@@ -1,70 +0,0 @@-/** Which of the window's shapes what this install holds implies. */-export type ShellShape = 'loading' | 'failed' | 'onboarding' | 'workspace';--/**- * Decide what fills the window from what is known about this install.- *- * Separated from the component because the wrong answer here is not a layout- * bug — `onboarding` shown to someone who has an install hides the whole of it- * behind a first-run page, and `workspace` shown on a fresh one is a sidebar- * listing nothing. The inputs are easy to get the wrong way round, so they are- * decided in one place that can be exercised directly.- *- * `loaded` is what separates an empty install from one that has not been asked- * yet; both leave `installIsEmpty` false.- */-export function shellShape({- loaded,- listError,- installIsEmpty,- viewWorksWithoutServer,- onboardingInProgress,-}: {- loaded: boolean;- /**- * The list read's own failure, not the store's shared error slot — every- * action in that store writes the shared one, and a rename that went wrong- * is not a reason to put the whole window into its failure shape.- *- * It must also outlive a retry rather than being cleared as one starts:- * otherwise pressing "Try again" takes the failure page off screen, and the- * button with it, for as long as the retry runs.- */- listError: string | null;- /**- * Whether this install holds nothing at all — no server, no location, no- * agent.- *- * Not "has no server". Removing a server keeps its agents and says so in the- * confirmation, and the sessions running in them carry on; reading that as a- * fresh install would hide all of it behind a welcome page, permanently and- * across relaunches.- */- installIsEmpty: boolean;- /**- * Whether what is on screen can be drawn with no server behind it.- *- * The way out of the onboarding page for the views that do not describe a- * server. Without one, ⌘, and the Preferences menu item do nothing on a- * fresh install. Each view says this about itself rather than being named- * here, so the next one of the same kind is not missed.- */- viewWorksWithoutServer: boolean;- /** Whether the first-run flow has been started and not yet finished. */- onboardingInProgress: boolean;-}): ShellShape {- // Checked before the read, not after. Such a view needs nothing from this- // install to draw, and a first read that failed is exactly when Settings —- // its logs, its database — is where the user has to be able to get to.- if (viewWorksWithoutServer) return 'workspace';- // A failed read that nevertheless loaded once keeps the workspace: the list- // in hand is still the list, and a later refresh failing is not a reason to- // take the app away.- if (!loaded) return listError === null ? 'loading' : 'failed';- // A flow in progress outranks what the install holds, because the flow is- // what changes it: the server is added several pages before the user has- // signed in to it, and going by the contents alone would throw them out of- // the flow at the moment it half-succeeded.- if (onboardingInProgress) return 'onboarding';- return installIsEmpty ? 'onboarding' : 'workspace';-}diff --git a/console/apps/switch-console-desktop/src/renderer/app/view-registry.ts b/console/apps/switch-console-desktop/src/renderer/app/view-registry.tsindex e94190add..fbd991036 100644--- a/console/apps/switch-console-desktop/src/renderer/app/view-registry.ts+++ b/console/apps/switch-console-desktop/src/renderer/app/view-registry.ts@@ -58,28 +58,12 @@ export type ViewDefinition<TParams extends object = Record<never, never>> = {* by older builds, so each guard must validate the shape before using it.*/canActivate?: (params: unknown) => GuardResult;- /**- * Set on a view that has something to show with no Switch server registered- * at all — Settings, the remote hosts. Everything else describes a server,- * or a workspace on one, and has nothing to draw without one.- *- * The shell reads it to decide whether the first-run page may be stepped out- * of. It lives on the view because only the view knows: a list of ids in the- * shell is a list someone has to remember to add to.- */- worksWithoutServer?: boolean;};type Views = typeof views;export type ViewId = keyof Views;-/** Whether the view on screen can be drawn before any server is registered. */-export function viewWorksWithoutServer(viewId: ViewId): boolean {- const view: Pick<ViewDefinition, 'MainPanel' | 'worksWithoutServer'> = views[viewId];- return view.worksWithoutServer === true;-}-/*** The registry and the shared list of view ids say the same thing.*diff --git a/console/apps/switch-console-desktop/src/renderer/app/workspace.tsx b/console/apps/switch-console-desktop/src/renderer/app/workspace.tsxindex cb2f395c4..648f23619 100644--- a/console/apps/switch-console-desktop/src/renderer/app/workspace.tsx+++ b/console/apps/switch-console-desktop/src/renderer/app/workspace.tsx@@ -1,130 +1,36 @@-import { observer } from 'mobx-react-lite';-import { useEffect, type ReactNode } from 'react';-import { OnboardingFlow } from '@renderer/features/onboarding/onboarding-flow';-import { onboardingStore } from '@renderer/features/onboarding/onboarding-store';import { LeftSidebar } from '@renderer/features/sidebar/left-sidebar';import { RoomEmbedLayer } from '@renderer/features/switch-rooms/room-embed-layer';-import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';import { CommandShortcutBinder } from '@renderer/lib/commands/command-shortcut-binder';import { AppKeyboardShortcuts } from '@renderer/lib/components/app-keyboard-shortcuts';import { MonacoKeyboardBridge } from '@renderer/lib/components/monaco-keyboard-bridge';import { useTheme } from '@renderer/lib/hooks/useTheme';-import { useCurrentViewId, useWorkspaceWrapParams } from '@renderer/lib/layout/navigation-provider';+import { useWorkspaceWrapParams } from '@renderer/lib/layout/navigation-provider';import { WorkspaceContentLayout, WorkspaceLayout } from '@renderer/lib/layout/workspace-layout';import { useWorkspaceSlots } from '@renderer/lib/layout/workspace-slots';-import { Button } from '@renderer/lib/ui/button';-import { Spinner } from '@renderer/lib/ui/spinner';import { Toaster } from '@renderer/lib/ui/toaster';-import { shellShape } from './shell-shape';-import { viewWorksWithoutServer } from './view-registry';-/**- * What fills the window.- *- * Two shapes, not one: the workspace — sidebar, views, the room layer — and the- * onboarding flow that takes the whole window before there is any server to- * show. The choice is made here rather than inside a view because it is the- * chrome itself that differs; an onboarding page rendered into the workspace- * would sit beside a sidebar listing nothing.- *- * The server list is read here for the same reason. It used to be loaded by the- * sidebar, which is no longer always mounted, and the shell cannot ask a- * component it may not render which shape to take.- */-export const Workspace = observer(function Workspace() {+export function Workspace() {useTheme();const { WrapView } = useWorkspaceSlots();const { wrapParams } = useWorkspaceWrapParams();- useEffect(() => {- void switchServersStore.init();- }, []);-return (<><AppKeyboardShortcuts /><CommandShortcutBinder /><MonacoKeyboardBridge />- <Shell+ <WorkspaceLayout+ leftSidebar={<LeftSidebar />}mainContent={<WrapView {...wrapParams}><WorkspaceViewContent /></WrapView>}+ persistentLayer={<RoomEmbedLayer />}/><Toaster /></>);-});--const Shell = observer(function Shell({ mainContent }: { mainContent: ReactNode }) {- const currentViewId = useCurrentViewId();- const shape = shellShape({- loaded: switchServersStore.loaded,- listError: switchServersStore.listError,- installIsEmpty: switchServersStore.installIsEmpty,- viewWorksWithoutServer: viewWorksWithoutServer(currentViewId),- onboardingInProgress: onboardingStore.inProgress,- });-- switch (shape) {- // Nothing on screen rather than a spinner: this is one or two local IPC- // round-trips, and a spinner that flashes is worse than a beat of window.- case 'loading':- return null;- case 'failed':- return (- <ShellFailure- message={switchServersStore.listError ?? 'Could not load your Switch servers.'}- detail={switchServersStore.listErrorDetail}- retrying={switchServersStore.loadingServers}- />- );- case 'onboarding':- return <OnboardingFlow />;- case 'workspace':- return (- <WorkspaceLayout- leftSidebar={<LeftSidebar />}- mainContent={mainContent}- persistentLayer={<RoomEmbedLayer />}- />- );- }-});--/**- * The window when the first read of the server list failed.- *- * A retry runs on this page rather than replacing it. The read clears nothing- * as it starts, so the message, the detail and the button all stay put and the- * button says it is working — otherwise pressing it would unmount the only- * thing on screen and leave a blank window for as long as the retry took.- */-function ShellFailure({- message,- detail,- retrying,-}: {- message: string;- detail: string | null;- retrying: boolean;-}) {- return (- <div className="flex h-full flex-col items-center justify-center gap-3 bg-background p-8 text-center [-webkit-app-region:drag]">- <p className="text-sm text-foreground">{message}</p>- {detail && <p className="max-w-md text-xs text-foreground-muted">{detail}</p>}- <Button- className="[-webkit-app-region:no-drag]"- variant="outline"- disabled={retrying}- onClick={() => void switchServersStore.init()}- >- {retrying && <Spinner size="sm" className="mr-2" />}- {retrying ? 'Trying again…' : 'Try again'}- </Button>- </div>- );}function WorkspaceViewContent() {diff --git a/console/apps/switch-console-desktop/src/renderer/features/command-palette/command-palette-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/command-palette/command-palette-modal.tsxindex ee6c0ebdf..42ee93357 100644--- a/console/apps/switch-console-desktop/src/renderer/features/command-palette/command-palette-modal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/command-palette/command-palette-modal.tsx@@ -16,7 +16,7 @@ import { useDebounce } from '@renderer/lib/hooks/useDebounce';import { getEffectiveHotkey } from '@renderer/lib/hooks/useKeyboardShortcuts';import { rpc } from '@renderer/lib/ipc';import { useNavigate } from '@renderer/lib/layout/navigation-provider';-import { scopeToLocationWorkspace } from '@renderer/lib/layout/scope-to-workspace';+import { scopeToLocationServer } from '@renderer/lib/layout/scope-to-server';import { type BaseModalProps } from '@renderer/lib/modal/modal-provider';import { appState, sidebarStore } from '@renderer/lib/stores/app-state';import { report } from '@renderer/lib/telemetry/report';@@ -194,7 +194,7 @@ export function CommandPaletteModal({// Search spans every server, but the sidebar only loads the one it is showing// — so the others' rooms are pulled here, by the feature that needs them.useEffect(() => {- void switchRoomsStore.loadRoomsInAllWorkspaces();+ void switchRoomsStore.loadRoomsOnAllServers();}, []);// Prefetch recents immediately on mount so the empty-query view is instant.@@ -272,7 +272,7 @@ export function CommandPaletteModal({// span every server, not the active one: you search precisely because you do// not know where a thing is.const roomResults = useObserver(() =>- matchRooms(switchRoomsStore.listedRoomsInAllWorkspaces, debouncedQuery)+ matchRooms(switchRoomsStore.listedRoomsOnAllServers, debouncedQuery));const serverResults = useObserver(() => matchServers(switchServersStore.servers, debouncedQuery));@@ -325,7 +325,7 @@ export function CommandPaletteModal({if (!item.locationId) return;const locationId = item.locationId;handleClose();- void scopeToLocationWorkspace(locationId).then(() =>+ void scopeToLocationServer(locationId).then(() =>navigate('session', { locationId, sessionId: item.id }));};@@ -342,7 +342,7 @@ export function CommandPaletteModal({if (!item.locationId) return;const locationId = item.locationId;handleClose();- void scopeToLocationWorkspace(locationId).then(() => {+ void scopeToLocationServer(locationId).then(() => {sidebarStore.ensureGroupExpanded(agentExpandKey(item.id));navigate('location', { locationId, agentName: item.title });});diff --git a/console/apps/switch-console-desktop/src/renderer/features/command-palette/palette-agent-item.tsx b/console/apps/switch-console-desktop/src/renderer/features/command-palette/palette-agent-item.tsxindex c2ba81298..a8e7ab034 100644--- a/console/apps/switch-console-desktop/src/renderer/features/command-palette/palette-agent-item.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/command-palette/palette-agent-item.tsx@@ -5,7 +5,7 @@ import { agentsStore } from '@renderer/features/locations/stores/agents-store';import { AgentAvatar } from '@renderer/lib/components/agent-avatar';import { AgentIcon } from '@renderer/lib/components/agent-icon';import { sidebarStore } from '@renderer/lib/stores/app-state';-import { useAgentIconUrl } from '@renderer/lib/stores/use-workspace-agents';+import { useAgentIconUrl } from '@renderer/lib/stores/use-remote-agents';import type { SearchItem } from '@shared/core/search';import { PALETTE_ITEM_CLASS } from './palette-item-styles';@@ -14,7 +14,7 @@ import { PALETTE_ITEM_CLASS } from './palette-item-styles';* agent's own face leads, and what it runs on follows its name as a small mark.** A row of its own rather than a branch of `PaletteKindIcon`, because the- * chosen icon comes from a query keyed by workspace and a hook cannot be called+ * chosen icon comes from a query keyed by server and a hook cannot be called* from inside a switch. An agent this app does not hold — a hit whose local row* has gone — still gets the bot drawn from its name, which is the same face the* Switch bridges show.@@ -29,7 +29,7 @@ export const PaletteAgentItem = observer(function PaletteAgentItem({onSelect: () => void;}) {const agent = agentsStore.agentById(item.id);- const iconUrl = useAgentIconUrl(agent?.workspaceId ?? null, agent?.switchAgentId ?? null);+ const iconUrl = useAgentIconUrl(agent?.serverId ?? null, agent?.switchAgentId ?? null);return (<Command.Item value={value} onSelect={onSelect} className={PALETTE_ITEM_CLASS}>diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsxindex 4ca49f85f..b206cd4bb 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx@@ -13,7 +13,6 @@ import {} from '@renderer/features/remote-hosts/host-readiness-notice';import { policyHasDeadRule } from '@renderer/features/switch-servers/addressing-policy-editor';import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';-import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { ProviderConnectionStatus } from '@renderer/lib/components/provider-connection-status';import { describeFailure } from '@renderer/lib/errors/describe-failure';import { toast } from '@renderer/lib/hooks/use-toast';@@ -24,7 +23,7 @@ import {useShowModal,type BaseModalProps,} from '@renderer/lib/modal/modal-provider';-import { useWorkspaceAgents } from '@renderer/lib/stores/use-workspace-agents';+import { useRemoteAgents } from '@renderer/lib/stores/use-remote-agents';import { Button } from '@renderer/lib/ui/button';import { ConfirmButton } from '@renderer/lib/ui/confirm-button';import {@@ -138,7 +137,7 @@ export const AddAgentModal = observer(function AddAgentModal({// Names already taken on the server, so a clash is refused before anything// is created rather than reported by the server afterwards.- const remoteAgents = useWorkspaceAgents(workspacesStore.idOnServerInScope(pickState.serverId));+ const remoteAgents = useRemoteAgents(pickState.serverId);const takenNames = useMemo(() => new Set((remoteAgents.data ?? []).map((a) => a.name)),[remoteAgents.data]@@ -387,13 +386,9 @@ export const AddAgentModal = observer(function AddAgentModal({setSubmitState('idle');return;}- if (- form.addressingPolicy !== null &&- result.agent.switchAgentId &&- result.agent.workspaceId- ) {- await rpc.workspaces.updateAddressingPolicy({- workspaceId: result.agent.workspaceId,+ if (form.addressingPolicy !== null && result.agent.switchAgentId) {+ await rpc.switchServers.updateAddressingPolicy({+ serverId: pickState.serverId,agentId: result.agent.switchAgentId,policy: form.addressingPolicy,});@@ -604,7 +599,7 @@ export const AddAgentModal = observer(function AddAgentModal({{canConfigureAgent && (<AgentSettingsSectionform={form}- workspaceId={workspacesStore.idOnServerInScope(pickState.serverId)}+ serverId={pickState.serverId}onAddServer={() => showAddServerModal({})}onOpenMessagingApps={() => {onClose();diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsxindex 7a7c13c41..428feb0e5 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsx@@ -9,7 +9,6 @@ import { switchServersStore } from '@renderer/features/switch-servers/switch-serimport { useMyIdentities } from '@renderer/features/switch-servers/use-my-identities';import { AgentIconPicker } from '@renderer/lib/components/agent-icon-picker';import { rpc } from '@renderer/lib/ipc';-import { useWorkspaceAgents } from '@renderer/lib/stores/use-workspace-agents';import { Alert, AlertAction, AlertDescription } from '@renderer/lib/ui/alert';import { Button } from '@renderer/lib/ui/button';import { DisclosureRow } from '@renderer/lib/ui/disclosure-row';@@ -30,12 +29,12 @@ import type { ConfigureAgentFormState } from './modes';*/export const AgentSettingsSection = observer(function AgentSettingsSection({form,- workspaceId,+ serverId,onAddServer,onOpenMessagingApps,}: {form: ConfigureAgentFormState;- workspaceId: string | null;+ serverId: string | null;onAddServer: () => void;onOpenMessagingApps: () => void;}) {@@ -49,24 +48,27 @@ export const AgentSettingsSection = observer(function AgentSettingsSection({const servers = switchServersStore.servers;- // Selector data for the addressing-policy editor, scoped to the workspace the- // chosen server is in scope for.+ // Selector data for the addressing-policy editor, scoped to the chosen server.const roomsQuery = useQuery({- queryKey: ['remote-rooms', workspaceId],- queryFn: () => rpc.workspaces.listRooms(workspaceId as string),- enabled: workspaceId !== null,+ queryKey: ['remote-rooms', serverId],+ queryFn: () => rpc.switchServers.listRemoteRooms(serverId as string),+ enabled: serverId !== null,});const groupsQuery = useQuery({- queryKey: ['remote-room-groups', workspaceId],- queryFn: () => rpc.workspaces.listRoomGroups(workspaceId as string),- enabled: workspaceId !== null,+ queryKey: ['remote-room-groups', serverId],+ queryFn: () => rpc.switchServers.listRemoteRoomGroups(serverId as string),+ enabled: serverId !== null,});const usersQuery = useQuery({- queryKey: ['remote-external-users', workspaceId],- queryFn: () => rpc.workspaces.listExternalUsers(workspaceId as string),- enabled: workspaceId !== null,+ queryKey: ['remote-external-users', serverId],+ queryFn: () => rpc.switchServers.listRemoteExternalUsers(serverId as string),+ enabled: serverId !== null,+ });+ const agentsQuery = useQuery({+ queryKey: ['remote-agents', serverId],+ queryFn: () => rpc.switchServers.listRemoteAgents(serverId as string),+ enabled: serverId !== null,});- const agentsQuery = useWorkspaceAgents(workspaceId);const roomOptions: OptionItem[] = (roomsQuery.data ?? []).map((r) => ({id: r.id,label: r.name,@@ -86,11 +88,11 @@ export const AgentSettingsSection = observer(function AgentSettingsSection({// Read here rather than inside the editor so the owner-only default can be// questioned before the agent exists, not after it has gone quiet.- const { identities } = useMyIdentities(workspaceId);+ const { identities } = useMyIdentities(serverId);const bridgesQuery = useQuery({- queryKey: ['remote-bridges', workspaceId],- queryFn: () => rpc.workspaces.listBridges(workspaceId as string),- enabled: workspaceId !== null,+ queryKey: ['remote-bridges', serverId],+ queryFn: () => rpc.switchServers.listRemoteBridges(serverId as string),+ enabled: serverId !== null,});const unlinkedApps =identities === null || bridgesQuery.data === undefineddiff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/location-titlebar.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/location-titlebar.tsxindex 1745fd09f..4dc8dfbfe 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/location-titlebar.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/location-titlebar.tsx@@ -19,7 +19,7 @@ import { useToast } from '@renderer/lib/hooks/use-toast';import { rpc } from '@renderer/lib/ipc';import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';import { useShowModal } from '@renderer/lib/modal/modal-provider';-import { useAgentIconUrl } from '@renderer/lib/stores/use-workspace-agents';+import { useAgentIconUrl } from '@renderer/lib/stores/use-remote-agents';import { Button } from '@renderer/lib/ui/button';import {DropdownMenu,@@ -38,7 +38,7 @@ import type { Agent } from '@shared/core/agents/agents';*/const AgentCrumb = observer(function AgentCrumb({ agent }: { agent: Agent | null }) {const label = agent?.name ?? 'Agent';- const iconUrl = useAgentIconUrl(agent?.workspaceId ?? null, agent?.switchAgentId ?? null);+ const iconUrl = useAgentIconUrl(agent?.serverId ?? null, agent?.switchAgentId ?? null);return (<TitlebarBreadcrumbcrumbs={[diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-page-header.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-page-header.tsxindex 896aff096..ee7380ce1 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-page-header.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-page-header.tsx@@ -8,10 +8,7 @@ import { useToast } from '@renderer/lib/hooks/use-toast';import { rpc } from '@renderer/lib/ipc';import { useParams } from '@renderer/lib/layout/navigation-provider';import { useShowModal } from '@renderer/lib/modal/modal-provider';-import {- workspaceAgentsQueryKey,- useWorkspaceAgents,-} from '@renderer/lib/stores/use-workspace-agents';+import { remoteAgentsQueryKey, useRemoteAgents } from '@renderer/lib/stores/use-remote-agents';import { Badge } from '@renderer/lib/ui/badge';import { Button } from '@renderer/lib/ui/button';import { providerDisplayName } from '@shared/core/providers/agent-provider-registry';@@ -38,8 +35,8 @@ export const AgentPageHeader = observer(function AgentPageHeader() {const agentMachineName = agent?.name ?? agentName ?? 'Agent';const provider = agent?.providerId ? providerDisplayName(agent.providerId) : null;- const workspaceId = agent?.workspaceId ?? null;- const { data: remoteAgents } = useWorkspaceAgents(workspaceId);+ const serverId = agent?.serverId ?? null;+ const { data: remoteAgents } = useRemoteAgents(serverId);const remote = (remoteAgents ?? []).find((a) => a.id === agent?.switchAgentId) ?? null;const description = remote?.description ?? null;@@ -48,7 +45,7 @@ export const AgentPageHeader = observer(function AgentPageHeader() {// Show machine name as subtitle only if displayName exists and differs from nameconst showMachineName = remote?.displayName != null && remote.displayName !== agentMachineName;- const roomable = workspaceId !== null && agent?.switchAgentId != null;+ const roomable = serverId !== null && agent?.switchAgentId != null;const queryClient = useQueryClient();const { toast } = useToast();@@ -58,10 +55,10 @@ export const AgentPageHeader = observer(function AgentPageHeader() {* request that can fail. It is reported rather than swallowed: a picture* that silently reverts on the next refresh is worse than an error. */const changeIcon = async (iconUrl: string | null) => {- if (workspaceId === null || switchAgentId === null) return;+ if (serverId === null || switchAgentId === null) return;try {- await rpc.workspaces.updateAgentIcon({ workspaceId, agentId: switchAgentId, iconUrl });- await queryClient.invalidateQueries({ queryKey: workspaceAgentsQueryKey(workspaceId) });+ await rpc.switchServers.updateAgentIcon({ serverId, agentId: switchAgentId, iconUrl });+ await queryClient.invalidateQueries({ queryKey: remoteAgentsQueryKey(serverId) });} catch (cause) {const { headline, detail } = describeFailure(cause, "Could not change the agent's icon.");toast({@@ -72,7 +69,7 @@ export const AgentPageHeader = observer(function AgentPageHeader() {}};- const editableIcon = workspaceId !== null && switchAgentId !== null;+ const editableIcon = serverId !== null && switchAgentId !== null;return (<header className="flex shrink-0 items-start gap-5 pt-10">@@ -120,7 +117,7 @@ export const AgentPageHeader = observer(function AgentPageHeader() {variant="outline"onClick={() =>showAddToRoom({- workspaceId: workspaceId as string,+ serverId: serverId as string,switchAgentId: agent.switchAgentId as string,agentName: title,})diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section.tsxindex fb9c4a4c2..fc9f8de75 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section.tsx@@ -32,7 +32,7 @@ export function AddressingPolicySettingsSection({});const switchAgents = (agents ?? []).filter(- (a) => a.workspaceId && a.switchAgentId && (!agentId || a.id === agentId)+ (a) => a.serverId && a.switchAgentId && (!agentId || a.id === agentId));if (switchAgents.length === 0) return null;@@ -41,7 +41,6 @@ export function AddressingPolicySettingsSection({{switchAgents.map((agent) => (<AddressingPolicyRowkey={agent.id}- workspaceId={agent.workspaceId as string}serverId={agent.serverId as string}agentId={agent.switchAgentId as string}agentName={agent.name}@@ -53,15 +52,11 @@ export function AddressingPolicySettingsSection({}function AddressingPolicyRow({- workspaceId,serverId,agentId,agentName,showName,}: {- workspaceId: string;- /** Only for the link out to the server's messaging apps, which is a page- * about the gateway rather than about this workspace's data. */serverId: string;agentId: string;agentName: string;@@ -69,37 +64,37 @@ function AddressingPolicyRow({}) {const queryClient = useQueryClient();const { navigate } = useNavigate();- const { identities } = useMyIdentities(workspaceId);+ const { identities } = useMyIdentities(serverId);const [draft, setDraft] = useState<AddressingPolicy | null>(null);const [dirty, setDirty] = useState(false);const [error, setError] = useState<string | null>(null);- const policyKey = ['agent-addressing-policy', workspaceId, agentId];+ const policyKey = ['agent-addressing-policy', serverId, agentId];const { data: saved } = useQuery({queryKey: policyKey,- queryFn: () => rpc.workspaces.getAddressingPolicy({ workspaceId, agentId }),+ queryFn: () => rpc.switchServers.getAddressingPolicy({ serverId, agentId }),});const rooms = useQuery({- queryKey: ['remote-rooms', workspaceId],- queryFn: () => rpc.workspaces.listRooms(workspaceId),+ queryKey: ['remote-rooms', serverId],+ queryFn: () => rpc.switchServers.listRemoteRooms(serverId),});const groups = useQuery({- queryKey: ['remote-room-groups', workspaceId],- queryFn: () => rpc.workspaces.listRoomGroups(workspaceId),+ queryKey: ['remote-room-groups', serverId],+ queryFn: () => rpc.switchServers.listRemoteRoomGroups(serverId),});const users = useQuery({- queryKey: ['remote-external-users', workspaceId],- queryFn: () => rpc.workspaces.listExternalUsers(workspaceId),+ queryKey: ['remote-external-users', serverId],+ queryFn: () => rpc.switchServers.listRemoteExternalUsers(serverId),});const remoteAgents = useQuery({- queryKey: ['remote-agents', workspaceId],- queryFn: () => rpc.workspaces.listAgents(workspaceId),+ queryKey: ['remote-agents', serverId],+ queryFn: () => rpc.switchServers.listRemoteAgents(serverId),});const bridges = useQuery({- queryKey: ['remote-bridges', workspaceId],- queryFn: () => rpc.workspaces.listBridges(workspaceId),+ queryKey: ['remote-bridges', serverId],+ queryFn: () => rpc.switchServers.listRemoteBridges(serverId),});- // The apps in this workspace the user has claimed no account on. Null until both+ // The apps on this server the user has claimed no account on. Null until both// halves have arrived: a bridge list without the identities would read as// every app unlinked.const unlinkedApps =@@ -114,7 +109,7 @@ function AddressingPolicyRow({const mutation = useMutation({mutationFn: (policy: AddressingPolicy | null) =>- rpc.workspaces.updateAddressingPolicy({ workspaceId, agentId, policy }),+ rpc.switchServers.updateAddressingPolicy({ serverId, agentId, policy }),onSuccess: (_result, policy) => {queryClient.setQueryData(policyKey, policy);setDirty(false);diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/stores/agents-store.test.ts b/console/apps/switch-console-desktop/src/renderer/features/locations/stores/agents-store.test.tsindex ea1004d6c..1fb86772d 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/stores/agents-store.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/stores/agents-store.test.ts@@ -4,75 +4,70 @@ import { agentsStore } from './agents-store';vi.mock('@renderer/lib/ipc', () => ({ rpc: {} }));-function agent(locationId: string, workspaceId: string | null, name: string): Agent {- return { locationId, workspaceId, name } as Agent;+function agent(locationId: string, serverId: string | null, name: string): Agent {+ return { locationId, serverId, name } as Agent;}/*** The premise these cover: a directory can hold agents registered against- * several workspaces at once, so "which workspace does this directory belong+ * several Switch servers at once, so "which server does this directory belong* to" has no single answer and must not be asked (CHOO-2044).*/-describe('AgentsStore workspace scoping', () => {+describe('AgentsStore server scoping', () => {afterEach(() => {agentsStore.byLocation.clear();- agentsStore.optimisticWorkspaceByLocation.clear();+ agentsStore.optimisticServerByLocation.clear();});- it('returns only the agents belonging to the given workspace', () => {+ it('returns only the agents belonging to the given server', () => {agentsStore.byLocation.set('shared', [- agent('shared', 'ws-1', 'a'),- agent('shared', 'ws-2', 'b'),+ agent('shared', 'server-1', 'a'),+ agent('shared', 'server-2', 'b'),agent('shared', null, 'unlinked'),]);- expect(agentsStore.agentsInWorkspaceAtLocation('shared', 'ws-1').map((a) => a.name)).toEqual([+ expect(agentsStore.agentsOnServerAtLocation('shared', 'server-1').map((a) => a.name)).toEqual(['a',]);- expect(agentsStore.agentsInWorkspaceAtLocation('shared', 'ws-2').map((a) => a.name)).toEqual([+ expect(agentsStore.agentsOnServerAtLocation('shared', 'server-2').map((a) => a.name)).toEqual(['b',]);- expect(agentsStore.agentsInWorkspaceAtLocation('shared', 'ws-3')).toEqual([]);+ expect(agentsStore.agentsOnServerAtLocation('shared', 'server-3')).toEqual([]);});- /**- * Two workspaces on the same server are still two scopes: the sidebar shows- * one of them at a time, so a directory present in both must answer for each- * separately rather than for the server they share.- */- it('separates two workspaces that live on the same server', () => {+ it('reports a shared directory as present on every server it has agents on', () => {agentsStore.byLocation.set('shared', [- agent('shared', 'ws-1', 'a'),- agent('shared', 'ws-2', 'b'),+ agent('shared', 'server-1', 'a'),+ agent('shared', 'server-2', 'b'),]);- expect(agentsStore.locationHasAgentsInWorkspace('shared', 'ws-1')).toBe(true);- expect(agentsStore.locationHasAgentsInWorkspace('shared', 'ws-2')).toBe(true);- expect(agentsStore.locationHasAgentsInWorkspace('shared', 'ws-3')).toBe(false);- expect(agentsStore.workspaceIdsForLocation('shared').sort()).toEqual(['ws-1', 'ws-2']);+ expect(agentsStore.locationHasAgentsOnServer('shared', 'server-1')).toBe(true);+ expect(agentsStore.locationHasAgentsOnServer('shared', 'server-2')).toBe(true);+ expect(agentsStore.locationHasAgentsOnServer('shared', 'server-3')).toBe(false);+ expect(agentsStore.serverIdsForLocation('shared').sort()).toEqual(['server-1', 'server-2']);});it('keeps a just-created location in scope before its agent row lands', () => {- agentsStore.noteLocationWorkspace('fresh', 'ws-1');+ agentsStore.noteLocationServer('fresh', 'server-1');- expect(agentsStore.locationHasAgentsInWorkspace('fresh', 'ws-1')).toBe(true);- expect(agentsStore.locationHasAgentsInWorkspace('fresh', 'ws-2')).toBe(false);- expect(agentsStore.workspaceIdsForLocation('fresh')).toEqual(['ws-1']);+ expect(agentsStore.locationHasAgentsOnServer('fresh', 'server-1')).toBe(true);+ expect(agentsStore.locationHasAgentsOnServer('fresh', 'server-2')).toBe(false);+ expect(agentsStore.serverIdsForLocation('fresh')).toEqual(['server-1']);});it('ignores the optimistic note once real agents exist', () => {- agentsStore.noteLocationWorkspace('shared', 'ws-9');- agentsStore.byLocation.set('shared', [agent('shared', 'ws-1', 'a')]);+ agentsStore.noteLocationServer('shared', 'server-9');+ agentsStore.byLocation.set('shared', [agent('shared', 'server-1', 'a')]);- expect(agentsStore.workspaceIdsForLocation('shared')).toEqual(['ws-1']);- expect(agentsStore.locationHasAgentsInWorkspace('shared', 'ws-9')).toBe(false);+ expect(agentsStore.serverIdsForLocation('shared')).toEqual(['server-1']);+ expect(agentsStore.locationHasAgentsOnServer('shared', 'server-9')).toBe(false);});- it('treats a location with only unlinked agents as in no workspace', () => {+ it('treats a location with only unlinked agents as on no server', () => {agentsStore.byLocation.set('orphan', [agent('orphan', null, 'a')]);- expect(agentsStore.workspaceIdsForLocation('orphan')).toEqual([]);- expect(agentsStore.locationHasAgentsInWorkspace('orphan', 'ws-1')).toBe(false);+ expect(agentsStore.serverIdsForLocation('orphan')).toEqual([]);+ expect(agentsStore.locationHasAgentsOnServer('orphan', 'server-1')).toBe(false);});});@@ -87,13 +82,13 @@ describe('AgentsStore workspace scoping', () => {describe('resolving the agent a location route is about', () => {afterEach(() => {agentsStore.byLocation.clear();- agentsStore.optimisticWorkspaceByLocation.clear();+ agentsStore.optimisticServerByLocation.clear();});it('picks the named agent out of a shared directory', () => {agentsStore.byLocation.set('dir', [- agent('dir', 'ws-1', 'charlie'),- agent('dir', 'ws-1', 'delta'),+ agent('dir', 'server-1', 'charlie'),+ agent('dir', 'server-1', 'delta'),]);expect(agentsStore.agentAtLocation('dir', 'charlie')?.name).toBe('charlie');@@ -102,22 +97,22 @@ describe('resolving the agent a location route is about', () => {it('resolves an unnamed route when the directory holds exactly one agent', () => {// Nothing to choose between, so there is nothing to get wrong.- agentsStore.byLocation.set('dir', [agent('dir', 'ws-1', 'charlie')]);+ agentsStore.byLocation.set('dir', [agent('dir', 'server-1', 'charlie')]);expect(agentsStore.agentAtLocation('dir', undefined)?.name).toBe('charlie');});it('refuses to guess between several agents', () => {agentsStore.byLocation.set('dir', [- agent('dir', 'ws-1', 'charlie'),- agent('dir', 'ws-1', 'delta'),+ agent('dir', 'server-1', 'charlie'),+ agent('dir', 'server-1', 'delta'),]);expect(agentsStore.agentAtLocation('dir', undefined)).toBeNull();});it('is null for a name that is not there, rather than the first agent', () => {- agentsStore.byLocation.set('dir', [agent('dir', 'ws-1', 'charlie')]);+ agentsStore.byLocation.set('dir', [agent('dir', 'server-1', 'charlie')]);expect(agentsStore.agentAtLocation('dir', 'nobody')).toBeNull();});diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/stores/agents-store.ts b/console/apps/switch-console-desktop/src/renderer/features/locations/stores/agents-store.tsindex 3d446c8f7..42a27c5bd 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/stores/agents-store.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/stores/agents-store.ts@@ -4,27 +4,26 @@ import type { Agent } from '@shared/core/agents/agents';/*** Renderer cache of every agent across all locations. The sidebar scopes its tree- * to the active workspace (see {@link workspacesStore.activeId}), so it needs a- * reactive lookup that does not depend on each row's own react-query.+ * to the active server (see {@link switchServersStore.activeServerId}), so it needs+ * a reactive lookup that does not depend on each row's own react-query.*- * **A workspace belongs to an agent, not to a directory.** A directory is a place- * on disk and can hold agents registered in several workspaces at once, so there- * is no such thing as "the location's workspace" to scope on — asking for one- * drags every agent in the directory under whichever answer came back first- * (CHOO-2044). Scope on {@link agentsInWorkspaceAtLocation}; a location is in- * scope when it has any.+ * **A server belongs to an agent, not to a directory.** A directory is a place on+ * disk and can hold agents registered against several servers at once, so there is+ * no such thing as "the location's server" to scope on — asking for one drags every+ * agent in the directory under whichever answer came back first (CHOO-2044). Scope+ * on {@link agentsOnServerAtLocation}; a location is in scope when it has any.*/export class AgentsStore {/** All agents grouped by their location id. */readonly byLocation = new Map<string, Agent[]>();/**- * Workspace id a just-created location's agent will belong to, recorded by the+ * Server id a just-created location's agent will belong to, recorded by the* add-agent modal before {@link load} has re-fetched the new agent. Used as a- * fallback in {@link locationHasAgentsInWorkspace} so a freshly-created location- * does not flicker out of the sidebar's workspace-scoped view during the gap- * between the location mounting and the agent list refreshing.+ * fallback in {@link locationHasAgentsOnServer} so a freshly-created location does+ * not flicker out of the sidebar's server-scoped view during the gap between the+ * location mounting and the agent list refreshing.*/- readonly optimisticWorkspaceByLocation = new Map<string, string>();+ readonly optimisticServerByLocation = new Map<string, string>();loaded = false;constructor() {@@ -42,16 +41,16 @@ export class AgentsStore {}// Drop optimistic notes now superseded by a real agent record.for (const locationId of this.byLocation.keys()) {- this.optimisticWorkspaceByLocation.delete(locationId);+ this.optimisticServerByLocation.delete(locationId);}this.loaded = true;});}- /** Record the workspace a location's agent will bind to, ahead of {@link load}. */- noteLocationWorkspace(locationId: string, workspaceId: string): void {+ /** Record the server a location's agent will bind to, ahead of {@link load}. */+ noteLocationServer(locationId: string, serverId: string): void {runInAction(() => {- this.optimisticWorkspaceByLocation.set(locationId, workspaceId);+ this.optimisticServerByLocation.set(locationId, serverId);});}@@ -98,60 +97,35 @@ export class AgentsStore {return matching.sort((a, b) => a.name.localeCompare(b.name));}- /**- * This install's agents in a given workspace — the ones the room views may- * list and offer.- *- * The workspace-addressed counterpart of {@link agentsOnServer}, and what a- * view scoped to a workspace asks for: its rooms and their members are that- * workspace's, and a server hosting several would otherwise offer agents from- * all of them.- */- agentsInWorkspace(workspaceId: string): Agent[] {- const matching: Agent[] = [];- for (const agents of this.byLocation.values()) {- for (const agent of agents) {- if (agent.workspaceId === workspaceId && agent.switchAgentId) matching.push(agent);- }- }- return matching.sort((a, b) => a.name.localeCompare(b.name));- }-- /**- * A location's agents that belong to one workspace — what the sidebar renders- * under that workspace. Agents in the same directory registered elsewhere are- * not this workspace's to show.- *- * Unlike {@link agentsInWorkspace} this keeps agents with no Switch identity:- * an agent still being registered has a workspace and a row in the tree, and- * dropping it would make it disappear from the sidebar mid-onboarding.- */- agentsInWorkspaceAtLocation(locationId: string, workspaceId: string): Agent[] {- return (this.byLocation.get(locationId) ?? []).filter((a) => a.workspaceId === workspaceId);+ /** A location's agents that belong to one server — what the sidebar renders+ * under that server. Agents in the same directory registered elsewhere are not+ * this server's to show. */+ agentsOnServerAtLocation(locationId: string, serverId: string): Agent[] {+ return (this.byLocation.get(locationId) ?? []).filter((a) => a.serverId === serverId);}- /** Whether a location has anything to show under `workspaceId`. */- locationHasAgentsInWorkspace(locationId: string, workspaceId: string): boolean {- return this.workspaceIdsForLocation(locationId).includes(workspaceId);+ /** Whether a location has anything to show under `serverId`. */+ locationHasAgentsOnServer(locationId: string, serverId: string): boolean {+ return this.serverIdsForLocation(locationId).includes(serverId);}/**- * The workspaces a location's agents belong to. A directory can span several,- * so this is a list rather than the one answer callers used to ask for.+ * The servers a location's agents belong to. A directory can span several, so+ * this is a list rather than the one answer callers used to ask for.** The optimistic note stands in only while the location has no agent rows at* all — that is the gap it exists to cover. Letting it also speak for a location- * that already has agents would have it claim a workspace the location is not in.+ * that already has agents would have it claim a server the location is not on.*/- workspaceIdsForLocation(locationId: string): string[] {+ serverIdsForLocation(locationId: string): string[] {const agents = this.byLocation.get(locationId);if (!agents || agents.length === 0) {- const optimistic = this.optimisticWorkspaceByLocation.get(locationId);+ const optimistic = this.optimisticServerByLocation.get(locationId);return optimistic ? [optimistic] : [];}const ids = new Set<string>();for (const agent of agents) {- if (agent.workspaceId !== null) ids.add(agent.workspaceId);+ if (agent.serverId !== null) ids.add(agent.serverId);}return [...ids];}diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/stores/location-manager.test.ts b/console/apps/switch-console-desktop/src/renderer/features/locations/stores/location-manager.test.tsindex 73e36e19b..5954402f8 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/stores/location-manager.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/stores/location-manager.test.ts@@ -74,7 +74,6 @@ function agent(overrides: Partial<Agent> = {}): Agent {providerId: 'claude',switchAgentId: 'sw-1',apiEndpoint: 'https://switch.example.com',- workspaceId: 'workspace-1',serverId: 'server-1',status: null,autoApprove: false,diff --git a/console/apps/switch-console-desktop/src/renderer/features/onboarding/create-workspace-page.tsx b/console/apps/switch-console-desktop/src/renderer/features/onboarding/create-workspace-page.tsxdeleted file mode 100644index af75cf12f..000000000--- a/console/apps/switch-console-desktop/src/renderer/features/onboarding/create-workspace-page.tsx+++ /dev/null@@ -1,137 +0,0 @@-import { useState } from 'react';-import { createWorkspaceFailureText } from '@renderer/features/workspaces/describe-create-failure';-import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';-import { failureText } from '@renderer/lib/errors/describe-failure';-import { Button } from '@renderer/lib/ui/button';-import { ConfirmButton } from '@renderer/lib/ui/confirm-button';-import { Field, FieldGroup, FieldLabel } from '@renderer/lib/ui/field';-import { Input } from '@renderer/lib/ui/input';-import { WizardFrame } from '@renderer/lib/ui/wizard-frame';-import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';-import type { Workspace } from '@shared/core/workspaces/workspaces';--/**- * Make the workspace the account will work in.- *- * A name and nothing else. The design's address hint under the field describes- * a workspace reachable at its own subdomain, which is not how a Switch- * workspace is addressed — it lives on the server you signed in to, and showing- * an address that resolves to nothing would be the app inventing an answer. The- * "let my team join automatically" toggle is gone for the same reason: joining- * by email domain is a thing no Switch server can do yet, so a switch for it- * would silently do nothing.- */-export function CreateWorkspacePage({- server,- onBack,- onCreated,-}: {- server: SwitchServer;- /** Null where the account is in no workspace, so there is no list behind this. */- onBack: (() => void) | null;- onCreated: () => void;-}) {- const [name, setName] = useState('');- const [submitting, setSubmitting] = useState(false);- const [error, setError] = useState<string | null>(null);- /**- * The workspace the server has already minted, when entering it is what- * failed.- *- * Asking again would offer a name the server has just taken and come back- * with a conflict that reads as the name being refused. On the page reached- * with no memberships there is no Back either, so the only remaining move has- * to be the one that can still work: entering what exists.- */- const [created, setCreated] = useState<Workspace | null>(null);-- const trimmed = name.trim();-- const submit = async () => {- if (submitting || (created === null && trimmed === '')) return;- setSubmitting(true);- setError(null);- try {- const workspace = created ?? (await workspacesStore.create(server.id, trimmed));- setCreated(workspace);- await workspacesStore.setActive(workspace.id);- onCreated();- } catch (cause) {- // Two different failures wear the same button. Before the workspace- // exists the likeliest one is the name, and after it exists the name is- // settled and what failed was the move into it — saying "could not- // create" then would be describing the wrong step.- setError(- created === null- ? createWorkspaceFailureText(- cause,- server.name,- `${server.name} could not create the workspace.`- )- : failureText(cause, `This window could not be moved into ${created.name}.`)- );- setSubmitting(false);- }- };-- return (- <WizardFrame- title="Create your workspace"- subtitle={- onBack === null- ? `You’re not in a workspace on ${server.name} yet, so you’re the first one here. A workspace is where your agents, rooms and teammates live.`- : 'A workspace is where your agents, rooms and teammates live.'- }- pager={{- pageName: 'Create your workspace',- onBack: onBack && !submitting && created === null ? onBack : null,- onNext: null,- }}- footer={- <>- {onBack && created === null && (- <Button variant="outline" onClick={onBack} disabled={submitting}>- Back- </Button>- )}- <ConfirmButton- onClick={() => void submit()}- disabled={submitting || (created === null && trimmed === '')}- >- {created !== null- ? submitting- ? 'Opening…'- : 'Open workspace'- : submitting- ? 'Creating…'- : 'Create workspace'}- </ConfirmButton>- </>- }- >- <FieldGroup>- <Field>- <FieldLabel>Name</FieldLabel>- <Input- value={name}- onChange={(e) => setName(e.target.value)}- placeholder="Acme Robotics"- autoFocus- disabled={created !== null}- onKeyDown={(e) => {- if (e.key === 'Enter') void submit();- }}- />- {error && <p className="mt-1 text-xs text-destructive">{error}</p>}- {created !== null && (- <p className="mt-1 text-xs text-foreground-muted">- {created.name} was created on {server.name}, but this window could not be moved into- it. Try again — asking for it a second time would only be refused for the name it- already has.- </p>- )}- </Field>- </FieldGroup>- </WizardFrame>- );-}diff --git a/console/apps/switch-console-desktop/src/renderer/features/onboarding/onboarding-flow.tsx b/console/apps/switch-console-desktop/src/renderer/features/onboarding/onboarding-flow.tsxdeleted file mode 100644index bf25b2ea5..000000000--- a/console/apps/switch-console-desktop/src/renderer/features/onboarding/onboarding-flow.tsx+++ /dev/null@@ -1,367 +0,0 @@-import { Link2, Server, TriangleAlert, Wrench } from 'lucide-react';-import { observer } from 'mobx-react-lite';-import { useCallback, useEffect, useState } from 'react';-import {- ChoiceCard,- ExternalServerStep,- LocalSetupStep,- RemoteHostSetupStep,- SignInStep,-} from '@renderer/features/switch-servers/AddServerModal';-import { LinkAccountsStep } from '@renderer/features/switch-servers/link-accounts-step';-import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';-import { describeFailure } from '@renderer/lib/errors/describe-failure';-import { rpc } from '@renderer/lib/ipc';-import { useNavigate } from '@renderer/lib/layout/navigation-provider';-import { report } from '@renderer/lib/telemetry/report';-import { Alert, AlertAction, AlertDescription, AlertTitle } from '@renderer/lib/ui/alert';-import { Button } from '@renderer/lib/ui/button';-import { Spinner } from '@renderer/lib/ui/spinner';-import { WizardChromeProvider, WizardFrame } from '@renderer/lib/ui/wizard-frame';-import type {- AddServerChoiceName,- AddServerStepName,-} from '@shared/core/switch-servers/add-server-steps';-import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';-import { CreateWorkspacePage } from './create-workspace-page';-import { onboardingStore, type OnboardingPage } from './onboarding-store';-import { PickWorkspacePage } from './pick-workspace-page';-import { WelcomePage } from './welcome-page';--/**- * The first-run pages and the add-server wizard's steps, named against each- * other so both funnels answer the same question.- *- * They are the same steps — the first-run pages are the wizard drawn full- * window — so reporting them under new names would split "how far did people- * get" in two. `firstRun` on the event is what keeps them apart where it- * matters. The welcome page belongs to neither: nothing has been chosen on it- * and there is no server being added yet.- *- * The workspace pages are unreported for the opposite reason: they are not- * steps of the add-server wizard at all — the modal has nothing like them,- * because by the time you open it you are already in a workspace — so counting- * them here would put drop-offs from one funnel into the other's numbers.- */-const STEP_FOR_PAGE: Record<OnboardingPage, AddServerStepName | null> = {- welcome: null,- whoRuns: 'choose',- local: 'local',- remoteHost: 'remoteHost',- connect: 'external',- signIn: 'signIn',- pickWorkspace: null,- createWorkspace: null,- linkAccounts: 'linkAccounts',-};--/**- * Which path each page belongs to.- *- * Unlike the modal's, none of these inherit: the only way to reach sign-in on a- * fresh install is by connecting to a server someone else runs.- */-const CHOICE_FOR_PAGE: Record<OnboardingPage, AddServerChoiceName> = {- welcome: 'none',- whoRuns: 'none',- local: 'local',- remoteHost: 'remoteHost',- connect: 'external',- signIn: 'external',- pickWorkspace: 'external',- createWorkspace: 'external',- linkAccounts: 'external',-};--/**- * Everything the window shows before there is a server to show.- *- * The pages after the first are the add-server wizard's own steps, drawn full- * window instead of in a dialog. Setting up a server is the same three- * questions whether you have none or nine, and a first-run copy of them would- * be a second place for the Docker check, the connection form and the sign-in- * to drift from what the rest of the app does.- *- * Running a managed stack on a remote host is offered only when there is a host- * to run it on. It needs one onboarded over SSH, which a fresh install has none- * of — but onboarding a host needs no server, so someone who deleted their last- * one may well arrive here with hosts already set up, and hiding the path from- * them would leave it unreachable.- */-export const OnboardingFlow = observer(function OnboardingFlow() {- const { navigate } = useNavigate();-- const goTo = (page: OnboardingPage) => {- onboardingStore.goTo(page);- reportPage(page);- };-- /**- * Leave the first-run pages for the app they were setting up.- *- * Landing on the new server's page rather than wherever the window would- * otherwise open: the flow was about that server, and dropping the user into- * an empty home view would make the last ten minutes look like they did- * nothing.- */- const finish = (serverId: string | null) => {- onboardingStore.reset();- if (serverId === null) return;- void switchServersStore.setActive(serverId);- navigate('server', { serverId });- };-- // The server as the list has it, not as the flow remembers it. Once one- // exists the window is the workspace again for any view that does not need a- // server, so it can be deleted from under the flow — and a form aimed at a- // row that is gone fails on submit with no way back to a working one.- const server = switchServersStore.serverById(pageServerId());-- /**- * Leave the flow for the app, with the server set up but the rest not done.- *- * Offered only once the page on screen has a server of its own, which is both- * when there is something to come back to and when the flow stops being the- * only thing the window can draw. Before that, stepping back off the welcome- * page is the way out.- */- const exit = server === null ? null : { label: 'Finish later', onExit: () => finish(server.id) };-- return (- <WizardChromeProvider chrome="page" exit={exit}>- {currentPage(server, goTo, finish)}- </WizardChromeProvider>- );-});--/**- * The server the page on screen is the setup of, if it has one yet.- *- * Asked per page rather than kept as one field, because the paths reach a- * server by different means and none of them owns another's: the connect page- * hands one over and every page after it works on that same one, while each- * managed page brings its own up. Reading a single field instead offered a way- * out to a server the current page had nothing to do with — connect to one,- * walk back, choose the local path, and the exit still pointed at the first.- */-function pageServerId(): string | null {- const page = onboardingStore.page;- if (onboardingStore.registeredOn?.page === page) return onboardingStore.registeredOn.serverId;- if (CHOICE_FOR_PAGE[page] !== 'external') return null;- return onboardingStore.server?.id ?? null;-}--function reportPage(page: OnboardingPage): void {- const step = STEP_FOR_PAGE[page];- if (step === null) return;- report('add_server_step', { step, choice: CHOICE_FOR_PAGE[page], first_run: true });-}--function currentPage(- server: SwitchServer | null,- goTo: (page: OnboardingPage) => void,- finish: (serverId: string | null) => void-) {- switch (onboardingStore.page) {- case 'welcome':- return <WelcomePage onContinue={() => goTo('whoRuns')} />;- case 'whoRuns':- return (- <WhoRunsPage- onBack={() => goTo('welcome')}- onLocal={() => goTo('local')}- onRemoteHost={() => goTo('remoteHost')}- onExternal={() => goTo('connect')}- />- );- case 'local':- return (- <LocalSetupStep- onBack={() => goTo('whoRuns')}- onDone={finish}- onClose={null}- onRegistered={(serverId) => onboardingStore.registered('local', serverId)}- />- );- case 'remoteHost':- return (- <RemoteHostSetupStep- onBack={() => goTo('whoRuns')}- onDone={finish}- onClose={() => goTo('whoRuns')}- onRegistered={(serverId) => onboardingStore.registered('remoteHost', serverId)}- />- );- case 'signIn':- // Both of these need the server the connect page added. Without one there- // is nothing to sign in to, so the flow goes back to the page that makes- // it rather than drawing a form against nothing.- if (server === null) break;- return (- <SignInStep- server={server}- onBack={() => goTo('connect')}- onClose={null}- onSignedIn={() => goTo('pickWorkspace')}- />- );- case 'pickWorkspace':- if (server === null) break;- return (- <PickWorkspacePage- server={server}- onBack={() => goTo('signIn')}- onPicked={() => goTo('linkAccounts')}- onCreate={() => goTo('createWorkspace')}- />- );- case 'createWorkspace':- if (server === null) break;- return (- <CreateWorkspacePage- server={server}- // Nothing to go back to when the account is in no workspace: the- // picker sent the user straight here, and returning to it would be a- // door onto the list it had nothing to show.- onBack={onboardingStore.serverWorkspaces?.length ? () => goTo('pickWorkspace') : null}- onCreated={() => goTo('linkAccounts')}- />- );- case 'linkAccounts':- if (server === null) break;- return (- <LinkAccountsStep- serverId={server.id}- serverName={server.name}- onDone={() => finish(server.id)}- />- );- case 'connect':- break;- }-- return (- <ExternalServerStep- initialGatewayUrl={null}- initialApiUrl={null}- initialName={null}- serverId={null}- isEdit={false}- firstRun- existing={server}- onBack={() => goTo('whoRuns')}- onClose={() => goTo('whoRuns')}- onSuccess={() => finish(server?.id ?? null)}- onConnected={(added) => {- onboardingStore.connected(added);- reportPage('signIn');- }}- />- );-}--/**- * Whether there are onboarded hosts to offer the managed path on.- *- * Three states, not two. A failed read is not an empty list — saying "no hosts"- * because the question could not be asked hides a path the user has already set- * up and leaves them no way to tell why.- */-type HostsRead =- | { kind: 'reading' }- | { kind: 'read'; hosts: { sshHost: string }[] }- | { kind: 'failed'; headline: string; detail: string | null };--function WhoRunsPage({- onBack,- onLocal,- onRemoteHost,- onExternal,-}: {- onBack: () => void;- onLocal: () => void;- onRemoteHost: () => void;- onExternal: () => void;-}) {- const [hosts, setHosts] = useState<HostsRead>({ kind: 'reading' });-- const readHosts = useCallback(() => {- setHosts({ kind: 'reading' });- void rpc.remoteHosts.listHosts().then(- (list) => setHosts({ kind: 'read', hosts: list }),- (cause) =>- setHosts({- kind: 'failed',- ...describeFailure(cause, 'Could not check for onboarded hosts.'),- })- );- }, []);-- useEffect(readHosts, [readHosts]);-- return (- <WizardFrame- title="Who runs the server?"- subtitle="Either Switch Console installs and looks after the stack for you, or you point it at one that already exists."- /* The chevron below repeats this. It is unlabelled, so it cannot be the- only way back from a page whose cards all lead forward. */- footer={- <Button variant="outline" onClick={onBack}>- Back- </Button>- }- pager={{ pageName: 'Who runs the server', onBack, onNext: null }}- >- {/* The whole set waits on the read, not just the card it decides. Painting- two and inserting a third between them a round trip later moves the- answer under a cursor already on its way to one. */}- {hosts.kind === 'reading' ? (- <div className="flex items-center gap-2 text-sm text-foreground-muted">- <Spinner className="size-3.5" />- <span>Looking for onboarded hosts…</span>- </div>- ) : (- <div className="grid gap-3">- {hosts.kind === 'failed' && (- // The two certain paths are still offered: not knowing about hosts- // is no reason to hold the whole question hostage. Retrying may add- // a third card, but only because it was asked for.- <Alert variant="destructive">- <TriangleAlert className="size-4" />- <AlertTitle>{hosts.headline}</AlertTitle>- <AlertDescription>- {hosts.detail ? `${hosts.detail} ` : ''}- Running a server on one of your own hosts is not offered until this succeeds.- </AlertDescription>- <AlertAction>- <Button variant="outline" size="sm" onClick={readHosts}>- Try again- </Button>- </AlertAction>- </Alert>- )}- <ChoiceCard- icon={<Wrench className="size-5" />}- title="Set it up for me"- description="Switch Console installs the full stack on this computer with Docker and keeps it updated."- onClick={onLocal}- />- {hosts.kind === 'read' && hosts.hosts.length > 0 && (- <ChoiceCard- icon={<Server className="size-5" />}- title="Set it up on one of my hosts"- description="Switch Console installs the stack over SSH on a host you've onboarded. Stays running when Switch Console is closed."- onClick={onRemoteHost}- />- )}- <ChoiceCard- icon={<Link2 className="size-5" />}- title="It's already running"- description="Connect by URL to a Switch gateway your team or someone else operates. You'll need its gateway and API addresses."- onClick={onExternal}- />- </div>- )}- </WizardFrame>- );-}diff --git a/console/apps/switch-console-desktop/src/renderer/features/onboarding/onboarding-store.ts b/console/apps/switch-console-desktop/src/renderer/features/onboarding/onboarding-store.tsdeleted file mode 100644index 0ea223da4..000000000--- a/console/apps/switch-console-desktop/src/renderer/features/onboarding/onboarding-store.ts+++ /dev/null@@ -1,113 +0,0 @@-import { makeAutoObservable } from 'mobx';-import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';-import type { Workspace } from '@shared/core/workspaces/workspaces';--/** Where a fresh install is in getting its first server. */-export type OnboardingPage =- | 'welcome'- | 'whoRuns'- | 'local'- | 'remoteHost'- | 'connect'- | 'signIn'- | 'pickWorkspace'- | 'createWorkspace'- | 'linkAccounts';--/**- * The first-run flow's place in itself.- *- * Held in a store rather than in the page that draws it, because the flow- * outlives its own component. The shell takes the window away from it whenever- * Settings is opened, and it decides between the first-run pages and the- * workspace from the server list — which stops being empty halfway through the- * flow, the moment the server is added but several pages before the user has- * signed in to it. Without somewhere to say "still going", adding the server- * would throw the user out of the flow that added it.- *- * Only the page and the server survive being unmounted. What is half typed into- * a form does not: the fields belong to the page drawing them, so a stray ⌘,- * on the connect page costs the two addresses.- */-class OnboardingStore {- page: OnboardingPage = 'welcome';- /** The server the connect page added, and the subject of the pages after it. */- server: SwitchServer | null = null;- /** The workspaces that server said the account is in, once it has been asked. */- serverWorkspaces: Workspace[] | null = null;- /**- * The server a managed path brought up, and the page that brought it up.- *- * The page is kept with it because the two managed paths do not share one:- * starting a stack on a host and then walking back to pick the local one- * leaves a server that the page now on screen did not make, and an exit- * offered to it would take the user somewhere they did not set up.- */- registeredOn: { page: OnboardingPage; serverId: string } | null = null;-- constructor() {- makeAutoObservable(this);- }-- /**- * Whether the user has committed to setting a server up.- *- * The welcome page is not in progress: it asks a question and nothing has- * been started, so a launch that finds servers should go straight past it.- */- get inProgress(): boolean {- return this.page !== 'welcome';- }-- goTo(page: OnboardingPage): void {- // Walking back to the welcome page gives up on the attempt, including the- // server it may already have registered and what that server answered.- // Holding on to that reference would point the next attempt's save at a row- // the user is free to delete in the meantime — the window is the workspace- // again the moment one exists — and nothing short of a restart would clear- // it.- if (page === 'welcome') {- this.server = null;- this.serverWorkspaces = null;- this.registeredOn = null;- }- this.page = page;- }-- /**- * A managed path has registered its server.- *- * Reported from an effect that fires on every render of a page whose stack is- * up, so writing the same pair again has to be a no-op — a fresh object each- * time would notify, re-render and report again without end.- */- registered(page: OnboardingPage, serverId: string): void {- if (this.registeredOn?.page === page && this.registeredOn.serverId === serverId) return;- this.registeredOn = { page, serverId };- }-- connected(server: SwitchServer): void {- this.server = server;- this.page = 'signIn';- }-- /**- * What the server answered when asked which workspaces this account is in.- *- * Kept so the create page knows whether there was anything to come back to:- * an account with no membership is sent straight to the form, and offering it- * a Back to a list of nothing would be a door onto a blank wall.- */- resolved(workspaces: Workspace[]): void {- this.serverWorkspaces = workspaces;- }-- reset(): void {- this.page = 'welcome';- this.server = null;- this.serverWorkspaces = null;- this.registeredOn = null;- }-}--export const onboardingStore = new OnboardingStore();diff --git a/console/apps/switch-console-desktop/src/renderer/features/onboarding/pick-workspace-page.tsx b/console/apps/switch-console-desktop/src/renderer/features/onboarding/pick-workspace-page.tsxdeleted file mode 100644index d3782bad8..000000000--- a/console/apps/switch-console-desktop/src/renderer/features/onboarding/pick-workspace-page.tsx+++ /dev/null@@ -1,195 +0,0 @@-import { useQuery } from '@tanstack/react-query';-import { Plus } from 'lucide-react';-import { observer } from 'mobx-react-lite';-import { useCallback, useEffect, useRef, useState } from 'react';-import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';-import { failureText } from '@renderer/lib/errors/describe-failure';-import { rpc } from '@renderer/lib/ipc';-import { Button } from '@renderer/lib/ui/button';-import { Spinner } from '@renderer/lib/ui/spinner';-import { WizardFrame } from '@renderer/lib/ui/wizard-frame';-import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';-import type { Workspace } from '@shared/core/workspaces/workspaces';-import { onboardingStore } from './onboarding-store';--/**- * Which of the server's workspaces the window should be scoped to.- *- * The page asks the server rather than reading the list this app already holds:- * signing in is the first moment the gateway will say what the account is a- * member of, and an install that has been sitting on the sign-in form is- * answering from before that.- *- * Only memberships are offered. The design also shows workspaces open to you- * because your email domain matches, and invitations waiting for your address —- * both are **absent here rather than empty**, because a Switch server cannot- * answer for either yet: it records no email domain against a workspace and has- * no way to list the invitations sent to an address. An empty "nobody has- * invited you" section would be a claim the server never made, and one that- * will read as false to the first person who was in fact invited.- */-export const PickWorkspacePage = observer(function PickWorkspacePage({- server,- onBack,- onPicked,- onCreate,-}: {- server: SwitchServer;- onBack: () => void;- onPicked: () => void;- onCreate: () => void;-}) {- const [opening, setOpening] = useState<string | null>(null);- const [openError, setOpenError] = useState<string | null>(null);-- const query = useQuery({- queryKey: ['onboarding-workspaces', server.id],- queryFn: () => rpc.switchServers.resolveWorkspaces(server.id),- });- const workspaces = query.data ?? null;-- const open = useCallback(- async (workspace: Workspace) => {- setOpening(workspace.id);- setOpenError(null);- try {- await workspacesStore.setActive(workspace.id);- onPicked();- } catch (cause) {- setOpenError(failureText(cause, `Could not open ${workspace.name}.`));- setOpening(null);- }- },- [onPicked]- );-- // Once per answer, not once per render: the callbacks are made fresh by the- // page above, so without the latch a re-render would re-run the choice that- // is already under way.- const settled = useRef(false);- useEffect(() => {- if (workspaces === null || settled.current) return;- settled.current = true;- onboardingStore.resolved(workspaces);- // A question with one answer is not a question, and with none there is- // nothing here to answer it with.- if (workspaces.length === 0) onCreate();- else if (workspaces.length === 1) void open(workspaces[0]!);- }, [workspaces, open, onCreate]);-- return (- <WizardFrame- title="Pick a workspace"- subtitle="You’re a member of these. A workspace is where your agents, rooms and teammates live."- /* The chevron below repeats this. It is unlabelled, so it cannot be the- only way back from a page whose rows all lead forward. Both are held- shut while a workspace is being opened, since leaving now would land- the user two pages on when it resolves. */- footer={- <Button variant="outline" onClick={onBack} disabled={opening !== null}>- Back- </Button>- }- pager={{- pageName: 'Pick a workspace',- onBack: opening === null ? onBack : null,- onNext: null,- }}- >- {query.isPending ? (- <p className="flex items-center gap-2 text-sm text-foreground-muted">- <Spinner className="size-3.5" />- Checking which workspaces you’re in…- </p>- ) : query.isError ? (- <div className="flex flex-col items-start gap-3">- <p className="text-sm text-destructive">- {failureText(query.error, `Could not ask ${server.name} which workspaces you’re in.`)}- </p>- <Button variant="outline" size="sm" onClick={() => void query.refetch()}>- Retry- </Button>- </div>- ) : (- <div className="flex w-full flex-col gap-3">- <ul className="flex flex-col gap-2">- {(workspaces ?? []).map((workspace) => (- <WorkspaceRow- key={workspace.id}- workspace={workspace}- opening={opening === workspace.id}- disabled={opening !== null}- onOpen={() => void open(workspace)}- />- ))}- </ul>-- {openError && <p className="text-sm text-destructive">{openError}</p>}-- <div className="flex items-center gap-3">- <span className="h-px flex-1 bg-border" />- <span className="text-xs text-foreground-muted">or start fresh</span>- <span className="h-px flex-1 bg-border" />- </div>-- <button- type="button"- onClick={onCreate}- disabled={opening !== null}- className="flex items-center justify-center gap-2 rounded-[10px] border border-dashed border-border px-3.5 py-3 text-sm font-medium text-foreground hover:bg-[var(--sel-soft)] disabled:opacity-50"- >- <Plus className="size-4" />- Create a new workspace- </button>- </div>- )}- </WizardFrame>- );-});--function WorkspaceRow({- workspace,- opening,- disabled,- onOpen,-}: {- workspace: Workspace;- opening: boolean;- disabled: boolean;- onOpen: () => void;-}) {- return (- <li>- <button- type="button"- onClick={onOpen}- disabled={disabled}- className="flex w-full items-center gap-3 rounded-[10px] border border-border bg-[var(--surface-2)] px-3.5 py-3 text-left hover:bg-[var(--sel-soft)] disabled:opacity-60"- >- <span className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-background-tertiary text-sm font-semibold text-foreground">- {initialOf(workspace.name)}- </span>- <span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">- {workspace.name}- </span>- {workspace.role && (- <span className="shrink-0 rounded bg-background-tertiary px-1 py-px text-[10px] font-medium tracking-wide text-foreground-muted uppercase">- {workspace.role}- </span>- )}- {opening ? (- <Spinner className="size-3.5 shrink-0" />- ) : (- <span className="shrink-0 text-sm text-foreground-muted">Open</span>- )}- </button>- </li>- );-}--const GRAPHEMES = new Intl.Segmenter();--/** By grapheme, so a name starting with an emoji is not cut in half. */-function initialOf(name: string): string {- return ([...GRAPHEMES.segment(name)][0]?.segment ?? '?').toUpperCase();-}diff --git a/console/apps/switch-console-desktop/src/renderer/features/onboarding/use-onboarding-checklist.ts b/console/apps/switch-console-desktop/src/renderer/features/onboarding/use-onboarding-checklist.tsindex b808d4669..1b79489ee 100644--- a/console/apps/switch-console-desktop/src/renderer/features/onboarding/use-onboarding-checklist.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/onboarding/use-onboarding-checklist.ts@@ -33,7 +33,7 @@ export function useOnboardingProgress(): OnboardingProgress {addServer: switchServersStore.servers.length > 0,agentProviders: (agentTypes ?? []).some((type) => type.available),onboardAgents: appState.locations.locations.size > 0,- createRoom: switchRoomsStore.listedRoomsInAllWorkspaces.length > 0,+ createRoom: switchRoomsStore.listedRoomsOnAllServers.length > 0,};}diff --git a/console/apps/switch-console-desktop/src/renderer/features/onboarding/welcome-page.tsx b/console/apps/switch-console-desktop/src/renderer/features/onboarding/welcome-page.tsxdeleted file mode 100644index 3cd6d121a..000000000--- a/console/apps/switch-console-desktop/src/renderer/features/onboarding/welcome-page.tsx+++ /dev/null@@ -1,109 +0,0 @@-import { Cloud, Server } from 'lucide-react';-import type { ReactNode } from 'react';-import { SwitchConsoleAppIcon } from '@renderer/lib/switch-console-app-icon';-import { Button } from '@renderer/lib/ui/button';-import { StepPager } from '@renderer/lib/ui/step-pager';-import { cn } from '@renderer/utils/utils';--const TAGLINE = 'Agents that work alongside your team, in the chat apps you already use.';--/**- * The first page of a fresh install: what Switch is, and where it should run.- *- * It takes the whole window. There is no sidebar behind it because there is- * nothing for a sidebar to list — no servers, so no rooms, agents or sessions —- * and a first impression made of empty containers says less about the app than- * one question does.- *- * The two places are a list, not a choice. Only one of them can be had: Switch- * Cloud has no endpoint to sign in to and no account to sign in with. A radio- * group would announce itself as something to pick between and then answer- * neither arrow key nor click, which is a worse page than an honest list of- * two, one of them marked unavailable. Cloud stays on the page rather than- * being left off it, because the question is "where should it run" and an- * answer that exists but is not ready yet is part of that answer.- *- * So nothing here is a control except the button, and the button says which of- * the two it takes — the emphasis on the card is a repeat of that in colour,- * not the only place it is written.- */-export function WelcomePage({ onContinue }: { onContinue: () => void }) {- return (- <div className="flex h-full flex-col bg-background text-foreground [-webkit-app-region:drag]">- <div className="flex min-h-0 flex-1 flex-col overflow-auto">- {/* Everything the page shows opts out of the drag region: a scroll- inside one is swallowed by the window move. What stays draggable is- the margin around it. */}- <div className="mx-auto flex w-full max-w-xl flex-1 flex-col justify-center gap-8 px-8 py-10 [-webkit-app-region:no-drag]">- <div className="flex flex-col items-center gap-4">- <SwitchConsoleAppIcon size={64} className="rounded-2xl" />- <h1 className="text-3xl font-semibold">Welcome to Switch</h1>- <p className="text-center text-sm text-foreground-muted">{TAGLINE}</p>- </div>-- <div className="flex flex-col gap-3">- <h2 className="text-sm font-medium">Where should it run?</h2>- <ul className="grid gap-3">- <HostingChoice- icon={<Cloud className="size-5" />}- title="Switch Cloud"- badge="Coming soon"- description="We would run it for you. Not open yet — there is nothing to sign in to."- unavailable- />- <HostingChoice- icon={<Server className="size-5" />}- title="Your own server"- description="Run the Switch stack on hardware you control. Your data and your accounts stay there."- />- </ul>- <div className="mt-1">- <Button onClick={onContinue}>Continue with your own server</Button>- </div>- </div>- </div>- </div>- <div className="[-webkit-app-region:no-drag]">- <StepPager pageName="Welcome" onBack={null} onNext={onContinue} />- </div>- </div>- );-}--function HostingChoice({- icon,- title,- badge,- description,- unavailable = false,-}: {- icon: ReactNode;- title: string;- badge?: string;- description: string;- /** Somewhere Switch cannot run yet. Said in the badge and the description- * too, so it does not rest on the greyed-out card alone. */- unavailable?: boolean;-}) {- return (- <li- className={cn(- 'flex list-none items-start gap-3 rounded-lg border p-4 text-left',- unavailable ? 'border-border opacity-60' : 'border-foreground'- )}- >- <span className="mt-0.5 text-foreground-muted">{icon}</span>- <div className="space-y-1">- <div className="flex items-center gap-2">- <span className="text-sm font-medium text-foreground">{title}</span>- {badge && (- <span className="rounded-full bg-background-tertiary-2 px-2 py-0.5 text-[10px] text-foreground-muted">- {badge}- </span>- )}- </div>- <p className="text-xs text-foreground-muted">{description}</p>- </div>- </li>- );-}diff --git a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/load-existing-agents-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/load-existing-agents-section.tsxindex b947f3e3e..5b2890e03 100644--- a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/load-existing-agents-section.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/load-existing-agents-section.tsx@@ -64,14 +64,10 @@ export const LOAD_AGENTS_QUERY_KEY = 'load-existing-agents';export function LoadExistingAgentsSection({sshHost,serverId,- workspaceId,initiallyOpen = false,}: {sshHost: string;serverId: string;- /** The workspace whose agents are discovered. One server can host several,- * and each answers `GET /agents` with its own list. */- workspaceId: string;initiallyOpen?: boolean;}) {const [isOpen, setIsOpen] = useState(initiallyOpen);@@ -80,8 +76,8 @@ export function LoadExistingAgentsSection({const showRemoveConfig = useShowModal('removeAgentConfigModal');const discovery = useQuery({- queryKey: [LOAD_AGENTS_QUERY_KEY, sshHost, workspaceId],- queryFn: () => rpc.agents.discoverLoadableAgentsOnHost({ sshHost, workspaceId }),+ queryKey: [LOAD_AGENTS_QUERY_KEY, sshHost, serverId],+ queryFn: () => rpc.agents.discoverLoadableAgentsOnHost({ sshHost, serverId }),enabled: isOpen && scanRequested,});@@ -198,7 +194,7 @@ export function LoadExistingAgentsSection({// waiting for the SSH round trip that a full refetch requires.const loaded = new Set(names);queryClient.setQueryData(- [LOAD_AGENTS_QUERY_KEY, sshHost, workspaceId],+ [LOAD_AGENTS_QUERY_KEY, sshHost, serverId],(prev: { agents: LoadableAgentRow[]; serverApiUrl: string } | undefined) => {if (!prev) return prev;return {@@ -220,9 +216,7 @@ export function LoadExistingAgentsSection({));- void queryClient.invalidateQueries({- queryKey: [LOAD_AGENTS_QUERY_KEY, sshHost, workspaceId],- });+ void queryClient.invalidateQueries({ queryKey: [LOAD_AGENTS_QUERY_KEY, sshHost, serverId] });},onError: (error) => {toast({@@ -252,9 +246,7 @@ export function LoadExistingAgentsSection({next.delete(key);return next;});- void queryClient.invalidateQueries({- queryKey: [LOAD_AGENTS_QUERY_KEY, sshHost, workspaceId],- });+ void queryClient.invalidateQueries({ queryKey: [LOAD_AGENTS_QUERY_KEY, sshHost, serverId] });},onError: (error) => {toast({@@ -279,8 +271,7 @@ export function LoadExistingAgentsSection({const [manualDir, setManualDir] = useState('');const manualScan = useMutation({- mutationFn: (dir: string) =>- rpc.agents.discoverLoadableAgentsInDir({ sshHost, dir, workspaceId }),+ mutationFn: (dir: string) => rpc.agents.discoverLoadableAgentsInDir({ sshHost, dir, serverId }),onSuccess: (found) => {setManualServerApiUrl(found.serverApiUrl);setManualAgents((prev) => {@@ -296,9 +287,9 @@ export function LoadExistingAgentsSection({const deepScan = useMutation({mutationFn: () =>- rpc.agents.discoverLoadableAgentsOnHost({ sshHost, workspaceId, includeHomeScan: true }),+ rpc.agents.discoverLoadableAgentsOnHost({ sshHost, serverId, includeHomeScan: true }),onSuccess: (result) => {- queryClient.setQueryData([LOAD_AGENTS_QUERY_KEY, sshHost, workspaceId], result);+ queryClient.setQueryData([LOAD_AGENTS_QUERY_KEY, sshHost, serverId], result);},});@@ -413,7 +404,7 @@ export function LoadExistingAgentsSection({disabled={discovery.isFetching}onClick={() =>void queryClient.invalidateQueries({- queryKey: [LOAD_AGENTS_QUERY_KEY, sshHost, workspaceId],+ queryKey: [LOAD_AGENTS_QUERY_KEY, sshHost, serverId],})}>diff --git a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-host-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-host-view.tsxindex 271f4b5d3..eb5d0dc3e 100644--- a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-host-view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-host-view.tsx@@ -37,7 +37,6 @@ import {import { deriveHostStatus } from '@shared/core/remote-hosts/host-status';import { isHostBlocked } from '@shared/core/remote-hosts/reachability';import { switchServersStore } from '../../switch-servers/switch-servers-store';-import { workspacesStore } from '../../workspaces/workspaces-store';import { hostReachabilityStore } from '../host-reachability-store';import { hostSetupStore } from '../host-setup-store';import { HostUnreachablePanel } from '../host-unreachable-panel';@@ -132,10 +131,6 @@ export const RemoteHostMainPanel = observer(function RemoteHostMainPanel() {if (managed) return managed.id;return activeServer?.id ?? servers[0]?.id ?? null;}, [sshHost, servers, activeServer]);- // Which of that server's workspaces the discovery below asks. `GET /agents`- // answers for one tenant, so without it the list would be whichever workspace- // the session last selected.- const workspaceId = workspacesStore.idOnServerInScope(serverId);const status = deriveHostStatus(reachability, plan.data ?? null);const { prerequisites, agentTypes } = useMemo(@@ -316,11 +311,10 @@ export const RemoteHostMainPanel = observer(function RemoteHostMainPanel() {</section>)}- {serverId && workspaceId && (+ {serverId && (<LoadExistingAgentsSectionsshHost={sshHost}serverId={serverId}- workspaceId={workspaceId}initiallyOpen={justAdded}/>)}@@ -355,9 +349,6 @@ export const remoteHostView = {// No titlebar slot: the page header already names the host and repeats the// alias underneath it, so a third copy in the title bar was only noise.MainPanel: RemoteHostMainPanel,- // A host is somewhere agents run, not something a server owns: its page says- // the same things with no server registered as with ten.- worksWithoutServer: true,canActivate: (params: unknown): GuardResult => {// Params can come from a snapshot written by an older build, so validate// rather than trust: a view with no host to show has nothing to render.diff --git a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-hosts-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-hosts-view.tsxindex d41c1cc8e..95760bd76 100644--- a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-hosts-view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-hosts-view.tsx@@ -342,10 +342,6 @@ function RemoveHostButton({*/export const remoteHostsView = {MainPanel: RemoteHostsSettingsPage,- // A host is somewhere agents run, not something a server owns, so the page- // stands up with no server registered — as does the Settings tab it forwards- // to.- worksWithoutServer: true,canActivate: (): GuardResult => ({ok: false,redirect: 'settings',diff --git a/console/apps/switch-console-desktop/src/renderer/features/room-templates/entity-fields.tsx b/console/apps/switch-console-desktop/src/renderer/features/room-templates/entity-fields.tsxindex 05d7ed228..88b0d245d 100644--- a/console/apps/switch-console-desktop/src/renderer/features/room-templates/entity-fields.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/room-templates/entity-fields.tsx@@ -20,11 +20,11 @@ import type {} from '@shared/core/switch-servers/switch-servers';/**- * Everything the workspace has that a template can point at, read once by the+ * Everything the server has that a template can point at, read once by the* wizard and handed to every field that offers a choice from it.*/export type EntityLists = {- workspaceId: string | null;+ serverId: string;agents: AgentPick[];agentsLoading: boolean;rooms: RoomPick[];@@ -32,10 +32,10 @@ export type EntityLists = {bridges: RemoteBridge[];/** Null while the signed-in user's linked accounts are unknown. */identities: LinkedIdentity[] | null;- /** Platform users Switch has already seen in this workspace. */+ /** Platform users Switch has already seen on this server. */knownUsers: RemoteExternalUser[];/** The bridge the room will land on, for directory lookups. Null when the- * template leaves it open and the workspace has no default. */+ * template leaves it open and the server has no default. */bridgeId: string | null;};@@ -54,7 +54,7 @@ function agentTileFor(name: string, lists: EntityLists, onRemove: () => void) {<ChosenAgentTilekey={name}agent={found}- subtitle={agentProviderLabelFor(found.id, lists.workspaceId)}+ subtitle={agentProviderLabelFor(found.id, lists.serverId)}onRemove={onRemove}/>) : (@@ -84,10 +84,7 @@ function AgentCombobox({onPick={(agent) => onPick(agent.name)}searchText={(agent) => agent.name}renderItem={(agent) => (- <AgentPickerRow- agent={agent}- subtitle={agentProviderLabelFor(agent.id, lists.workspaceId)}- />+ <AgentPickerRow agent={agent} subtitle={agentProviderLabelFor(agent.id, lists.serverId)} />)}disabled={lists.agentsLoading}placeholder={lists.agentsLoading ? 'Loading agents…' : 'Search agents…'}@@ -278,13 +275,12 @@ function UserCombobox({const [query, setQuery] = useState('');const debounced = useDebounce(query.trim(), SEARCH_DEBOUNCE_MS);const bridgeId = lists.bridgeId;- const searchable =- bridgeId !== null && lists.workspaceId !== null && debounced.length >= MIN_QUERY_LENGTH;+ const searchable = bridgeId !== null && debounced.length >= MIN_QUERY_LENGTH;const directory = useQuery({- queryKey: ['bridge-directory', lists.workspaceId, bridgeId, debounced],+ queryKey: ['bridge-directory', lists.serverId, bridgeId, debounced],queryFn: () =>- rpc.workspaces.searchBridgeDirectory({- workspaceId: lists.workspaceId as string,+ rpc.switchServers.searchBridgeDirectory({+ serverId: lists.serverId,bridgeId: bridgeId as string,query: debounced,}),diff --git a/console/apps/switch-console-desktop/src/renderer/features/room-templates/room-template-capture-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/room-templates/room-template-capture-view.tsxindex 59eedad2c..f6f3bddca 100644--- a/console/apps/switch-console-desktop/src/renderer/features/room-templates/room-template-capture-view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/room-templates/room-template-capture-view.tsx@@ -8,7 +8,6 @@ import { ServerSectionTitlebar } from '@renderer/features/switch-servers/server-import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';import { prefillForSave } from '@renderer/features/templates/agent-template-data';-import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { failureText } from '@renderer/lib/errors/describe-failure';import { rpc } from '@renderer/lib/ipc';import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';@@ -239,9 +238,7 @@ const CapturePanel = observer(function CapturePanel() {let cancelled = false;void (async () => {try {- const workspaceId = workspacesStore.idOnServerInScope(serverId);- if (workspaceId === null) throw new Error('This server’s workspace is not known yet.');- const yaml = await rpc.workspaces.exportRoomYaml({ workspaceId, roomId });+ const yaml = await rpc.switchServers.exportRoomYaml({ serverId, roomId });if (cancelled) return;setOriginalYaml(yaml);setCandidates(extractCandidates(yaml));diff --git a/console/apps/switch-console-desktop/src/renderer/features/room-templates/room-template-import-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/room-templates/room-template-import-view.tsxindex dfb3128e8..ea7f4c836 100644--- a/console/apps/switch-console-desktop/src/renderer/features/room-templates/room-template-import-view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/room-templates/room-template-import-view.tsx@@ -12,7 +12,6 @@ import {type TemplateAccess,visibilityOf,} from '@renderer/features/templates/template-visibility';-import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { failureText } from '@renderer/lib/errors/describe-failure';import { toast } from '@renderer/lib/hooks/use-toast';import { rpc } from '@renderer/lib/ipc';@@ -24,7 +23,6 @@ import { Button } from '@renderer/lib/ui/button';import { Field, FieldGroup, FieldLabel } from '@renderer/lib/ui/field';import { Input } from '@renderer/lib/ui/input';import { SegmentedControl } from '@renderer/lib/ui/segmented-control';-import { StepPager } from '@renderer/lib/ui/step-pager';// ── Source step ─────────────────────────────────────────────────────────────@@ -41,7 +39,6 @@ function SourceStep({onYamlChange,parseError,onNext,- canAdvance,onFileSelect,onSaveToServer,saving,@@ -51,9 +48,6 @@ function SourceStep({onYamlChange: (text: string) => void;parseError: string | null;onNext: () => void;- /** Whether there is a document to go on with. Decided by the page, so the- * Next button and the pager's arrow cannot come to different answers. */- canAdvance: boolean;onFileSelect: (name: string) => void;onSaveToServer: () => void;saving: boolean;@@ -180,7 +174,7 @@ function SourceStep({<Save className="mr-1.5 size-3.5" />{saving ? 'Saving…' : 'Save to workspace'}</Button>- <Button disabled={!canAdvance} onClick={onNext}>+ <Button disabled={!yamlText.trim() || saving} onClick={onNext}>Next<ArrowRight className="ml-1.5 size-3.5" /></Button>@@ -294,10 +288,8 @@ const TemplateImportPanel = observer(function TemplateImportPanel() {const kind = yamlText !== initialYaml ? await rpc.agentTemplates.kind({ yamlText }) : null;// Each field is sent only when changed, so saving one cannot put back// another that someone else changed meanwhile.- const workspaceId = workspacesStore.idOnServerInScope(serverId);- if (workspaceId === null) throw new Error('This server’s workspace is not known yet.');- const saved = await rpc.workspaces.updateTemplate({- workspaceId,+ const saved = await rpc.switchServers.updateTemplate({+ serverId,templateId: editingTemplate.id,...(name.trim() !== editingTemplate.name.trim() ? { name: name.trim() } : {}),...(description.trim() !== editingTemplate.description.trim()@@ -335,10 +327,6 @@ const TemplateImportPanel = observer(function TemplateImportPanel() {}}, [initialTemplateId, initialYaml, editing, serverId, handleParseAndAdvance]);- // The pager's arrow only repeats the Next button below, so both read this- // rather than spelling the condition once each and drifting apart.- const canAdvance = yamlText.trim().length > 0 && !saving;-if (editingTemplate) {const nothingChanged =yamlText === initialYaml &&@@ -388,7 +376,6 @@ const TemplateImportPanel = observer(function TemplateImportPanel() {onYamlChange={setYamlText}parseError={parseError}onNext={handleParseAndAdvance}- canAdvance={canAdvance}onFileSelect={setSourceName}onSaveToServer={handleSaveToServer}saving={saving}@@ -411,20 +398,12 @@ const TemplateImportPanel = observer(function TemplateImportPanel() {<ServerPagetitle="Import a template"description="Paste an agent, room or group template, or pick a YAML file. The document says which it is."- footer={- <StepPager- pageName="Pick a template"- onBack={null}- onNext={canAdvance ? () => void handleParseAndAdvance() : null}- />- }><SourceStepyamlText={yamlText}onYamlChange={setYamlText}parseError={parseError}onNext={handleParseAndAdvance}- canAdvance={canAdvance}onFileSelect={setSourceName}onSaveToServer={handleSaveToServer}saving={saving}diff --git a/console/apps/switch-console-desktop/src/renderer/features/sessions/create-session-modal/create-session-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/sessions/create-session-modal/create-session-modal.tsxindex 161812877..6bd08e04f 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sessions/create-session-modal/create-session-modal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sessions/create-session-modal/create-session-modal.tsx@@ -83,27 +83,28 @@ function useDefaultLocationId(propLocationId?: string): string | undefined {*/function useRoomMemberAgents(roomId: string | undefined): {agents: Agent[];- workspaceId: string | null;+ serverId: string | null;loading: boolean;} {- const workspaceId = roomId ? switchRoomsStore.roomWorkspaceId(roomId) : null;+ const serverId = roomId ? switchRoomsStore.roomServerId(roomId) : null;useEffect(() => {if (roomId) void agentsStore.load();}, [roomId]);const membersQuery = useQuery({- queryKey: ['roomAgentIds', workspaceId, roomId],- queryFn: () => rpc.workspaces.listRoomAgentIds({ workspaceId: workspaceId!, roomId: roomId! }),- enabled: !!workspaceId && !!roomId,+ queryKey: ['roomAgentIds', serverId, roomId],+ queryFn: () => rpc.switchServers.listRoomAgentIds({ serverId: serverId!, roomId: roomId! }),+ enabled: !!serverId && !!roomId,});const memberIds = useMemo(() => new Set(membersQuery.data ?? []), [membersQuery.data]);- const agents = (workspaceId ? agentsStore.agentsInWorkspace(workspaceId) : []).filter(- (a) => a.switchAgentId && memberIds.has(a.switchAgentId)- );+ const agents = [...agentsStore.byLocation.values()]+ .flat()+ .filter((a) => a.serverId === serverId && a.switchAgentId && memberIds.has(a.switchAgentId))+ .sort((a, b) => a.name.localeCompare(b.name));- return { agents, workspaceId, loading: membersQuery.isLoading || !agentsStore.loaded };+ return { agents, serverId, loading: membersQuery.isLoading || !agentsStore.loaded };}/**@@ -210,30 +211,24 @@ export const CreateSessionModal = observer(function CreateSessionModal({? (locationAgents.find((a) => a.name === effectiveAgentName) ?? null): null;- const agentWorkspaceId = effectiveAgentName- ? (subagent?.workspaceId ?? null)- : (agent?.workspaceId ?? null);+ const serverId = effectiveAgentName ? (subagent?.serverId ?? null) : (agent?.serverId ?? null);const switchAgentId = effectiveAgentName? (subagent?.switchAgentId ?? null): (agent?.switchAgentId ?? null);useEffect(() => {- if (!roomFirst && agentWorkspaceId && switchAgentId) {- void switchRoomsStore.fetchAgentRooms(agentWorkspaceId, switchAgentId);+ if (!roomFirst && serverId && switchAgentId) {+ void switchRoomsStore.fetchAgentRooms(serverId, switchAgentId);}- }, [roomFirst, agentWorkspaceId, switchAgentId]);+ }, [roomFirst, serverId, switchAgentId]);const rooms =- agentWorkspaceId && switchAgentId- ? (switchRoomsStore.roomsFor(agentWorkspaceId, switchAgentId) ?? []).filter(- (r) => !r.archived- )+ serverId && switchAgentId+ ? (switchRoomsStore.roomsFor(serverId, switchAgentId) ?? []).filter((r) => !r.archived): [];const roomsLoading =- !!agentWorkspaceId &&- !!switchAgentId &&- switchRoomsStore.isLoading(agentWorkspaceId, switchAgentId);- const canConnectRoom = !roomFirst && !!agentWorkspaceId && !!switchAgentId;+ !!serverId && !!switchAgentId && switchRoomsStore.isLoading(serverId, switchAgentId);+ const canConnectRoom = !roomFirst && !!serverId && !!switchAgentId;// In room-first mode the room is given, not chosen; everything downstream// (roles, the connect prompt) keys off the same value either way.@@ -248,15 +243,15 @@ export const CreateSessionModal = observer(function CreateSessionModal({}: null: room;- const roleWorkspaceId = roomFirst ? roomMembers.workspaceId : agentWorkspaceId;+ const roleServerId = roomFirst ? roomMembers.serverId : serverId;// Roles are room-scoped, so only fetch once a room is chosen. The set is small// and changes rarely, so a plain per-room query (no shared cache) is enough.const rolesQuery = useQuery({- queryKey: ['roomRoles', roleWorkspaceId, activeRoom?.roomId],+ queryKey: ['roomRoles', roleServerId, activeRoom?.roomId],queryFn: () =>- rpc.workspaces.listRoomRoles({ workspaceId: roleWorkspaceId!, roomId: activeRoom!.roomId }),- enabled: !!roleWorkspaceId && !!activeRoom,+ rpc.switchServers.listRoomRoles({ serverId: roleServerId!, roomId: activeRoom!.roomId }),+ enabled: !!roleServerId && !!activeRoom,});const roles = rolesQuery.data ?? [];diff --git a/console/apps/switch-console-desktop/src/renderer/features/settings/settings-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/settings/settings-view.tsxindex 110e01933..ddba564ae 100644--- a/console/apps/switch-console-desktop/src/renderer/features/settings/settings-view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/settings/settings-view.tsx@@ -67,8 +67,4 @@ export function SettingsMainPanel() {export const settingsView = {WrapView: SettingsViewWrapper,MainPanel: SettingsMainPanel,- // Preferences, themes, remote hosts and connector installs all stand on their- // own before any server is registered, and ⌘, has to lead somewhere on a- // fresh install.- worksWithoutServer: true,};diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-item.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-item.tsxindex db229f148..8eafba01d 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-item.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-item.tsx@@ -23,7 +23,7 @@ import { useNavigate, useParams } from '@renderer/lib/layout/navigation-providerimport { useWorkspaceSlots } from '@renderer/lib/layout/workspace-slots';import { useShowModal } from '@renderer/lib/modal/modal-provider';import { sidebarStore } from '@renderer/lib/stores/app-state';-import { useAgentIconUrl } from '@renderer/lib/stores/use-workspace-agents';+import { useAgentIconUrl } from '@renderer/lib/stores/use-remote-agents';import {ContextMenu,ContextMenuContent,@@ -64,7 +64,7 @@ export const SidebarAgentItem = observer(function SidebarAgentItem({const agentName = agent.name;const location = getLocationStore(agent.locationId);- const iconUrl = useAgentIconUrl(agent.workspaceId, agent.switchAgentId);+ const iconUrl = useAgentIconUrl(agent.serverId, agent.switchAgentId);// The agent's name IS its Switch identity: Switch Console chose it, registered it// under that name, and keys its credentials and definition by it. Reading thediff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-agent-row.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-agent-row.tsxindex 43c7a5ca2..16346bef2 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-agent-row.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-agent-row.tsx@@ -14,7 +14,7 @@ import { rpc } from '@renderer/lib/ipc';import { useNavigate } from '@renderer/lib/layout/navigation-provider';import { useShowModal } from '@renderer/lib/modal/modal-provider';import { appState, sidebarStore } from '@renderer/lib/stores/app-state';-import { useAgentIconUrl } from '@renderer/lib/stores/use-workspace-agents';+import { useAgentIconUrl } from '@renderer/lib/stores/use-remote-agents';import {ContextMenu,ContextMenuContent,@@ -62,7 +62,7 @@ export const RoomAgentRow = observer(function RoomAgentRow({// This is a Switch room's member list, so the Switch identity is what matters// — and that is the stored name: it is what was registered on the server.const label = agent.name || 'Unnamed agent';- const iconUrl = useAgentIconUrl(agent.workspaceId, agent.switchAgentId);+ const iconUrl = useAgentIconUrl(agent.serverId, agent.switchAgentId);const expandKey = roomAgentGroupKey(roomId, agent.id);const expanded = sidebarStore.isGroupExpanded(expandKey);@@ -82,12 +82,12 @@ export const RoomAgentRow = observer(function RoomAgentRow({if (!location) return null;const removeFromRoom = () => {- const workspaceId = switchRoomsStore.roomWorkspaceId(roomId);- if (!workspaceId || !agent.switchAgentId) return;+ const serverId = switchRoomsStore.roomServerId(roomId);+ if (!serverId || !agent.switchAgentId) return;const roomLabel = switchRoomsStore.roomNameById(roomId) ?? 'the room';void toastPromise(- rpc.workspaces- .removeRoomAgent({ workspaceId, roomId, agentId: agent.switchAgentId })+ rpc.switchServers+ .removeRoomAgent({ serverId, roomId, agentId: agent.switchAgentId }).then(() => switchRoomsStore.refreshRoomState()),{loading: `Removing ${label} from ${roomLabel}…`,diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsxindex 996bed691..94aac1b64 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx@@ -132,8 +132,8 @@ export const SidebarGroupedList = observer(function SidebarGroupedList() {*/const RoomStateDisclosure = observer(function RoomStateDisclosure() {const { navigate } = useNavigate();- const signedOut = switchRoomsStore.workspacesNotSignedIn;- const failed = switchRoomsStore.workspacesThatFailedToLoad;+ const signedOut = switchRoomsStore.serversNotSignedIn;+ const failed = switchRoomsStore.serversThatFailedToLoad;// Being signed out is the whole explanation, so it is said on its own: the// memberships that "didn't load" are the same fact, and offering a retry fordiff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-icon-backfill-toast.test.ts b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-icon-backfill-toast.test.tsindex d21018db3..d1076cb30 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-icon-backfill-toast.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-icon-backfill-toast.test.ts@@ -1,8 +1,8 @@import { beforeEach, describe, expect, it, vi } from 'vitest';/**- * The agent-icon backfill notice must be said once per workspace per run,- * however many times the sidebar refreshes (CHOO-2344).+ * The agent-icon backfill notice must be said once per server per run, however+ * many times the sidebar refreshes (CHOO-2344).** `refreshSidebarRoomState` runs on first paint, window focus, sign-in, the* background reconcile, the retry button and every membership-changing@@ -20,20 +20,19 @@ const AGENT = {id: 'agent-1',name: 'agent one',serverId: 'server-1',- workspaceId: 'workspace-1',switchAgentId: 'switch-agent-1',createdAt: '2026-01-01T00:00:00.000Z',};vi.mock('@renderer/lib/hooks/use-toast', () => ({ toast }));vi.mock('@renderer/lib/ipc', () => ({- rpc: { workspaces: { backfillAgentIcons } },+ rpc: { switchServers: { backfillAgentIcons } },}));vi.mock('@renderer/features/locations/stores/agents-store', () => ({agentsStore: {load: vi.fn().mockResolvedValue(undefined),byLocation: new Map([[LOCATION.id, [AGENT]]]),- agentsInWorkspaceAtLocation: () => [AGENT],+ agentsOnServerAtLocation: () => [AGENT],},}));vi.mock('@renderer/features/switch-servers/switch-rooms-store', () => ({@@ -42,8 +41,8 @@ vi.mock('@renderer/features/switch-servers/switch-rooms-store', () => ({loadRoomNames: vi.fn().mockResolvedValue(undefined),},}));-vi.mock('@renderer/features/workspaces/workspaces-store', () => ({- workspacesStore: { activeId: 'workspace-1' },+vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({+ switchServersStore: { activeServerId: 'server-1' },}));vi.mock('@renderer/lib/stores/app-state', () => ({sidebarStore: {@@ -69,7 +68,7 @@ describe('agent icon backfill reporting', () => {backfillAgentIcons.mockReset();});- it('reports a workspace without the icon endpoint once, not on every refresh', async () => {+ it('reports a server without the icon endpoint once, not on every refresh', async () => {backfillAgentIcons.mockResolvedValue({ kind: 'unsupported' });const { refreshSidebarRoomState } = await loadSubject();diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsxindex afb66e379..697081c75 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsx@@ -54,14 +54,14 @@ export function isRoomNameKnown(roomKey: string): boolean {*/export function deleteRoomAction(roomKey: string,- showDeleteRoomModal: (args: { workspaceId: string; roomId: string; roomName: string }) => void+ showDeleteRoomModal: (args: { serverId: string; roomId: string; roomName: string }) => void): (() => void) | null {if (roomKey === UNASSIGNED_ROOM_KEY) return null;- const workspaceId = switchRoomsStore.roomWorkspaceId(roomKey);+ const serverId = switchRoomsStore.roomServerId(roomKey);const room = switchRoomsStore.roomSummaryById(roomKey);- if (!workspaceId || !room) return null;- if (!switchRoomsStore.canDeleteRoom(workspaceId, room)) return null;- return () => showDeleteRoomModal({ workspaceId, roomId: roomKey, roomName: room.name });+ if (!serverId || !room) return null;+ if (!switchRoomsStore.canDeleteRoom(serverId, room)) return null;+ return () => showDeleteRoomModal({ serverId, roomId: roomKey, roomName: room.name });}/** Show a room's conversation in the main panel (no-op for Unassigned, whichdiff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-store.test.ts b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-store.test.tsindex 2bcfdb4e8..1d1d1eef9 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-store.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-store.test.ts@@ -1,9 +1,8 @@import { afterEach, describe, expect, it, vi } from 'vitest';import { agentsStore } from '@renderer/features/locations/stores/agents-store';-import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';+import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';import type { AgentConnectionKind } from '@shared/core/agents/agent-connection';import type { Agent } from '@shared/core/agents/agents';-import type { Workspace } from '@shared/core/workspaces/workspaces';import {agentExpandKey,agentRoomGroupKey,@@ -15,19 +14,6 @@ import {type SidebarLocationManager = ConstructorParameters<typeof SidebarStore>[0];-/**- * Scope the window to a workspace, the way choosing one in the switcher does.- * Both workspaces here sit on the same server, which is the case the scope has- * to tell apart: scoping by server would show them as one tree.- */-function scopeToWorkspace(workspaceId: string | null): void {- workspacesStore.workspaces = [- { id: 'ws-1', serverId: 'server-1' } as Workspace,- { id: 'ws-2', serverId: 'server-1' } as Workspace,- ];- workspacesStore.activeId = workspaceId;-}-vi.mock('@renderer/lib/ipc', () => ({events: {on: vi.fn(),@@ -281,88 +267,87 @@ describe('SidebarStore grouping', () => {});});-describe('SidebarStore active-workspace scoping', () => {- function linkAgent(locationId: string, workspaceId: string | null) {- agentsStore.byLocation.set(locationId, [{ locationId, workspaceId } as Agent]);+describe('SidebarStore active-server scoping', () => {+ function linkAgent(locationId: string, serverId: string | null) {+ agentsStore.byLocation.set(locationId, [{ locationId, serverId } as Agent]);}afterEach(() => {- scopeToWorkspace(null);+ switchServersStore.activeServerId = null;agentsStore.byLocation.clear();});- it("shows only the active workspace's locations", () => {+ it("shows only the active server's locations", () => {const store = new SidebarStore(locationManager([{ id: 'a', createdAt: '2026-01-01T00:00:00.000Z' },{ id: 'b', createdAt: '2026-01-02T00:00:00.000Z' },]));- linkAgent('a', 'ws-1');- linkAgent('b', 'ws-2');- scopeToWorkspace('ws-1');+ linkAgent('a', 'server-1');+ linkAgent('b', 'server-2');+ switchServersStore.activeServerId = 'server-1';expect(store.orderedLocations.map((p) => p.id)).toEqual(['a']);expect(store.isEmpty).toBe(false);});- it('shows all locations when no workspace is active', () => {+ it('shows all locations when no server is active', () => {const store = new SidebarStore(locationManager([{ id: 'a', createdAt: '2026-01-01T00:00:00.000Z' },{ id: 'b', createdAt: '2026-01-02T00:00:00.000Z' },]));- linkAgent('a', 'ws-1');- linkAgent('b', 'ws-2');+ linkAgent('a', 'server-1');+ linkAgent('b', 'server-2');expect(store.orderedLocations.map((p) => p.id).sort()).toEqual(['a', 'b']);});- it('hides unlinked locations when a workspace is active', () => {+ it('hides unlinked locations when a server is active', () => {const store = new SidebarStore(locationManager([{ id: 'a', createdAt: '2026-01-01T00:00:00.000Z' }]));linkAgent('a', null);- scopeToWorkspace('ws-1');+ switchServersStore.activeServerId = 'server-1';expect(store.orderedLocations).toEqual([]);expect(store.isEmpty).toBe(true);});- it('shows a directory shared between workspaces under both (CHOO-2044)', () => {- // A directory is a place on disk, not one workspace's territory. Resolving it- // to a single one filed it under whichever agent came back first, and the- // other workspace's agents vanished from the tree. The two here share a- // server, so a server-scoped tree would not tell them apart at all.+ it('shows a directory shared between servers under both (CHOO-2044)', () => {+ // A directory is a place on disk, not one server's territory. Resolving it to+ // a single server filed it under whichever agent came back first, and the+ // other server's agents vanished from the tree.const store = new SidebarStore(locationManager([{ id: 'shared', createdAt: '2026-01-01T00:00:00.000Z' }]));agentsStore.byLocation.set('shared', [- { locationId: 'shared', workspaceId: 'ws-1' } as Agent,- { locationId: 'shared', workspaceId: 'ws-2' } as Agent,+ { locationId: 'shared', serverId: 'server-1' } as Agent,+ { locationId: 'shared', serverId: 'server-2' } as Agent,]);- scopeToWorkspace('ws-1');+ switchServersStore.activeServerId = 'server-1';expect(store.orderedLocations.map((p) => p.id)).toEqual(['shared']);- scopeToWorkspace('ws-2');+ switchServersStore.activeServerId = 'server-2';expect(store.orderedLocations.map((p) => p.id)).toEqual(['shared']);- scopeToWorkspace('ws-3');+ switchServersStore.activeServerId = 'server-3';expect(store.orderedLocations).toEqual([]);});- it('describes a shared directory by an agent in the active workspace (CHOO-2044)', () => {+ it('describes a shared directory by an agent on the active server (CHOO-2044)', () => {const store = new SidebarStore(locationManager([{ id: 'shared', createdAt: '2026-01-01T00:00:00.000Z' }]));agentsStore.byLocation.set('shared', [- { locationId: 'shared', workspaceId: 'ws-1', providerId: 'claude' } as Agent,- { locationId: 'shared', workspaceId: 'ws-2', providerId: 'codex' } as Agent,+ { locationId: 'shared', serverId: 'server-1', providerId: 'claude' } as Agent,+ { locationId: 'shared', serverId: 'server-2', providerId: 'codex' } as Agent,]);- scopeToWorkspace('ws-2');+ switchServersStore.activeServerId = 'server-2';expect(store.locationProviderId('shared')).toBe('codex');});});@@ -423,12 +408,12 @@ describe('SidebarStore filters', () => {}function linkAgent(locationId: string, fields: { providerId?: Agent['providerId'] }) {- agentsStore.byLocation.set(locationId, [{ locationId, workspaceId: null, ...fields } as Agent]);+ agentsStore.byLocation.set(locationId, [{ locationId, serverId: null, ...fields } as Agent]);}afterEach(() => {agentsStore.byLocation.clear();- scopeToWorkspace(null);+ switchServersStore.activeServerId = null;});it('returns all locations unfiltered when no filter is active', () => {diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-store.ts b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-store.tsindex 5e2d0501a..8a5725397 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-store.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-store.ts@@ -8,7 +8,7 @@ import {unregisteredSessionData,type SessionStore,} from '@renderer/features/sessions/stores/session-store';-import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';+import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';import type { Snapshottable } from '@renderer/lib/stores/snapshottable';import type { AgentConnectionKind } from '@shared/core/agents/agent-connection';import {@@ -237,27 +237,27 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {}/**- * Whether a location has anything to show under the active workspace. The whole- * sidebar tree is scoped to one workspace at a time: a location shows when it- * holds at least one agent in {@link workspacesStore.activeId}. Unregistered- * locations (mid-onboarding, no agent row yet) always show so the user sees- * progress. When no workspace is active, nothing is hidden.+ * Whether a location has anything to show under the active server. The whole+ * sidebar tree is scoped to one server at a time: a location shows when it holds+ * at least one agent linked to {@link switchServersStore.activeServerId}.+ * Unregistered locations (mid-onboarding, no agent row yet) always show so the+ * user sees progress. When no server is active, nothing is hidden.*- * A directory can hold agents for several workspaces, so this is "has any here",+ * A directory can hold agents for several servers, so this is "has any here",* not "belongs to". Which of its agents are then drawn is* {@link scopedAgents}' business — a location being in scope does not put every- * agent in it on this workspace's tree (CHOO-2044).+ * agent in it on this server's tree (CHOO-2044).*/isLocationInActiveScope(locationId: string): boolean {- const activeWorkspaceId = workspacesStore.activeId;- if (!activeWorkspaceId) return true;+ const activeServerId = switchServersStore.activeServerId;+ if (!activeServerId) return true;const location = this.locationManager.locations.get(locationId);if (location && location.state === 'unregistered') return true;- return agentsStore.locationHasAgentsInWorkspace(locationId, activeWorkspaceId);+ return agentsStore.locationHasAgentsOnServer(locationId, activeServerId);}/**- * Workspace-scoped locations, newest first. Locations are no longer a level of+ * Server-scoped locations, newest first. Locations are no longer a level of* the sidebar tree — the manual order the user drags lives on agents and* rooms — so this is the plain default order the agent list is built from.*/@@ -271,12 +271,12 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {/** The representative agent of a location (the agent shown on its sidebar row):* the first real (non-definition) agent, not a former subagent's row. Restricted- * to the active workspace, so a directory shared with another does not describe- * itself by an agent this tree is not showing. */+ * to the active server, so a directory shared with another server does not+ * describe itself by an agent this tree is not showing. */private parentAgent(locationId: string) {- const activeWorkspaceId = workspacesStore.activeId;- const agents = activeWorkspaceId- ? agentsStore.agentsInWorkspaceAtLocation(locationId, activeWorkspaceId)+ const activeServerId = switchServersStore.activeServerId;+ const agents = activeServerId+ ? agentsStore.agentsOnServerAtLocation(locationId, activeServerId): (agentsStore.byLocation.get(locationId) ?? []);return agents[0] ?? (agentsStore.byLocation.get(locationId) ?? [])[0];}diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-tree-data.ts b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-tree-data.tsindex a5e875889..f9e406607 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-tree-data.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-tree-data.ts@@ -2,7 +2,7 @@ import { agentsStore } from '@renderer/features/locations/stores/agents-store';import type { LocationStore } from '@renderer/features/locations/stores/location';import type { SessionStore } from '@renderer/features/sessions/stores/session-store';import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';-import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';+import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';import { toast } from '@renderer/lib/hooks/use-toast';import { rpc } from '@renderer/lib/ipc';import { sidebarStore } from '@renderer/lib/stores/app-state';@@ -20,26 +20,22 @@ import type { AgentIconBackfill } from '@shared/core/switch-servers/switch-serveexport type AgentEntry = { agent: Agent; location: LocationStore };/**- * A location's agents that the active workspace's tree should draw.+ * A location's agents that the active server's tree should draw.*- * A location is in scope when *some* of its agents are in the active workspace,- * but a directory can hold agents for several at once — so scope has to be+ * A location is in scope when *some* of its agents are on the active server, but a+ * directory can hold agents for several servers at once — so scope has to be* re-applied per agent here. Taking the location's whole list instead drew agents- * belonging to another workspace under this one, which read as "onboarding brought+ * belonging to another server under this one, which read as "onboarding brought* them across" when nothing had been onboarded at all (CHOO-2044).- *- * The workspace and not its server: two workspaces on one server are two separate- * trees, and scoping on the server would draw both of them under whichever name- * the sidebar is showing.*/function agentsAtLocationInScope(location: LocationStore): Agent[] {- const activeWorkspaceId = workspacesStore.activeId;- if (!activeWorkspaceId) return agentsStore.byLocation.get(location.id) ?? [];- return agentsStore.agentsInWorkspaceAtLocation(location.id, activeWorkspaceId);+ const activeServerId = switchServersStore.activeServerId;+ if (!activeServerId) return agentsStore.byLocation.get(location.id) ?? [];+ return agentsStore.agentsOnServerAtLocation(location.id, activeServerId);}/**- * The flat list of agents in the active-workspace scope. Switch Console shows agents+ * The flat list of agents in the active-server scope. Switch Console shows agents* as a flat list — not grouped by directory (CHOO-1440).** Newest first, then overlaid with the user's manual drag order: an agent they@@ -61,7 +57,7 @@ export function scopedAgents(): AgentEntry[] {}/**- * Every agent in the active workspace, ignoring the agent filters.+ * Every agent on the active server, ignoring the agent filters.** Room membership is a fact about a room, so the agents a room lists — and the* agents whose membership is fetched at all — must not depend on which filters@@ -92,14 +88,14 @@ export function agentSessions(entry: AgentEntry): SessionStore[] {);}-/** Every agent in the active scope that has a Switch identity, as+/** Every agent on the active server that has a Switch identity, as* membership-lookup keys. Unfiltered on purpose — see* {@link agentsInActiveScope}. */-export function switchIdentities(): { workspaceId: string; switchAgentId: string }[] {- const identities: { workspaceId: string; switchAgentId: string }[] = [];+export function switchIdentities(): { serverId: string; switchAgentId: string }[] {+ const identities: { serverId: string; switchAgentId: string }[] = [];for (const { agent } of agentsInActiveScope()) {- if (agent.workspaceId && agent.switchAgentId) {- identities.push({ workspaceId: agent.workspaceId, switchAgentId: agent.switchAgentId });+ if (agent.serverId && agent.switchAgentId) {+ identities.push({ serverId: agent.serverId, switchAgentId: agent.switchAgentId });}}return identities;@@ -155,7 +151,7 @@ export async function refreshSidebarRoomStateAfterOnboarding(): Promise<void> {/*** Fill in the avatar of any of this user's agents registered before icons- * existed (CHOO-2171). The main process does it once per workspace per run, so+ * existed (CHOO-2171). The main process does it once per server per run, so* calling it on every refresh costs nothing after the first.** Not awaited by the caller and never allowed to throw: the sidebar must paint@@ -168,13 +164,13 @@ export async function refreshSidebarRoomStateAfterOnboarding(): Promise<void> {* lettered picture with nothing explaining why.*/async function giveExistingAgentsAnIcon(): Promise<void> {- const workspaceIds = new Set(switchIdentities().map((identity) => identity.workspaceId));- for (const workspaceId of workspaceIds) {+ const serverIds = new Set(switchIdentities().map((identity) => identity.serverId));+ for (const serverId of serverIds) {try {- reportBackfill(workspaceId, await rpc.workspaces.backfillAgentIcons(workspaceId));+ reportBackfill(serverId, await rpc.switchServers.backfillAgentIcons(serverId));} catch (cause) {- log.warn('could not give existing agents their icons', { workspaceId, cause });- reportOnce(workspaceId, 'failed', {+ log.warn('could not give existing agents their icons', { serverId, cause });+ reportOnce(serverId, 'failed', {title: 'Agent icons could not be saved',description:'Your agents show a generated icon here, but the Switch server has not stored it — so they keep their old picture in Slack and the other chat apps.',@@ -185,14 +181,13 @@ async function giveExistingAgentsAnIcon(): Promise<void> {}/**- * What each workspace was last told to the user about, so an unresolved- * condition is not re-announced on every refresh.+ * What each server was last told to the user about, so an unresolved condition+ * is not re-announced on every refresh.** The caller runs on first paint, window focus, sign-in, the background- * reconcile, the retry button and every membership-changing mutation. A- * workspace whose server is signed out or too old to store icons fails all of- * them, which turned one standing problem into a toast every few seconds- * (CHOO-2344).+ * reconcile, the retry button and every membership-changing mutation. A server+ * that is signed out or too old to store icons fails all of them, which turned+ * one standing problem into a toast every few seconds (CHOO-2344).** Keyed by outcome, not a bare "said something already": if the situation* changes — a signed-out server starts answering and turns out to be too old —@@ -201,15 +196,15 @@ async function giveExistingAgentsAnIcon(): Promise<void> {*/const reportedBackfill = new Map<string, string>();-function reportOnce(workspaceId: string, outcome: string, notice: Parameters<typeof toast>[0]) {- if (reportedBackfill.get(workspaceId) === outcome) return;- reportedBackfill.set(workspaceId, outcome);+function reportOnce(serverId: string, outcome: string, notice: Parameters<typeof toast>[0]) {+ if (reportedBackfill.get(serverId) === outcome) return;+ reportedBackfill.set(serverId, outcome);toast(notice);}-function reportBackfill(workspaceId: string, outcome: AgentIconBackfill): void {+function reportBackfill(serverId: string, outcome: AgentIconBackfill): void {if (outcome.kind === 'unsupported') {- reportOnce(workspaceId, 'unsupported', {+ reportOnce(serverId, 'unsupported', {title: 'This Switch server does not support agent icons yet',description:'Your agents show a generated icon here, but it cannot be saved, so they keep their old picture in Slack and the other chat apps. Updating the server fixes it.',@@ -218,7 +213,7 @@ function reportBackfill(workspaceId: string, outcome: AgentIconBackfill): void {return;}if (outcome.kind === 'partial') {- reportOnce(workspaceId, `partial:${outcome.failed}`, {+ reportOnce(serverId, `partial:${outcome.failed}`, {title: `${outcome.failed} agent${outcome.failed === 1 ? '' : 's'} kept the old icon`,description:'Their icon could not be saved to the Switch server, so it will not show in Slack or the other chat apps.',@@ -226,5 +221,5 @@ function reportBackfill(workspaceId: string, outcome: AgentIconBackfill): void {});return;}- reportedBackfill.delete(workspaceId);+ reportedBackfill.delete(serverId);}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentToRoomsModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentToRoomsModal.tsxindex e1e09335c..e4a435895 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentToRoomsModal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentToRoomsModal.tsx@@ -17,12 +17,12 @@ import {import { Field, FieldLabel } from '@renderer/lib/ui/field';type Props = BaseModalProps<void> & {- workspaceId: string;+ serverId: string;switchAgentId: string;agentName: string;};-/** A room the agent can be put in: one in its own workspace it is not already in. */+/** A room the agent can be put in: one on its own server it is not already in. */type Candidate = { id: string; name: string; bridgeType: string | null };/**@@ -31,11 +31,10 @@ type Candidate = { id: string; name: string; bridgeType: string | null };** Both write the same membership through `addRoomAgents`; which one you reach* for is only a matter of what you were looking at. An agent can only join rooms- * in the workspace it is registered in, so the choice is scoped to that- * workspace.+ * on the server it is registered with, so the choice is scoped to that server.*/export const AddAgentToRoomsModal = observer(function AddAgentToRoomsModal({- workspaceId,+ serverId,switchAgentId,agentName,onSuccess,@@ -51,7 +50,7 @@ export const AddAgentToRoomsModal = observer(function AddAgentToRoomsModal({// so the rooms offered here and the rooms the agent is shown under cannot// disagree. Undefined means it was never fetched — offering every room then// would invite a join that is already in place, so say so instead.- const memberships = switchRoomsStore.roomsFor(workspaceId, switchAgentId);+ const memberships = switchRoomsStore.roomsFor(serverId, switchAgentId);const membershipUnknown = memberships === undefined;const alreadyIn = new Set((memberships ?? []).map((m) => m.roomId));@@ -59,7 +58,7 @@ export const AddAgentToRoomsModal = observer(function AddAgentToRoomsModal({// agent's usefulness is mostly in rooms someone else set up, and a picker that// omitted them made those rooms unreachable from here entirely.const candidates: Candidate[] = switchRoomsStore- .readableRoomsInWorkspace(workspaceId)+ .readableRoomsOnServer(serverId).filter((room) => !alreadyIn.has(room.id) && !selected.some((s) => s.id === room.id)).map((room) => ({ id: room.id, name: room.name, bridgeType: room.bridgeType }));const nothingToAdd = candidates.length === 0 && selected.length === 0;@@ -71,8 +70,8 @@ export const AddAgentToRoomsModal = observer(function AddAgentToRoomsModal({setError(null);try {for (const room of selected) {- await rpc.workspaces.addRoomAgents({- workspaceId,+ await rpc.switchServers.addRoomAgents({+ serverId,roomId: room.id,agentIds: [switchAgentId],direction: 'room_to_agents',@@ -86,7 +85,7 @@ export const AddAgentToRoomsModal = observer(function AddAgentToRoomsModal({setIsSubmitting(false);setCloseGuard(false);}- }, [workspaceId, switchAgentId, selected, onSuccess, setCloseGuard]);+ }, [serverId, switchAgentId, selected, onSuccess, setCloseGuard]);return (<>@@ -131,13 +130,13 @@ export const AddAgentToRoomsModal = observer(function AddAgentToRoomsModal({/>{membershipUnknown && (<p className="mt-1 text-xs text-foreground-warning">- Which rooms {agentName} is already in could not be read, so every room in the- workspace is listed. Adding it to one it already belongs to changes nothing.+ Which rooms {agentName} is already in could not be read, so every room on the server+ is listed. Adding it to one it already belongs to changes nothing.</p>)}{nothingToAdd && !membershipUnknown && (<p className="mt-1 text-xs text-foreground-muted">- {agentName} is already in every room you can see in this workspace.+ {agentName} is already in every room you can see on this server.</p>)}</Field>diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentsToRoomModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentsToRoomModal.tsxindex 34cc9679f..0398d3a8d 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentsToRoomModal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentsToRoomModal.tsx@@ -6,7 +6,6 @@ import { agentsStore } from '@renderer/features/locations/stores/agents-store';import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';import { bundledTemplates } from '@renderer/features/templates/bundled-templates';-import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { agentProviderLabel } from '@renderer/lib/components/agent-mark';import { AgentPickerRow, ChosenAgentTile } from '@renderer/lib/components/agent-picker';import { PickerCombobox } from '@renderer/lib/components/picker-combobox';@@ -15,7 +14,7 @@ import { toast } from '@renderer/lib/hooks/use-toast';import { rpc } from '@renderer/lib/ipc';import { useNavigate } from '@renderer/lib/layout/navigation-provider';import { type BaseModalProps, useModalContext } from '@renderer/lib/modal/modal-provider';-import { useWorkspaceAgents } from '@renderer/lib/stores/use-workspace-agents';+import { useRemoteAgents } from '@renderer/lib/stores/use-remote-agents';import { Button } from '@renderer/lib/ui/button';import { ConfirmButton } from '@renderer/lib/ui/confirm-button';import {@@ -43,10 +42,7 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({}: Props) {const { setCloseGuard } = useModalContext();const { navigate } = useNavigate();- const workspaceId = switchRoomsStore.roomWorkspaceId(roomId);- // The template pages are still routed by server, so the Use page is reached- // through the workspace's host.- const serverId = workspaceId === null ? null : workspacesStore.serverIdFor(workspaceId);+ const serverId = switchRoomsStore.roomServerId(roomId);const roomName = switchRoomsStore.roomNameById(roomId);// Templates can create an agent straight into this room. The bundled@@ -54,10 +50,10 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({// returns.const [serverTemplates, setServerTemplates] = useState<StoredTemplateSummary[]>([]);useEffect(() => {- if (workspaceId === null) return;+ if (!serverId) return;let cancelled = false;- rpc.workspaces- .listTemplates({ workspaceId, kind: 'agent' })+ rpc.switchServers+ .listTemplates({ serverId, kind: 'agent' }).then((list) => {if (!cancelled) setServerTemplates(list);})@@ -73,7 +69,7 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({return () => {cancelled = true;};- }, [workspaceId]);+ }, [serverId]);// A built-in template the signed-in user saved to the workspace is listed// once, as their copy. Names are unique only per owner, so someone else's// template of the same name is not a copy.@@ -120,14 +116,14 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({const members = new Set(switchRoomsStore.localMemberIds(roomId));// The agents' own icons live on the server, not in the local row, so the// list is joined against the server's summary to draw them.- const { data: remoteAgents } = useWorkspaceAgents(workspaceId);+ const { data: remoteAgents } = useRemoteAgents(serverId);const remoteById = new Map((remoteAgents ?? []).map((agent) => [agent.id, agent]));// Only this install's agents are offered. An agent registered on another// Switch Console could be added server-side but could never be shown or driven// from here, so it is not ours to offer.- const candidates: Candidate[] = workspaceId+ const candidates: Candidate[] = serverId? agentsStore- .agentsInWorkspace(workspaceId)+ .agentsOnServer(serverId).map((agent) => ({id: agent.switchAgentId as string,name: agent.name,@@ -139,13 +135,13 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({const nothingToAdd = candidates.length === 0 && selected.length === 0;const handleSubmit = useCallback(async () => {- if (!workspaceId || selected.length === 0) return;+ if (!serverId || selected.length === 0) return;setIsSubmitting(true);setCloseGuard(true);setError(null);try {- await rpc.workspaces.addRoomAgents({- workspaceId,+ await rpc.switchServers.addRoomAgents({+ serverId,roomId,agentIds: selected.map((a) => a.id),direction: 'agents_to_room',@@ -158,7 +154,7 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({setIsSubmitting(false);setCloseGuard(false);}- }, [workspaceId, roomId, selected, onSuccess, setCloseGuard]);+ }, [serverId, roomId, selected, onSuccess, setCloseGuard]);return (<>@@ -167,9 +163,9 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({</DialogHeader><DialogContentArea className="pt-0"><div className="flex w-full flex-col gap-4">- {!workspaceId && (+ {!serverId && (<p className="text-xs text-destructive">- This room's workspace is not known yet, so its members cannot be changed.+ This room's server is not known yet, so its members cannot be changed.</p>)}@@ -251,7 +247,7 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({</Button><ConfirmButtononClick={() => void handleSubmit()}- disabled={!workspaceId || selected.length === 0 || isSubmitting}+ disabled={!serverId || selected.length === 0 || isSubmitting}>{isSubmitting ? 'Adding…' : 'Add to room'}</ConfirmButton>diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/DeleteRoomModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/DeleteRoomModal.tsxindex 889d29585..11a65e610 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/DeleteRoomModal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/DeleteRoomModal.tsx@@ -15,7 +15,7 @@ import {} from '@renderer/lib/ui/dialog';type Props = BaseModalProps<void> & {- workspaceId: string;+ serverId: string;roomId: string;roomName: string;};@@ -28,7 +28,7 @@ type Props = BaseModalProps<void> & {* trying, so they are said before rather than reported after.*/export const DeleteRoomModal = observer(function DeleteRoomModal({- workspaceId,+ serverId,roomId,roomName,onSuccess,@@ -47,7 +47,7 @@ export const DeleteRoomModal = observer(function DeleteRoomModal({setCloseGuard(true);setError(null);try {- await switchRoomsStore.deleteRoom(workspaceId, roomId);+ await switchRoomsStore.deleteRoom(serverId, roomId);onSuccess();} catch (cause) {setError(failureText(cause, 'Could not delete the room.'));@@ -55,7 +55,7 @@ export const DeleteRoomModal = observer(function DeleteRoomModal({} finally {setCloseGuard(false);}- }, [workspaceId, roomId, onSuccess, setCloseGuard]);+ }, [serverId, roomId, onSuccess, setCloseGuard]);return (<>diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/open-room.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/open-room.tsindex 7c59190c3..05981eb11 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/open-room.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/open-room.ts@@ -1,4 +1,4 @@-import { scopeToRoomWorkspace } from '@renderer/lib/layout/scope-to-workspace';+import { scopeToRoomServer } from '@renderer/lib/layout/scope-to-server';import { appState, sidebarStore } from '@renderer/lib/stores/app-state';/**@@ -12,7 +12,7 @@ import { appState, sidebarStore } from '@renderer/lib/stores/app-state';* findable in the tree it belongs to.*/export async function openRoom(roomId: string): Promise<void> {- await scopeToRoomWorkspace(roomId);+ await scopeToRoomServer(roomId);sidebarStore.setGrouping('room');sidebarStore.ensureRoomExpanded(roomId);appState.navigation.navigate('room', { roomId });diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsxindex 19d924287..0e827fc81 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx@@ -10,7 +10,7 @@ import { describeFailure, failureText } from '@renderer/lib/errors/describe-failimport { rpc } from '@renderer/lib/ipc';import { useNavigate } from '@renderer/lib/layout/navigation-provider';import { useShowModal } from '@renderer/lib/modal/modal-provider';-import { useWorkspaceAgents } from '@renderer/lib/stores/use-workspace-agents';+import { useRemoteAgents } from '@renderer/lib/stores/use-remote-agents';import { Button } from '@renderer/lib/ui/button';import { Input } from '@renderer/lib/ui/input';import {@@ -31,8 +31,8 @@ import { openRoomChannel } from './room-links';/** Query key for one room's own settings — shared so a save can write the* server's answer straight back into what the page is reading. */-function roomDetailKey(workspaceId: string, roomId: string) {- return ['remote-room-detail', workspaceId, roomId] as const;+function roomDetailKey(serverId: string, roomId: string) {+ return ['remote-room-detail', serverId, roomId] as const;}/**@@ -48,15 +48,15 @@ export const RoomConfigurationPanel = observer(function RoomConfigurationPanel({}: {roomId: string;}) {- const workspaceId = switchRoomsStore.roomWorkspaceId(roomId);+ const serverId = switchRoomsStore.roomServerId(roomId);const query = useQuery({- queryKey: roomDetailKey(workspaceId ?? '', roomId),- queryFn: () => rpc.workspaces.getRoomDetail({ workspaceId: workspaceId as string, roomId }),- enabled: workspaceId !== null,+ queryKey: roomDetailKey(serverId ?? '', roomId),+ queryFn: () => rpc.switchServers.getRoomDetail({ serverId: serverId as string, roomId }),+ enabled: serverId !== null,});- if (workspaceId === null) {- return <PanelNotice title="This room’s workspace is still loading." />;+ if (serverId === null) {+ return <PanelNotice title="This room’s server is still loading." />;}if (query.isPending) {@@ -91,13 +91,13 @@ export const RoomConfigurationPanel = observer(function RoomConfigurationPanel({return (<div className="h-full overflow-y-auto"><div className="mx-auto flex w-full max-w-4xl flex-col gap-8 px-10 py-8">- <RoomHeading serverId={switchRoomsStore.roomServerId(roomId)} room={room} />+ <RoomHeading serverId={serverId} room={room} />{/* Keyed on the room so the drafts below belong to the room on screen:switching rooms starts a fresh form rather than carrying half-typedtext across. */}- <GeneralSection key={room.id} workspaceId={workspaceId} room={room} />- <ParticipantsSection workspaceId={workspaceId} room={room} />- <DeleteRoomSection workspaceId={workspaceId} room={room} />+ <GeneralSection key={room.id} serverId={serverId} room={room} />+ <ParticipantsSection serverId={serverId} room={room} />+ <DeleteRoomSection serverId={serverId} room={room} /></div></div>);@@ -111,16 +111,16 @@ export const RoomConfigurationPanel = observer(function RoomConfigurationPanel({* none to find — the room is someone else's.*/const DeleteRoomSection = observer(function DeleteRoomSection({- workspaceId,+ serverId,room,}: {- workspaceId: string;+ serverId: string;room: RemoteRoomDetail;}) {const showDeleteRoomModal = useShowModal('deleteRoomModal');const { navigate } = useNavigate();- if (!switchRoomsStore.canDeleteRoom(workspaceId, room)) return null;+ if (!switchRoomsStore.canDeleteRoom(serverId, room)) return null;return (<section className="border-t border-border pt-6">@@ -138,7 +138,7 @@ const DeleteRoomSection = observer(function DeleteRoomSection({className="shrink-0 border-red-500/40 text-red-500 hover:bg-red-500/10 hover:text-red-500"onClick={() =>showDeleteRoomModal({- workspaceId,+ serverId,roomId: room.id,roomName: roomTitle(room),// The page this is on is the deleted room's own, so staying would@@ -154,7 +154,7 @@ const DeleteRoomSection = observer(function DeleteRoomSection({);});-function RoomHeading({ serverId, room }: { serverId: string | null; room: RemoteRoomDetail }) {+function RoomHeading({ serverId, room }: { serverId: string; room: RemoteRoomDetail }) {const platform = bridgePlatformLabel(room.bridgeType);const { navigate } = useNavigate();return (@@ -168,16 +168,14 @@ function RoomHeading({ serverId, room }: { serverId: string | null; room: Remote</p></div><div className="flex shrink-0 items-center gap-2">- {serverId !== null && (- <Button- variant="outline"- size="sm"- onClick={() => navigate('templateCapture', { serverId, roomId: room.id })}- >- <FileText className="size-3.5" />- Capture as template- </Button>- )}+ <Button+ variant="outline"+ size="sm"+ onClick={() => navigate('templateCapture', { serverId, roomId: room.id })}+ >+ <FileText className="size-3.5" />+ Capture as template+ </Button>{room.externalChannelUrl && (<>{room.bridgeDisplayName && (@@ -210,7 +208,7 @@ type SaveState = { phase: 'idle' | 'saving' | 'saved' } | { phase: 'failed'; mes** One request carries both fields, so the pair is stored together or not at all.*/-function GeneralSection({ workspaceId, room }: { workspaceId: string; room: RemoteRoomDetail }) {+function GeneralSection({ serverId, room }: { serverId: string; room: RemoteRoomDetail }) {const queryClient = useQueryClient();const savedDescription = room.description;const savedInstructions = room.instructions ?? '';@@ -223,13 +221,13 @@ function GeneralSection({ workspaceId, room }: { workspaceId: string; room: Remoasync function save() {setState({ phase: 'saving' });try {- const updated = await rpc.workspaces.updateRoom({- workspaceId,+ const updated = await rpc.switchServers.updateRoom({+ serverId,roomId: room.id,description,instructions,});- queryClient.setQueryData(roomDetailKey(workspaceId, room.id), updated);+ queryClient.setQueryData(roomDetailKey(serverId, room.id), updated);setState({ phase: 'saved' });} catch (cause) {setState({ phase: 'failed', message: failureText(cause, 'Could not save the change.') });@@ -324,10 +322,10 @@ function Field({* hierarchy the room does not have.*/const ParticipantsSection = observer(function ParticipantsSection({- workspaceId,+ serverId,room,}: {- workspaceId: string;+ serverId: string;room: RemoteRoomDetail;}) {const queryClient = useQueryClient();@@ -337,11 +335,11 @@ const ParticipantsSection = observer(function ParticipantsSection({// Names for agents belonging to other installs, which this computer has no// local record of. Shares its key with the rest of the app, so it is usually// already in hand.- const remoteAgents = useWorkspaceAgents(workspaceId);+ const remoteAgents = useRemoteAgents(serverId);const remoteById = new Map((remoteAgents.data ?? []).map((a) => [a.id, a]));async function refresh() {- await queryClient.invalidateQueries({ queryKey: roomDetailKey(workspaceId, room.id) });+ await queryClient.invalidateQueries({ queryKey: roomDetailKey(serverId, room.id) });await switchRoomsStore.refreshRoomState();}@@ -382,11 +380,9 @@ const ParticipantsSection = observer(function ParticipantsSection({{room.agentIds.map((agentId) => (<ParticipantCardkey={agentId}- mark={- <AgentMark agentId={agentId} workspaceId={workspaceId} remoteById={remoteById} />- }- name={agentNameFor(agentId, workspaceId, remoteById)}- detail={agentKindFor(agentId, workspaceId, remoteById)}+ mark={<AgentMark agentId={agentId} serverId={serverId} remoteById={remoteById} />}+ name={agentNameFor(agentId, serverId, remoteById)}+ detail={agentKindFor(agentId, serverId, remoteById)}/>))}{room.connectedUserNames.map((name) => (@@ -404,7 +400,7 @@ const ParticipantsSection = observer(function ParticipantsSection({</div>)}- {adding && <AddAgentPanel workspaceId={workspaceId} room={room} onAdded={refresh} />}+ {adding && <AddAgentPanel serverId={serverId} room={room} onAdded={refresh} />}</section>);});@@ -437,11 +433,11 @@ function ParticipantCard({* whose owner never agreed to it.*/const AddAgentPanel = observer(function AddAgentPanel({- workspaceId,+ serverId,room,onAdded,}: {- workspaceId: string;+ serverId: string;room: RemoteRoomDetail;onAdded: () => Promise<void>;}) {@@ -450,11 +446,11 @@ const AddAgentPanel = observer(function AddAgentPanel({const [error, setError] = useState<string | null>(null);const members = new Set(room.agentIds);- const { data: remoteAgents } = useWorkspaceAgents(workspaceId);+ const { data: remoteAgents } = useRemoteAgents(serverId);const remoteById = new Map((remoteAgents ?? []).map((agent) => [agent.id, agent]));const query = filter.trim().toLowerCase();const candidates = agentsStore- .agentsInWorkspace(workspaceId)+ .agentsOnServer(serverId).filter((agent) => agent.switchAgentId !== null && !members.has(agent.switchAgentId)).filter((agent) => query === '' || agent.name.toLowerCase().includes(query));@@ -462,8 +458,8 @@ const AddAgentPanel = observer(function AddAgentPanel({setBusyId(switchAgentId);setError(null);try {- await rpc.workspaces.addRoomAgents({- workspaceId,+ await rpc.switchServers.addRoomAgents({+ serverId,roomId: room.id,agentIds: [switchAgentId],direction: 'agents_to_room',@@ -573,18 +569,18 @@ function PanelNotice({/** An agent's own picture, beside the human participants' initials discs. */function AgentMark({agentId,- workspaceId,+ serverId,remoteById,}: {agentId: string;- workspaceId: string;+ serverId: string;remoteById: Map<string, RemoteAgentSummary>;}) {const remote = remoteById.get(agentId) ?? null;return (<span className="flex size-7 shrink-0 items-center justify-center"><AgentAvatar- name={agentNameFor(agentId, workspaceId, remoteById)}+ name={agentNameFor(agentId, serverId, remoteById)}iconUrl={remote?.iconUrl ?? null}size={26}/>@@ -594,22 +590,19 @@ function AgentMark({/** This install's record of a Switch agent, which is where its provider is* known — the server says what type an agent is, not what runs it here. */-function localAgentFor(switchAgentId: string, workspaceId: string) {+function localAgentFor(switchAgentId: string, serverId: string) {return (- agentsStore.agentsInWorkspace(workspaceId).find((a) => a.switchAgentId === switchAgentId) ??- null+ agentsStore.agentsOnServer(serverId).find((a) => a.switchAgentId === switchAgentId) ?? null);}function agentNameFor(switchAgentId: string,- workspaceId: string,+ serverId: string,remoteById: Map<string, RemoteAgentSummary>): string {return (- localAgentFor(switchAgentId, workspaceId)?.name ??- remoteById.get(switchAgentId)?.name ??- 'Agent'+ localAgentFor(switchAgentId, serverId)?.name ?? remoteById.get(switchAgentId)?.name ?? 'Agent');}@@ -617,10 +610,10 @@ function agentNameFor(* otherwise the type the server knows it by. */function agentKindFor(switchAgentId: string,- workspaceId: string,+ serverId: string,remoteById: Map<string, RemoteAgentSummary>): string {- const providerId = localAgentFor(switchAgentId, workspaceId)?.providerId ?? null;+ const providerId = localAgentFor(switchAgentId, serverId)?.providerId ?? null;const knownType = remoteById.get(switchAgentId)?.knownAgentType ?? null;return providerDisplayName(providerId) ?? providerDisplayName(knownType) ?? 'agent';}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/session-deeplink-listener.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/session-deeplink-listener.tsxindex 211cc0891..d699ea9c9 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/session-deeplink-listener.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/session-deeplink-listener.tsx@@ -4,7 +4,7 @@ import { agentsStore } from '@renderer/features/locations/stores/agents-store';import { getLocationManagerStore } from '@renderer/features/locations/stores/location-selectors';import { getSessionManagerStore } from '@renderer/features/sessions/stores/session-selectors';import { events } from '@renderer/lib/ipc';-import { scopeToLocationWorkspace } from '@renderer/lib/layout/scope-to-workspace';+import { scopeToLocationServer } from '@renderer/lib/layout/scope-to-server';import { appState } from '@renderer/lib/stores/app-state';import { report } from '@renderer/lib/telemetry/report';import { sessionDeeplinkChannel } from '@shared/core/switch-rooms/switchRoomEvents';@@ -95,7 +95,7 @@ export function SessionDeeplinkListener(): null {// is filtered out of the server-scoped tree and there is no row to// reveal. Navigating is all the sidebar needs — it expands and scrolls// to whatever the open view selects, from any origin.- await scopeToLocationWorkspace(match.locationId);+ await scopeToLocationServer(match.locationId);appState.navigation.navigate('session', match);})();}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/AddServerModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/AddServerModal.tsxindex 723b4623a..868374054 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/AddServerModal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/AddServerModal.tsx@@ -1,4 +1,4 @@-import { CircleCheck, Globe, Info, Laptop, Server, TriangleAlert } from 'lucide-react';+import { CircleCheck, Globe, Laptop, Server, TriangleAlert } from 'lucide-react';import { observer } from 'mobx-react-lite';import { useCallback, useEffect, useRef, useState } from 'react';import { HostReachabilityNotice } from '@renderer/features/remote-hosts/host-reachability-notice';@@ -10,10 +10,16 @@ import { report } from '@renderer/lib/telemetry/report';import { Alert, AlertDescription, AlertTitle } from '@renderer/lib/ui/alert';import { Button } from '@renderer/lib/ui/button';import { ConfirmButton } from '@renderer/lib/ui/confirm-button';+import {+ DialogContentArea,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@renderer/lib/ui/dialog';import { Field, FieldGroup, FieldLabel } from '@renderer/lib/ui/field';import { Input } from '@renderer/lib/ui/input';import { Spinner } from '@renderer/lib/ui/spinner';-import { WizardFrame } from '@renderer/lib/ui/wizard-frame';+import { WizardStepHeader } from '@renderer/lib/ui/wizard-step-header';import type {AddServerChoiceName,AddServerStepName,@@ -85,6 +91,16 @@ const _stepsAreComplete: Step extends AddServerStepName ? true : never = true;void _stepsAreExhaustive;void _stepsAreComplete;+/**+ * How many steps connecting to a server someone else runs takes: choose that+ * path, point at the server, sign in, then say which messaging account is you.+ *+ * The chooser is step 1 but carries no counter — the other two paths it leads+ * to are not four steps, and a count shown before the choice would promise a+ * length that depends on what is clicked next.+ */+const CONNECT_STEPS = 4;+/*** Add a Switch server: run one here, run one on a host you have onboarded, or* connect to one someone else runs.@@ -142,7 +158,7 @@ export const AddServerModal = observer(function AddServerModal(props: Props) {useEffect(() => {if (isEdit || reportedOpening.current) return;reportedOpening.current = true;- report('add_server_step', { step: openedAt, choice: openedWith, first_run: false });+ report('add_server_step', { step: openedAt, choice: openedWith });}, [isEdit, openedAt, openedWith]);/**@@ -157,7 +173,7 @@ export const AddServerModal = observer(function AddServerModal(props: Props) {const nextChoice = CHOICE_FOR_STEP[next] ?? choice;setChoice(nextChoice);setStep(next);- report('add_server_step', { step: next, choice: nextChoice, first_run: false });+ report('add_server_step', { step: next, choice: nextChoice });};// The server the wizard just created, and the subject of every step after// it. Null in edit mode and on the two managed paths, which is what@@ -196,9 +212,6 @@ export const AddServerModal = observer(function AddServerModal(props: Props) {onBack={isEdit ? undefined : () => goToStep('choose')}onDone={finish}onClose={props.onClose}- // The dialog is closed, not left part-way: Cancel is the way out and it- // has no server to name.- onRegistered={null}/>);}@@ -208,7 +221,6 @@ export const AddServerModal = observer(function AddServerModal(props: Props) {onBack={() => goToStep('choose')}onDone={finish}onClose={props.onClose}- onRegistered={null}/>);}@@ -227,22 +239,18 @@ export const AddServerModal = observer(function AddServerModal(props: Props) {<LinkAccountsStepserverId={connected.id}serverName={connected.name}+ step={CONNECT_STEPS}+ of={CONNECT_STEPS}onDone={() => finish(connected.id)}/>);}return (<ExternalServerStep- onSuccess={props.onSuccess}- onClose={props.onClose}- initialGatewayUrl={props.initialGatewayUrl ?? null}- initialApiUrl={props.initialApiUrl ?? null}- initialName={props.initialName ?? null}- serverId={props.serverId ?? null}+ {...props}isEdit={isEdit}- firstRun={false}existing={connected}- onBack={isEdit ? null : () => goToStep('choose')}+ onBack={isEdit ? undefined : () => goToStep('choose')}onConnected={(server) => {setConnected(server);goToStep('signIn');@@ -267,41 +275,42 @@ function ChooseStep({onClose: () => void;}) {return (- <WizardFrame- title="Add a Switch server"- subtitle={null}- pager={{ pageName: 'Add a server', onBack: null, onNext: null }}- footer={+ <>+ <DialogHeader showCloseButton={false}>+ <DialogTitle>Add a Switch server</DialogTitle>+ </DialogHeader>+ <DialogContentArea className="pt-0">+ <div className="grid gap-3">+ <ChoiceCard+ icon={<Laptop className="size-5" />}+ title="Run a server on this computer"+ description="Switch Console sets up and runs the full Switch stack here with Docker. Best for trying Switch out."+ onClick={onLocal}+ />+ <ChoiceCard+ icon={<Server className="size-5" />}+ title="Run a server on a remote host"+ description="Switch Console sets it up over SSH on a host you've onboarded. Stays running when Switch Console is closed."+ onClick={onRemoteHost}+ />+ <ChoiceCard+ icon={<Globe className="size-5" />}+ title="Connect to an existing server"+ description="Point Switch Console at a Switch gateway someone else runs, by URL."+ onClick={onExternal}+ />+ </div>+ </DialogContentArea>+ <DialogFooter><Button variant="outline" onClick={onClose}>Cancel</Button>- }- >- <div className="grid gap-3">- <ChoiceCard- icon={<Laptop className="size-5" />}- title="Run a server on this computer"- description="Switch Console sets up and runs the full Switch stack here with Docker. Best for trying Switch out."- onClick={onLocal}- />- <ChoiceCard- icon={<Server className="size-5" />}- title="Run a server on a remote host"- description="Switch Console sets it up over SSH on a host you've onboarded. Stays running when Switch Console is closed."- onClick={onRemoteHost}- />- <ChoiceCard- icon={<Globe className="size-5" />}- title="Connect to an existing server"- description="Point Switch Console at a Switch gateway someone else runs, by URL."- onClick={onExternal}- />- </div>- </WizardFrame>+ </DialogFooter>+ </>);}-export function ChoiceCard({+function ChoiceCard({icon,title,description,@@ -340,24 +349,15 @@ function SetupStepItem({ children }: { children: React.ReactNode }) {// Step 2a — local server setup (preflight → progress → done)// ----------------------------------------------------------------------------export const LocalSetupStep = observer(function LocalSetupStep({+const LocalSetupStep = observer(function LocalSetupStep({onBack,onDone,onClose,- onRegistered,}: {onBack?: () => void;/** Reports the server the stack registered, so the flow can end on it. */onDone: (serverId: string | null) => void;- /** Null where the flow has no way out but forwards — the first-run pages. */- onClose: (() => void) | null;- /**- * Reports the server the moment it is registered rather than when Done is- * pressed, so a flow that offers a way out can aim it at the right row.- * Null for a chrome with no such offer — the dialog, which is closed instead- * of left.- */- onRegistered: ((serverId: string) => void) | null;+ onClose: () => void;}) {const store = localServerStore;@@ -366,11 +366,6 @@ export const LocalSetupStep = observer(function LocalSetupStep({void store.checkDocker();}, [store]);- const registeredId = store.status?.serverId ?? null;- useEffect(() => {- if (registeredId !== null) onRegistered?.(registeredId);- }, [registeredId, onRegistered]);-const running = store.isRunning;const starting = store.isTransitioning;const docker = store.docker;@@ -378,14 +373,6 @@ export const LocalSetupStep = observer(function LocalSetupStep({const dockerUnavailable = docker && !docker.available ? docker : null;const idle = !running && !starting;- // The pager's back arrow only ever repeats the footer's Back, so the two read- // one const. Open during the install too: the store is a singleton the main- // process streams into, so leaving loses only what is on screen, and holding- // the page shut left the full-window flow with no live control at all through- // a multi-gigabyte pull — while the same page in the dialog could still be- // dismissed with Escape.- const goBack = onBack ?? null;-const primaryLabel = running ? 'Done' : store.phase === 'error' ? 'Retry' : 'Start';const onPrimary = () => {if (running) onDone(store.status?.serverId ?? null);@@ -393,25 +380,11 @@ export const LocalSetupStep = observer(function LocalSetupStep({};return (- <WizardFrame- title="Set up a server on this computer"- subtitle="Switch Console installs the full stack with Docker and keeps it updated."- pager={{ pageName: 'Set up a server', onBack: goBack, onNext: null }}- footer={- <>- <BackOrClose- onBack={goBack}- onClose={onClose}- closeDisabled={starting}- closeLabel={running ? 'Close' : 'Cancel'}- />- <ConfirmButton onClick={onPrimary} disabled={starting || (!running && !dockerReady)}>- {starting ? 'Starting…' : primaryLabel}- </ConfirmButton>- </>- }- >- <div className="space-y-4">+ <>+ <DialogHeader showCloseButton={false}>+ <DialogTitle>Set up a server on this computer</DialogTitle>+ </DialogHeader>+ <DialogContentArea className="space-y-4 pt-0"><div className="flex items-center gap-3"><div className="flex size-10 shrink-0 items-center justify-center rounded-lg bg-background-tertiary text-foreground-muted"><Laptop className="size-5" />@@ -463,16 +436,9 @@ export const LocalSetupStep = observer(function LocalSetupStep({{(starting || store.logs.length > 0) && !running && (<div className="space-y-1.5">{store.message && starting && (- <div className="space-y-1">- <div className="flex items-center gap-2 text-sm text-foreground">- <Spinner className="size-3.5" />- <span>{store.message}</span>- </div>- {/* Said out loud, because Back being live during a download- that takes minutes otherwise looks like it cancels one. */}- <p className="text-xs text-foreground-muted">- This keeps running if you leave the page — come back here to watch it.- </p>+ <div className="flex items-center gap-2 text-sm text-foreground">+ <Spinner className="size-3.5" />+ <span>{store.message}</span></div>)}<LogTail@@ -481,51 +447,25 @@ export const LocalSetupStep = observer(function LocalSetupStep({/></div>)}- </div>- </WizardFrame>+ </DialogContentArea>+ <DialogFooter>+ {onBack && !starting ? (+ <Button variant="outline" onClick={onBack}>+ Back+ </Button>+ ) : (+ <Button variant="outline" onClick={onClose} disabled={starting}>+ {running ? 'Close' : 'Cancel'}+ </Button>+ )}+ <ConfirmButton onClick={onPrimary} disabled={starting || (!running && !dockerReady)}>+ {starting ? 'Starting…' : primaryLabel}+ </ConfirmButton>+ </DialogFooter>+ </>);});-/**- * The button on the left of a wizard's footer.- *- * A page that can be left offers Cancel; one that can only be stepped back- * through offers Back; the first-run pages can do neither while a stack is- * installing, and get a Back that is visibly held rather than no button and a- * footer that changes shape under the eye.- */-function BackOrClose({- onBack,- onClose,- closeDisabled,- closeLabel,-}: {- onBack: (() => void) | null;- onClose: (() => void) | null;- closeDisabled: boolean;- closeLabel: string;-}) {- if (onBack) {- return (- <Button variant="outline" onClick={onBack}>- Back- </Button>- );- }- if (onClose) {- return (- <Button variant="outline" onClick={onClose} disabled={closeDisabled}>- {closeLabel}- </Button>- );- }- return (- <Button variant="outline" disabled>- Back- </Button>- );-}-function DockerStatus({ready,unavailable,@@ -571,18 +511,15 @@ function DockerStatus({// Step 2b — remote-host managed setup (pick an onboarded SSH host → start)// ----------------------------------------------------------------------------export const RemoteHostSetupStep = observer(function RemoteHostSetupStep({+const RemoteHostSetupStep = observer(function RemoteHostSetupStep({onBack,onDone,onClose,- onRegistered,}: {onBack: () => void;/** Reports the server the stack registered, so the flow can end on it. */onDone: (serverId: string | null) => void;onClose: () => void;- /** As on the local page: the registration, not the Done press. */- onRegistered: ((serverId: string) => void) | null;}) {const store = remoteServerStore;const [hosts, setHosts] = useState<{ sshHost: string; name: string }[] | null>(null);@@ -612,17 +549,8 @@ export const RemoteHostSetupStep = observer(function RemoteHostSetupStep({const status = sshHost ? store.statusFor(sshHost) : null;const logs = sshHost ? store.logsFor(sshHost) : [];- const registeredId = sshHost ? (status?.serverId ?? null) : null;- useEffect(() => {- if (registeredId !== null) onRegistered?.(registeredId);- }, [registeredId, onRegistered]);-const hostBlocked = sshHost ? store.isHostBlocked(sshHost) : false;const canStart = !!sshHost && name.trim().length > 0 && dockerReady && !starting && !hostBlocked;- // One const for the footer's Back and the pager's back arrow, which only- // repeats it. Open during the install, for the same reason as the local page:- // the store outlives the page, so nothing is abandoned by leaving it.- const goBack = onBack;const primaryLabel = running ? 'Done' : status?.phase === 'error' ? 'Retry' : 'Start';const onPrimary = () => {if (running) onDone(sshHost ? (store.statusFor(sshHost).serverId ?? null) : null);@@ -630,24 +558,11 @@ export const RemoteHostSetupStep = observer(function RemoteHostSetupStep({};return (- <WizardFrame- title="Set up a server on a remote host"- subtitle={null}- pager={{- pageName: 'Set up on a remote host',- onBack: goBack,- onNext: null,- }}- footer={- <>- <BackOrClose onBack={goBack} onClose={onClose} closeDisabled closeLabel="Cancel" />- <ConfirmButton onClick={onPrimary} disabled={!running && !canStart}>- {starting ? 'Starting…' : primaryLabel}- </ConfirmButton>- </>- }- >- <div className="space-y-4">+ <>+ <DialogHeader showCloseButton={false}>+ <DialogTitle>Set up a server on a remote host</DialogTitle>+ </DialogHeader>+ <DialogContentArea className="space-y-4 pt-0">{hosts === null ? (<div className="flex items-center gap-2 text-sm text-foreground-muted"><Spinner className="size-3.5" />@@ -767,8 +682,22 @@ export const RemoteHostSetupStep = observer(function RemoteHostSetupStep({)}</>)}- </div>- </WizardFrame>+ </DialogContentArea>+ <DialogFooter>+ {!starting ? (+ <Button variant="outline" onClick={onBack}>+ Back+ </Button>+ ) : (+ <Button variant="outline" onClick={onClose} disabled>+ Cancel+ </Button>+ )}+ <ConfirmButton onClick={onPrimary} disabled={!running && !canStart}>+ {starting ? 'Starting…' : primaryLabel}+ </ConfirmButton>+ </DialogFooter>+ </>);});@@ -785,24 +714,7 @@ function looksLikeUrl(value: string): boolean {}}-/**- * A name for a server the user was never asked to name.- *- * The first-run form leaves the field out — someone connecting their only- * server has nothing to tell it apart from, and a required text box between- * them and a working app is a question asked for the list's benefit rather than- * theirs. The hostname is what they would have typed anyway, and renaming is a- * click away once there is a sidebar to see it in.- */-function nameFromGatewayUrl(gatewayUrl: string): string {- // The host rather than the hostname: two servers on one machine differ only- // by port, and a sidebar with two rows both called `localhost` names neither- // of them. An IPv6 address keeps its brackets, which is how an address with- // a port beside it is written.- return new URL(gatewayUrl).host;-}--export const ExternalServerStep = observer(function ExternalServerStep({+const ExternalServerStep = observer(function ExternalServerStep({onSuccess,onClose,onBack,@@ -811,21 +723,11 @@ export const ExternalServerStep = observer(function ExternalServerStep({initialName,serverId,isEdit,- firstRun,existing,onConnected,-}: {- initialGatewayUrl: string | null;- initialApiUrl: string | null;- initialName: string | null;- serverId: string | null;+}: Props & {isEdit: boolean;- /** The first-run wording of the same form: no name to ask for, and the- * server's own accounts worth saying out loud before the sign-in step. */- firstRun: boolean;- onSuccess: () => void;- onClose: () => void;- onBack: (() => void) | null;+ onBack?: () => void;/** Set when the wizard has already created the server and the user came back* to fix what they typed — the same form, saving instead of adding. */existing: SwitchServer | null;@@ -842,11 +744,9 @@ export const ExternalServerStep = observer(function ExternalServerStep({const trimmedApi = apiUrl.trim();const gatewayValid = looksLikeUrl(trimmedGateway);const apiValid = looksLikeUrl(trimmedApi);- // In edit mode the name is owned by the separate Rename action, and on first- // run it comes from the gateway, so neither shows the field or requires it.- const asksForName = !isEdit && !firstRun;- const isValid = (!asksForName || trimmedName.length > 0) && gatewayValid && apiValid;- const submittedName = firstRun && gatewayValid ? nameFromGatewayUrl(trimmedGateway) : trimmedName;+ // In edit mode the name is owned by the separate Rename action, so this form+ // only edits the URLs — the name field isn't shown and isn't required.+ const isValid = (isEdit || trimmedName.length > 0) && gatewayValid && apiValid;const gatewayMessage =trimmedGateway.length > 0 && !gatewayValid@@ -868,7 +768,7 @@ export const ExternalServerStep = observer(function ExternalServerStep({if (savedId) {const result = await switchServersStore.updateServer(savedId,- submittedName,+ trimmedName,trimmedGateway,trimmedApi);@@ -883,7 +783,7 @@ export const ExternalServerStep = observer(function ExternalServerStep({return;}} else {- const saved = await switchServersStore.addServer(submittedName, trimmedGateway, trimmedApi);+ const saved = await switchServersStore.addServer(trimmedName, trimmedGateway, trimmedApi);if (!saved) {setError(switchServersStore.errorText ?? 'Could not add the server.');setSubmitting(false);@@ -893,117 +793,64 @@ export const ExternalServerStep = observer(function ExternalServerStep({return;}onSuccess();- }, [isValid, isEdit, savedId, submittedName, trimmedGateway, trimmedApi, onSuccess, onConnected]);-- // First run is asked before the saved row, because a page that goes on to the- // sign-in must not offer "Save changes" — the user stepped back to fix an- // address, and the button still takes them forward rather than closing.- const submitLabel = submitting- ? savedId- ? 'Saving…'- : 'Adding…'- : firstRun- ? 'Sign in to this server'- : savedId- ? 'Save changes'- : 'Add server';-- // The footer's Back and the pager's back arrow are the same move, so they- // read one const. Shut while the form is submitting: the write registers a- // server, and stepping off it mid-way leaves one behind with no page on it.- const goBack = onBack && !submitting ? onBack : null;+ }, [isValid, isEdit, savedId, trimmedName, trimmedGateway, trimmedApi, onSuccess, onConnected]);return (- <WizardFrame- title={- isEdit- ? 'Edit connection'- : firstRun- ? 'Connect to your server'- : 'Connect to an existing server'- }- subtitle={firstRun ? 'Whoever set it up can give you these addresses.' : null}- /* Editing a connection is one dialog rather than a flow, and a pager on- it would invent pages either side that do not exist. */- pager={- isEdit- ? null- : {- pageName: 'Connect to a server',- onBack: goBack,- onNext: null,- }- }- footer={- <>- <Button- variant="outline"- onClick={goBack ?? onClose}- disabled={!!onBack && goBack === null}- >- {onBack ? 'Back' : 'Cancel'}- </Button>- <ConfirmButton onClick={() => void handleSubmit()} disabled={!isValid || submitting}>- {submitLabel}- </ConfirmButton>- </>- }- >- <FieldGroup>- {asksForName && (+ <>+ {isEdit ? (+ <DialogHeader showCloseButton={false}>+ <DialogTitle>Edit connection</DialogTitle>+ </DialogHeader>+ ) : (+ <WizardStepHeader title="Connect to an existing server" step={2} of={CONNECT_STEPS} />+ )}+ <DialogContentArea className="pt-0">+ <FieldGroup>+ {!isEdit && (+ <Field>+ <FieldLabel>Name</FieldLabel>+ <Input+ value={name}+ onChange={(e) => setName(e.target.value)}+ placeholder="Pilot"+ autoFocus+ />+ </Field>+ )}<Field>- <FieldLabel>Name</FieldLabel>+ <FieldLabel>Gateway URL</FieldLabel><Input- value={name}- onChange={(e) => setName(e.target.value)}- placeholder="Pilot"- autoFocus+ value={gatewayUrl}+ onChange={(e) => setGatewayUrl(e.target.value)}+ placeholder="https://switch-gateway.example.com"+ autoFocus={isEdit}/>+ {gatewayMessage && <p className="mt-1 text-xs text-destructive">{gatewayMessage}</p>}</Field>- )}- <Field>- <FieldLabel>Gateway URL</FieldLabel>- <Input- value={gatewayUrl}- onChange={(e) => setGatewayUrl(e.target.value)}- placeholder="https://switch-gateway.example.com"- autoFocus={isEdit || firstRun}- />- {firstRun && (- <p className="mt-1 text-xs text-foreground-muted">Where the app and its chat live.</p>- )}- {gatewayMessage && <p className="mt-1 text-xs text-destructive">{gatewayMessage}</p>}- </Field>- <Field>- <FieldLabel>API URL</FieldLabel>- <Input- value={apiUrl}- onChange={(e) => setApiUrl(e.target.value)}- placeholder="https://switch-api.example.com"- onKeyDown={(e) => {- if (e.key === 'Enter') void handleSubmit();- }}- />- {firstRun && (- <p className="mt-1 text-xs text-foreground-muted">- Where agents connect. Often the same host on a different port — whoever set the server- up knows which.- </p>- )}- {apiMessage && <p className="mt-1 text-xs text-destructive">{apiMessage}</p>}- {error && <p className="mt-1 text-xs text-destructive">{error}</p>}- </Field>- {firstRun && (- <Alert>- <Info className="size-4" />- <AlertDescription>- This server keeps its own accounts. Signing in here signs you in to it, not to- anything else.- </AlertDescription>- </Alert>- )}- </FieldGroup>- </WizardFrame>+ <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();+ }}+ />+ {apiMessage && <p className="mt-1 text-xs text-destructive">{apiMessage}</p>}+ {error && <p className="mt-1 text-xs text-destructive">{error}</p>}+ </Field>+ </FieldGroup>+ </DialogContentArea>+ <DialogFooter>+ <Button variant="outline" onClick={onBack ?? onClose}>+ {onBack ? 'Back' : 'Cancel'}+ </Button>+ <ConfirmButton onClick={() => void handleSubmit()} disabled={!isValid || submitting}>+ {submitting ? (savedId ? 'Saving…' : 'Adding…') : savedId ? 'Save changes' : 'Add server'}+ </ConfirmButton>+ </DialogFooter>+ </>);});@@ -1017,7 +864,7 @@ export const ExternalServerStep = observer(function ExternalServerStep({* signed-out server lists no rooms, no agents and no messaging apps, and looks* broken rather than unauthenticated.*/-export const SignInStep = observer(function SignInStep({+const SignInStep = observer(function SignInStep({server,onBack,onClose,@@ -1025,8 +872,7 @@ export const SignInStep = observer(function SignInStep({}: {server: SwitchServer;onBack: () => void;- /** Null where there is nothing to close onto — the first-run pages. */- onClose: (() => void) | null;+ onClose: () => void;onSignedIn: () => void;}) {const signIn = useServerSignIn(server.id);@@ -1037,47 +883,40 @@ export const SignInStep = observer(function SignInStep({if (await signIn.signInWithPassword()) onSignedIn();};- // One const for the footer's Back and the pager's back arrow that repeats it.- const goBack = signIn.submitting ? null : onBack;-return (- <WizardFrame- title={`Sign in to ${server.name}`}- subtitle={null}- pager={{ pageName: 'Sign in', onBack: goBack, onNext: null }}- footer={- <>- <Button variant="outline" onClick={onBack} disabled={goBack === null}>- Back- </Button>- {canUsePassword ? (- <ConfirmButton- onClick={() => void submit()}- disabled={!signIn.canSubmitPassword || signIn.submitting}- >- {signIn.submitting ? 'Signing in…' : 'Sign in'}- </ConfirmButton>- ) : (- // Nothing for a primary button to do: either the only method is the- // provider button in the body, or the server offers none at all and- // the body says so. Leaving a dead "Sign in" there would imply the- // form was incomplete rather than absent.- !canUseOidc &&- onClose && (- <Button variant="outline" onClick={onClose}>- Close- </Button>- )- )}- </>- }- >- <ServerSignInFields- signIn={signIn}- idPrefix="connect-server-sign-in"- gatewayUrl={server.gatewayUrl}- onSignedIn={onSignedIn}- />- </WizardFrame>+ <>+ <WizardStepHeader title={`Sign in to ${server.name}`} step={3} of={CONNECT_STEPS} />+ <DialogContentArea className="pt-0">+ <ServerSignInFields+ signIn={signIn}+ idPrefix="connect-server-sign-in"+ gatewayUrl={server.gatewayUrl}+ onSignedIn={onSignedIn}+ />+ </DialogContentArea>+ <DialogFooter>+ <Button variant="outline" onClick={onBack} disabled={signIn.submitting}>+ Back+ </Button>+ {canUsePassword ? (+ <ConfirmButton+ onClick={() => void submit()}+ disabled={!signIn.canSubmitPassword || signIn.submitting}+ >+ {signIn.submitting ? 'Signing in…' : 'Sign in'}+ </ConfirmButton>+ ) : (+ // Nothing for a primary button to do: either the only method is the+ // provider button in the body, or the server offers none at all and+ // the body says so. Leaving a dead "Sign in" there would imply the+ // form was incomplete rather than absent.+ !canUseOidc && (+ <Button variant="outline" onClick={onClose}>+ Close+ </Button>+ )+ )}+ </DialogFooter>+ </>);});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ClaimIdentityModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ClaimIdentityModal.tsxindex 4d234aea1..47be809ce 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ClaimIdentityModal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ClaimIdentityModal.tsx@@ -13,14 +13,15 @@ import {} from '@renderer/lib/ui/dialog';import type { LinkedIdentity } from '@shared/core/switch-servers/switch-servers';import { BridgeIdentitySearch } from './bridge-identity-search';+import { switchServersStore } from './switch-servers-store';import { useMyIdentities } from './use-my-identities';type ClaimIdentityModalArgs = {- /** The workspace the account is claimed in. Required rather than defaulted to- * the active one: every entry point knows which workspace it opened from, and- * falling back would claim the account somewhere the user was not looking. */- workspaceId: string;- /** The messaging app to claim an account in. */+ /** Claim on this server instead of the active one. */+ serverId?: string;+ /** The messaging app to claim an account in. Required: an account is claimed+ * in one workspace, and every entry point knows which one it opened from —+ * asking again would be a question the caller has already answered. */bridgeId: string;};@@ -40,20 +41,22 @@ type Props = BaseModalProps<{ identity: LinkedIdentity }> & ClaimIdentityModalAr* never posted in.*/export const ClaimIdentityModal = observer(function ClaimIdentityModal({- workspaceId,+ serverId: overrideServerId,bridgeId,onSuccess,onClose,}: Props) {+ const serverId = overrideServerId ?? switchServersStore.activeServerId ?? '';// The search raises the close guard while a claim or unlink is in flight, so// this is also the signal that leaving now would abandon one.const { hasActiveCloseGuard } = useModalContext();- const { identities } = useMyIdentities(workspaceId);+ const { identities } = useMyIdentities(serverId || null);const bridgesQuery = useQuery({- queryKey: ['remote-bridges', workspaceId],- queryFn: () => rpc.workspaces.listBridges(workspaceId),+ queryKey: ['remote-bridges', serverId],+ queryFn: () => rpc.switchServers.listRemoteBridges(serverId),+ enabled: !!serverId,});const bridges = bridgesQuery.data ?? [];@@ -77,9 +80,15 @@ export const ClaimIdentityModal = observer(function ClaimIdentityModal({Tell Switch which account is you, so your own agents can tell it's you.</p>+ {!serverId && (+ <p className="text-xs text-destructive">+ No Switch server is selected. Choose a server in the sidebar first.+ </p>+ )}+{bridgeIsGone && (<p className="text-xs text-destructive">- That messaging app is no longer connected to this workspace.+ That messaging app is no longer connected to this server.</p>)}@@ -96,7 +105,7 @@ export const ClaimIdentityModal = observer(function ClaimIdentityModal({)}<BridgeIdentitySearch- workspaceId={workspaceId}+ serverId={serverId}bridgeId={bridgeId}bridgeDisplayName={selectedBridge?.displayName ?? 'the workspace'}platform={bridgePlatformLabel(selectedBridge?.type ?? '')}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsxindex f76278d93..28f13a321 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsx@@ -2,7 +2,6 @@ import { useQuery } from '@tanstack/react-query';import { ExternalLink } from 'lucide-react';import { observer } from 'mobx-react-lite';import { useCallback, useMemo, useState } from 'react';-import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';import { bridgePlatformLabel, bridgeSetupDocsUrl } from '@renderer/lib/components/bridge-platform';import { failureText } from '@renderer/lib/errors/describe-failure';@@ -56,7 +55,6 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppModconst { setCloseGuard } = useModalContext();const serverId = overrideServerId ?? switchServersStore.activeServerId ?? '';- const workspaceId = workspacesStore.idOnServerInScope(serverId || null);const server = switchServersStore.servers.find((s) => s.id === serverId) ?? null;const isAdmin = switchServersStore.statusFor(serverId)?.user?.role === 'admin';@@ -75,9 +73,9 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppModconst [error, setError] = useState<string | null>(null);const typesQuery = useQuery({- queryKey: ['remote-bridge-types', workspaceId],- queryFn: () => rpc.workspaces.listBridgeTypes(workspaceId as string),- enabled: workspaceId !== null,+ queryKey: ['remote-bridge-types', serverId],+ queryFn: () => rpc.switchServers.listRemoteBridgeTypes(serverId),+ enabled: !!serverId,});const types = useMemo(() => typesQuery.data ?? [], [typesQuery.data]);@@ -115,12 +113,7 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppModreturn !(value ?? '').trim();});const canSubmit =- workspaceId !== null &&- isAdmin &&- !!selectedType &&- !!trimmedName &&- !missingRequired &&- !isSubmitting;+ !!serverId && isAdmin && !!selectedType && !!trimmedName && !missingRequired && !isSubmitting;const handleSubmit = useCallback(async () => {if (!canSubmit || !selectedType) return;@@ -142,8 +135,8 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppModif (trimmed) connectionConfig[field.key] = trimmed;}- const result = await rpc.workspaces.createBridge({- workspaceId: workspaceId as string,+ const result = await rpc.switchServers.createBridge({+ serverId,bridgeType: selectedType.key,displayName: trimmedName,connectionConfig,@@ -172,7 +165,7 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppMod}, [canSubmit,selectedType,- workspaceId,+ serverId,trimmedName,config,setAsDefault,diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsxindex c16adda19..759887001 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx@@ -4,7 +4,6 @@ import { useCallback, useState } from 'react';import { agentsStore } from '@renderer/features/locations/stores/agents-store';import { openRoomView } from '@renderer/features/sidebar/sidebar-room-grouping';import { refreshSidebarRoomState } from '@renderer/features/sidebar/sidebar-tree-data';-import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import {AgentPickerRow,ChosenAgentTile,@@ -50,7 +49,6 @@ export const CreateRoomModal = observer(function CreateRoomModal({// asking again would let the user create a room somewhere they are not// looking, and then wonder where it went.const serverId = overrideServerId ?? switchServersStore.activeServerId ?? '';- const workspaceId = workspacesStore.idOnServerInScope(serverId || null);const server = switchServersStore.servers.find((s) => s.id === serverId) ?? null;const [name, setName] = useState('');@@ -63,20 +61,20 @@ export const CreateRoomModal = observer(function CreateRoomModal({const [error, setError] = useState<string | null>(null);const bridgesQuery = useQuery({- queryKey: ['remote-bridges', workspaceId],- queryFn: () => rpc.workspaces.listBridges(workspaceId as string),- enabled: workspaceId !== null,+ queryKey: ['remote-bridges', serverId],+ queryFn: () => rpc.switchServers.listRemoteBridges(serverId),+ enabled: !!serverId,});const agentsQuery = useQuery({- queryKey: ['remote-agents', workspaceId],- queryFn: () => rpc.workspaces.listAgents(workspaceId as string),- enabled: workspaceId !== null,+ queryKey: ['remote-agents', serverId],+ queryFn: () => rpc.switchServers.listRemoteAgents(serverId),+ enabled: !!serverId,});// Which account on each app is the person creating the room. A room on an app// they have not claimed an account on works, but their own messages in it are// from a stranger as far as the agents are concerned — so it is said here,// while the app is being chosen, rather than discovered later.- const { identities } = useMyIdentities(workspaceId);+ const { identities } = useMyIdentities(serverId);/*** Only agents this install registered on the server.@@ -88,11 +86,7 @@ export const CreateRoomModal = observer(function CreateRoomModal({* follow.*/const invitableAgents = (agentsQuery.data ?? []).filter((remote) =>- workspaceId === null- ? false- : agentsStore- .agentsInWorkspace(workspaceId)- .some((local) => local.switchAgentId === remote.id)+ agentsStore.agentsOnServer(serverId).some((local) => local.switchAgentId === remote.id));// Only a running bridge can back a new room, and creating a room here means@@ -117,11 +111,7 @@ export const CreateRoomModal = observer(function CreateRoomModal({const trimmedName = name.trim();const trimmedDescription = description.trim();const canSubmit =- workspaceId !== null &&- !!trimmedName &&- !!trimmedDescription &&- !!selectedBridge &&- !isSubmitting;+ !!serverId && !!trimmedName && !!trimmedDescription && !!selectedBridge && !isSubmitting;const handleSubmit = useCallback(async () => {if (!canSubmit || !selectedBridge) return;@@ -130,8 +120,8 @@ export const CreateRoomModal = observer(function CreateRoomModal({setError(null);try {- const result = await rpc.workspaces.createRoom({- workspaceId: workspaceId as string,+ const result = await rpc.switchServers.createRoom({+ serverId,name: trimmedName,description: trimmedDescription,instructions: instructions.trim() || undefined,@@ -170,7 +160,7 @@ export const CreateRoomModal = observer(function CreateRoomModal({}, [canSubmit,selectedBridge,- workspaceId,+ serverId,trimmedName,trimmedDescription,instructions,@@ -296,7 +286,7 @@ export const CreateRoomModal = observer(function CreateRoomModal({<ChosenAgentTilekey={agent.id}agent={agent}- subtitle={agentProviderLabelFor(agent.id, workspaceId)}+ subtitle={agentProviderLabelFor(agent.id, serverId)}onRemove={() =>setAgents((current) => current.filter((a) => a.id !== agent.id))}@@ -310,10 +300,7 @@ export const CreateRoomModal = observer(function CreateRoomModal({onPick={(next) => setAgents((current) => [...current, next])}searchText={(item) => item.name}renderItem={(item) => (- <AgentPickerRow- agent={item}- subtitle={agentProviderLabelFor(item.id, workspaceId)}- />+ <AgentPickerRow agent={item} subtitle={agentProviderLabelFor(item.id, serverId)} />)}disabled={agentsQuery.isLoading}placeholder={agentsQuery.isLoading ? 'Loading agents…' : 'Search agents to add...'}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/DisconnectMessagingAppModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/DisconnectMessagingAppModal.tsxindex 47494721b..dad51f0b5 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/DisconnectMessagingAppModal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/DisconnectMessagingAppModal.tsx@@ -17,7 +17,7 @@ import { Input } from '@renderer/lib/ui/input';import type { DeleteBridgeResult } from '@shared/core/switch-servers/switch-servers';type DisconnectMessagingAppModalArgs = {- workspaceId: string;+ serverId: string;bridgeId: string;bridgeDisplayName: string;};@@ -25,7 +25,7 @@ type DisconnectMessagingAppModalArgs = {type Props = BaseModalProps<void> & DisconnectMessagingAppModalArgs;/**- * Confirm disconnecting a messaging app from a workspace (CHOO-2137).+ * Confirm disconnecting a messaging app from a Switch server (CHOO-2137).** "Disconnect" undersells it: the server deletes every Switch room on the* bridge before removing the bridge itself, so this is the most destructive@@ -40,7 +40,7 @@ type Props = BaseModalProps<void> & DisconnectMessagingAppModalArgs;export const DisconnectMessagingAppModal = observer(function DisconnectMessagingAppModal({bridgeDisplayName,bridgeId,- workspaceId,+ serverId,onSuccess,onClose,}: Props) {@@ -55,7 +55,7 @@ export const DisconnectMessagingAppModal = observer(function DisconnectMessagingsetIsDeleting(true);setError(null);try {- const result = await rpc.workspaces.deleteBridge({ workspaceId, bridgeId });+ const result = await rpc.switchServers.deleteBridge({ serverId, bridgeId });if (result.kind !== 'deleted') {setError(messageFor(result));setIsDeleting(false);@@ -66,7 +66,7 @@ export const DisconnectMessagingAppModal = observer(function DisconnectMessagingsetError(failureText(cause, 'Could not disconnect the messaging app.'));setIsDeleting(false);}- }, [typeConfirmed, workspaceId, bridgeId, onSuccess]);+ }, [typeConfirmed, serverId, bridgeId, onSuccess]);return (<>diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsxindex 8bf8f73fe..eb09a49d1 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx@@ -14,7 +14,6 @@ import {} from 'lucide-react';import { observer } from 'mobx-react-lite';import { useEffect, useMemo, useState } from 'react';-import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';import { failureText } from '@renderer/lib/errors/describe-failure';@@ -91,16 +90,15 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({const showConnectMessagingApp = useShowModal('connectMessagingAppModal');const showClaimIdentity = useShowModal('claimIdentityModal');const showDisconnectMessagingApp = useShowModal('disconnectMessagingAppModal');- const workspaceId = workspacesStore.idOnServerInScope(serverId);const isAdmin = switchServersStore.statusFor(serverId)?.user?.role === 'admin';// Only a stack Switch Console runs has a chat whose credentials it generated and// can therefore show; anyone else's Mattermost is their own to hand out.const isManaged = !!switchServersStore.servers.find((s) => s.id === serverId)?.managed;const bridgesQuery = useQuery({- queryKey: ['remote-bridges', workspaceId],- queryFn: () => rpc.workspaces.listBridges(workspaceId as string),- enabled: workspaceId !== null,+ queryKey: ['remote-bridges', serverId],+ queryFn: () => rpc.switchServers.listRemoteBridges(serverId),+ enabled: !!serverId,});const bridges = useMemo(() => orderBridges(bridgesQuery.data ?? []), [bridgesQuery.data]);@@ -109,7 +107,7 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({identities,error: identitiesError,refresh: refreshIdentities,- } = useMyIdentities(workspaceId);+ } = useMyIdentities(serverId);// Whose claim to drop when unlinking. Every account here is one the signed-in// user claimed, and other people may hold the same one — so name the user// rather than let the server infer it. Null until the session is read back,@@ -124,9 +122,9 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({// agent's policy should stop the warning on the next look, not a minute later.const anyUnlinked = hasUnlinkedMessagingApp(bridges, identities);const ownerAgentsQuery = useQuery({- queryKey: ['owns-owner-addressed-agent', workspaceId],- queryFn: () => rpc.workspaces.ownsOwnerAddressedAgent(workspaceId as string),- enabled: workspaceId !== null && anyUnlinked,+ queryKey: ['owns-owner-addressed-agent', serverId],+ queryFn: () => rpc.switchServers.ownsOwnerAddressedAgent(serverId),+ enabled: !!serverId && anyUnlinked,});// The probe failing costs no data on screen, only the warning — so it is// logged rather than shown, and the card does not warn on a guess.@@ -134,11 +132,11 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({useEffect(() => {if (ownerAgentsError) {log.warn('Could not check for owner-addressed agents', {- workspaceId,+ serverId,error: ownerAgentsError,});}- }, [ownerAgentsError, workspaceId]);+ }, [ownerAgentsError, serverId]);const unrecognisedIn = unrecognisedMessagingApps({bridges,@@ -153,12 +151,11 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({const [toggleError, setToggleError] = useState<string | null>(null);const handleToggleChannelCreation = async (bridge: RemoteBridge, enabled: boolean) => {- if (workspaceId === null) return;setSavingBridgeId(bridge.id);setToggleError(null);try {- const result = await rpc.workspaces.updateBridge({- workspaceId,+ const result = await rpc.switchServers.updateBridge({+ serverId,bridgeId: bridge.id,channelCreationEnabled: enabled,});@@ -166,7 +163,7 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({setToggleError(`Could not update ${bridge.displayName}: ${messageForUpdate(result)}`);return;}- await queryClient.invalidateQueries({ queryKey: ['remote-bridges', workspaceId] });+ await queryClient.invalidateQueries({ queryKey: ['remote-bridges', serverId] });} catch (cause) {setToggleError(failureText(cause, `Could not update ${bridge.displayName}.`));} finally {@@ -209,7 +206,7 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({onSuccess: ({ bridgeId, displayName, directorySearchSupported }) => {// Refresh the bridge list everywhere it is consumed — this// card and the room-creation picker share the query key.- void queryClient.invalidateQueries({ queryKey: ['remote-bridges', workspaceId] });+ void queryClient.invalidateQueries({ queryKey: ['remote-bridges', serverId] });void switchRoomsStore.refreshRoomState();// Step 2 of connecting a workspace: say which account in it// is yours (CHOO-2137). Offered here because this is the one@@ -225,11 +222,8 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({// has messaged the app and there is a name to pick. Say that,// rather than closing on nothing and leaving the step looking// forgotten.- if (- workspaceId !== null &&- shouldOfferIdentityLinkOnConnect({ directorySearchSupported })- ) {- showClaimIdentity({ workspaceId, bridgeId });+ if (shouldOfferIdentityLinkOnConnect({ directorySearchSupported })) {+ showClaimIdentity({ serverId, bridgeId });return;}const note = identityLinkOrderingNote({ displayName, directorySearchSupported });@@ -286,7 +280,6 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({{bridges.map((bridge) => (<MessagingAppRowkey={bridge.id}- workspaceId={workspaceId}serverId={serverId}bridge={bridge}/* Nothing is drawn in the identity column until the list@@ -302,23 +295,22 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({onToggleChannelCreation={(enabled) =>void handleToggleChannelCreation(bridge, enabled)}- onDisconnect={() => {- if (workspaceId === null) return;+ onDisconnect={() =>showDisconnectMessagingApp({- workspaceId,+ serverId,bridgeId: bridge.id,bridgeDisplayName: bridge.displayName,onSuccess: () => {void queryClient.invalidateQueries({- queryKey: ['remote-bridges', workspaceId],+ queryKey: ['remote-bridges', serverId],});// The rooms on that bridge went with it, so the sidebar// is stale in a way the bridge list alone does not// repair.void switchRoomsStore.refreshRoomState();},- });- }}+ })+ }/>))}</div>@@ -339,7 +331,6 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({* disconnecting it — is in the menu.*/export function MessagingAppRow({- workspaceId,serverId,bridge,identities,@@ -351,13 +342,9 @@ export function MessagingAppRow({onToggleChannelCreation,onDisconnect,}: {- /** Null while this install has not resolved the server's workspace; the- * identity actions are the only thing that needs it, and they wait. */- workspaceId: string | null;- /** Only for the bundled chat's sign-in, which is about the gateway. */serverId: string;bridge: RemoteBridge;- /** Accounts the user has claimed in this workspace, or null while unknown. */+ /** Accounts the user has claimed on this server, or null while unknown. */identities: LinkedIdentity[] | null;currentUserId: string | null;onReleased: () => void;@@ -374,18 +361,14 @@ export function MessagingAppRow({const identity = identities?.find((i) => i.bridgeId === bridge.id) ?? null;const platform = bridgePlatformLabel(bridge.type);- const claim = () => {- if (workspaceId === null) return;- showClaimIdentity({ workspaceId, bridgeId: bridge.id });- };+ const claim = () => showClaimIdentity({ serverId, bridgeId: bridge.id });const release = async (identityId: string) => {- if (workspaceId === null) return;setReleasing(true);setReleaseError(null);try {- await rpc.workspaces.releaseBridgeIdentity({- workspaceId,+ await rpc.switchServers.releaseBridgeIdentity({+ serverId,bridgeId: bridge.id,identityId,userId: currentUserId,diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/agent-server-picker.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/agent-server-picker.tsxindex e28b9d554..c3437f11c 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/agent-server-picker.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/agent-server-picker.tsx@@ -2,7 +2,6 @@ import { useQuery } from '@tanstack/react-query';import { CheckCircle2, CircleAlert, Loader2 } from 'lucide-react';import { observer } from 'mobx-react-lite';import { useEffect } from 'react';-import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { rpc } from '@renderer/lib/ipc';import {Select,@@ -16,7 +15,7 @@ import type { AgentVerifyResult } from '@shared/core/switch-servers/switch-serveimport { switchServersStore } from './switch-servers-store';/** Verification phase the picker reports up so a parent can gate submission. */-export type ServerVerifyState = 'idle' | 'checking' | 'no-workspace' | AgentVerifyResult;+export type ServerVerifyState = 'idle' | 'checking' | AgentVerifyResult;interface AgentServerPickerProps {/** The Switch agent id to verify against the chosen server. */@@ -51,24 +50,17 @@ export const AgentServerPicker = observer(function AgentServerPicker({const servers = switchServersStore.servers;- const workspaceId = workspacesStore.idOnServerInScope(serverId);const verifyQuery = useQuery({- queryKey: ['verifyAgent', workspaceId, switchAgentId],- queryFn: () =>- rpc.workspaces.verifyAgent({ workspaceId: workspaceId!, agentId: switchAgentId }),- enabled: !!workspaceId && !!switchAgentId,+ queryKey: ['verifyAgent', serverId, switchAgentId],+ queryFn: () => rpc.switchServers.verifyAgent({ serverId: serverId!, agentId: switchAgentId }),+ enabled: !!serverId && !!switchAgentId,});- // A disabled query reports `isPending` forever, so a server with no workspace- // to verify against has to be its own state: read as "checking" it would spin- // for as long as the dialog is open and never say why submit stays shut.const state: ServerVerifyState = !serverId? 'idle'- : workspaceId === null- ? 'no-workspace'- : verifyQuery.isPending- ? 'checking'- : (verifyQuery.data ?? 'checking');+ : verifyQuery.isPending+ ? 'checking'+ : (verifyQuery.data ?? 'checking');useEffect(() => {onVerifyStateChange(state);@@ -125,13 +117,6 @@ function VerifyStatus({ state, serverName }: { state: ServerVerifyState; serverN</Row>);}- if (state === 'no-workspace') {- return (- <Row icon={<CircleAlert className="size-3.5 text-amber-500" />}>- {serverName} has no workspace to register this agent in yet.- </Row>- );- }if (state === 'unauthenticated') {return (<Row icon={<CircleAlert className="size-3.5 text-amber-500" />}>diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/bridge-identity-search.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/bridge-identity-search.tsxindex 52e8c8a8d..0439ea870 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/bridge-identity-search.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/bridge-identity-search.tsx@@ -2,7 +2,6 @@ import { useQuery, useQueryClient } from '@tanstack/react-query';import { CircleAlert } from 'lucide-react';import { observer } from 'mobx-react-lite';import { useState } from 'react';-import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { failureText } from '@renderer/lib/errors/describe-failure';import { useDebounce } from '@renderer/lib/hooks/useDebounce';import { rpc } from '@renderer/lib/ipc';@@ -39,7 +38,7 @@ const MIN_QUERY_LENGTH = 2;* written first.*/export const BridgeIdentitySearch = observer(function BridgeIdentitySearch({- workspaceId,+ serverId,bridgeId,bridgeDisplayName,platform,@@ -47,9 +46,9 @@ export const BridgeIdentitySearch = observer(function BridgeIdentitySearch({autoFocus,onClaimed,}: {- workspaceId: string;+ serverId: string;bridgeId: string;- /** The bridge being searched — two connections on the same platform can+ /** The workspace being searched — two connections on the same platform can* exist, and only the name tells them apart. */bridgeDisplayName: string;/** The platform as a person names it, for prose about what is searchable. */@@ -60,24 +59,21 @@ export const BridgeIdentitySearch = observer(function BridgeIdentitySearch({}) {const { setCloseGuard } = useModalContext();const queryClient = useQueryClient();- const serverId = workspacesStore.serverIdFor(workspaceId);- const currentUserId = serverId- ? (switchServersStore.statusFor(serverId)?.user?.id ?? null)- : null;+ const currentUserId = switchServersStore.statusFor(serverId)?.user?.id ?? null;const [search, setSearch] = useState('');const [claiming, setClaiming] = useState<string | null>(null);const [releasing, setReleasing] = useState<string | null>(null);const [error, setError] = useState<string | null>(null);- const { refresh: refreshIdentities } = useMyIdentities(workspaceId || null);+ const { refresh: refreshIdentities } = useMyIdentities(serverId || null);const debouncedQuery = useDebounce(search.trim(), SEARCH_DEBOUNCE_MS);- const searchable = !!workspaceId && debouncedQuery.length >= MIN_QUERY_LENGTH;+ const searchable = !!serverId && debouncedQuery.length >= MIN_QUERY_LENGTH;const directoryQuery = useQuery({- queryKey: ['bridge-directory', workspaceId, bridgeId, debouncedQuery],+ queryKey: ['bridge-directory', serverId, bridgeId, debouncedQuery],queryFn: () =>- rpc.workspaces.searchBridgeDirectory({ workspaceId, bridgeId, query: debouncedQuery }),+ rpc.switchServers.searchBridgeDirectory({ serverId, bridgeId, query: debouncedQuery }),enabled: searchable,});@@ -86,8 +82,8 @@ export const BridgeIdentitySearch = observer(function BridgeIdentitySearch({setCloseGuard(true);setError(null);try {- const result = await rpc.workspaces.claimBridgeIdentity({- workspaceId,+ const result = await rpc.switchServers.claimBridgeIdentity({+ serverId,bridgeId,externalUserId: person.externalUserId,username: person.username,@@ -115,16 +111,14 @@ export const BridgeIdentitySearch = observer(function BridgeIdentitySearch({setCloseGuard(true);setError(null);try {- await rpc.workspaces.releaseBridgeIdentity({- workspaceId,+ await rpc.switchServers.releaseBridgeIdentity({+ serverId,bridgeId,identityId: person.knownExternalUserId,userId: currentUserId,});refreshIdentities();- await queryClient.invalidateQueries({- queryKey: ['bridge-directory', workspaceId, bridgeId],- });+ await queryClient.invalidateQueries({ queryKey: ['bridge-directory', serverId, bridgeId] });} catch (cause) {setError(failureText(cause, 'Could not unlink this account.'));} finally {diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-accounts-step.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-accounts-step.tsxindex 495a98e58..05fa1b28b 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-accounts-step.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-accounts-step.tsx@@ -2,15 +2,15 @@ import { useQuery } from '@tanstack/react-query';import { Check, Link2, MessageSquare, TriangleAlert } from 'lucide-react';import { observer } from 'mobx-react-lite';import { useState } from 'react';-import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';import { failureText } from '@renderer/lib/errors/describe-failure';import { rpc } from '@renderer/lib/ipc';import { Button } from '@renderer/lib/ui/button';import { ConfirmButton } from '@renderer/lib/ui/confirm-button';+import { DialogContentArea, DialogFooter } from '@renderer/lib/ui/dialog';import { Spinner } from '@renderer/lib/ui/spinner';-import { WizardFrame } from '@renderer/lib/ui/wizard-frame';+import { WizardStepHeader } from '@renderer/lib/ui/wizard-step-header';import type { LinkedIdentity, RemoteBridge } from '@shared/core/switch-servers/switch-servers';import { BridgeIdentitySearch } from './bridge-identity-search';import { connectedAppsSummary, LINK_ACCOUNTS_LATER } from './link-accounts-prose';@@ -28,10 +28,14 @@ import { useMyIdentities } from './use-my-identities';export const LinkAccountsStep = observer(function LinkAccountsStep({serverId,serverName,+ step,+ of,onDone,}: {serverId: string;serverName: string;+ step: number;+ of: number;onDone: () => void;}) {// Which app's directory is open, or null while the list is. Linking happens@@ -39,81 +43,63 @@ export const LinkAccountsStep = observer(function LinkAccountsStep({// to and give the user two Backs meaning different things.const [linking, setLinking] = useState<RemoteBridge | null>(null);- const workspaceId = workspacesStore.idOnServerInScope(serverId);const bridgesQuery = useQuery({- queryKey: ['remote-bridges', workspaceId],- queryFn: () => rpc.workspaces.listBridges(workspaceId as string),- enabled: workspaceId !== null,+ queryKey: ['remote-bridges', serverId],+ queryFn: () => rpc.switchServers.listRemoteBridges(serverId),});- // A disabled query never leaves its pending state, so without this the page- // would spin on "reading the apps" forever and never say that it is not- // reading anything. Messaging apps hang off a workspace; with none in scope- // there is nothing to list and nothing to link an account to.- const noWorkspace =- workspaceId === null- ? new Error(`Your account has no workspace on ${serverName} to link accounts in.`)- : null;- const { identities } = useMyIdentities(workspaceId);+ const { identities } = useMyIdentities(serverId);- // The footer's Back and the pager's back arrow are the same move, so they- // read one const.- const goBack = () => setLinking(null);-- if (linking && workspaceId !== null) {+ if (linking) {return (- <WizardFrame- title={`Link your ${bridgePlatformLabel(linking.type)} account`}- subtitle={null}- pager={{- pageName: `Link ${bridgePlatformLabel(linking.type)}`,- onBack: goBack,- onNext: null,- }}- footer={- <Button variant="outline" onClick={goBack}>+ <>+ <WizardStepHeader+ title={`Link your ${bridgePlatformLabel(linking.type)} account`}+ step={step}+ of={of}+ />+ <DialogContentArea className="pt-0">+ <div className="flex w-full flex-col gap-4">+ <p className="text-sm text-foreground-muted">+ Find yourself in {linking.displayName} and tell Switch that account is you.+ </p>+ <BridgeIdentitySearch+ serverId={serverId}+ bridgeId={linking.id}+ bridgeDisplayName={linking.displayName}+ platform={bridgePlatformLabel(linking.type)}+ directorySearchSupported={linking.directorySearchSupported}+ autoFocus+ onClaimed={() => setLinking(null)}+ />+ </div>+ </DialogContentArea>+ <DialogFooter>+ <Button variant="outline" onClick={() => setLinking(null)}>Back</Button>- }- >- <div className="flex w-full flex-col gap-4">- <p className="text-sm text-foreground-muted">- Find yourself in {linking.displayName} and tell Switch that account is you.- </p>- <BridgeIdentitySearch- workspaceId={workspaceId}- bridgeId={linking.id}- bridgeDisplayName={linking.displayName}- platform={bridgePlatformLabel(linking.type)}- directorySearchSupported={linking.directorySearchSupported}- autoFocus- onClaimed={() => setLinking(null)}- />- </div>- </WizardFrame>+ </DialogFooter>+ </>);}return (- <WizardFrame- title="Link your messaging accounts"- subtitle={null}- /* The last page of the flow, and signing in cannot be undone by walking- backwards, so there is nowhere for either arrow to go. */- pager={{ pageName: 'Link accounts', onBack: null, onNext: null }}- footer={<ConfirmButton onClick={onDone}>Done</ConfirmButton>}- >- <BridgeList- serverName={serverName}- bridges={bridgesQuery.isSuccess ? orderBridges(bridgesQuery.data) : null}- identities={identities}- isPending={noWorkspace === null && bridgesQuery.isPending}- error={noWorkspace ?? (bridgesQuery.isError ? bridgesQuery.error : null)}- onRetry={() =>- void (noWorkspace === null ? bridgesQuery.refetch() : workspacesStore.refresh())- }- onLink={setLinking}- />- </WizardFrame>+ <>+ <WizardStepHeader title="Link your messaging accounts" step={step} of={of} />+ <DialogContentArea className="pt-0">+ <BridgeList+ serverName={serverName}+ bridges={bridgesQuery.isSuccess ? orderBridges(bridgesQuery.data) : null}+ identities={identities}+ isPending={bridgesQuery.isPending}+ error={bridgesQuery.isError ? bridgesQuery.error : null}+ onRetry={() => void bridgesQuery.refetch()}+ onLink={setLinking}+ />+ </DialogContentArea>+ <DialogFooter>+ <ConfirmButton onClick={onDone}>Done</ConfirmButton>+ </DialogFooter>+ </>);});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 12e97c28c..d8f0c0ede 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-agents-view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-agents-view.tsx@@ -13,7 +13,7 @@ import { useToast } from '@renderer/lib/hooks/use-toast';import { rpc } from '@renderer/lib/ipc';import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';import { useShowModal } from '@renderer/lib/modal/modal-provider';-import { useAgentIconUrl } from '@renderer/lib/stores/use-workspace-agents';+import { useAgentIconUrl } from '@renderer/lib/stores/use-remote-agents';import { Button } from '@renderer/lib/ui/button';import {DropdownMenu,@@ -96,7 +96,7 @@ const AgentCard = observer(function AgentCard({const sshHost = location?.data?.sshHost ?? null;const label = agent.name || 'Unnamed agent';const provider = providerDisplayName(agent.providerId);- const iconUrl = useAgentIconUrl(agent.workspaceId, agent.switchAgentId);+ const iconUrl = useAgentIconUrl(serverId, agent.switchAgentId);const gatewayUrl =agent.switchAgentId && switchRoomsStore.gatewayAgentUrl(serverId, agent.switchAgentId);diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-page.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-page.tsxindex c1d76cb5f..cd80e2b23 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-page.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-page.tsx@@ -10,7 +10,6 @@ export function ServerPage({title,description,action,- footer,children,}: {title: string;@@ -18,26 +17,20 @@ export function ServerPage({/** Header-level action, where the page has one. Agents has none: its add* affordance is the first tile of its grid. */action?: ReactNode;- /** A bar pinned under the page, outside the scrolling content — a pager for- * the pages that are one step of a flow. */- footer?: ReactNode;children: ReactNode;}) {return (- <div className="relative z-10 flex min-h-0 flex-1 flex-col bg-background">- <div className="flex min-h-0 flex-1 flex-col overflow-auto">- <div className="mx-auto w-full max-w-4xl space-y-6 p-6">- <header className="flex items-start justify-between gap-3">- <div className="min-w-0">- <h2 className="truncate text-2xl font-semibold text-foreground">{title}</h2>- <p className="mt-1 text-sm text-foreground-muted">{description}</p>- </div>- {action && <div className="flex shrink-0 items-center gap-2">{action}</div>}- </header>- {children}- </div>+ <div className="relative z-10 flex min-h-0 flex-1 flex-col overflow-auto bg-background">+ <div className="mx-auto w-full max-w-4xl space-y-6 p-6">+ <header className="flex items-start justify-between gap-3">+ <div className="min-w-0">+ <h2 className="truncate text-2xl font-semibold text-foreground">{title}</h2>+ <p className="mt-1 text-sm text-foreground-muted">{description}</p>+ </div>+ {action && <div className="flex shrink-0 items-center gap-2">{action}</div>}+ </header>+ {children}</div>- {footer}</div>);}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-rooms-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-rooms-view.tsxindex 0dda4c543..5ca6828d2 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-rooms-view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-rooms-view.tsx@@ -6,13 +6,12 @@ import { agentsStore } from '@renderer/features/locations/stores/agents-store';import { refreshSidebarRoomState } from '@renderer/features/sidebar/sidebar-tree-data';import { openRoom } from '@renderer/features/switch-rooms/open-room';import { roomTitle } from '@renderer/features/switch-rooms/room-labels';-import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { AgentAvatar } from '@renderer/lib/components/agent-avatar';import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';import { useParams } from '@renderer/lib/layout/navigation-provider';import { useShowModal } from '@renderer/lib/modal/modal-provider';-import { useWorkspaceAgents } from '@renderer/lib/stores/use-workspace-agents';+import { useRemoteAgents } from '@renderer/lib/stores/use-remote-agents';import { Button } from '@renderer/lib/ui/button';import { SearchInput } from '@renderer/lib/ui/search-input';import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';@@ -44,10 +43,9 @@ const ServerRoomsPanel = observer(function ServerRoomsPanel() {void refreshSidebarRoomState(false);}, [serverId]);- const workspaceId = workspacesStore.idOnServerInScope(serverId);- const rooms = workspaceId === null ? [] : switchRoomsStore.readableRoomsInWorkspace(workspaceId);- const signedOut = switchRoomsStore.workspacesNotSignedIn.some((w) => w.id === workspaceId);- const failed = switchRoomsStore.workspacesThatFailedToLoad.some((w) => w.id === workspaceId);+ const rooms = switchRoomsStore.readableRoomsOnServer(serverId);+ const signedOut = switchRoomsStore.serversNotSignedIn.some((s) => s.id === serverId);+ const failed = switchRoomsStore.serversThatFailedToLoad.some((s) => s.id === serverId);const query = filter.trim().toLowerCase();const matching = query === '' ? rooms : rooms.filter((r) => r.name.toLowerCase().includes(query));@@ -58,24 +56,16 @@ const ServerRoomsPanel = observer(function ServerRoomsPanel() {title="Your Rooms"description={`Rooms on ${server?.name ?? 'this server'}. Create one, see who is in it, and where it is bridged.`}action={- <Button- size="sm"- disabled={signedOut || workspaceId === null}- onClick={() => showCreateRoomModal({ serverId })}- >+ <Button size="sm" disabled={signedOut} onClick={() => showCreateRoomModal({ serverId })}><Plus className="size-4" />Create room</Button>}>- {/* Four ways to have no rows, and only one of them means "there are no- rooms". Saying that in the others would send someone off to create a+ {/* Three ways to have no rows, and only one of them means "there are no+ rooms". Saying that in the other two would send someone off to create aroom they already have. */}- {workspaceId === null ? (- <ServerTableEmpty>- This server has no workspace yet, so its rooms cannot be read.- </ServerTableEmpty>- ) : signedOut ? (+ {signedOut ? (<ServerTableEmpty>Sign in to {server?.name ?? 'this server'} to see its rooms.</ServerTableEmpty>@@ -108,7 +98,6 @@ const ServerRoomsPanel = observer(function ServerRoomsPanel() {key={group.key}group={group}serverId={serverId}- workspaceId={workspaceId}// Nothing folds while a filter is on. Typing a name and being// shown a "Show 3 more" where the match is hiding is the one// moment the fold would cost more than it saves.@@ -182,12 +171,10 @@ const ROOMS_BEFORE_FOLD = 5;const MessagingAppGroup = observer(function MessagingAppGroup({group,serverId,- workspaceId,fold,}: {group: RoomGroup;serverId: string;- workspaceId: string;/** Whether long groups are cut short. False while the list is filtered. */fold: boolean;}) {@@ -230,7 +217,7 @@ const MessagingAppGroup = observer(function MessagingAppGroup({{open && (<div className="divide-y divide-border overflow-hidden rounded-[10px] border border-border">{shown.map((room) => (- <RoomRow key={room.id} room={room} serverId={serverId} workspaceId={workspaceId} />+ <RoomRow key={room.id} room={room} serverId={serverId} />))}{fold && group.rooms.length > ROOMS_BEFORE_FOLD && (<button@@ -253,14 +240,12 @@ const MessagingAppGroup = observer(function MessagingAppGroup({const RoomRow = observer(function RoomRow({room,serverId,- workspaceId,}: {room: RemoteRoomSummary;serverId: string;- workspaceId: string;}) {const members = switchRoomsStore.localMemberIds(room.id);- const { data: remoteAgents } = useWorkspaceAgents(workspaceId);+ const { data: remoteAgents } = useRemoteAgents(serverId);const remoteById = new Map((remoteAgents ?? []).map((agent) => [agent.id, agent]));const localAgents = agentsStore.agentsOnServer(serverId)diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-stat-tiles.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-stat-tiles.tsxindex 1f1c299f8..185fca734 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-stat-tiles.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-stat-tiles.tsx@@ -2,7 +2,6 @@ import { useQuery } from '@tanstack/react-query';import { observer } from 'mobx-react-lite';import { useEffect } from 'react';import { agentsStore } from '@renderer/features/locations/stores/agents-store';-import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { rpc } from '@renderer/lib/ipc';import { switchRoomsStore } from './switch-rooms-store';@@ -19,14 +18,12 @@ export const ServerStatTiles = observer(function ServerStatTiles({}: {serverId: string;}) {- const workspaceId = workspacesStore.idOnServerInScope(serverId);-// Shares the key every other bridge reader uses, so the list is already in// cache by the time this renders and the tile never fetches on its own.const bridgesQuery = useQuery({- queryKey: ['remote-bridges', workspaceId],- queryFn: () => rpc.workspaces.listBridges(workspaceId as string),- enabled: workspaceId !== null,+ queryKey: ['remote-bridges', serverId],+ queryFn: () => rpc.switchServers.listRemoteBridges(serverId),+ enabled: !!serverId,});// The sidebar loads this too, but the page must not depend on the sidebar@@ -43,11 +40,7 @@ export const ServerStatTiles = observer(function ServerStatTiles({/><StatTilelabel="Your Rooms"- value={- workspaceId === null- ? null- : switchRoomsStore.readableRoomsInWorkspace(workspaceId).length- }+ value={switchRoomsStore.readableRoomsOnServer(serverId).length}/><StatTile label="Messaging apps" value={bridgesQuery.data?.length ?? null} /></div>diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.test.tsindex e30d987d9..eb2e1fcbb 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.test.ts@@ -1,32 +1,20 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { RemoteRoomSummary } from '@shared/core/switch-servers/switch-servers';-const listRooms = vi.hoisted(() => vi.fn());+const listRemoteRooms = vi.hoisted(() => vi.fn());const listAgentRooms = vi.hoisted(() => vi.fn());const serversStore = vi.hoisted(() => ({servers: [] as { id: string; name?: string; managed?: boolean }[],+ activeServerId: null as string | null,isConnected: (_serverId: string): boolean => true,// These servers answer; they are simply not signed in to.isUnreachable: (_serverId: string): boolean => false,statusFor: (serverId: string) => ({ user: { id: `user-of-${serverId}` } }),}));-const workspaces = vi.hoisted(() => ({- workspaces: [] as { id: string; serverId: string; name: string }[],- activeId: null as string | null,- byId(workspaceId: string) {- return this.workspaces.find((w) => w.id === workspaceId) ?? null;- },- serverIdFor(workspaceId: string) {- return this.byId(workspaceId)?.serverId ?? null;- },-}));vi.mock('@renderer/lib/ipc', () => ({events: { on: vi.fn() },- rpc: { workspaces: { listRooms, listAgentRooms } },-}));-vi.mock('@renderer/features/workspaces/workspaces-store', () => ({- workspacesStore: workspaces,+ rpc: { switchServers: { listRemoteRooms, listAgentRooms } },}));vi.mock('./switch-servers-store', () => ({ switchServersStore: serversStore }));vi.mock('./local-server-store', () => ({ localServerStore: { isRunning: true } }));@@ -51,28 +39,19 @@ function room(id: string, ownerId: string | null, overrides: Partial<RemoteRoomS} satisfies RemoteRoomSummary;}-/** Two workspaces, one per server, which is what every install has today. */-function twoWorkspaces() {- workspaces.workspaces = [- { id: 'ws-a', serverId: 'srv-a', name: 'Alpha' },- { id: 'ws-b', serverId: 'srv-b', name: 'Beta' },- ];-}-describe('listed rooms', () => {beforeEach(() => {vi.clearAllMocks();serversStore.servers = [{ id: 'srv-a' }, { id: 'srv-b' }];- twoWorkspaces();- workspaces.activeId = null;+ serversStore.activeServerId = null;});- it('lists every room in a workspace on a server this install manages', async () => {+ it('lists every room on a server this install manages', async () => {// You run that deployment. Nothing on it should need a second app to see.serversStore.servers = [{ id: 'srv-a', managed: true }, { id: 'srv-b' }];- workspaces.activeId = 'ws-a';- listRooms.mockImplementation(async (workspaceId: string) =>- workspaceId === 'ws-a'+ serversStore.activeServerId = 'srv-a';+ listRemoteRooms.mockImplementation(async (serverId: string) =>+ serverId === 'srv-a'? [room('mine', 'user-of-srv-a'),room('someone-elses', 'user-of-someone-else'),@@ -88,8 +67,8 @@ describe('listed rooms', () => {});it('lists only rooms owned by that server’s signed-in user, excluding archived ones', async () => {- listRooms.mockImplementation(async (workspaceId: string) =>- workspaceId === 'ws-a'+ listRemoteRooms.mockImplementation(async (serverId: string) =>+ serverId === 'srv-a'? [room('mine', 'user-of-srv-a'),room('someone-elses', 'user-of-someone-else'),@@ -105,117 +84,138 @@ describe('listed rooms', () => {expect(store.listedRoomsInActiveScope.map((r: { id: string }) => r.id)).toEqual(['mine']);});- it('shows only the active workspace’s rooms, not every connected one’s', async () => {- listRooms.mockImplementation(async (workspaceId: string) => [- room(`${workspaceId}-room`, `user-of-${workspaces.serverIdFor(workspaceId)}`),+ it('shows only the active server’s rooms, not every connected server’s', async () => {+ listRemoteRooms.mockImplementation(async (serverId: string) => [+ room(`${serverId}-room`, `user-of-${serverId}`),]);const store = new SwitchRoomsStore();await store.loadRoomNames();- workspaces.activeId = 'ws-b';+ serversStore.activeServerId = 'srv-b';- expect(store.listedRoomsInActiveScope.map((r: { id: string }) => r.id)).toEqual(['ws-b-room']);+ expect(store.listedRoomsInActiveScope.map((r: { id: string }) => r.id)).toEqual(['srv-b-room']);});- it('hides nothing when no workspace is active, matching how locations are scoped', async () => {- listRooms.mockImplementation(async (workspaceId: string) => [- room(`${workspaceId}-room`, `user-of-${workspaces.serverIdFor(workspaceId)}`),+ it('hides nothing when no server is active, matching how locations are scoped', async () => {+ listRemoteRooms.mockImplementation(async (serverId: string) => [+ room(`${serverId}-room`, `user-of-${serverId}`),]);const store = new SwitchRoomsStore();await store.loadRoomNames();expect(store.listedRoomsInActiveScope.map((r: { id: string }) => r.id)).toEqual([- 'ws-a-room',- 'ws-b-room',+ 'srv-a-room',+ 'srv-b-room',]);});- it('keeps a workspace that failed to respond from dropping the others', async () => {- listRooms.mockImplementation(async (workspaceId: string) => {- if (workspaceId === 'ws-a') throw new Error('unreachable');- return [room('ws-b-room', 'user-of-srv-b')];+ it('keeps a server that failed to respond from dropping the others', async () => {+ listRemoteRooms.mockImplementation(async (serverId: string) => {+ if (serverId === 'srv-a') throw new Error('unreachable');+ return [room('srv-b-room', 'user-of-srv-b')];});const store = new SwitchRoomsStore();await store.loadRoomNames();- expect(store.listedRoomsInActiveScope.map((r: { id: string }) => r.id)).toEqual(['ws-b-room']);+ expect(store.listedRoomsInActiveScope.map((r: { id: string }) => r.id)).toEqual(['srv-b-room']);});- it('says the room list is incomplete when a workspace could not be read', async () => {- listRooms.mockImplementation(async (workspaceId: string) => {- if (workspaceId === 'ws-a') throw new Error('unreachable');- return [room('ws-b-room', 'user-of-srv-b')];+ it('says the room list is incomplete when a server could not be read', async () => {+ serversStore.servers = [+ { id: 'srv-a', name: 'Alpha' },+ { id: 'srv-b', name: 'Beta' },+ ];+ listRemoteRooms.mockImplementation(async (serverId: string) => {+ if (serverId === 'srv-a') throw new Error('unreachable');+ return [room('srv-b-room', 'user-of-srv-b')];});const store = new SwitchRoomsStore();await store.loadRoomNames();- expect(store.workspacesThatFailedToLoad.map((w) => w.name)).toEqual(['Alpha']);+ expect(store.serversThatFailedToLoad.map((s) => s.name)).toEqual(['Alpha']);});- it('asks only the active workspace for its rooms', async () => {- workspaces.activeId = 'ws-b';- listRooms.mockImplementation(async () => []);+ it('asks only the active server for its rooms', async () => {+ serversStore.servers = [+ { id: 'srv-a', name: 'Alpha' },+ { id: 'srv-b', name: 'Beta' },+ ];+ serversStore.activeServerId = 'srv-b';+ listRemoteRooms.mockImplementation(async () => []);const store = new SwitchRoomsStore();await store.loadRoomNames();- expect(listRooms).toHaveBeenCalledExactlyOnceWith('ws-b');+ expect(listRemoteRooms).toHaveBeenCalledExactlyOnceWith('srv-b');});- it('does not report another workspace’s failure against the one you are viewing', async () => {- // Each workspace is its own world. One you are not looking at being- // unreadable says nothing about the one you are, and warning about it trains- // you to ignore the warning.- listRooms.mockImplementation(async (workspaceId: string) => {- if (workspaceId === 'ws-a') throw new Error('unreachable');- return [room('ws-b-room', 'user-of-srv-b')];+ it('does not report another server’s failure against the one you are viewing', async () => {+ // Each server is its own world. A server you are not looking at being down+ // says nothing about the one you are, and warning about it trains you to+ // ignore the warning.+ serversStore.servers = [+ { id: 'srv-a', name: 'Alpha' },+ { id: 'srv-b', name: 'Beta' },+ ];+ listRemoteRooms.mockImplementation(async (serverId: string) => {+ if (serverId === 'srv-a') throw new Error('unreachable');+ return [room('srv-b-room', 'user-of-srv-b')];});const store = new SwitchRoomsStore();- // Search loads every workspace, so Alpha's failure is on the record...- await store.loadRoomsInAllWorkspaces();- expect(store.workspacesThatFailedToLoad.map((w) => w.name)).toEqual(['Alpha']);+ // Search loads every server, so Alpha's failure is on the record...+ await store.loadRoomsOnAllServers();+ expect(store.serversThatFailedToLoad.map((s) => s.name)).toEqual(['Alpha']);- // ...but it must not surface while Beta is the workspace on screen.- workspaces.activeId = 'ws-b';- expect(store.workspacesThatFailedToLoad).toEqual([]);- expect(store.workspacesNotSignedIn).toEqual([]);+ // ...but it must not surface while Beta is the server on screen.+ serversStore.activeServerId = 'srv-b';+ expect(store.serversThatFailedToLoad).toEqual([]);+ expect(store.serversNotSignedIn).toEqual([]);});- it('does not report a signed-out workspace you are not viewing', async () => {- workspaces.activeId = 'ws-b';+ it('does not report a disconnected server you are not viewing', async () => {+ serversStore.servers = [+ { id: 'srv-a', name: 'Alpha' },+ { id: 'srv-b', name: 'Beta' },+ ];+ serversStore.activeServerId = 'srv-b';serversStore.isConnected = (serverId: string) => serverId !== 'srv-a';- listRooms.mockImplementation(async () => []);+ listRemoteRooms.mockImplementation(async () => []);const store = new SwitchRoomsStore();- await store.loadRoomsInAllWorkspaces();+ await store.loadRoomsOnAllServers();- expect(store.workspacesNotSignedIn).toEqual([]);+ expect(store.serversNotSignedIn).toEqual([]);serversStore.isConnected = () => true;});- it('reports a workspace it is not signed in to as needing sign-in, not as failed', async () => {+ it('reports a server it is not signed in to as needing sign-in, not as failed', async () => {// Signing in is an action the user takes; a retry button cannot fix it, and// calling it a failure sends them round in a circle.- workspaces.activeId = 'ws-b';+ serversStore.servers = [+ { id: 'srv-a', name: 'Alpha' },+ { id: 'srv-b', name: 'Beta' },+ ];+ serversStore.activeServerId = 'srv-b';serversStore.isConnected = (serverId: string) => serverId !== 'srv-b';- listRooms.mockImplementation(async () => []);+ listRemoteRooms.mockImplementation(async () => []);const store = new SwitchRoomsStore();await store.loadRoomNames();- expect(store.workspacesNotSignedIn.map((w) => w.name)).toEqual(['Beta']);- expect(store.workspacesThatFailedToLoad).toEqual([]);+ expect(store.serversNotSignedIn.map((s) => s.name)).toEqual(['Beta']);+ expect(store.serversThatFailedToLoad).toEqual([]);serversStore.isConnected = () => true;});it('marks a room’s name as blocked on sign-in when its server is signed out', async () => {- workspaces.activeId = 'ws-a';+ serversStore.servers = [{ id: 'srv-a', name: 'Alpha' }];+ serversStore.activeServerId = 'srv-a';serversStore.isConnected = () => false;- listRooms.mockImplementation(async () => []);+ listRemoteRooms.mockImplementation(async () => []);const store = new SwitchRoomsStore();await store.loadRoomNames();@@ -225,26 +225,25 @@ describe('listed rooms', () => {expect(store.roomNameBlockedBySignIn('some-room')).toBe(false);});- it('clears a workspace’s failure once it can be read again', async () => {- workspaces.activeId = 'ws-a';- listRooms.mockImplementation(async () => {+ it('clears a server’s failure once it can be read again', async () => {+ serversStore.servers = [{ id: 'srv-a', name: 'Alpha' }];+ listRemoteRooms.mockImplementation(async () => {throw new Error('unreachable');});const store = new SwitchRoomsStore();await store.loadRoomNames();- expect(store.workspacesThatFailedToLoad.map((w) => w.name)).toEqual(['Alpha']);+ expect(store.serversThatFailedToLoad.map((s) => s.name)).toEqual(['Alpha']);- listRooms.mockImplementation(async () => [room('back', 'user-of-srv-a')]);+ listRemoteRooms.mockImplementation(async () => [room('back', 'user-of-srv-a')]);await store.loadRoomNames();- expect(store.workspacesThatFailedToLoad).toEqual([]);+ expect(store.serversThatFailedToLoad).toEqual([]);});});describe('agent memberships', () => {beforeEach(() => {vi.clearAllMocks();- twoWorkspaces();listAgentRooms.mockImplementation(async ({ agentId }: { agentId: string }) => [{roomId: `room-of-${agentId}`,@@ -260,17 +259,17 @@ describe('agent memberships', () => {const store = new SwitchRoomsStore();await store.ensureMembershipsFor([- { workspaceId: 'ws-a', switchAgentId: 'agent-1' },- { workspaceId: 'ws-a', switchAgentId: 'agent-2' },+ { serverId: 'srv-a', switchAgentId: 'agent-1' },+ { serverId: 'srv-a', switchAgentId: 'agent-2' },]);- expect(store.roomsFor('ws-a', 'agent-1')?.[0].roomId).toBe('room-of-agent-1');- expect(store.roomsFor('ws-a', 'agent-2')?.[0].roomId).toBe('room-of-agent-2');+ expect(store.roomsFor('srv-a', 'agent-1')?.[0].roomId).toBe('room-of-agent-1');+ expect(store.roomsFor('srv-a', 'agent-2')?.[0].roomId).toBe('room-of-agent-2');});it('serves cached memberships without refetching, unless forced', async () => {const store = new SwitchRoomsStore();- const agents = [{ workspaceId: 'ws-a', switchAgentId: 'agent-1' }];+ const agents = [{ serverId: 'srv-a', switchAgentId: 'agent-1' }];await store.ensureMembershipsFor(agents);await store.ensureMembershipsFor(agents);@@ -294,8 +293,8 @@ describe('agent memberships', () => {const store = new SwitchRoomsStore();await store.ensureMembershipsFor([- { workspaceId: 'ws-a', switchAgentId: 'agent-1' },- { workspaceId: 'ws-a', switchAgentId: 'agent-2' },+ { serverId: 'srv-a', switchAgentId: 'agent-1' },+ { serverId: 'srv-a', switchAgentId: 'agent-2' },]);expect(store.localMemberIds('shared').sort()).toEqual(['agent-1', 'agent-2']);@@ -308,7 +307,7 @@ describe('agent memberships', () => {]);const store = new SwitchRoomsStore();- await store.ensureMembershipsFor([{ workspaceId: 'ws-a', switchAgentId: 'agent-1' }]);+ await store.ensureMembershipsFor([{ serverId: 'srv-a', switchAgentId: 'agent-1' }]);expect(store.localMemberIds('gone')).toEqual([]);});@@ -320,20 +319,20 @@ describe('agent memberships', () => {if (agentId === 'agent-late') throw new Error('not yet');return [{ roomId: 'room-a', roomName: 'r', archived: false, status: 'live', roomRole: null }];});- listRooms.mockImplementation(async () => []);+ listRemoteRooms.mockImplementation(async () => []);const store = new SwitchRoomsStore();await store.ensureMembershipsFor([- { workspaceId: 'ws-a', switchAgentId: 'agent-1' },- { workspaceId: 'ws-a', switchAgentId: 'agent-late' },+ { serverId: 'srv-a', switchAgentId: 'agent-1' },+ { serverId: 'srv-a', switchAgentId: 'agent-late' },]);- expect(store.roomsFor('ws-a', 'agent-late')).toBeUndefined();+ expect(store.roomsFor('srv-a', 'agent-late')).toBeUndefined();listAgentRooms.mockImplementation(async () => [{ roomId: 'room-b', roomName: 'r', archived: false, status: 'live', roomRole: null },]);await store.refreshRoomState();- expect(store.roomsFor('ws-a', 'agent-late')?.[0].roomId).toBe('room-b');+ expect(store.roomsFor('srv-a', 'agent-late')?.[0].roomId).toBe('room-b');});it('reports an agent whose membership failed as unknown, not as in no rooms', async () => {@@ -344,8 +343,8 @@ describe('agent memberships', () => {const store = new SwitchRoomsStore();await store.ensureMembershipsFor([- { workspaceId: 'ws-a', switchAgentId: 'agent-1' },- { workspaceId: 'ws-a', switchAgentId: 'agent-2' },+ { serverId: 'srv-a', switchAgentId: 'agent-1' },+ { serverId: 'srv-a', switchAgentId: 'agent-2' },]);expect(store.agentsWithUnknownMembership).toBe(1);@@ -355,8 +354,8 @@ describe('agent memberships', () => {const store = new SwitchRoomsStore();await store.ensureMembershipsFor([- { workspaceId: 'ws-a', switchAgentId: 'agent-1' },- { workspaceId: 'ws-a', switchAgentId: 'agent-2' },+ { serverId: 'srv-a', switchAgentId: 'agent-1' },+ { serverId: 'srv-a', switchAgentId: 'agent-2' },]);expect(store.agentsWithUnknownMembership).toBe(0);@@ -370,38 +369,15 @@ describe('agent memberships', () => {const store = new SwitchRoomsStore();await store.ensureMembershipsFor([- { workspaceId: 'ws-a', switchAgentId: 'agent-1' },- { workspaceId: 'ws-a', switchAgentId: 'agent-2' },+ { serverId: 'srv-a', switchAgentId: 'agent-1' },+ { serverId: 'srv-a', switchAgentId: 'agent-2' },]);- expect(store.roomsFor('ws-a', 'agent-1')).toBeUndefined();- expect(store.errorFor('ws-a', 'agent-1')).toBe(+ expect(store.roomsFor('srv-a', 'agent-1')).toBeUndefined();+ expect(store.errorFor('srv-a', 'agent-1')).toBe('Could not load the rooms this agent belongs to. (nope)');- expect(store.roomsFor('ws-a', 'agent-2')?.[0].roomId).toBe('room-b');- });-- it('keeps the same agent’s membership in two workspaces apart', async () => {- // One server can host several, and an agent id is the server's — so a cache- // keyed on the agent alone would answer one workspace with the other's rooms.- listAgentRooms.mockImplementation(async ({ workspaceId }: { workspaceId: string }) => [- {- roomId: `room-in-${workspaceId}`,- roomName: 'r',- archived: false,- status: 'live',- roomRole: null,- },- ]);- const store = new SwitchRoomsStore();-- await store.ensureMembershipsFor([- { workspaceId: 'ws-a', switchAgentId: 'agent-1' },- { workspaceId: 'ws-b', switchAgentId: 'agent-1' },- ]);-- expect(store.roomsFor('ws-a', 'agent-1')?.[0].roomId).toBe('room-in-ws-a');- expect(store.roomsFor('ws-b', 'agent-1')?.[0].roomId).toBe('room-in-ws-b');+ expect(store.roomsFor('srv-a', 'agent-2')?.[0].roomId).toBe('room-b');});});@@ -409,15 +385,14 @@ describe('rooms offered to a picker', () => {beforeEach(() => {vi.clearAllMocks();serversStore.servers = [{ id: 'srv-a' }];- workspaces.workspaces = [{ id: 'ws-a', serverId: 'srv-a', name: 'Alpha' }];- workspaces.activeId = 'ws-a';+ serversStore.activeServerId = 'srv-a';});- it('offers every room the workspace returned, not only the ones this user made', async () => {- // The sidebar deliberately lists a narrower set — see `listedRoomsInWorkspace`.+ it('offers every room the server returned, not only the ones this user made', async () => {+ // The sidebar deliberately lists a narrower set — see `listedRoomsOnServer`.// A picker is a list you went looking for, so it must not hide a room you// are entitled to join.- listRooms.mockResolvedValue([+ listRemoteRooms.mockResolvedValue([room('mine', 'user-of-srv-a'),room('someone-elses', 'user-of-someone-else'),room('ownerless', null),@@ -426,16 +401,16 @@ describe('rooms offered to a picker', () => {const store = new SwitchRoomsStore();await store.loadRoomNames();- expect(store.readableRoomsInWorkspace('ws-a').map((r) => r.id)).toEqual([+ expect(store.readableRoomsOnServer('srv-a').map((r) => r.id)).toEqual(['mine','someone-elses','ownerless',]);- expect(store.listedRoomsInWorkspace('ws-a').map((r) => r.id)).toEqual(['mine']);+ expect(store.listedRoomsOnServer('srv-a').map((r) => r.id)).toEqual(['mine']);});it('leaves out archived rooms, which are not joinable', async () => {- listRooms.mockResolvedValue([+ listRemoteRooms.mockResolvedValue([room('live', 'user-of-someone-else'),room('gone', 'user-of-someone-else', { archived: true }),]);@@ -443,11 +418,11 @@ describe('rooms offered to a picker', () => {const store = new SwitchRoomsStore();await store.loadRoomNames();- expect(store.readableRoomsInWorkspace('ws-a').map((r) => r.id)).toEqual(['live']);+ expect(store.readableRoomsOnServer('srv-a').map((r) => r.id)).toEqual(['live']);});- it('offers nothing for a workspace whose rooms were never read', () => {- expect(new SwitchRoomsStore().readableRoomsInWorkspace('ws-a')).toEqual([]);+ it('offers nothing for a server whose rooms were never read', () => {+ expect(new SwitchRoomsStore().readableRoomsOnServer('srv-a')).toEqual([]);});});@@ -460,7 +435,6 @@ describe('who may delete a room', () => {beforeEach(() => {vi.clearAllMocks();serversStore.servers = [{ id: 'srv-a' }];- workspaces.workspaces = [{ id: 'ws-a', serverId: 'srv-a', name: 'Alpha' }];serversStore.statusFor = statusWithRole(undefined);});@@ -470,36 +444,28 @@ describe('who may delete a room', () => {it('lets the owner delete their own room', () => {const store = new SwitchRoomsStore();- expect(store.canDeleteRoom('ws-a', room('r', 'user-of-srv-a'))).toBe(true);+ expect(store.canDeleteRoom('srv-a', room('r', 'user-of-srv-a'))).toBe(true);});it('refuses someone else’s room', () => {const store = new SwitchRoomsStore();- expect(store.canDeleteRoom('ws-a', room('r', 'user-of-someone-else'))).toBe(false);+ expect(store.canDeleteRoom('srv-a', room('r', 'user-of-someone-else'))).toBe(false);});it('lets an admin delete a room they do not own, matching the gateway', () => {serversStore.statusFor = statusWithRole('admin');const store = new SwitchRoomsStore();- expect(store.canDeleteRoom('ws-a', room('r', 'user-of-someone-else'))).toBe(true);+ expect(store.canDeleteRoom('srv-a', room('r', 'user-of-someone-else'))).toBe(true);});it('refuses an ownerless room to a non-admin, rather than treating it as unclaimed', () => {const store = new SwitchRoomsStore();- expect(store.canDeleteRoom('ws-a', room('r', null))).toBe(false);+ expect(store.canDeleteRoom('srv-a', room('r', null))).toBe(false);});it('refuses while signed out, when there is no one to compare against', () => {serversStore.statusFor = () => ({ user: null }) as never;const store = new SwitchRoomsStore();- expect(store.canDeleteRoom('ws-a', room('r', 'user-of-srv-a'))).toBe(false);- });-- it('refuses a workspace whose server is not known yet', () => {- // The permission is the server's to answer, so an unresolved workspace is- // not a licence to offer the action.- workspaces.workspaces = [];- const store = new SwitchRoomsStore();- expect(store.canDeleteRoom('ws-a', room('r', 'user-of-srv-a'))).toBe(false);+ expect(store.canDeleteRoom('srv-a', room('r', 'user-of-srv-a'))).toBe(false);});});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.tsindex 80995b7de..345702c77 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts@@ -1,5 +1,4 @@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 {@@ -10,9 +9,9 @@ import { UNBRIDGED_FILTER_VALUE } from '@shared/view-state';import { serverAvailability } from './server-availability';import { switchServersStore } from './switch-servers-store';-/** Cache key for an agent's room membership: workspace + Switch agent id. */-function key(workspaceId: string, switchAgentId: string): string {- return `${workspaceId}:${switchAgentId}`;+/** Cache key for an agent's room membership: server + Switch agent id. */+function key(serverId: string, switchAgentId: string): string {+ return `${serverId}:${switchAgentId}`;}/**@@ -21,50 +20,43 @@ function key(workspaceId: string, switchAgentId: string): string {* Entries are cached in memory and re-fetched on demand or on window focus, so* the "connect to room" picker and the room-focused sidebar grouping render the* last-known set instantly while a refresh runs.- *- * Everything here is keyed by workspace, because that is what a room belongs- * to: one server can host several, and the same server answers with a different- * set of rooms in each. Where a fact is about the gateway rather than about the- * rooms — whether it is reachable, who is signed in, what its web app's URL is- * — the server is resolved from the workspace and asked for that alone.*/export class SwitchRoomsStore {- /** Membership per `${workspaceId}:${switchAgentId}`. */+ /** Membership per `${serverId}:${switchAgentId}`. */private readonly roomsByAgent = new Map<string, RemoteAgentRoom[]>();- /** Room id → display name, aggregated across workspaces (room ids are+ /** Room id → display name, aggregated across connected servers (room ids are* globally unique UUIDs, so a flat map is safe). Drives sidebar room headers. */private readonly roomNames = new Map<string, string>();- /** Room id → owning workspace id, so a room can be addressed and linked. */- private readonly roomWorkspaceById = new Map<string, string>();+ /** Room id → owning server id, so a room can be linked to its gateway web app. */+ private readonly roomServerById = new Map<string, string>();/** Room id → bridge type (`slack`, `mattermost`, …) when the room is bridged* to an external platform, so the sidebar can show that platform's icon. */private readonly bridgeTypeByRoom = new Map<string, string>();/** Room id → native deeplink that opens its channel in the messaging app's* desktop client, when the room is bridged and the link could be built. */private readonly channelUrlByRoom = new Map<string, string>();- /** Workspace id → the active rooms in it owned by the signed-in user.+ /** Server id → the active rooms on that server owned by the signed-in user.* The sidebar lists these even when no session is connected to them, so a* room you create in Switch Console is visible the moment it exists rather than* only once an agent joins it. */- private readonly ownedRoomsByWorkspace = new Map<string, RemoteRoomSummary[]>();- /** Workspace id → every active room in it. Listed in full for a workspace on a- * server this install manages; elsewhere it backs lookups rather than the- * room list. */- private readonly allRoomsByWorkspace = new Map<string, RemoteRoomSummary[]>();+ private readonly ownedRoomsByServer = new Map<string, RemoteRoomSummary[]>();+ /** Server id → every active room on it. Listed in full for a server this+ * install manages; elsewhere it backs lookups rather than the room list. */+ private readonly allRoomsByServer = new Map<string, RemoteRoomSummary[]>();/** Keys with an in-flight fetch. */readonly loading = new Set<string>();/** Last error per key, if the most recent fetch failed. */readonly errors = new Map<string, string>();- /** Workspace id → why its room list could not be read, if the last try failed. */+ /** Server id → why its room list could not be read, if the last try failed. */private readonly roomListErrors = new Map<string, string>();- /** Workspaces whose server was not connected when the room list was last- * refreshed, so their rooms were never asked for at all. */- private unreachableWorkspaceIds: string[] = [];+ /** Servers that were not connected when the room list was last refreshed, so+ * their rooms were never asked for at all. */+ private unreachableServerIds: string[] = [];/** The agents whose membership this store is responsible for keeping current.* Recorded on {@link ensureMembershipsFor} so a refresh re-reads the current* set rather than only the keys that happen to be cached — an agent created* after the sidebar mounted is otherwise never fetched. */- private trackedIdentities: { workspaceId: string; switchAgentId: string }[] = [];+ private trackedIdentities: { serverId: string; switchAgentId: string }[] = [];constructor() {makeAutoObservable(this);@@ -87,26 +79,18 @@ export class SwitchRoomsStore {return this.channelUrlByRoom.get(roomId) ?? null;}- /** Id of the workspace a room belongs to, or null if not yet loaded. This is- * what a call about the room is addressed with. */- roomWorkspaceId(roomId: string): string | null {- return this.roomWorkspaceById.get(roomId) ?? null;- }-- /** Id of the server hosting a room's workspace, for the things that are about- * the gateway rather than the room — its web app, its Mattermost session. */+ /** Id of the server a room belongs to, or null if not yet loaded. The room+ * view needs it to resolve that server's Mattermost session. */roomServerId(roomId: string): string | null {- const workspaceId = this.roomWorkspaceById.get(roomId);- if (!workspaceId) return null;- return workspacesStore.serverIdFor(workspaceId);+ return this.roomServerById.get(roomId) ?? null;}/*** URL of a room's detail page in the gateway web app, or null if the room's- * owning server isn't known yet (names/workspaces are loaded by loadRoomNames).+ * owning server isn't known yet (names/servers are loaded by loadRoomNames).*/gatewayRoomUrl(roomId: string): string | null {- const serverId = this.roomServerId(roomId);+ const serverId = this.roomServerById.get(roomId);if (!serverId) return null;const server = switchServersStore.servers.find((s) => s.id === serverId);if (!server) return null;@@ -131,69 +115,71 @@ export class SwitchRoomsStore {* considered — the ones that are there because of what they are, not because* one of this install's agents is in them.*- * In a workspace on a server this install manages, that is **every** room: you- * run the deployment, so there is nothing on it you should have to go- * elsewhere to see. Anywhere else it is the rooms you created, which would- * otherwise disappear the moment you made one and put no agent in it.+ * On a server this install manages, that is **every** room: you run the+ * deployment, so there is nothing on it you should have to go elsewhere to+ * see. On any other server it is the rooms you created, which would otherwise+ * disappear the moment you made one and put no agent in it.*- * The sidebar tree shows one workspace at a time, so these follow the same- * scope rule as locations do — including that no active workspace hides- * nothing.+ * The sidebar tree shows one server at a time, so these follow the same scope+ * rule as locations do — including that no active server hides nothing.*/get listedRoomsInActiveScope(): RemoteRoomSummary[] {- const listed = this.workspaceIdsInScope.flatMap((id) => this.listedRoomsInWorkspace(id));+ const activeServerId = switchServersStore.activeServerId;+ const serverIds = activeServerId+ ? [activeServerId]+ : [...new Set([...this.allRoomsByServer.keys(), ...this.ownedRoomsByServer.keys()])];+ const listed = serverIds.flatMap((serverId) => this.listedRoomsOnServer(serverId));return listed.sort((a, b) => a.name.localeCompare(b.name));}/**- * The rooms one workspace contributes to the lists above, under the same scope- * rule. Named separately so a page about a single workspace asks for that- * workspace rather than for whichever one happens to be active.+ * The rooms one server contributes to the lists above, under the same scope+ * rule. Named separately so a page about a single server asks for that+ * server rather than for whichever one happens to be active.*/- listedRoomsInWorkspace(workspaceId: string): RemoteRoomSummary[] {- const serverId = workspacesStore.serverIdFor(workspaceId);+ listedRoomsOnServer(serverId: string): RemoteRoomSummary[] {const managed = switchServersStore.servers.find((s) => s.id === serverId)?.managed ?? false;return (- (managed- ? this.allRoomsByWorkspace.get(workspaceId)- : this.ownedRoomsByWorkspace.get(workspaceId)) ?? []+ (managed ? this.allRoomsByServer.get(serverId) : this.ownedRoomsByServer.get(serverId)) ?? []);}/**- * Every active room the signed-in user can see in a workspace — what the- * gateway returned, which is already scoped to rooms they may read.+ * Every active room the signed-in user can see on a server — what the gateway+ * returned, which is already scoped to rooms they may read.*- * Wider than {@link listedRoomsInWorkspace} on purpose. A standing list has to+ * Wider than {@link listedRoomsOnServer} on purpose. A standing list has to* earn its place on screen, so the sidebar shows only rooms with a claim on* you; a picker is a list you went looking for, and one that hides rooms you* have every right to join cannot be searched into showing them.*/- readableRoomsInWorkspace(workspaceId: string): RemoteRoomSummary[] {- return this.allRoomsByWorkspace.get(workspaceId) ?? [];+ readableRoomsOnServer(serverId: string): RemoteRoomSummary[] {+ return this.allRoomsByServer.get(serverId) ?? [];}/*** The same listed rooms as {@link listedRoomsInActiveScope}, but across every- * workspace rather than the active one.+ * server rather than the active one.*- * Search is deliberately not scoped to the active workspace: you search- * precisely because you do not know where a thing is, and a result set- * silently limited to the one you happen to be looking at cannot answer that.- * Navigating to one of these switches the active workspace (see- * `scopeToRoomWorkspace`), so the sidebar follows you there rather than- * filtering the room back out.+ * Search is deliberately not scoped to the active server: you search precisely+ * because you do not know where a thing is, and a result set silently limited+ * to the server you happen to be looking at cannot answer that. Navigating to+ * one of these switches the active server (see `scopeToRoomServer`), so the+ * sidebar follows you there rather than filtering the room back out.*/- get listedRoomsInAllWorkspaces(): RemoteRoomSummary[] {- const listed = workspacesStore.workspaces.flatMap((w) => this.listedRoomsInWorkspace(w.id));+ get listedRoomsOnAllServers(): RemoteRoomSummary[] {+ const serverIds = [+ ...new Set([...this.allRoomsByServer.keys(), ...this.ownedRoomsByServer.keys()]),+ ];+ const listed = serverIds.flatMap((serverId) => this.listedRoomsOnServer(serverId));return listed.sort((a, b) => a.name.localeCompare(b.name));}/**- * The messaging-app values worth offering as a room filter in the active- * workspace: the bridge types actually in use, plus the unbridged sentinel- * when some room has no messaging app. Offering a platform with no rooms- * behind it would be a filter that can only ever empty the list.+ * The messaging-app values worth offering as a room filter on the active+ * server: the bridge types actually in use, plus the unbridged sentinel when+ * some room has no messaging app. Offering a platform with no rooms behind it+ * would be a filter that can only ever empty the list.*/get bridgeFilterValuesInActiveScope(): string[] {const present = new Set<string>();@@ -208,105 +194,102 @@ export class SwitchRoomsStore {});}- /** Full detail for a room, when its workspace's room list has been loaded. */+ /** Full detail for a room, when its server's room list has been loaded. */roomSummaryById(roomId: string): RemoteRoomSummary | null {- const workspaceId = this.roomWorkspaceById.get(roomId);- if (!workspaceId) return null;- return this.allRoomsByWorkspace.get(workspaceId)?.find((room) => room.id === roomId) ?? null;+ const serverId = this.roomServerById.get(roomId);+ if (!serverId) return null;+ return this.allRoomsByServer.get(serverId)?.find((room) => room.id === roomId) ?? null;}/*** Whether the signed-in user may delete a room: they own it, or they are an- * admin on the server hosting its workspace.+ * admin on its server.** This mirrors the gateway's own rule so the action is not offered where it* would only be refused. It is not the check that protects anything — the* server's is — and where ownership is unknown the answer is no, since* showing a delete that fails is worse than not showing one.*/- canDeleteRoom(workspaceId: string, room: RemoteRoomSummary): boolean {- const serverId = workspacesStore.serverIdFor(workspaceId);- if (!serverId) return false;+ canDeleteRoom(serverId: string, room: RemoteRoomSummary): boolean {const user = switchServersStore.statusFor(serverId)?.user ?? null;if (!user) return false;return room.ownerId === user.id || user.role === 'admin';}/**- * Delete a room in its workspace, then re-read what is left.+ * Delete a room on its server, then re-read what is left.** Throws on refusal rather than reporting a boolean: the caller is a* confirmation dialog, and a delete that quietly did nothing would leave the* room on screen with no account of why.*/- async deleteRoom(workspaceId: string, roomId: string): Promise<void> {- await rpc.workspaces.deleteRoom({ workspaceId, roomId });+ async deleteRoom(serverId: string, roomId: string): Promise<void> {+ await rpc.switchServers.deleteRoom({ serverId, roomId });await this.refreshRoomState();}/**- * The workspaces whose state is on screen: the active one, or all of them- * when none is active (the same scope rule the room and location lists- * follow).+ * The servers whose state is on screen: the active one, or all of them when+ * none is active (the same scope rule the room and location lists follow).*- * Each workspace is its own world — its own rooms, its own agents. Reading or- * reporting on one you are not looking at is both wasted work and, worse,- * someone else's problem presented as yours.+ * Each server is its own world — its own rooms, its own agents, its own+ * connection. Reading or reporting on one you are not looking at is both+ * wasted work and, worse, someone else's problem presented as yours.*/- private get workspaceIdsInScope(): string[] {- const activeId = workspacesStore.activeId;- if (activeId) return [activeId];- return workspacesStore.workspaces.map((w) => w.id);+ private get serverIdsInScope(): string[] {+ const activeServerId = switchServersStore.activeServerId;+ if (activeServerId) return [activeServerId];+ return switchServersStore.servers.map((s) => s.id);}/**- * Refresh the room catalogue for the workspaces on screen.+ * Refresh the room catalogue for the servers on screen.*- * A workspace that cannot be read keeps its last-known rooms rather than- * losing them, but the failure is recorded in {@link roomListErrors} instead- * of being swallowed: last-known data rendered as if it were current is the- * one outcome worse than showing nothing.+ * A server that cannot be read keeps its last-known rooms rather than losing+ * them, but the failure is recorded in {@link roomListErrors} instead of being+ * swallowed: last-known data rendered as if it were current is the one outcome+ * worse than showing nothing.*/async loadRoomNames(): Promise<void> {- await this.loadRoomsFrom(this.workspaceIdsInScope);+ await this.loadRoomsFrom(this.serverIdsInScope);}/**- * Refresh the room catalogue for **every** workspace.+ * Refresh the room catalogue for **every** server.*- * Only for cross-workspace search, which is deliberately not scoped — you- * search because you do not know where a thing is. Everything else loads the- * workspaces it is actually showing.+ * Only for cross-server search, which is deliberately not scoped — you search+ * because you do not know where a thing is. Everything else loads the servers+ * it is actually showing.*/- async loadRoomsInAllWorkspaces(): Promise<void> {- await this.loadRoomsFrom(workspacesStore.workspaces.map((w) => w.id));+ async loadRoomsOnAllServers(): Promise<void> {+ await this.loadRoomsFrom(switchServersStore.servers.map((s) => s.id));}- private async loadRoomsFrom(workspaceIds: string[]): Promise<void> {- const asked = workspacesStore.workspaces.filter((w) => workspaceIds.includes(w.id));- const connected = asked.filter((w) => switchServersStore.isConnected(w.serverId));+ private async loadRoomsFrom(serverIds: string[]): Promise<void> {+ const servers = switchServersStore.servers.filter((s) => serverIds.includes(s.id));+ const connected = servers.filter((s) => switchServersStore.isConnected(s.id));runInAction(() => {// Not being connected is not a failure — there is simply nothing to ask- // right now — but the rooms in that workspace are equally unknown, and the+ // right now — but the rooms on that server are equally unknown, and the// sidebar has to be able to say so.- const askedIds = new Set(workspaceIds);- this.unreachableWorkspaceIds = [- ...this.unreachableWorkspaceIds.filter((id) => !askedIds.has(id)),- ...asked.filter((w) => !switchServersStore.isConnected(w.serverId)).map((w) => w.id),+ const asked = new Set(serverIds);+ this.unreachableServerIds = [+ ...this.unreachableServerIds.filter((id) => !asked.has(id)),+ ...servers.filter((s) => !switchServersStore.isConnected(s.id)).map((s) => s.id),];});await Promise.all(- connected.map(async (workspace) => {+ connected.map(async (server) => {try {- const rooms = await rpc.workspaces.listRooms(workspace.id);+ const rooms = await rpc.switchServers.listRemoteRooms(server.id);// Ownership is per server: the same person is a different user row on// each gateway, so match against that server's signed-in identity.- const signedInUserId = switchServersStore.statusFor(workspace.serverId)?.user?.id ?? null;+ const signedInUserId = switchServersStore.statusFor(server.id)?.user?.id ?? null;runInAction(() => {- this.roomListErrors.delete(workspace.id);+ this.roomListErrors.delete(server.id);for (const room of rooms) {this.roomNames.set(room.id, room.name);- this.roomWorkspaceById.set(room.id, workspace.id);+ this.roomServerById.set(room.id, server.id);if (room.bridgeType) this.bridgeTypeByRoom.set(room.id, room.bridgeType);else this.bridgeTypeByRoom.delete(room.id);if (room.externalChannelUrl)@@ -314,17 +297,17 @@ export class SwitchRoomsStore {else this.channelUrlByRoom.delete(room.id);}const active = rooms.filter((r) => !r.archived);- this.allRoomsByWorkspace.set(workspace.id, active);- this.ownedRoomsByWorkspace.set(- workspace.id,+ this.allRoomsByServer.set(server.id, active);+ this.ownedRoomsByServer.set(+ server.id,signedInUserId ? active.filter((r) => r.ownerId === signedInUserId) : []);});} catch (cause) {runInAction(() => {this.roomListErrors.set(- workspace.id,- failureText(cause, `Could not load the rooms in ${workspace.name}.`)+ server.id,+ failureText(cause, `Could not load the rooms on ${server.name}.`));});}@@ -341,44 +324,42 @@ export class SwitchRoomsStore {* being asked to wait or to act.*/roomNameBlockedBySignIn(roomId: string): boolean {- const workspaceId = this.roomWorkspaceById.get(roomId) ?? workspacesStore.activeId;- if (!workspaceId) return false;- const serverId = workspacesStore.serverIdFor(workspaceId);+ const serverId = this.roomServerById.get(roomId) ?? switchServersStore.activeServerId;if (!serverId) return false;return serverAvailability(serverId) === 'signed-out';}/**- * Workspaces on screen whose room list was asked for and failed.+ * Servers on screen whose room list was asked for and failed.*- * Distinct from {@link workspacesNotSignedIn}: this is a fault, it may be+ * Distinct from {@link serversNotSignedIn}: this is a fault, it may be* transient, and retrying is a sensible thing to offer.*/- get workspacesThatFailedToLoad(): { id: string; name: string }[] {- return this.namedWorkspacesInScope([...this.roomListErrors.keys()]);+ get serversThatFailedToLoad(): { id: string; name: string }[] {+ return this.namedServersInScope([...this.roomListErrors.keys()]);}/**- * Workspaces on screen that were never asked because Switch Console is not- * signed in to their server.+ * Servers on screen that were never asked because Switch Console is not signed in+ * to them.** Not a fault and not retryable — the user has to sign in. Reporting it as a* failure with a retry button offers an action that cannot work.*/- get workspacesNotSignedIn(): { id: string; name: string }[] {- return this.namedWorkspacesInScope(- this.unreachableWorkspaceIds.filter((id) => {- const serverId = workspacesStore.serverIdFor(id);- return serverId !== null && serverAvailability(serverId) === 'signed-out';- })+ get serversNotSignedIn(): { id: string; name: string }[] {+ return this.namedServersInScope(+ this.unreachableServerIds.filter((id) => serverAvailability(id) === 'signed-out'));}- private namedWorkspacesInScope(workspaceIds: string[]): { id: string; name: string }[] {- const inScope = new Set(this.workspaceIdsInScope);- return [...new Set(workspaceIds)]+ private namedServersInScope(serverIds: string[]): { id: string; name: string }[] {+ const inScope = new Set(this.serverIdsInScope);+ return [...new Set(serverIds)].filter((id) => inScope.has(id))- .map((id) => ({ id, name: workspacesStore.byId(id)?.name ?? id }))+ .map((id) => ({+ id,+ name: switchServersStore.servers.find((s) => s.id === id)?.name ?? id,+ })).sort((a, b) => a.name.localeCompare(b.name));}@@ -390,15 +371,15 @@ export class SwitchRoomsStore {*/get agentsWithUnknownMembership(): number {return this.trackedIdentities.filter(- ({ workspaceId, switchAgentId }) =>- this.roomsByAgent.get(key(workspaceId, switchAgentId)) === undefined &&- !this.isLoading(workspaceId, switchAgentId)+ ({ serverId, switchAgentId }) =>+ this.roomsByAgent.get(key(serverId, switchAgentId)) === undefined &&+ !this.isLoading(serverId, switchAgentId)).length;}/** Cached membership, or undefined if never fetched. */- roomsFor(workspaceId: string, switchAgentId: string): RemoteAgentRoom[] | undefined {- return this.roomsByAgent.get(key(workspaceId, switchAgentId));+ roomsFor(serverId: string, switchAgentId: string): RemoteAgentRoom[] | undefined {+ return this.roomsByAgent.get(key(serverId, switchAgentId));}/**@@ -455,23 +436,23 @@ export class SwitchRoomsStore {* agent's at a time.*/async ensureMembershipsFor(- agents: { workspaceId: string; switchAgentId: string }[],+ agents: { serverId: string; switchAgentId: string }[],options: { force?: boolean } = {}): Promise<void> {runInAction(() => {this.trackedIdentities = agents;});await Promise.all(- agents.map((a) => this.fetchAgentRooms(a.workspaceId, a.switchAgentId, options))+ agents.map((a) => this.fetchAgentRooms(a.serverId, a.switchAgentId, options)));}- isLoading(workspaceId: string, switchAgentId: string): boolean {- return this.loading.has(key(workspaceId, switchAgentId));+ isLoading(serverId: string, switchAgentId: string): boolean {+ return this.loading.has(key(serverId, switchAgentId));}- errorFor(workspaceId: string, switchAgentId: string): string | null {- return this.errors.get(key(workspaceId, switchAgentId)) ?? null;+ errorFor(serverId: string, switchAgentId: string): string | null {+ return this.errors.get(key(serverId, switchAgentId)) ?? null;}/**@@ -479,11 +460,11 @@ export class SwitchRoomsStore {* cache. Returns the membership, or null if the fetch failed.*/async fetchAgentRooms(- workspaceId: string,+ serverId: string,switchAgentId: string,options: { force?: boolean } = {}): Promise<RemoteAgentRoom[] | null> {- const k = key(workspaceId, switchAgentId);+ const k = key(serverId, switchAgentId);const cached = this.roomsByAgent.get(k);if (cached && !options.force) return cached;@@ -492,7 +473,7 @@ export class SwitchRoomsStore {this.errors.delete(k);});try {- const rooms = await rpc.workspaces.listAgentRooms({ workspaceId, agentId: switchAgentId });+ const rooms = await rpc.switchServers.listAgentRooms({ serverId, agentId: switchAgentId });runInAction(() => {this.roomsByAgent.set(k, rooms);});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.test.tsindex 842fb3400..7a6539c7a 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.test.ts@@ -4,10 +4,8 @@ import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';const getAuthConfig = vi.hoisted(() => vi.fn());const getConnectionStatus = vi.hoisted(() => vi.fn());const listServers = vi.hoisted(() => vi.fn());-const installIsEmpty = vi.hoisted(() => vi.fn());+const getActiveServerId = vi.hoisted(() => vi.fn());const setActiveServer = vi.hoisted(() => vi.fn());-/** The workspace selection as the main process holds it, by the server it is on. */-const selection = vi.hoisted(() => ({ serverId: null as string | null }));const removeServer = vi.hoisted(() => vi.fn());const addServer = vi.hoisted(() => vi.fn());/** SSH hosts the reachability manager currently considers down. */@@ -20,40 +18,11 @@ vi.mock('@renderer/lib/ipc', () => ({getAuthConfig,getConnectionStatus,listServers,+ getActiveServerId,setActiveServer,removeServer,addServer,},- onboarding: { installIsEmpty },- },-}));-/**- * Stands in for the workspace selection this store now reads its active server- * off, faithfully enough that the selection logic is still being tested rather- * than asserted against a constant.- *- * Each server gets one workspace, which is the state every install is in, so- * `listServers` and {@link selectServer} stay the knobs a test turns. A- * selection naming a server that is no longer listed resolves to no workspace —- * which is exactly what happens for real once the removed server takes its- * workspace row with it.- */-vi.mock('@renderer/features/workspaces/workspaces-store', () => ({- workspacesStore: {- workspaces: [] as { id: string; serverId: string }[],- activeId: null as string | null,- get active(): { id: string; serverId: string } | null {- return this.workspaces.find((w) => w.id === this.activeId) ?? null;- },- get activeServerId(): string | null {- return this.active?.serverId ?? null;- },- async refresh(): Promise<void> {- const servers: SwitchServer[] = await listServers();- const activeServerId = selection.serverId;- this.workspaces = servers.map((s) => ({ id: `ws-${s.id}`, serverId: s.id }));- this.activeId = activeServerId === null ? null : `ws-${activeServerId}`;- },},}));vi.mock('@renderer/features/remote-hosts/host-reachability-store', () => ({@@ -66,11 +35,6 @@ vi.mock('@renderer/lib/stores/app-state', () => ({const { SwitchServersStore } = await import('./switch-servers-store');-/** Scope the window to a server, the way choosing one of its workspaces does. */-function selectServer(serverId: string | null): void {- selection.serverId = serverId;-}-const authConfig = { passwordLoginEnabled: true, oidcEnabled: false, oidcProviderLabel: null };function server(id: string, overrides: Partial<SwitchServer> = {}): SwitchServer {@@ -127,10 +91,6 @@ beforeEach(() => {user: null,}));getAuthConfig.mockResolvedValue(authConfig);- listServers.mockResolvedValue([]);- installIsEmpty.mockResolvedValue(true);- selectServer(null);- setActiveServer.mockImplementation(async (serverId: string) => selectServer(serverId));});describe('fetching sign-in options', () => {@@ -236,7 +196,7 @@ describe('recovering when connectivity returns', () => {getAuthConfig.mockRejectedValueOnce(new Error('offline'));await store.ensureAuthConfig('srv-a');listServers.mockResolvedValue([]);- selectServer(null);+ getActiveServerId.mockResolvedValue(null);removeServer.mockResolvedValue(undefined);await store.removeServer('srv-a');@@ -247,134 +207,11 @@ describe('recovering when connectivity returns', () => {});});-describe('reading the server list', () => {- it('serves callers arriving together one read', async () => {- // The shell asks on the first frame and so does the sidebar. Two reads of- // the same list race each other into the same fields for no gain.- listServers.mockResolvedValue([server('srv-a')]);- selectServer('srv-a');- const store = new SwitchServersStore();-- await Promise.all([store.init(), store.init(), store.init()]);-- expect(revalidate).toHaveBeenCalledTimes(1);- });-- it('reads again for a caller arriving after the last read settled', async () => {- // Sharing only the read in flight: the paths that change something and then- // ask for the list back must not be handed the answer from before it.- const store = new SwitchServersStore();- await store.init();- listServers.mockResolvedValue([server('srv-a')]);-- await store.init();-- expect(store.servers.map((s) => s.id)).toEqual(['srv-a']);- });-- it('keeps the failure on screen for as long as the retry runs', async () => {- // The window draws its failure page — message, detail and the button that- // starts the retry — from `listError`. Clearing it as the retry begins- // unmounts the page and the button with it, leaving a blank window until- // the retry lands.- listServers.mockRejectedValueOnce(new Error('gateway unreachable'));- const store = new SwitchServersStore();- await store.init();- expect(store.listError).not.toBeNull();-- const retryRead = deferred<SwitchServer[]>();- listServers.mockReturnValueOnce(retryRead.promise);- const retrying = store.init();- await flush();-- expect(store.listError).not.toBeNull();- expect(store.loadingServers).toBe(true);-- retryRead.resolve([server('srv-a')]);- await retrying;-- expect(store.listError).toBeNull();- expect(store.listErrorDetail).toBeNull();- });-- it('reads what the install holds rather than inferring it from the list', async () => {- // An install whose server was removed keeps its agents — the confirmation- // says so — and the sessions in them are still running. An empty list is- // therefore not the fresh-install answer, and the shell needs that answer- // to decide whether to replace the window with a first-run page.- listServers.mockResolvedValue([]);- installIsEmpty.mockResolvedValue(false);- const store = new SwitchServersStore();-- await store.init();-- expect(store.servers).toEqual([]);- expect(store.installIsEmpty).toBe(false);- });-- it('says a read is not coming back rather than leaving the window blank', async () => {- // Nothing is drawn until the first read lands, so a handler that never- // settles is a blank, inert window with no message and no way to ask again.- vi.useFakeTimers();- try {- listServers.mockReturnValueOnce(deferred<SwitchServer[]>().promise);- const store = new SwitchServersStore();- void store.init();-- // Well past any deadline worth having: what is asserted is that one- // exists, not the exact number of seconds.- await vi.advanceTimersByTimeAsync(60_000);-- expect(store.loaded).toBe(false);- expect(store.listError).not.toBeNull();- expect(store.loadingServers).toBe(false);- } finally {- vi.useRealTimers();- }- });-- it('ignores a given-up read that lands after the retry has answered', async () => {- // The read cannot be cancelled, only abandoned — so the stale one is still- // out there, and letting it write would replace a good list with the one- // the user already gave up on.- vi.useFakeTimers();- try {- const stuck = deferred<SwitchServer[]>();- listServers.mockReturnValueOnce(stuck.promise);- const store = new SwitchServersStore();- void store.init();- await vi.advanceTimersByTimeAsync(60_000);-- listServers.mockResolvedValue([server('srv-a')]);- await store.init();- stuck.resolve([server('srv-stale')]);- await vi.advanceTimersByTimeAsync(1);-- expect(store.servers.map((s) => s.id)).toEqual(['srv-a']);- expect(store.listError).toBeNull();- } finally {- vi.useRealTimers();- }- });-- it('keeps a failure from elsewhere out of the slot the window reads', async () => {- // `error` is the banner, written by every action here — a rename, a sign-out,- // adding a server. None of those is a reason to take the window away.- const store = newStore([server('srv-a')]);- removeServer.mockRejectedValue(new Error('still in use'));-- await store.removeServer('srv-a');-- expect(store.error).not.toBeNull();- expect(store.listError).toBeNull();- });-});-describe('a page left on a server that is gone', () => {it('is revalidated when the server is removed', async () => {const store = newStore([server('srv-a')]);listServers.mockResolvedValue([]);- selectServer(null);+ getActiveServerId.mockResolvedValue(null);removeServer.mockResolvedValue(undefined);await store.removeServer('srv-a');@@ -387,7 +224,7 @@ describe('a page left on a server that is gone', () => {expect(store.loaded).toBe(false);listServers.mockResolvedValue([server('srv-a')]);- selectServer('srv-a');+ getActiveServerId.mockResolvedValue('srv-a');await store.init();expect(store.loaded).toBe(true);@@ -606,14 +443,14 @@ describe('a server that cannot be reached', () => {});/**- * The switcher, the sidebar and the sessions under it all read the active- * workspace, so "servers exist but none is active" is a state the UI cannot- * render. Nothing on the main side picks one, so the store must.+ * A server is a workspace: the switcher, the sidebar and the sessions under it+ * all read the active one, so "servers exist but none is active" is a state the+ * UI cannot render. Nothing on the main side picks one, so the store must.*/describe('keeping a server active', () => {it('selects the first server when nothing was active', async () => {listServers.mockResolvedValue([server('srv-a'), server('srv-b')]);- selectServer(null);+ getActiveServerId.mockResolvedValue(null);const store = new SwitchServersStore();await store.init();@@ -623,7 +460,7 @@ describe('keeping a server active', () => {it('keeps the server the user last chose', async () => {listServers.mockResolvedValue([server('srv-a'), server('srv-b')]);- selectServer('srv-b');+ getActiveServerId.mockResolvedValue('srv-b');const store = new SwitchServersStore();await store.init();@@ -637,7 +474,7 @@ describe('keeping a server active', () => {// workspace at all — no switcher, no destinations, no sidebar tree — while// a perfectly good server sat in the list.listServers.mockResolvedValue([server('srv-b')]);- selectServer('srv-gone');+ getActiveServerId.mockResolvedValue('srv-gone');const store = new SwitchServersStore();await store.init();@@ -651,7 +488,7 @@ describe('keeping a server active', () => {// the very first one left the app with no workspace to show — the sidebar// stayed on "Add a server" until the next launch.listServers.mockResolvedValue([]);- selectServer(null);+ getActiveServerId.mockResolvedValue(null);const store = new SwitchServersStore();await store.init();@@ -666,7 +503,7 @@ describe('keeping a server active', () => {it('does not move the workspace when a second server is added', async () => {listServers.mockResolvedValue([server('srv-a')]);- selectServer('srv-a');+ getActiveServerId.mockResolvedValue('srv-a');const store = new SwitchServersStore();await store.init();@@ -681,7 +518,7 @@ describe('keeping a server active', () => {it('leaves nothing active when there are no servers at all', async () => {listServers.mockResolvedValue([]);- selectServer(null);+ getActiveServerId.mockResolvedValue(null);const store = new SwitchServersStore();await store.init();diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.tsindex dd7e4df98..053bb39aa 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.ts@@ -1,7 +1,6 @@import { makeAutoObservable, runInAction } from 'mobx';import { hostReachabilityStore } from '@renderer/features/remote-hosts/host-reachability-store';-import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';-import { describeFailure, type FailureDescription } from '@renderer/lib/errors/describe-failure';+import { describeFailure } from '@renderer/lib/errors/describe-failure';import { rpc } from '@renderer/lib/ipc';import { appState } from '@renderer/lib/stores/app-state';import type {@@ -11,13 +10,6 @@ import type {UpdateServerResult,} from '@shared/core/switch-servers/switch-servers';-/**- * How long the first read of the server list may take before the window says so- * instead of staying blank. Generous: this is local IPC, so anything near it is- * already a handler that is not coming back.- */-const LIST_READ_DEADLINE_MS = 10_000;-/*** Renderer store for the Switch-server integration. Holds the registered* gateways, the per-server connection status (so the sidebar can show a dot per@@ -29,6 +21,7 @@ const LIST_READ_DEADLINE_MS = 10_000;*/export class SwitchServersStore {servers: SwitchServer[] = [];+ activeServerId: string | null = null;/** Connection status per server id, refreshed on focus / select / manually. */readonly statuses = new Map<string, ServerConnectionStatus>();@@ -70,41 +63,9 @@ export class SwitchServersStore {error: string | null = null;/** Diagnostics for the same failure, rendered under `error` rather than in it. */errorDetail: string | null = null;- /**- * The list read's own failure, as opposed to {@link error}, which every- * action in this store writes — adding a server, renaming one, signing out.- *- * The shell decides what fills the window from this. Reading `error` there- * would put the whole window into its failure shape because a rename went- * wrong. Set only when a read fails and cleared only when one succeeds:- * clearing it as a retry starts would take the failure page off screen — and- * the retry button with it — for as long as the retry ran.- */- listError: string | null = null;- /** Diagnostics for the failure in {@link listError}. */- listErrorDetail: string | null = null;- /**- * Whether this install holds nothing at all — no server, no location, no- * agent. Read alongside the list, because the shell decides between the- * first-run page and the workspace from it and an empty server list is not- * the same question: removing a server keeps its agents and says so, and- * those agents plus the sessions running in them are still something to show.- *- * False until the first read lands; `loaded` is what separates that from an- * install that really is empty.- */- installIsEmpty = false;- /** The read in flight, so callers arriving together share one. Nothing renders it. */- initInFlight: Promise<void> | null = null;- /**- * Which read is allowed to write. Bumped by each new read and by the deadline- * below, so a read that has been given up on cannot land later and overwrite- * the answer of the one that replaced it. Nothing renders it.- */- private listReadGeneration = 0;constructor() {- makeAutoObservable(this, { initInFlight: false });+ makeAutoObservable(this);}/** Headline and detail as one string, for the modals that have a single slot. */@@ -121,24 +82,8 @@ export class SwitchServersStore {return hostReachabilityStore.isBlocked(server.sshHost);}- /**- * The server the window is scoped to.- *- * Read off the active workspace rather than held here, so the two cannot- * disagree. What the user selects is a workspace; the server is whichever one- * hosts it, and the main process resolves it the same way.- */- get activeServerId(): string | null {- return workspacesStore.activeServerId;- }-get activeServer(): SwitchServer | null {- return this.serverById(this.activeServerId);- }-- serverById(serverId: string | null): SwitchServer | null {- if (!serverId) return null;- return this.servers.find((s) => s.id === serverId) ?? null;+ return this.servers.find((s) => s.id === this.activeServerId) ?? null;}statusFor(serverId: string): ServerConnectionStatus | null {@@ -185,48 +130,21 @@ export class SwitchServersStore {return this.authConfigInFlight.has(serverId);}- /**- * Read the server list, once however many callers ask for it.- *- * The shell and the sidebar both ask on the first frame, and so does every- * panel that needs a server list to draw. They share the read in flight- * rather than making the same round-trip several times over; a caller- * arriving after it settles starts a fresh one, so this never hands back a- * stale answer to someone refreshing after a change of their own.- */- init(): Promise<void> {- if (this.initInFlight) return this.initInFlight;- // Only if it is still ours: a read given up on below is unhooked while it- // is still running, and its eventual settling must not unhook the read that- // replaced it.- const read = this.readServers().finally(() => {- if (this.initInFlight === read) this.initInFlight = null;- });- this.initInFlight = read;- return read;- }-- private async readServers(): Promise<void> {- const generation = ++this.listReadGeneration;+ async init(): Promise<void> {runInAction(() => {this.loadingServers = true;this.error = null;this.errorDetail = null;});- const deadline = setTimeout(() => this.giveUpOnListRead(generation), LIST_READ_DEADLINE_MS);try {- const [servers, installIsEmpty] = await Promise.all([+ const [servers, activeServerId] = await Promise.all([rpc.switchServers.listServers(),- rpc.onboarding.installIsEmpty(),- workspacesStore.refresh(),+ rpc.switchServers.getActiveServerId(),]);- if (generation !== this.listReadGeneration) return;runInAction(() => {this.servers = servers;- this.installIsEmpty = installIsEmpty;+ this.activeServerId = activeServerId;this.loaded = true;- this.listError = null;- this.listErrorDetail = null;});// A page restored onto a server that has since been deleted can only be// judged once the list is known, and startup restores navigation before@@ -235,63 +153,27 @@ export class SwitchServersStore {await this.ensureActiveServer();await this.refreshAllStatuses();} catch (cause) {- if (generation !== this.listReadGeneration) return;- const { headline, detail } = this.setError(cause, 'Could not load your Switch servers.');+ this.setError(cause, 'Could not load your Switch servers.');+ } finally {runInAction(() => {- this.listError = headline;- this.listErrorDetail = detail;+ this.loadingServers = false;});- } finally {- clearTimeout(deadline);- if (generation === this.listReadGeneration) {- runInAction(() => {- this.loadingServers = false;- });- }}}/**- * Stop waiting on a read that has not answered.- *- * Before the first one lands the shell has nothing to draw, so a handler that- * never settles leaves a blank, inert window with no way to say anything went- * wrong and no way to ask again. Saying so is the whole point: the read is- * abandoned rather than cancelled — it cannot be cancelled — and the- * generation bump is what stops it landing later on top of the retry's- * answer.- *- * Only before the first success. Once there is a list in hand, a slow refresh- * is not a reason to take the app away from someone using it.- */- private giveUpOnListRead(generation: number): void {- if (generation !== this.listReadGeneration || this.loaded) return;- this.listReadGeneration += 1;- this.initInFlight = null;- runInAction(() => {- this.loadingServers = false;- this.listError = 'Could not load your Switch servers.';- this.listErrorDetail = `Nothing came back after ${LIST_READ_DEADLINE_MS / 1000} seconds.`;- });- }-- /**- * The switcher, the sidebar and the sessions under it all read the active- * workspace, so one must be selected whenever any exists. Nothing on the main- * side picks it — adding the first server leaves the selection empty — so- * every path that changes the list ends here.- *- * A stored selection that no longer names a workspace counts as none. It is- * not hypothetical: removing the active server and adding another leaves the- * id pointing at the removed one, and treating that as a selection left the- * app with no workspace at all — no switcher, no sidebar tree, no way back.+ * A server is a workspace: the switcher, the sidebar and the sessions under+ * it all read the active one, so one must be selected whenever any server+ * exists. Nothing on the main side picks it — adding the first server leaves+ * the active id null — so every path that changes the list ends here.*- * Which one it lands on is expressed over servers rather than workspaces,- * because a server is what the user just added or removed, and its own- * workspaces are then the main process's to choose between.+ * A stored id that no longer names a server counts as no selection. It is not+ * hypothetical: removing the active server and adding another leaves the id+ * pointing at the removed one, and treating that as a selection left the app+ * with no workspace at all — no switcher, no sidebar tree, no way back.*/private async ensureActiveServer(): Promise<void> {- if (workspacesStore.active) return;+ if (this.activeServerId && this.servers.some((s) => s.id === this.activeServerId)) return;const first = this.servers[0];if (first) await this.setActive(first.id);}@@ -446,12 +328,13 @@ export class SwitchServersStore {this.clearError();try {const created = await rpc.switchServers.addServer({ name, gatewayUrl, apiUrl });- const [servers] = await Promise.all([+ const [servers, activeServerId] = await Promise.all([rpc.switchServers.listServers(),- workspacesStore.refresh(),+ rpc.switchServers.getActiveServerId(),]);runInAction(() => {this.servers = servers;+ this.activeServerId = activeServerId;});await this.ensureActiveServer();await this.refreshStatus(created.id);@@ -530,12 +413,13 @@ export class SwitchServersStore {this.clearError();try {await rpc.switchServers.removeServer(serverId);- const [servers] = await Promise.all([+ const [servers, activeServerId] = await Promise.all([rpc.switchServers.listServers(),- workspacesStore.refresh(),+ rpc.switchServers.getActiveServerId(),]);runInAction(() => {this.servers = servers;+ this.activeServerId = activeServerId;this.statuses.delete(serverId);this.authConfigs.delete(serverId);this.authConfigWanted.delete(serverId);@@ -552,20 +436,13 @@ export class SwitchServersStore {}}- /**- * Scope the window to a server, for the callers that know only one — adding- * a server, and following a navigation onto another server's room or agent.- *- * Which of its workspaces that lands on is the main process's to decide: it- * keeps the current selection if it is already on this server, and otherwise- * picks one. Picking here instead would make this store the second place that- * answers the same question.- */async setActive(serverId: string): Promise<void> {this.clearError();try {await rpc.switchServers.setActiveServer(serverId);- await workspacesStore.refresh();+ runInAction(() => {+ this.activeServerId = serverId;+ });} catch (cause) {this.setError(cause, 'Could not switch to that server.');}@@ -581,9 +458,7 @@ export class SwitchServersStore {});return false;}- // Signing in is when the server first says which workspaces the account- // belongs to, so the list this app holds is stale the moment it returns.- await Promise.all([this.refreshStatus(serverId), workspacesStore.refresh()]);+ await this.refreshStatus(serverId);return true;}@@ -600,7 +475,7 @@ export class SwitchServersStore {}return false;}- await Promise.all([this.refreshStatus(serverId), workspacesStore.refresh()]);+ await this.refreshStatus(serverId);return true;}@@ -626,17 +501,13 @@ export class SwitchServersStore {* shared boundary rather than carrying whatever was thrown. The fallback is* per-action: the store knows which request failed, and the failure itself* usually does not.- *- * Returns what it wrote, for the one caller that also keeps the failure in a- * slot of its own.*/- private setError(cause: unknown, fallback: string): FailureDescription {+ private setError(cause: unknown, fallback: string): void {const { headline, detail } = describeFailure(cause, fallback);runInAction(() => {this.error = headline;this.errorDetail = detail;});- return { headline, detail };}}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/use-my-identities.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/use-my-identities.tsindex bc13dd5d9..6e8a1fa2d 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/use-my-identities.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/use-my-identities.ts@@ -5,21 +5,21 @@ import type { LinkedIdentity } from '@shared/core/switch-servers/switch-servers'/** Shared so every surface that claims or releases an identity refreshes the* same cache entry the owner-only warning reads. */-export function myIdentitiesQueryKey(workspaceId: string | null): unknown[] {- return ['my-switch-identities', workspaceId];+export function myIdentitiesQueryKey(serverId: string | null): unknown[] {+ return ['my-switch-identities', serverId];}/**- * The messaging accounts the signed-in user has claimed in a workspace+ * The messaging accounts the signed-in user has claimed on a server* (CHOO-2137).*- * `identities` is null while the answer is unknown — not signed in, no- * workspace chosen, still loading, or the read failed. Callers must treat that as+ * `identities` is null while the answer is unknown — not signed in, no server+ * chosen, still loading, or the read failed. Callers must treat that as* "unknown" rather than "none": warning that an owner-only agent is* unreachable, on the strength of a list that has not arrived, is the same* false alarm every time the page opens.*/-export function useMyIdentities(workspaceId: string | null): {+export function useMyIdentities(serverId: string | null): {identities: LinkedIdentity[] | null;isLoading: boolean;error: unknown;@@ -27,14 +27,14 @@ export function useMyIdentities(workspaceId: string | null): {} {const queryClient = useQueryClient();const query = useQuery({- queryKey: myIdentitiesQueryKey(workspaceId),- queryFn: () => rpc.workspaces.listMyIdentities(workspaceId as string),- enabled: workspaceId !== null,+ queryKey: myIdentitiesQueryKey(serverId),+ queryFn: () => rpc.switchServers.listMyIdentities(serverId as string),+ enabled: serverId !== null,});const refresh = useCallback(() => {- void queryClient.invalidateQueries({ queryKey: myIdentitiesQueryKey(workspaceId) });- }, [queryClient, workspaceId]);+ void queryClient.invalidateQueries({ queryKey: myIdentitiesQueryKey(serverId) });+ }, [queryClient, serverId]);return {identities: query.isSuccess ? query.data : null,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 be2a5b807..7cb17f9c0 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/view.tsx@@ -16,7 +16,6 @@ import { agentsStore } from '@renderer/features/locations/stores/agents-store';import { hostReachabilityStore } from '@renderer/features/remote-hosts/host-reachability-store';import { HostUnreachablePanel } from '@renderer/features/remote-hosts/host-unreachable-panel';import { useAppSettingsKey } from '@renderer/features/settings/use-app-settings-key';-import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { rpc } from '@renderer/lib/ipc';import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';import { useShowModal } from '@renderer/lib/modal/modal-provider';@@ -120,15 +119,12 @@ const ServerMainPanel = observer(function ServerMainPanel() {*/const refreshEverything = async (): Promise<void> => {setRefreshingPage(true);- // The three caches below are keyed by workspace, so a server id would- // invalidate nothing and the button would spin over stale cards.- const workspaceId = workspacesStore.idOnServerInScope(serverId);try {await Promise.all([store.refreshServer(serverId),- queryClient.invalidateQueries({ queryKey: ['remote-bridges', workspaceId] }),- queryClient.invalidateQueries({ queryKey: myIdentitiesQueryKey(workspaceId) }),- queryClient.invalidateQueries({ queryKey: ['owns-owner-addressed-agent', workspaceId] }),+ queryClient.invalidateQueries({ queryKey: ['remote-bridges', serverId] }),+ queryClient.invalidateQueries({ queryKey: myIdentitiesQueryKey(serverId) }),+ queryClient.invalidateQueries({ queryKey: ['owns-owner-addressed-agent', serverId] }),switchRoomsStore.refreshRoomState(),agentsStore.load(),new Promise((resolve) => setTimeout(resolve, MIN_REFRESH_FEEDBACK_MS)),diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-switcher.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-switcher.tsxindex 574e8a1b4..aaa72a706 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-switcher.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-switcher.tsx@@ -1,8 +1,6 @@-import { ChevronsUpDown, Plus, Server } from 'lucide-react';+import { ChevronsUpDown, Plus } from 'lucide-react';import { observer } from 'mobx-react-lite';import { useEffect } from 'react';-import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';-import { useToast } from '@renderer/lib/hooks/use-toast';import { useNavigate } from '@renderer/lib/layout/navigation-provider';import { useShowModal } from '@renderer/lib/modal/modal-provider';import { SwitchConsoleMark } from '@renderer/lib/switch-console-mark';@@ -18,11 +16,6 @@ import {import { Spinner } from '@renderer/lib/ui/spinner';import { cn } from '@renderer/utils/utils';import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';-import {- type Workspace,- type WorkspaceUnavailability,- workspaceUnavailability,-} from '@shared/core/workspaces/workspaces';import { localServerStore } from './local-server-store';import { remoteServerStore } from './remote-server-store';import { serverIcon } from './server-icon';@@ -37,40 +30,21 @@ import {} from './server-presentation';import { switchServersStore } from './switch-servers-store';-/**- * How the button names where you are.- *- * A server registered before its workspaces are known names its only workspace- * after itself, and until the account has been asked the two names are the same- * — saying both would read as a stutter. Where they differ the server is the- * more important half of the answer, since the same workspace name can exist on- * two of them.- */-function switcherSubtitle(workspace: Workspace, server: SwitchServer): string {- const status = serverSubtitleLabel(server);- return workspace.name === server.name ? status : `${server.name} · ${status}`;-}-/*** The workspace switcher at the top of the sidebar.*- * The window is scoped to one workspace: the sidebar, its sessions and- * everything under them show that workspace's world and nothing else, so- * exactly one is on screen at a time and the rest live behind this control.- *- * Workspaces are listed under the server hosting them rather than in one flat- * list. A workspace only means anything on its server — two servers can each- * have a "Default" — and the server is also what carries reachability, so the- * group heading is where it is said once instead of on every row.+ * A server is a workspace: the sidebar, its sessions and everything under them+ * are scoped to whichever one is active, so exactly one is on screen at a time+ * and the rest live behind this control. Before it, all servers were listed+ * side by side and the scoping was left to be inferred from a highlighted row.*- * With no workspace there is nothing to switch between, so it collapses to the+ * With no servers there is nothing to switch between, so it collapses to the* one action that leads anywhere.*/export const WorkspaceSwitcher = observer(function WorkspaceSwitcher() {const store = switchServersStore;const { navigate } = useNavigate();const showAddServerModal = useShowModal('addServerModal');- const showCreateWorkspaceModal = useShowModal('createWorkspaceModal');useEffect(() => {void store.init();@@ -85,10 +59,9 @@ export const WorkspaceSwitcher = observer(function WorkspaceSwitcher() {};}, [store]);- const active = workspacesStore.active;- const activeServer = active ? store.serverById(active.serverId) : null;+ const active = store.activeServer;- if (!active || !activeServer) {+ if (!active) {return (<div className="px-2"><LocalServerPendingButton />@@ -106,8 +79,8 @@ export const WorkspaceSwitcher = observer(function WorkspaceSwitcher() {);}- const ActiveIcon = serverIcon(activeServer);- const drift = serverDrift(activeServer);+ const ActiveIcon = serverIcon(active);+ const drift = serverDrift(active);return (<div className="px-2">@@ -116,18 +89,18 @@ export const WorkspaceSwitcher = observer(function WorkspaceSwitcher() {render={<buttontype="button"- aria-label="Switch workspace"+ aria-label="Switch server"className="flex w-full items-center gap-[10px] rounded-lg px-2 py-1.5 text-left hover:bg-[var(--sel-soft)]">- <ServerAvatar server={activeServer} size="md" />+ <ServerAvatar server={active} size="md" /><span className="min-w-0 flex-1"><span className="block truncate text-sm font-medium text-foreground">{active.name}</span><span className="flex items-center gap-1.5 text-xs text-foreground-muted"><ActiveIcon className="size-3 shrink-0" />- <span className="truncate">{switcherSubtitle(active, activeServer)}</span>- <ServerStatusDot server={activeServer} />+ <span className="truncate">{serverSubtitleLabel(active)}</span>+ <ServerStatusDot server={active} />{drift && <ServerDriftIndicator drift={drift} />}</span></span>@@ -136,27 +109,17 @@ export const WorkspaceSwitcher = observer(function WorkspaceSwitcher() {}/><DropdownMenuContent align="start" className="min-w-72">- {store.servers.map((server) => (- <ServerWorkspaceGroup key={server.id} server={server} />- ))}+ <DropdownMenuGroup>+ <DropdownMenuLabel className="text-xs font-medium text-foreground-passive">+ Servers+ </DropdownMenuLabel>+ {store.servers.map((server) => (+ <ServerMenuItem key={server.id} server={server} />+ ))}+ </DropdownMenuGroup><DropdownMenuSeparator />- {/* Above Add server because it is the commoner errand by far: you add- a server once and make workspaces on it for as long as you use- it. It opens on the server you are already in — the modal asks- which only where there is more than one to ask about. */}- <DropdownMenuItem- onClick={() =>- showCreateWorkspaceModal({- serverId: activeServer.id,- onSuccess: (workspace) => navigate('server', { serverId: workspace.serverId }),- })- }- >- <Plus className="size-4" />- New workspace- </DropdownMenuItem><DropdownMenuItem onClick={() => showAddServerModal({})}>- <Server className="size-4" />+ <Plus className="size-4" />Add server</DropdownMenuItem><DropdownMenuSeparator />@@ -201,130 +164,44 @@ const LocalServerPendingButton = observer(function LocalServerPendingButton() {);});-/** One server, as a heading over the workspaces the account has on it. */-const ServerWorkspaceGroup = observer(function ServerWorkspaceGroup({- server,-}: {- server: SwitchServer;-}) {+const ServerMenuItem = observer(function ServerMenuItem({ server }: { server: SwitchServer }) {+ const store = switchServersStore;+ const { navigate } = useNavigate();const Icon = serverIcon(server);const placement = serverPlacementLabel(server);const drift = serverDrift(server);- const workspaces = workspacesStore.onServer(server.id);-- return (- <DropdownMenuGroup>- <DropdownMenuLabel className="flex items-center gap-2 py-1.5">- <ServerAvatar server={server} size="sm" />- <span className="min-w-0 flex-1">- <span className="block truncate text-xs font-medium text-foreground">{server.name}</span>- <span className="flex min-w-0 items-center gap-1.5 text-xs font-normal text-foreground-muted">- <Icon className="size-3 shrink-0" />- <span className="truncate">{serverStatusLabel(server)}</span>- {/* Beside the words it qualifies rather than at the row's right edge,- where it read as a property of the row instead of of the status. */}- <ServerStatusDot server={server} />- {placement && (- <span className="shrink-0 rounded bg-background-tertiary px-1 py-px text-[10px] font-medium tracking-wide text-foreground-muted uppercase">- {placement}- </span>- )}- </span>- </span>- {drift && <ServerDriftIndicator drift={drift} />}- </DropdownMenuLabel>- {workspaces.length === 0 ? (- // Registering a server is what creates its first workspace, so a server- // with none did not finish being registered. Saying so beats an empty- // heading, which reads as a rendering fault.- <div className="px-2 py-1.5 pl-9 text-xs text-foreground-muted">- No workspace yet — this server has not finished being set up.- </div>- ) : (- workspaces.map((workspace) => (- <WorkspaceMenuItem- key={workspace.id}- workspace={workspace}- server={server}- onServerCount={workspaces.length}- />- ))- )}- </DropdownMenuGroup>- );-});--const UNAVAILABLE_BADGE: Record<WorkspaceUnavailability, string> = {- withdrawn: 'No longer a member',- unmatched: 'Not matched',-};--/**- * What to do about a workspace that cannot be opened — said on the row rather- * than after the click, since the app already knows.- *- * The unmatched case deliberately does not say "sign in again": signing in- * re-runs the reconcile, which is what left the row unmatched, and would do so- * again. The row only survives because it holds agents, so the way out is the- * workspace beside it plus adding those agents there.- */-const UNAVAILABLE_REASON: Record<WorkspaceUnavailability, (name: string) => string> = {- withdrawn: (name) =>- `This account is no longer a member of ${name}. Its agents are still here; ask an admin to add you back to open it.`,- unmatched: (name) =>- `${name} was never matched to a workspace on this server, so there is no way to tell which one to ask for. Open one of the others; the agents left here have to be added again in the workspace they belong to.`,-};--const WorkspaceMenuItem = observer(function WorkspaceMenuItem({- workspace,- server,- onServerCount,-}: {- workspace: Workspace;- server: SwitchServer;- onServerCount: number;-}) {- const { navigate } = useNavigate();- const { toast } = useToast();- const isActive = workspacesStore.activeId === workspace.id;- // Kept in the list rather than hidden: its agents are still here and the row- // is the only thing that says where they went. Disabled, because the gateway- // refuses every call scoped to it — offering it would turn a fact the app- // already knows into an error after the click.- const unavailable = workspaceUnavailability(workspace, onServerCount);+ const isActive = store.activeServerId === server.id;return (<DropdownMenuItem- // The active workspace is shown by filling its row rather than by a tick- // in the right margin, so the row you are on reads at a glance instead of+ // The active server is shown by filling its row rather than by a tick in+ // the right margin, so the row you are on reads at a glance instead of// needing the eye to travel to the end of it. `aria-current` carries the// same fact for anything that cannot see the fill.aria-current={isActive ? 'true' : undefined}- className={cn('pl-9', isActive && 'bg-[var(--sel)]')}- disabled={unavailable !== null}- title={unavailable ? UNAVAILABLE_REASON[unavailable](workspace.name) : undefined}+ className={cn(isActive && 'bg-[var(--sel)]')}onClick={() => {- void workspacesStore- .setActive(workspace.id)- .then(() => navigate('server', { serverId: server.id }))- .catch(() => {- // Said out loud rather than swallowed: the sidebar would otherwise- // keep showing the workspace you left, under the name of the one- // you picked.- toast({- title: 'Could not switch workspace',- description: `${workspace.name} is still there; the app stayed where it was.`,- variant: 'destructive',- });- });+ void store.setActive(server.id);+ navigate('server', { serverId: server.id });}}>- <span className="min-w-0 flex-1 truncate text-sm text-foreground">{workspace.name}</span>- {(unavailable || workspace.role) && (- <span className="shrink-0 rounded bg-background-tertiary px-1 py-px text-[10px] font-medium tracking-wide text-foreground-muted uppercase">- {unavailable ? UNAVAILABLE_BADGE[unavailable] : workspace.role}+ <ServerAvatar server={server} size="md" />+ <span className="min-w-0 flex-1">+ <span className="block truncate text-sm font-medium text-foreground">{server.name}</span>+ <span className="flex min-w-0 items-center gap-1.5 text-xs text-foreground-muted">+ <Icon className="size-3 shrink-0" />+ <span className="truncate">{serverStatusLabel(server)}</span>+ {/* Beside the words it qualifies rather than at the row's right edge,+ where it read as a property of the row instead of of the status. */}+ <ServerStatusDot server={server} />+ {placement && (+ <span className="shrink-0 rounded bg-background-tertiary px-1 py-px text-[10px] font-medium tracking-wide text-foreground-muted uppercase">+ {placement}+ </span>+ )}</span>- )}+ </span>+ {drift && <ServerDriftIndicator drift={drift} />}</DropdownMenuItem>);});diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/agent-template-data.ts b/console/apps/switch-console-desktop/src/renderer/features/templates/agent-template-data.tsindex 67af9d2e8..133d4e935 100644--- a/console/apps/switch-console-desktop/src/renderer/features/templates/agent-template-data.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/agent-template-data.ts@@ -4,7 +4,6 @@ import type { TemplateSummary } from '@main/core/agent-templates/template-summarimport type { AgentTemplateOrigin } from '@main/core/agents/agent-config-file';import type { ParsedTemplate } from '@main/core/room-templates/controller';import type { StoredTemplateSummary } from '@main/core/switch-servers/gateway-client';-import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { rpc } from '@renderer/lib/ipc';import { type BundledTemplate, bundledTemplates, findBundledTemplate } from './bundled-templates';@@ -74,37 +73,18 @@ export async function loadAgentTemplateByOrigin(if (!bundled) throw new Error(`This Console no longer bundles "${origin.name}".`);return agentTemplateFromContent(origin.name, bundled.yamlText, bundled.instructions, origin);}- const detail = await rpc.workspaces.getTemplateDetail({- workspaceId: templateWorkspaceId(origin),+ if (!origin.serverId)+ throw new Error(`"${origin.name}" came from a server this Console does not know.`);+ const detail = await rpc.switchServers.getTemplateDetail({+ serverId: origin.serverId,templateId: origin.id,});return agentTemplateFromContent(origin.name, detail.definition, null, origin);}-/**- * The workspace to ask for a server template, from what the origin recorded.- *- * A registry belongs to a workspace, so an origin naming only a server is- * answerable exactly while that server holds one. Where it holds several the- * window's own workspace is not an answer: it would load a different template- * of the same id, or none, and offer it as this agent's.- */-function templateWorkspaceId(origin: AgentTemplateOrigin): string {- if (origin.workspaceId) return origin.workspaceId;- if (!origin.serverId)- throw new Error(`"${origin.name}" came from a server this Console does not know.`);- const onServer = workspacesStore.onServer(origin.serverId);- if (onServer.length === 1) return onServer[0]!.id;- if (onServer.length === 0)- throw new Error(`The workspace "${origin.name}" came from is not known yet.`);- throw new Error(- `"${origin.name}" was recorded before this Console kept which workspace a template came from, and its Switch server now has ${onServer.length}. Open it from that workspace's template list instead.`- );-}-/** Resolve a listing entry (bundled or from the server's registry) into the agent it describes. */export async function loadAgentTemplate(- workspaceId: string,+ serverId: string,template: StoredTemplateSummary): Promise<AgentTemplate> {const bundled = findBundledTemplate(template.id);@@ -115,14 +95,12 @@ export async function loadAgentTemplate(source: 'bundled',});}- const detail = await rpc.workspaces.getTemplateDetail({ workspaceId, templateId: template.id });- const serverId = workspacesStore.serverIdFor(workspaceId);+ const detail = await rpc.switchServers.getTemplateDetail({ serverId, templateId: template.id });return agentTemplateFromContent(detail.name, detail.definition, null, {id: detail.id,name: detail.name,source: 'server',- workspaceId,- ...(serverId ? { serverId } : {}),+ serverId,});}@@ -157,7 +135,7 @@ export type LoadedTemplate = {* owner, so someone else's template of the same name is not a copy.*/export async function loadTemplateById(- workspaceId: string,+ serverId: string,templateId: string,meId: string | null): Promise<LoadedTemplate> {@@ -170,7 +148,7 @@ export async function loadTemplateById(let savedCopy: StoredTemplateSummary | null = null;if (bundled) {savedCopy =- (await rpc.workspaces.listTemplates({ workspaceId }).catch(() => [])).find(+ (await rpc.switchServers.listTemplates({ serverId }).catch(() => [])).find((t) => t.name === bundled.name && meId !== null && t.ownerId === meId) ?? null;name = bundled.name;@@ -182,7 +160,7 @@ export async function loadTemplateById(}): bundled.yamlText;} else {- const detail = await rpc.workspaces.getTemplateDetail({ workspaceId, templateId });+ const detail = await rpc.switchServers.getTemplateDetail({ serverId, templateId });const { definition, ...summary } = detail;name = detail.name;description = detail.description;diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/save-template-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/templates/save-template-modal.tsxindex 285d7646a..0d1a433ad 100644--- a/console/apps/switch-console-desktop/src/renderer/features/templates/save-template-modal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/save-template-modal.tsx@@ -1,5 +1,4 @@import { useId, useState } from 'react';-import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { failureText } from '@renderer/lib/errors/describe-failure';import { toast } from '@renderer/lib/hooks/use-toast';import { rpc } from '@renderer/lib/ipc';@@ -54,18 +53,12 @@ export function SaveTemplateModal({const [saving, setSaving] = useState(false);const [error, setError] = useState<string | null>(null);- const workspaceId = workspacesStore.idOnServerInScope(serverId);-const save = async () => {- if (workspaceId === null) {- setError('This server’s workspace is not known yet.');- return;- }setSaving(true);setError(null);try {- const saved = await rpc.workspaces.saveTemplate({- workspaceId,+ const saved = await rpc.switchServers.saveTemplate({+ serverId,name: name.trim(),description: description.trim(),kind,diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/template-detail-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/templates/template-detail-view.tsxindex 9df654e55..a078cdabf 100644--- a/console/apps/switch-console-desktop/src/renderer/features/templates/template-detail-view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/template-detail-view.tsx@@ -15,7 +15,6 @@ import { useEffect, useState } from 'react';import type { GuardResult, ViewDefinition } from '@renderer/app/view-registry';import { ServerSectionTitlebar } from '@renderer/features/switch-servers/server-section-titlebar';import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';-import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { PageHeader } from '@renderer/lib/components/page-header';import { failureText } from '@renderer/lib/errors/describe-failure';import { toast } from '@renderer/lib/hooks/use-toast';@@ -156,7 +155,6 @@ const KIND_LABEL: Record<LoadedTemplate['kind'], string> = {const TemplateDetailPanel = observer(function TemplateDetailPanel() {const { serverId, templateId } = useViewParams();- const workspaceId = workspacesStore.idOnServerInScope(serverId);const { navigate } = useNavigate();const server = switchServersStore.servers.find((s) => s.id === serverId);const me = switchServersStore.statusFor(serverId)?.user ?? null;@@ -169,18 +167,10 @@ const TemplateDetailPanel = observer(function TemplateDetailPanel() {const [showInstructions, setShowInstructions] = useState(false);useEffect(() => {- // No workspace is an answer, not a wait. Returning with neither a template- // nor an error leaves the spinner below up forever, claiming something is- // on its way that nobody is fetching.- if (workspaceId === null) {- setLoaded(null);- setError('This server has no workspace yet, so its templates cannot be read.');- return;- }let cancelled = false;setLoaded(null);setError(null);- loadTemplateById(workspaceId, templateId, me?.id ?? null)+ loadTemplateById(serverId, templateId, me?.id ?? null).then((t) => {if (cancelled) return;setLoaded(t);@@ -193,7 +183,7 @@ const TemplateDetailPanel = observer(function TemplateDetailPanel() {cancelled = true;setCurrentName(null);};- }, [workspaceId, templateId, me?.id]);+ }, [serverId, templateId, me?.id]);const back = (<Button@@ -242,11 +232,11 @@ const TemplateDetailPanel = observer(function TemplateDetailPanel() {const use = () => navigate('templateUse', { serverId, templateId });const saveToServer = async () => {- if (!loaded.bundled || workspaceId === null) return;+ if (!loaded.bundled) return;setBusy('save');try {- const saved = await rpc.workspaces.saveTemplate({- workspaceId,+ const saved = await rpc.switchServers.saveTemplate({+ serverId,name: loaded.bundled.name,description: loaded.bundled.description,kind: loaded.bundled.kind,@@ -266,10 +256,10 @@ const TemplateDetailPanel = observer(function TemplateDetailPanel() {};const remove = async () => {- if (!loaded.server || workspaceId === null) return;+ if (!loaded.server) return;setBusy('delete');try {- await rpc.workspaces.deleteTemplate({ workspaceId, templateId: loaded.server.id });+ await rpc.switchServers.deleteTemplate({ serverId, templateId: loaded.server.id });toast({ title: `"${loaded.name}" removed from ${server?.name ?? 'the workspace'}` });navigate('templates', { serverId });} catch (e) {diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/template-use-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/templates/template-use-view.tsxindex 308e81388..9a3822dc2 100644--- a/console/apps/switch-console-desktop/src/renderer/features/templates/template-use-view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/template-use-view.tsx@@ -28,17 +28,13 @@ import { refreshSidebarRoomState } from '@renderer/features/sidebar/sidebar-treeimport { ServerSectionTitlebar } from '@renderer/features/switch-servers/server-section-titlebar';import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';import { useMyIdentities } from '@renderer/features/switch-servers/use-my-identities';-import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { failureText } from '@renderer/lib/errors/describe-failure';import { toast } from '@renderer/lib/hooks/use-toast';import { rpc } from '@renderer/lib/ipc';import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';import { useModalContext } from '@renderer/lib/modal/modal-provider';import { useAgentTypeAvailability } from '@renderer/lib/stores/use-agent-type-availability';-import {- useWorkspaceAgents,- workspaceAgentsQueryKey,-} from '@renderer/lib/stores/use-workspace-agents';+import { remoteAgentsQueryKey, useRemoteAgents } from '@renderer/lib/stores/use-remote-agents';import { Alert, AlertDescription } from '@renderer/lib/ui/alert';import { Button } from '@renderer/lib/ui/button';import { Switch } from '@renderer/lib/ui/switch';@@ -123,7 +119,7 @@ type UsePageTemplate = {warnings: string[];};-async function loadUsePageTemplate(workspaceId: string, params: Params): Promise<UsePageTemplate> {+async function loadUsePageTemplate(serverId: string, params: Params): Promise<UsePageTemplate> {let name: string;let yamlText: string;let instructions: string | null = null;@@ -136,20 +132,13 @@ async function loadUsePageTemplate(workspaceId: string, params: Params): Promiseinstructions = bundled.instructions;origin = { id: bundled.id, name: bundled.name, source: 'bundled' };} else {- const detail = await rpc.workspaces.getTemplateDetail({- workspaceId,+ const detail = await rpc.switchServers.getTemplateDetail({+ serverId,templateId: params.templateId,});name = detail.name;yamlText = detail.definition;- const serverId = workspacesStore.serverIdFor(workspaceId);- origin = {- id: detail.id,- name: detail.name,- source: 'server',- workspaceId,- ...(serverId ? { serverId } : {}),- };+ origin = { id: detail.id, name: detail.name, source: 'server', serverId };}} else if (params.yamlText) {name = params.sourceName?.replace(/(\.template)?\.ya?ml$/i, '') ?? 'Pasted template';@@ -169,7 +158,7 @@ async function loadUsePageTemplate(workspaceId: string, params: Params): Promise// Without the schema the form is built from the Console's own parse and// the server validates on create, so an older server without the schema// endpoint still gets a working page.- const schema = await rpc.workspaces.fetchTemplateSchema(workspaceId).catch(() => null);+ const schema = await rpc.switchServers.fetchTemplateSchema(serverId).catch(() => null);const parsed = forForm? await rpc.roomTemplates.parse({ yamlText: forForm, schema: schema ?? undefined }): null;@@ -248,7 +237,6 @@ type SlotSetup = {const TemplateUsePanel = observer(function TemplateUsePanel() {const params = useViewParams();const { serverId, intoRoomId = null } = params;- const workspaceId = workspacesStore.idOnServerInScope(serverId);const { navigate } = useNavigate();const { showModal } = useModalContext();const queryClient = useQueryClient();@@ -267,7 +255,7 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {// What the server returned for the room, kept so that a step failing after// it does not make Retry create the room a second time.const createdRoom = useRef<Awaited<- ReturnType<typeof rpc.workspaces.createRoomFromTemplate>+ ReturnType<typeof rpc.switchServers.createRoomFromTemplate>> | null>(null);const [roomStatus, setRoomStatus] = useState<SlotStatus>('idle');const [createError, setCreateError] = useState<string | null>(null);@@ -288,18 +276,10 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {// render would reset the form.const { templateId, yamlText: givenYaml, sourceName } = params;useEffect(() => {- // No workspace is an answer, not a wait. Returning with neither a template- // nor an error leaves the page spinning forever, and Deploy reading- // "Loading…" for something nobody is fetching.- if (workspaceId === null) {- setLoaded(null);- setLoadError('This server has no workspace yet, so this template cannot be read.');- return;- }let cancelled = false;setLoaded(null);setLoadError(null);- loadUsePageTemplate(workspaceId, { serverId, templateId, yamlText: givenYaml, sourceName })+ loadUsePageTemplate(serverId, { serverId, templateId, yamlText: givenYaml, sourceName }).then((result) => {if (cancelled) return;setLoaded(result);@@ -325,7 +305,7 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {return () => {cancelled = true;};- }, [serverId, workspaceId, templateId, givenYaml, sourceName]);+ }, [serverId, templateId, givenYaml, sourceName]);const parsed = loaded?.parsed ?? null;// In the singular `agent:` form the room refers to the agent as `{agent}`.@@ -384,23 +364,20 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {const directoryParam = unboundOfType('directory');// ── Server lists (pickers, identities, bridges) ─────────────────────────- const agents = useWorkspaceAgents(workspaceId);+ const agents = useRemoteAgents(serverId);const roomsQuery = useQuery({- queryKey: ['remote-rooms', workspaceId],- queryFn: () => rpc.workspaces.listRooms(workspaceId as string),- enabled: workspaceId !== null,+ queryKey: ['remote-rooms', serverId],+ queryFn: () => rpc.switchServers.listRemoteRooms(serverId),});const bridgesQuery = useQuery({- queryKey: ['remote-bridges', workspaceId],- queryFn: () => rpc.workspaces.listBridges(workspaceId as string),- enabled: workspaceId !== null,+ queryKey: ['remote-bridges', serverId],+ queryFn: () => rpc.switchServers.listRemoteBridges(serverId),});const knownUsersQuery = useQuery({- queryKey: ['remote-external-users', workspaceId],- queryFn: () => rpc.workspaces.listExternalUsers(workspaceId as string),- enabled: workspaceId !== null,+ queryKey: ['remote-external-users', serverId],+ queryFn: () => rpc.switchServers.listRemoteExternalUsers(serverId),});- const { identities, refresh: refreshIdentities } = useMyIdentities(workspaceId);+ const { identities, refresh: refreshIdentities } = useMyIdentities(serverId);const bridges = useMemo(() => bridgesQuery.data ?? [], [bridgesQuery.data]);const allowedHosts = useAllowedHosts(serverId);const hostLabel = useCallback(@@ -431,20 +408,19 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {templateBridge !== null &&identities !== null &&creatorIdentity === null;- const linkAccount =- templateBridge && workspaceId !== null- ? () =>- showModal('claimIdentityModal', {- workspaceId,- bridgeId: templateBridge.id,- onSuccess: () => refreshIdentities(),- })- : null;+ const linkAccount = templateBridge+ ? () =>+ showModal('claimIdentityModal', {+ serverId,+ bridgeId: templateBridge.id,+ onSuccess: () => refreshIdentities(),+ })+ : null;const noMessagingApp = parsed !== null && bridgesQuery.data !== undefined && bridges.length === 0;const lists = useMemo((): EntityLists => ({- workspaceId,+ serverId,agents: agents.data ?? [],agentsLoading: agents.isLoading,rooms: roomsQuery.data ?? [],@@ -455,7 +431,7 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {bridgeId: templateBridge?.id ?? null,}),[- workspaceId,+ serverId,agents.data,agents.isLoading,roomsQuery.data,@@ -698,7 +674,7 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {const blockedReason: string | null =phase !== 'form'? null- : loaded === null || workspaceId === null+ : loaded === null? 'Loading…': missing.length > 0? `Fill in ${missing.map(paramLabel).join(', ')}`@@ -743,7 +719,6 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {}, [parsed, editedAgents, templateParams, values, slots, agents.data]);const [allowingHandoffs, setAllowingHandoffs] = useState(false);const allowHandoffs = useCallback(async () => {- if (workspaceId === null) return;const byName = new Map((agents.data ?? []).map((a) => [a.name, a]));setAllowingHandoffs(true);try {@@ -765,26 +740,26 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {}return next;});- await rpc.workspaces.updateAddressingPolicy({- workspaceId,+ await rpc.switchServers.updateAddressingPolicy({+ serverId,agentId: target.id,policy: { rules },});}- await queryClient.invalidateQueries({ queryKey: workspaceAgentsQueryKey(workspaceId) });+ await queryClient.invalidateQueries({ queryKey: remoteAgentsQueryKey(serverId) });} catch (e) {toast({ title: failureText(e, 'Could not update the agents.'), variant: 'destructive' });} finally {setAllowingHandoffs(false);}- }, [agents.data, handoffBlocked, workspaceId, queryClient]);+ }, [agents.data, handoffBlocked, serverId, queryClient]);// ── Create ──────────────────────────────────────────────────────────────const setSlot = (i: number, patch: Partial<AgentSlot>) =>setSlots((prev) => prev.map((s, j) => (j === i ? { ...s, ...patch } : s)));const createAll = async () => {- if (!loaded || workspaceId === null || blockedReason !== null) return;+ if (!loaded || blockedReason !== null) return;setPhase('creating');setCreateError(null);setFieldErrors({});@@ -856,8 +831,8 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {// must be written as the open policy; leaving the default would keep it closed.if (switchAgentId && slot.entry.addressing) {setSlot(i, { step: 'policy' });- await rpc.workspaces.updateAddressingPolicy({- workspaceId,+ await rpc.switchServers.updateAddressingPolicy({+ serverId,agentId: switchAgentId,policy:slot.entry.addressing === 'owner-agents'@@ -880,7 +855,7 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {// fails must not fail the run.await agentsStore.load().catch(() => {});await queryClient- .invalidateQueries({ queryKey: workspaceAgentsQueryKey(workspaceId) })+ .invalidateQueries({ queryKey: remoteAgentsQueryKey(serverId) }).catch(() => {});}// A recent is used again from its own text, so a bundled template whose@@ -936,8 +911,8 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {setRoomStatus('creating');try {for (const [roomId, ids] of joinsByRoom) {- await rpc.workspaces.addRoomAgents({- workspaceId,+ await rpc.switchServers.addRoomAgents({+ serverId,roomId,agentIds: [...new Set(ids)],direction: 'agents_to_room',@@ -1020,7 +995,7 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {}const result =createdRoom.current ??- (await rpc.workspaces.createRoomFromTemplate(workspaceId, coreYaml, inputs));+ (await rpc.switchServers.createRoomFromTemplate(serverId, coreYaml, inputs));createdRoom.current = result;setRoomStatus('created');// The room exists whether or not the sidebar refreshes.diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/templates-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/templates/templates-view.tsxindex 7399728a7..21f5a9178 100644--- a/console/apps/switch-console-desktop/src/renderer/features/templates/templates-view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/templates-view.tsx@@ -21,7 +21,6 @@ import type { GuardResult, ViewDefinition } from '@renderer/app/view-registry';import { ServerPage } from '@renderer/features/switch-servers/server-page';import { ServerSectionTitlebar } from '@renderer/features/switch-servers/server-section-titlebar';import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';-import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { failureText } from '@renderer/lib/errors/describe-failure';import { toast } from '@renderer/lib/hooks/use-toast';import { rpc } from '@renderer/lib/ipc';@@ -115,18 +114,18 @@ function summaryLine(s: TemplateSummary): string {// template and keeps it for the session.const summaryCache = new Map<string, Promise<TemplateSummary>>();-function fetchSummary(workspaceId: string, item: TemplateListEntry): Promise<TemplateSummary> {+function fetchSummary(serverId: string, item: TemplateListEntry): Promise<TemplateSummary> {// The version is part of the key, so an edit made elsewhere refreshes the// card as soon as the listing reports it.- const key = `${workspaceId}:${item.id}:${item.server?.version ?? 0}`;+ const key = `${serverId}:${item.id}:${item.server?.version ?? 0}`;let pending = summaryCache.get(key);if (!pending) {pending = (async () => {const yamlText =item.content ??(- await rpc.workspaces.getTemplateDetail({- workspaceId,+ await rpc.switchServers.getTemplateDetail({+ serverId,templateId: item.id,})).definition;@@ -138,15 +137,11 @@ function fetchSummary(workspaceId: string, item: TemplateListEntry): Promise<Temreturn pending;}-function useTemplateSummary(- workspaceId: string | null,- item: TemplateListEntry-): TemplateSummary | null {+function useTemplateSummary(serverId: string, item: TemplateListEntry): TemplateSummary | null {const [summary, setSummary] = useState<TemplateSummary | null>(null);useEffect(() => {- if (workspaceId === null) return;let cancelled = false;- fetchSummary(workspaceId, item)+ fetchSummary(serverId, item).then((s) => {if (!cancelled) setSummary(s);})@@ -156,7 +151,7 @@ function useTemplateSummary(return () => {cancelled = true;};- }, [workspaceId, item]);+ }, [serverId, item]);return summary;}@@ -176,14 +171,14 @@ function OwnerRow({ name, mine }: { name: string; mine: boolean }) {}function TemplateCard({- workspaceId,+ serverId,item,meId,busy,onOpen,onUse,}: {- workspaceId: string | null;+ serverId: string;item: TemplateListEntry;meId: string | null;busy: boolean;@@ -191,7 +186,7 @@ function TemplateCard({onUse: () => void;}) {const Icon = KIND_ICON[item.kind];- const summary = useTemplateSummary(workspaceId, item);+ const summary = useTemplateSummary(serverId, item);const mine = item.server !== null && meId !== null && item.server.ownerId === meId;return (<div className="group relative flex min-h-[168px] flex-col rounded-[11px] border border-border bg-background transition-colors hover:border-border-1">@@ -408,7 +403,6 @@ function RecentsSection({const TemplatesPanel = observer(function TemplatesPanel() {const serverId = useServerId();- const workspaceId = workspacesStore.idOnServerInScope(serverId);const server = switchServersStore.servers.find((s) => s.id === serverId);const meId = switchServersStore.statusFor(serverId)?.user?.id ?? null;const { navigate } = useNavigate();@@ -432,14 +426,14 @@ const TemplatesPanel = observer(function TemplatesPanel() {const [searchHits, setSearchHits] = useState<StoredTemplateSummary[] | null>(null);useEffect(() => {const q = query.trim();- if (q.length === 0 || workspaceId === null) {+ if (q.length === 0) {setSearchHits(null);return;}let cancelled = false;const timer = window.setTimeout(() => {- rpc.workspaces- .listTemplates({ workspaceId, q })+ rpc.switchServers+ .listTemplates({ serverId, q }).then((hits) => {if (!cancelled) setSearchHits(hits);})@@ -452,7 +446,7 @@ const TemplatesPanel = observer(function TemplatesPanel() {cancelled = true;window.clearTimeout(timer);};- }, [workspaceId, query, reloadKey]);+ }, [serverId, query, reloadKey]);// An agent template needs a coding agent where its agents will run, and// this computer is the default run location. Say at the top of the listing@@ -462,19 +456,11 @@ const TemplatesPanel = observer(function TemplatesPanel() {const noProvider = availability !== undefined && !availability.some((a) => a.available);useEffect(() => {- // No workspace is an answer, not a wait. The bundled templates below still- // render; leaving the spinner up would claim a list is on its way.- if (workspaceId === null) {- setTemplates([]);- setListError('This server has no workspace yet, so its templates cannot be read.');- setLoading(false);- return;- }let cancelled = false;setLoading(true);setListError(null);- rpc.workspaces- .listTemplates({ workspaceId })+ rpc.switchServers+ .listTemplates({ serverId }).then((result) => {if (!cancelled) setTemplates(result);})@@ -492,7 +478,7 @@ const TemplatesPanel = observer(function TemplatesPanel() {return () => {cancelled = true;};- }, [workspaceId, reloadKey]);+ }, [serverId, reloadKey]);const { builtIn, onWorkspace } = useMemo(() => {// A bundled card is always the bundled document. Saving it creates a@@ -557,7 +543,7 @@ const TemplatesPanel = observer(function TemplatesPanel() {const card = (item: TemplateListEntry) => (<TemplateCardkey={item.id}- workspaceId={workspaceId}+ serverId={serverId}item={item}meId={meId}busy={false}diff --git a/console/apps/switch-console-desktop/src/renderer/features/workspaces/create-workspace-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/workspaces/create-workspace-modal.tsxdeleted file mode 100644index 7a2ae23aa..000000000--- a/console/apps/switch-console-desktop/src/renderer/features/workspaces/create-workspace-modal.tsx+++ /dev/null@@ -1,245 +0,0 @@-import { observer } from 'mobx-react-lite';-import { useEffect, useState } from 'react';-import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';-import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';-import { failureText } from '@renderer/lib/errors/describe-failure';-import { useModalContext, type BaseModalProps } from '@renderer/lib/modal/modal-provider';-import { Button } from '@renderer/lib/ui/button';-import { ConfirmButton } from '@renderer/lib/ui/confirm-button';-import {- DialogContentArea,- DialogFooter,- DialogHeader,- DialogTitle,-} from '@renderer/lib/ui/dialog';-import { Field, FieldGroup, FieldLabel } from '@renderer/lib/ui/field';-import { Input } from '@renderer/lib/ui/input';-import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,-} from '@renderer/lib/ui/select';-import type { Workspace } from '@shared/core/workspaces/workspaces';-import { createWorkspaceFailureText } from './describe-create-failure';--type CreateWorkspaceModalArgs = {- /** The server to create it on — the one the window is currently scoped to. */- serverId: string;-};--type Props = BaseModalProps<Workspace> & CreateWorkspaceModalArgs;--/**- * Why a server cannot be asked to create a workspace, or null when it can.- *- * Three refusals rather than one, because the remedies are three different- * things and only one of them is a password. Telling someone to sign in again- * because the network is down misattributes an outage to their credentials,- * which is the same mistake as blaming the name for an authentication failure —- * the one this modal exists to avoid — with the arrow reversed.- */-function whyNotReady(serverId: string): string | null {- const server = switchServersStore.serverById(serverId);- if (server === null) return 'That server is no longer registered on this computer.';- if (!switchServersStore.statuses.has(serverId)) {- return `Checking whether you’re signed in to ${server.name}…`;- }- if (switchServersStore.isUnreachable(serverId)) {- return `${server.name} can’t be reached right now, so it can’t be asked to create anything.`;- }- if (!switchServersStore.isConnected(serverId)) {- return `You are not signed in to ${server.name}, so it cannot be asked to create anything. Sign in on its page first.`;- }- return null;-}--/**- * Make a workspace from the switcher.- *- * A workspace belongs to a server, so the first thing this has to be sure of is- * which one. It opens on the server the window is already in and offers the- * others only where there is a choice to make — on the ordinary single-server- * install the question never appears.- *- * Only a server you are signed in to can be asked. Offering the rest and- * letting Create come back with an authentication failure would blame the name- * for something the name had nothing to do with, so the modal says which server- * is not ready and keeps the button off.- *- * The design's address hint and "let my team join automatically" toggle are not- * here: a Switch workspace has no subdomain of its own, and no server can yet- * admit people by email domain. See the first-run create page, which leaves- * them out for the same reasons.- */-export const CreateWorkspaceModal = observer(function CreateWorkspaceModal({- serverId,- onSuccess,- onClose,-}: Props) {- const { transitionModal, setCloseGuard } = useModalContext();- const [chosen, setChosen] = useState<string | null>(null);- const [name, setName] = useState('');- const [submitting, setSubmitting] = useState(false);- const [error, setError] = useState<string | null>(null);- /**- * The workspace the gateway has already minted, when entering it is what- * failed.- *- * Creating it again would ask for a name the server has just taken and come- * back with a conflict that reads as the name being refused — so once this is- * set the button stops offering to create and offers to open instead.- */- const [created, setCreated] = useState<Workspace | null>(null);-- const candidates = switchServersStore.servers.filter((server) =>- switchServersStore.isConnected(server.id)- );- // The server the window is in, when it can be asked; otherwise the only one- // that can. A default that is not a candidate would hide the picker on a- // question the user still has to answer, and leave Create disabled with the- // usable server offered nowhere.- const fallback = candidates.some((server) => server.id === serverId)- ? serverId- : (candidates[0]?.id ?? serverId);- const where = chosen ?? fallback;- const target = switchServersStore.serverById(where);- const notReady = whyNotReady(where);- const trimmed = name.trim();-- // A status nobody has read yet leaves the modal saying "checking" forever,- // since nothing else on screen is watching this server.- useEffect(() => {- if (!switchServersStore.statuses.has(where)) void switchServersStore.refreshStatus(where);- }, [where]);-- const submit = async () => {- if (submitting) return;- if (created === null && (notReady !== null || trimmed === '')) return;- setSubmitting(true);- setCloseGuard(true);- setError(null);- try {- const workspace = created ?? (await workspacesStore.create(where, trimmed));- setCreated(workspace);- // Made and then entered: you asked for a workspace to work in, and- // leaving the window in the old one would look like nothing happened.- await workspacesStore.setActive(workspace.id);- onSuccess(workspace);- } catch (cause) {- // Two different failures wear the same button. Before the workspace- // exists the likeliest one is the name, and after it exists the name is- // settled and what failed was the move into it — saying "could not- // create" then would be describing the wrong step.- setError(- created === null- ? createWorkspaceFailureText(- cause,- target?.name ?? 'that server',- `${target?.name ?? 'That server'} could not create it.`- )- : failureText(cause, `This window could not be moved into ${created.name}.`)- );- setSubmitting(false);- } finally {- setCloseGuard(false);- }- };-- return (- <>- <DialogHeader showCloseButton={false}>- <DialogTitle>Create a workspace</DialogTitle>- </DialogHeader>- <DialogContentArea className="pt-0">- <FieldGroup>- <Field>- <FieldLabel>Name</FieldLabel>- <Input- value={name}- onChange={(e) => {- setName(e.target.value);- setError(null);- }}- onKeyDown={(e) => {- if (e.key === 'Enter') void submit();- }}- placeholder="Weekend Robotics"- autoFocus- disabled={created !== null}- />- </Field>-- {candidates.length > 1 && (- <Field>- <FieldLabel>Server</FieldLabel>- <Select- value={where}- onValueChange={(value) => value && setChosen(value)}- disabled={submitting || created !== null}- >- <SelectTrigger>- <SelectValue />- </SelectTrigger>- <SelectContent>- {candidates.map((server) => (- <SelectItem key={server.id} value={server.id}>- {server.name}- </SelectItem>- ))}- </SelectContent>- </Select>- </Field>- )}-- {created !== null ? (- <p className="text-xs text-foreground-muted">- {created.name} was created on {target?.name ?? 'the server'}, but this window could- not be moved into it. Try again, or close this and pick it from the switcher.- </p>- ) : notReady !== null ? (- <p className="text-xs text-destructive">{notReady}</p>- ) : target !== null && candidates.length <= 1 ? (- <p className="text-xs text-foreground-muted">- It will live on {target.name}, along with its rooms and agents.- </p>- ) : null}-- {error && <p className="text-xs text-destructive">{error}</p>}-- <p className="text-xs text-foreground-muted">- Rather put it somewhere else?{' '}- <button- type="button"- className="underline underline-offset-2 hover:text-foreground disabled:opacity-50"- disabled={submitting || created !== null}- onClick={() => transitionModal('addServerModal', {})}- >- Add a server- </button>- </p>- </FieldGroup>- </DialogContentArea>- <DialogFooter>- <Button variant="outline" onClick={onClose} disabled={submitting}>- {created === null ? 'Cancel' : 'Close'}- </Button>- <ConfirmButton- onClick={() => void submit()}- /* Entering a workspace that already exists is a local move, so once it- has been created the server's readiness stops being the question. */- disabled={submitting || (created === null && (notReady !== null || trimmed === ''))}- >- {created !== null- ? submitting- ? 'Opening…'- : 'Open workspace'- : submitting- ? 'Creating…'- : 'Create workspace'}- </ConfirmButton>- </DialogFooter>- </>- );-});diff --git a/console/apps/switch-console-desktop/src/renderer/features/workspaces/describe-create-failure.test.ts b/console/apps/switch-console-desktop/src/renderer/features/workspaces/describe-create-failure.test.tsdeleted file mode 100644index d7de0cc47..000000000--- a/console/apps/switch-console-desktop/src/renderer/features/workspaces/describe-create-failure.test.ts+++ /dev/null@@ -1,57 +0,0 @@-import { describe, expect, it } from 'vitest';-import { RpcError } from '@shared/lib/ipc/rpc-error';-import { createWorkspaceFailureText } from './describe-create-failure';--function gatewayError(status: number, detail: string): RpcError {- return new RpcError({- __switchConsoleRpcError: true,- code: 'GatewayError',- message: `Gateway returned ${status}: ${detail}`,- data: { kind: 'http', status, detail },- } as unknown as ConstructorParameters<typeof RpcError>[0]);-}--const FALLBACK = 'Local dev could not create it.';--describe('creating a workspace, when it fails', () => {- /**- * The gateway's own words are `Slug already taken: acme-robotics` — no- * terminal punctuation, so the shared description does not read it as a- * sentence and shows it as diagnostics instead. What reached the user was a- * status code and a slug they never typed, for the one refusal that is- * entirely about what they did type.- */- it('blames the name for a name conflict, and says nothing about slugs', () => {- const text = createWorkspaceFailureText(- gatewayError(409, 'Slug already taken: acme-robotics'),- 'Local dev',- FALLBACK- );-- expect(text).toContain('already goes by that name');- expect(text).toContain('Local dev');- expect(text).not.toContain('acme-robotics');- expect(text).not.toContain('409');- });-- // The whole point of the rewrite is that the name is at fault. Saying so over- // an expired session sends the user to rename a workspace when what they have- // to do is sign in.- it('leaves every other gateway refusal to the shared description', () => {- const expired = new RpcError({- __switchConsoleRpcError: true,- code: 'GatewayError',- message: 'Gateway returned 401',- data: { kind: 'unauthorized', status: 401 },- } as unknown as ConstructorParameters<typeof RpcError>[0]);-- expect(createWorkspaceFailureText(expired, 'Local dev', FALLBACK)).toContain('Sign in again');- });-- it('keeps the caller’s sentence for a failure it cannot place', () => {- const text = createWorkspaceFailureText(new Error('socket hang up'), 'Local dev', FALLBACK);-- expect(text).toContain(FALLBACK);- expect(text).toContain('socket hang up');- });-});diff --git a/console/apps/switch-console-desktop/src/renderer/features/workspaces/describe-create-failure.ts b/console/apps/switch-console-desktop/src/renderer/features/workspaces/describe-create-failure.tsdeleted file mode 100644index 37d626664..000000000--- a/console/apps/switch-console-desktop/src/renderer/features/workspaces/describe-create-failure.ts+++ /dev/null@@ -1,31 +0,0 @@-import { failureText } from '@renderer/lib/errors/describe-failure';-import { RpcError } from '@shared/lib/ipc/rpc-error';--/**- * What to put under the name field when creating a workspace fails.- *- * The name being taken is by far the likeliest way this form fails, and it is- * the only failure the person at the keyboard can fix. The gateway derives a- * slug from the name and refuses a duplicate with `Slug already taken:- * acme-robotics` — no terminal punctuation, so the generic description does not- * read it as a sentence and shows it as diagnostic text instead: a status code- * and a slug the user never typed, for the one refusal that is about what they- * did type.- *- * Only that route's conflict is rewritten. Everything else keeps the shared- * description, because a name-specific sentence over an expired session or an- * unreachable server would blame the name for something it had nothing to do- * with.- */-export function createWorkspaceFailureText(- error: unknown,- serverName: string,- fallback: string-): string {- const conflict =- error instanceof RpcError &&- error.code === 'GatewayError' &&- error.numberField('status') === 409;- if (!conflict) return failureText(error, fallback);- return `A workspace on ${serverName} already goes by that name. Capitalisation and punctuation do not make it a different one, so pick a name that stands apart.`;-}diff --git a/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspaces-store.test.ts b/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspaces-store.test.tsdeleted file mode 100644index 59f9e3163..000000000--- a/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspaces-store.test.ts+++ /dev/null@@ -1,184 +0,0 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';-import type { Workspace } from '@shared/core/workspaces/workspaces';--const list = vi.hoisted(() => vi.fn());-const getActiveId = vi.hoisted(() => vi.fn());-const setActive = vi.hoisted(() => vi.fn());-const subscribers = vi.hoisted(() => new Map<string, (data: unknown) => void>());--vi.mock('@renderer/lib/ipc', () => ({- events: {- on: (event: { name: string }, cb: (data: unknown) => void) => {- subscribers.set(event.name, cb);- return () => subscribers.delete(event.name);- },- },- rpc: { workspaces: { list, getActiveId, setActive } },-}));--const { WorkspacesStore } = await import('./workspaces-store');-const { workspacesChangedChannel } = await import('@shared/core/workspaces/workspaceEvents');--function workspace(id: string, serverId: string, name = id): Workspace {- return {- id,- serverId,- name,- tenantId: `tenant-${id}`,- slug: id,- role: 'member',- createdAt: '2026-01-01T00:00:00Z',- updatedAt: '2026-01-01T00:00:00Z',- };-}--/** A store holding the given workspaces, scoped to one of them. */-async function loaded(workspaces: Workspace[], activeId: string | null) {- list.mockResolvedValue(workspaces);- getActiveId.mockResolvedValue(activeId);- const store = new WorkspacesStore();- await store.refresh();- return store;-}--beforeEach(() => {- vi.clearAllMocks();- subscribers.clear();- setActive.mockResolvedValue(undefined);-});--/** Fire the main process's "the list moved" event at whoever subscribed. */-function announceChange(): void {- const notify = subscribers.get(workspacesChangedChannel.name);- expect(notify, 'nothing subscribed to the workspaces-changed event').toBeDefined();- notify!(undefined);-}--describe('keeping up with the main process', () => {- /**- * The reconcile adds and matches rows without a window having asked — the- * boot sweep, and every sign-in. Nothing else would tell an open window, so a- * membership gained since the last launch would stay invisible for the whole- * session.- */- it('re-reads the list when the main process says it changed', async () => {- const store = await loaded([workspace('ws-a', 'srv-1')], 'ws-a');-- list.mockResolvedValue([workspace('ws-a', 'srv-1'), workspace('ws-b', 'srv-1')]);- announceChange();-- await vi.waitFor(() => expect(store.workspaces).toHaveLength(2));- });-- /**- * The sweep drops the placeholder a server was registered with once every- * membership has a row of its own. A window still listing it offers a- * workspace that is not there, and the only thing it can report on the click- * is that the switch failed — not that the row went.- */- it('drops a workspace the main process no longer has', async () => {- const store = await loaded([workspace('ws-a', 'srv-1'), workspace('ws-b', 'srv-1')], 'ws-a');-- list.mockResolvedValue([workspace('ws-b', 'srv-1')]);- getActiveId.mockResolvedValue('ws-b');- announceChange();-- await vi.waitFor(() => expect(store.byId('ws-a')).toBeNull());- expect(store.activeId).toBe('ws-b');- });-});--describe('what the window is scoped to', () => {- it('reads the server off the workspace rather than holding its own', async () => {- const store = await loaded([workspace('ws-a', 'srv-1'), workspace('ws-b', 'srv-2')], 'ws-b');-- expect(store.active?.id).toBe('ws-b');- expect(store.activeServerId).toBe('srv-2');- });-- // Every install has this moment: the list arrives before anything has chosen.- it('is scoped to nothing while no workspace is selected', async () => {- const store = await loaded([workspace('ws-a', 'srv-1')], null);-- expect(store.active).toBeNull();- expect(store.activeServerId).toBeNull();- });-- /**- * Removing a server takes its workspaces with it, leaving the stored- * selection naming one that is gone. Reading that as a selection would scope- * the window to a server that is no longer there.- */- it('is scoped to nothing when the selection names a workspace that has gone', async () => {- const store = await loaded([workspace('ws-a', 'srv-1')], 'ws-removed');-- expect(store.active).toBeNull();- expect(store.activeServerId).toBeNull();- });-- it('moves the scope when a workspace is chosen', async () => {- const store = await loaded([workspace('ws-a', 'srv-1'), workspace('ws-b', 'srv-1')], 'ws-a');-- await store.setActive('ws-b');-- expect(setActive).toHaveBeenCalledWith('ws-b');- expect(store.activeId).toBe('ws-b');- });-- /**- * A switch that failed quietly would leave the sidebar listing one- * workspace's rooms under another one's name — indistinguishable from the- * rooms having disappeared.- */- it('raises and stays put when the selection cannot be saved', async () => {- const store = await loaded([workspace('ws-a', 'srv-1'), workspace('ws-b', 'srv-1')], 'ws-a');- setActive.mockRejectedValue(new Error('database is locked'));-- await expect(store.setActive('ws-b')).rejects.toThrow('database is locked');- expect(store.activeId).toBe('ws-a');- });-});--describe('the workspace a server-routed view acts in', () => {- it('is the active one when the window is scoped to that server', async () => {- const store = await loaded(- [workspace('ws-a', 'srv-1'), workspace('ws-b', 'srv-1'), workspace('ws-c', 'srv-2')],- 'ws-b'- );-- expect(store.onServerInScope('srv-1')?.id).toBe('ws-b');- });-- // A server with one workspace has nothing to choose between, so a page for it- // works whether or not the window is scoped there.- it('falls back to the only workspace on another server', async () => {- const store = await loaded([workspace('ws-a', 'srv-1'), workspace('ws-c', 'srv-2')], 'ws-a');-- expect(store.onServerInScope('srv-2')?.id).toBe('ws-c');- });-- // Addressing the wrong one answers with somebody else's rooms while looking- // entirely correct, so the view has to render the absence instead.- it('answers nothing for another server with several workspaces', async () => {- const store = await loaded(- [workspace('ws-a', 'srv-1'), workspace('ws-b', 'srv-2'), workspace('ws-c', 'srv-2')],- 'ws-a'- );-- expect(store.onServerInScope('srv-2')).toBeNull();- expect(store.idOnServerInScope('srv-2')).toBeNull();- });-- it('answers nothing for a server whose registration left it with none', async () => {- const store = await loaded([workspace('ws-a', 'srv-1')], 'ws-a');-- expect(store.idOnServerInScope('srv-2')).toBeNull();- });-- // Every page routed by server reads this before its server is known.- it('answers nothing before a server has been chosen', async () => {- const store = await loaded([workspace('ws-a', 'srv-1')], 'ws-a');-- expect(store.idOnServerInScope(null)).toBeNull();- });-});diff --git a/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspaces-store.ts b/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspaces-store.tsdeleted file mode 100644index 71e3eebc1..000000000--- a/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspaces-store.ts+++ /dev/null@@ -1,152 +0,0 @@-import { makeAutoObservable, runInAction } from 'mobx';-import { events, rpc } from '@renderer/lib/ipc';-import { workspacesChangedChannel } from '@shared/core/workspaces/workspaceEvents';-import type { Workspace } from '@shared/core/workspaces/workspaces';--/**- * Renderer view of the workspaces this install knows about, and which one the- * window is scoped to.- *- * Everything that reads or writes what a workspace owns — rooms, agents,- * bridges, identities — is addressed by workspace id, so this is where a view- * holding a server or an agent gets the id to address it with. The server's own- * identity stays in the servers store: reachability, sign-in and the gateway- * URL are facts about a gateway, not about whose data it answers with.- *- * The selection is persisted by the main process, so this mirrors it rather- * than owning it — but the window is scoped to a workspace, so this is where- * the scope is read and changed, and the servers store derives its own notion- * of "which server" from it.- */-export class WorkspacesStore {- workspaces: Workspace[] = [];- activeId: string | null = null;- /** Ordinal of the most recent {@link setActive}; nothing renders it. */- lastSwitch = 0;-- constructor() {- makeAutoObservable(this, { lastSwitch: false });-- // The reconcile adds, matches and drops rows without a window asking, so- // the calls the servers store makes are not the only times this list moves.- // A membership gained or lost since the last launch would otherwise stay- // invisible until the next one, and a row the boot sweep deleted would go- // on being offered here after it had gone.- events.on(workspacesChangedChannel, () => {- void this.refresh();- });- }-- get active(): Workspace | null {- return this.workspaces.find((w) => w.id === this.activeId) ?? null;- }-- /**- * The server the window is scoped to, for the parts of the app still keyed by- * one.- *- * Derived rather than stored alongside the workspace: the server is simply- * the one hosting the selection, and the main process reads it back the same- * way, so the two cannot come to disagree about which server the app is on.- */- get activeServerId(): string | null {- return this.active?.serverId ?? null;- }-- /**- * Scope the window to a workspace.- *- * Raises if the selection does not take. The caller shows it: a switch that- * failed quietly would leave the sidebar listing one workspace's rooms under- * another one's name, which looks like data loss rather than a failed click.- *- * Only the last switch started may write the mirror. Two clicks in quick- * succession are two round trips that can finish in either order, and the- * slower one landing second would leave this pointing at a workspace the main- * process has already moved off — every read after it addressed under a name- * the window is no longer showing.- */- async setActive(workspaceId: string): Promise<void> {- const request = ++this.lastSwitch;- await rpc.workspaces.setActive(workspaceId);- if (request !== this.lastSwitch) return;- runInAction(() => {- this.activeId = workspaceId;- });- }-- /**- * Create a workspace on a server and return it.- *- * Refreshes before returning, so a caller that scopes the window to the new- * workspace is not doing it against a list that does not contain it yet.- * Failures propagate: the name may be refused for a slug already in use, and- * the form has to say so rather than appear to have worked.- */- async create(serverId: string, name: string): Promise<Workspace> {- const workspace = await rpc.switchServers.createWorkspace({ serverId, name });- await this.refresh();- return workspace;- }-- async refresh(): Promise<void> {- const [workspaces, activeId] = await Promise.all([- rpc.workspaces.list(),- rpc.workspaces.getActiveId(),- ]);- runInAction(() => {- this.workspaces = workspaces;- this.activeId = activeId;- });- }-- byId(workspaceId: string): Workspace | null {- return this.workspaces.find((w) => w.id === workspaceId) ?? null;- }-- /** The server hosting a workspace, or null while the list is not loaded. */- serverIdFor(workspaceId: string): string | null {- return this.byId(workspaceId)?.serverId ?? null;- }-- onServer(serverId: string): Workspace[] {- return this.workspaces.filter((w) => w.serverId === serverId);- }-- /**- * The workspace a view about a server acts in — its page, its cards, its- * pickers.- *- * The active one when the window is scoped to that server, which is the- * ordinary case: choosing a workspace in the switcher is how you reach its- * pages at all. A view about some other server falls back to its only- * workspace, since then there is nothing to choose.- *- * Null rather than a guess where neither applies. A server with no workspace- * has not finished registering; a server with several, none of them active,- * means the view is the one that has to say which, and addressing the wrong- * one answers with somebody else's rooms while looking entirely correct.- * Callers render the absence; they must not substitute the server id, which- * would reach the gateway and succeed.- */- onServerInScope(serverId: string | null): Workspace | null {- if (serverId === null) return null;- const active = this.active;- if (active?.serverId === serverId) return active;- const found = this.onServer(serverId);- return found.length === 1 ? found[0]! : null;- }-- /**- * {@link onServerInScope} as an id, for a view still routed by server.- *- * Null means "no workspace to act in yet", and a view must hold its reads and- * writes until it is not: the list arrives asynchronously, so this answers- * null on the first render of every such page.- */- idOnServerInScope(serverId: string | null): string | null {- return this.onServerInScope(serverId)?.id ?? null;- }-}--export const workspacesStore = new WorkspacesStore();diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/agent-picker.tsx b/console/apps/switch-console-desktop/src/renderer/lib/components/agent-picker.tsxindex e1570e126..38e8388d1 100644--- a/console/apps/switch-console-desktop/src/renderer/lib/components/agent-picker.tsx+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/agent-picker.tsx@@ -15,13 +15,9 @@ export type AgentPick = {* type an agent is, not what provider drives it here; an agent registered from* another Switch Console has no local record and reads as a plain "Agent".*/-export function agentProviderLabelFor(switchAgentId: string, workspaceId: string | null): string {+export function agentProviderLabelFor(switchAgentId: string, serverId: string): string {const local =- workspaceId === null- ? null- : (agentsStore- .agentsInWorkspace(workspaceId)- .find((a) => a.switchAgentId === switchAgentId) ?? null);+ agentsStore.agentsOnServer(serverId).find((a) => a.switchAgentId === switchAgentId) ?? null;return agentProviderLabel(local?.providerId);}diff --git a/console/apps/switch-console-desktop/src/renderer/lib/layout/scope-to-server.ts b/console/apps/switch-console-desktop/src/renderer/lib/layout/scope-to-server.tsnew file mode 100644index 000000000..fe047b200--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/lib/layout/scope-to-server.ts@@ -0,0 +1,42 @@+import { agentsStore } from '@renderer/features/locations/stores/agents-store';+import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';+import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';++/**+ * Make a target's Switch server the active one before navigating to it.+ *+ * The active server scopes the whole sidebar — `sidebarStore.isLocationInActiveScope`+ * and `switchRoomsStore.listedRoomsInActiveScope` both filter on it. Navigating+ * to something on another server without this opens the view but leaves the+ * sidebar showing a tree the target is not in, so the row you just opened is+ * nowhere to be seen.+ *+ * A no-op when the target is already on the active server, when its server+ * cannot be resolved (an unlinked location), or when no server is active.+ */+async function activateServer(serverId: string | null): Promise<void> {+ if (!serverId) return;+ if (switchServersStore.activeServerId === serverId) return;+ await switchServersStore.setActive(serverId);+}++/**+ * Scope to a server that shows `locationId` — for agents and sessions.+ *+ * A directory can hold agents for several servers, so there may be more than one+ * right answer. If the active server is already one of them there is nothing to do;+ * switching away would hide the row the caller is navigating to (CHOO-2044).+ */+export async function scopeToLocationServer(locationId: string): Promise<void> {+ if (!agentsStore.loaded) await agentsStore.load();+ const serverIds = agentsStore.serverIdsForLocation(locationId);+ if (serverIds.length === 0) return;+ const active = switchServersStore.activeServerId;+ if (active && serverIds.includes(active)) return;+ await activateServer(serverIds[0]);+}++/** Scope to the server owning `roomId`. */+export async function scopeToRoomServer(roomId: string): Promise<void> {+ await activateServer(switchRoomsStore.roomServerId(roomId));+}diff --git a/console/apps/switch-console-desktop/src/renderer/lib/layout/scope-to-workspace.ts b/console/apps/switch-console-desktop/src/renderer/lib/layout/scope-to-workspace.tsdeleted file mode 100644index 219acde55..000000000--- a/console/apps/switch-console-desktop/src/renderer/lib/layout/scope-to-workspace.ts+++ /dev/null@@ -1,44 +0,0 @@-import { agentsStore } from '@renderer/features/locations/stores/agents-store';-import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';-import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';--/**- * Make a target's workspace the active one before navigating to it.- *- * The active workspace scopes the whole sidebar — `sidebarStore.isLocationInActiveScope`- * and `switchRoomsStore.listedRoomsInActiveScope` both filter on it. Navigating- * to something in another workspace without this opens the view but leaves the- * sidebar showing a tree the target is not in, so the row you just opened is- * nowhere to be seen. Scoping to the *server* is not enough: its other workspace- * filters the target out just as surely as another server would.- *- * A no-op when the target is already in the active workspace, or when its- * workspace cannot be resolved (an unlinked location).- */-async function activateWorkspace(workspaceId: string | null): Promise<void> {- if (!workspaceId) return;- if (workspacesStore.activeId === workspaceId) return;- await workspacesStore.setActive(workspaceId);-}--/**- * Scope to a workspace that shows `locationId` — for agents and sessions.- *- * A directory can hold agents for several workspaces, so there may be more than- * one right answer. If the active workspace is already one of them there is- * nothing to do; switching away would hide the row the caller is navigating to- * (CHOO-2044).- */-export async function scopeToLocationWorkspace(locationId: string): Promise<void> {- if (!agentsStore.loaded) await agentsStore.load();- const workspaceIds = agentsStore.workspaceIdsForLocation(locationId);- if (workspaceIds.length === 0) return;- const active = workspacesStore.activeId;- if (active && workspaceIds.includes(active)) return;- await activateWorkspace(workspaceIds[0]!);-}--/** Scope to the workspace owning `roomId`. */-export async function scopeToRoomWorkspace(roomId: string): Promise<void> {- await activateWorkspace(switchRoomsStore.roomWorkspaceId(roomId));-}diff --git a/console/apps/switch-console-desktop/src/renderer/lib/stores/use-workspace-agents.ts b/console/apps/switch-console-desktop/src/renderer/lib/stores/use-remote-agents.tssimilarity index 55%rename from console/apps/switch-console-desktop/src/renderer/lib/stores/use-workspace-agents.tsrename to console/apps/switch-console-desktop/src/renderer/lib/stores/use-remote-agents.tsindex 8a1859a96..2b2b4798c 100644--- a/console/apps/switch-console-desktop/src/renderer/lib/stores/use-workspace-agents.ts+++ b/console/apps/switch-console-desktop/src/renderer/lib/stores/use-remote-agents.ts@@ -2,39 +2,39 @@ import { useQuery } from '@tanstack/react-query';import { rpc } from '@renderer/lib/ipc';import type { RemoteAgentSummary } from '@shared/core/switch-servers/switch-servers';-/** The agent list a workspace holds, keyed so every surface shares one fetch.+/** The agent list a server holds, keyed so every surface shares one fetch.* Several unrelated views ask for this at once — the sidebar rows, the room* panels, the agent page — and they must agree, so the key is defined once* here rather than retyped at each call site. */-export function workspaceAgentsQueryKey(workspaceId: string | null) {- return ['workspace-agents', workspaceId] as const;+export function remoteAgentsQueryKey(serverId: string | null) {+ return ['remote-agents', serverId] as const;}/**- * Every agent registered in `workspaceId`, or an idle query when there is no- * workspace to ask.+ * Every agent registered on `serverId`, or an idle query when there is no+ * server to ask.*/-export function useWorkspaceAgents(workspaceId: string | null) {+export function useRemoteAgents(serverId: string | null) {return useQuery<RemoteAgentSummary[]>({- queryKey: workspaceAgentsQueryKey(workspaceId),- queryFn: () => rpc.workspaces.listAgents(workspaceId as string),- enabled: workspaceId !== null,+ queryKey: remoteAgentsQueryKey(serverId),+ queryFn: () => rpc.switchServers.listRemoteAgents(serverId as string),+ enabled: serverId !== null,});}/**- * An agent's chosen icon, or null when it has none, is not in this workspace,- * or the list has not arrived yet.+ * An agent's chosen icon, or null when it has none, is not on this server, or+ * the list has not arrived yet.** Null is not an error and callers must not treat it as one: `AgentAvatar`* draws a bot from the agent's name instead, so a row renders the right* picture on first paint and simply sharpens to a custom icon if there is one.*/export function useAgentIconUrl(- workspaceId: string | null,+ serverId: string | null,switchAgentId: string | null): string | null {- const agents = useWorkspaceAgents(workspaceId);+ const agents = useRemoteAgents(serverId);if (switchAgentId === null) return null;return agents.data?.find((agent) => agent.id === switchAgentId)?.iconUrl ?? null;}diff --git a/console/apps/switch-console-desktop/src/renderer/lib/ui/step-pager.tsx b/console/apps/switch-console-desktop/src/renderer/lib/ui/step-pager.tsxdeleted file mode 100644index 85e8c1e1a..000000000--- a/console/apps/switch-console-desktop/src/renderer/lib/ui/step-pager.tsx+++ /dev/null@@ -1,67 +0,0 @@-import { ChevronLeft, ChevronRight } from 'lucide-react';-import { cn } from '@renderer/utils/utils';-import { Button } from './button';--/**- * The bar at the foot of a paged flow: which page you are on, and the way back- * or on from it.- *- * It names the page rather than counting it. A count is only honest once the- * sequence has a fixed length, and these flows branch — how many pages are left- * after "Add a server" depends on the answer given there — so a number would- * have to renumber itself halfway through.- *- * An arrow only repeats a move the page already offers — its Back, its Next.- * Where the way on is a button that installs a stack, signs you in or creates a- * server, the page passes a null `onNext`: a chevron whose whole label is "next"- * must not be the thing that commits you to any of those. The inert arrow stays- * on screen rather than disappearing, so the bar keeps its shape from page to- * page and the name does not shift under the eye.- *- * An inert arrow is `aria-disabled` rather than `disabled`, and says in its- * label why it leads nowhere. A chevron is already a control that explains- * nothing on sight; dropping it out of the tab order as well would leave the- * one place the reason is written unreachable by the people who most need it.- */-export function StepPager({- pageName,- onBack,- onNext,-}: {- pageName: string;- onBack: (() => void) | null;- onNext: (() => void) | null;-}) {- return (- <nav- aria-label="Pages in this flow"- className="flex shrink-0 items-center justify-center gap-4 border-t border-border bg-background-quaternary-1 px-3 py-1.5"- >- <Button- variant="ghost"- size="icon-xs"- aria-label={onBack === null ? 'Previous page — this is the first page' : 'Previous page'}- aria-disabled={onBack === null || undefined}- className={cn(onBack === null && 'opacity-50')}- onClick={onBack ?? undefined}- >- <ChevronLeft className="size-3.5" />- </Button>- <span aria-current="step" className="min-w-40 text-center text-xs text-foreground-muted">- {pageName}- </span>- <Button- variant="ghost"- size="icon-xs"- aria-label={- onNext === null ? 'Next page — use the button on this page to go on' : 'Next page'- }- aria-disabled={onNext === null || undefined}- className={cn(onNext === null && 'opacity-50')}- onClick={onNext ?? undefined}- >- <ChevronRight className="size-3.5" />- </Button>- </nav>- );-}diff --git a/console/apps/switch-console-desktop/src/renderer/lib/ui/wizard-frame.tsx b/console/apps/switch-console-desktop/src/renderer/lib/ui/wizard-frame.tsxdeleted file mode 100644index 52cf103c5..000000000--- a/console/apps/switch-console-desktop/src/renderer/lib/ui/wizard-frame.tsx+++ /dev/null@@ -1,124 +0,0 @@-import { createContext, useContext, type ReactNode } from 'react';-import { Button } from './button';-import { DialogContentArea, DialogFooter, DialogHeader, DialogTitle } from './dialog';-import { StepPager } from './step-pager';--/**- * Where a wizard page is being drawn: inside a dialog, or filling the window.- *- * The same pages serve both. Setting up a server is a dialog once you already- * have one and the whole window on a fresh install, where there is no app- * behind the dialog for it to sit on top of — but it is the same three- * questions either way, and a second copy of them would be a second place for- * the Docker check, the log tail and the sign-in form to drift.- */-export type WizardChrome = 'dialog' | 'page';--const WizardChromeContext = createContext<WizardChrome>('dialog');--/**- * The way out of a wizard that fills the window.- *- * A dialog has its own — Escape, the backdrop, a Cancel button — and something- * behind it to return to. A full-window wizard has neither, so a flow that can- * be left part-way has to say so in words on every page rather than relying on- * the user pressing Back until the window changes shape under them.- */-export type WizardExit = { label: string; onExit: () => void };--const WizardExitContext = createContext<WizardExit | null>(null);--export function WizardChromeProvider({- chrome,- exit,- children,-}: {- chrome: WizardChrome;- /** Null until there is something to leave behind — a flow that has registered- * nothing yet is left by finishing it or by stepping back off its first page. */- exit: WizardExit | null;- children: ReactNode;-}) {- return (- <WizardChromeContext.Provider value={chrome}>- <WizardExitContext.Provider value={exit}>{children}</WizardExitContext.Provider>- </WizardChromeContext.Provider>- );-}--/** The pager under a page, or null where the page is not part of a sequence. */-export type WizardPager = {- pageName: string;- onBack: (() => void) | null;- onNext: (() => void) | null;-};--/**- * One page of a wizard: its question, its body, what it offers at the foot.- *- * The page supplies no chrome of its own. A dialog's title bar and a full- * window's centred heading are the same title, and which one gets rendered is- * the frame's business rather than the page's.- */-export function WizardFrame({- title,- subtitle,- footer,- pager,- children,-}: {- title: string;- /** The line under the title, or null where the title says enough. */- subtitle: string | null;- /** Buttons for the foot of the page, in reading order, or null for a page- * whose only way on is the choice made in its body. */- footer: ReactNode | null;- pager: WizardPager | null;- children: ReactNode;-}) {- const chrome = useContext(WizardChromeContext);- const exit = useContext(WizardExitContext);-- if (chrome === 'dialog') {- return (- <>- <DialogHeader showCloseButton={false}>- <DialogTitle>{title}</DialogTitle>- </DialogHeader>- <DialogContentArea className="pt-0">- {subtitle && <p className="pb-2 text-sm text-foreground-muted">{subtitle}</p>}- {children}- </DialogContentArea>- {footer && <DialogFooter>{footer}</DialogFooter>}- {pager && <StepPager {...pager} />}- </>- );- }-- return (- <div className="flex h-full flex-col bg-background text-foreground [-webkit-app-region:drag]">- {exit && (- <div className="flex justify-end px-3 pt-3 [-webkit-app-region:no-drag]">- <Button variant="ghost" size="sm" onClick={exit.onExit}>- {exit.label}- </Button>- </div>- )}- <div className="flex min-h-0 flex-1 flex-col overflow-auto">- <div className="mx-auto flex w-full max-w-xl flex-1 flex-col justify-center gap-6 px-8 py-10 [-webkit-app-region:no-drag]">- <div className="flex flex-col items-center gap-2 text-center">- <h1 className="text-2xl font-semibold">{title}</h1>- {subtitle && <p className="text-sm text-foreground-muted">{subtitle}</p>}- </div>- {children}- {footer && <div className="flex gap-2">{footer}</div>}- </div>- </div>- {pager && (- <div className="[-webkit-app-region:no-drag]">- <StepPager {...pager} />- </div>- )}- </div>- );-}diff --git a/console/apps/switch-console-desktop/src/renderer/lib/ui/wizard-step-header.tsx b/console/apps/switch-console-desktop/src/renderer/lib/ui/wizard-step-header.tsxnew file mode 100644index 000000000..61c2c4a9c--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/lib/ui/wizard-step-header.tsx@@ -0,0 +1,19 @@+import { DialogHeader, DialogTitle } from './dialog';++/**+ * A dialog header that says where in a sequence you are.+ *+ * The count is only honest once the sequence has a fixed length, so a step that+ * might or might not be reached must not be counted — a wizard that renumbers+ * itself halfway through is worse than one that never numbered itself at all.+ */+export function WizardStepHeader({ title, step, of }: { title: string; step: number; of: number }) {+ return (+ <DialogHeader className="flex-col items-start gap-1">+ <DialogTitle>{title}</DialogTitle>+ <p className="text-xs text-foreground-muted">+ Step {step} of {of}+ </p>+ </DialogHeader>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/add-agent-settings-disclosure.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/add-agent-settings-disclosure.test.tsxindex 7d90e5d75..8b46dc958 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/add-agent-settings-disclosure.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/add-agent-settings-disclosure.test.tsx@@ -31,12 +31,12 @@ vi.hoisted(() => {vi.mock('@renderer/lib/ipc', () => ({events: { on: vi.fn() },rpc: {- workspaces: {- listRooms: () => Promise.resolve([]),- listRoomGroups: () => Promise.resolve([]),- listExternalUsers: () => Promise.resolve([]),- listAgents: () => Promise.resolve([]),- listBridges: () => Promise.resolve(remote.bridges),+ switchServers: {+ listRemoteRooms: () => Promise.resolve([]),+ listRemoteRoomGroups: () => Promise.resolve([]),+ listRemoteExternalUsers: () => Promise.resolve([]),+ listRemoteAgents: () => Promise.resolve([]),+ listRemoteBridges: () => Promise.resolve(remote.bridges),listMyIdentities: () => Promise.resolve(remote.identities),},},@@ -72,7 +72,7 @@ function Panel() {return (<AgentSettingsSectionform={form}- workspaceId="ws-1"+ serverId="srv-1"onAddServer={() => {}}onOpenMessagingApps={() => {}}/>diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/create-workspace-modal.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/create-workspace-modal.test.tsxdeleted file mode 100644index ba243866c..000000000--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/create-workspace-modal.test.tsx+++ /dev/null@@ -1,369 +0,0 @@-/**- * Making a workspace from the switcher.- *- * A workspace belongs to a server, so what this has to get right is which one:- * the question is only asked where there is a choice, and a server that cannot- * be asked at all is said to be so rather than allowed to fail on Create.- */-import { act } from 'react';-import { createRoot, type Root } from 'react-dom/client';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--const create = vi.hoisted(() => vi.fn());-const setActiveWorkspace = vi.hoisted(() => vi.fn());-const connected = vi.hoisted(() => new Set<string>());-/** Ids a status read has answered for. Not asked yet is its own state. */-const statuses = vi.hoisted(() => new Map<string, unknown>());-const unreachable = vi.hoisted(() => new Set<string>());-const refreshStatus = vi.hoisted(() => vi.fn());-const servers = vi.hoisted(() => [] as { id: string; name: string }[]);--vi.hoisted(() => {- window.electronAPI ??= {- invoke: () => Promise.resolve(undefined),- eventOn: () => () => {},- eventSend: () => {},- } as unknown as typeof window.electronAPI;-});--vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({- switchServersStore: {- get servers() {- return servers;- },- statuses,- isConnected: (id: string) => connected.has(id),- isUnreachable: (id: string) => unreachable.has(id),- refreshStatus,- serverById: (id: string) => servers.find((s) => s.id === id) ?? null,- },-}));--vi.mock('@renderer/features/workspaces/workspaces-store', () => ({- workspacesStore: { create, setActive: setActiveWorkspace },-}));--import { CreateWorkspaceModal } from '@renderer/features/workspaces/create-workspace-modal';-import { modalStore } from '@renderer/lib/modal/modal-store';-import { Dialog } from '@renderer/lib/ui/dialog';-import { RpcError } from '@shared/lib/ipc/rpc-error';--let container: HTMLDivElement | null = null;-let root: Root | null = null;--const onSuccess = vi.fn();-const onClose = vi.fn();--function workspace(id: string, serverId: string) {- return {- id,- serverId,- name: 'Weekend Robotics',- tenantId: 't1',- slug: 'weekend-robotics',- role: 'owner' as const,- createdAt: '',- updatedAt: '',- };-}--beforeEach(() => {- create.mockReset();- setActiveWorkspace.mockReset().mockResolvedValue(undefined);- refreshStatus.mockReset();- onSuccess.mockReset();- onClose.mockReset();- servers.length = 0;- connected.clear();- statuses.clear();- unreachable.clear();- modalStore.closeGuardActive = false;-});--/**- * A server the app knows about, in one of the four states the modal tells- * apart.- *- * `unknown` is the one that is not a failure: no status read has answered for- * it yet, which is a different thing from having answered "not signed in".- */-function addServer(- id: string,- name: string,- state: 'signedIn' | 'signedOut' | 'unreachable' | 'unknown'-) {- servers.push({ id, name });- if (state === 'unknown') return;- statuses.set(id, { serverId: id, connected: state === 'signedIn', user: null });- if (state === 'signedIn') connected.add(id);- if (state === 'unreachable') unreachable.add(id);-}--function deferred<T>() {- let resolve!: (value: T) => void;- let reject!: (cause: unknown) => void;- const promise = new Promise<T>((res, rej) => {- resolve = res;- reject = rej;- });- return { promise, resolve, reject };-}--afterEach(async () => {- if (root) await act(async () => root!.unmount());- container?.remove();- container = null;- root = null;-});--async function render(serverId: string): Promise<HTMLDivElement> {- container = document.createElement('div');- document.body.appendChild(container);- root = createRoot(container);- // The modal renders the dialog's parts and not the dialog itself — the- // registry supplies that in the app, and this supplies it here.- await act(async () =>- root!.render(- <Dialog open onOpenChange={() => {}}>- <CreateWorkspaceModal serverId={serverId} onSuccess={onSuccess} onClose={onClose} />- </Dialog>- )- );- return container;-}--async function settle(): Promise<void> {- for (let i = 0; i < 8; i++) await act(async () => await Promise.resolve());-}--/** By substring: the confirm button carries its keyboard shortcut in its text. */-function button(el: HTMLElement, label: string): HTMLButtonElement {- const found = [...el.querySelectorAll<HTMLButtonElement>('button')].find((b) =>- b.textContent?.includes(label)- );- expect(found, `no ${label} button`).toBeDefined();- return found!;-}--async function typeName(el: HTMLElement, value: string): Promise<void> {- const input = el.querySelector('input')!;- const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;- await act(async () => {- setter.call(input, value);- input.dispatchEvent(new Event('input', { bubbles: true }));- });-}--/** A label that is present in the dialog, ignoring the select's own portal. */-function hasLabel(el: HTMLElement, text: string): boolean {- return [...el.querySelectorAll('label')].some((l) => l.textContent?.trim() === text);-}--describe('the create-workspace modal', () => {- it('creates on the server the window is in, and goes there', async () => {- addServer('srv-1', 'Acme prod', 'signedIn');- const made = workspace('ws-9', 'srv-1');- create.mockResolvedValue(made);-- const el = await render('srv-1');- await typeName(el, ' Weekend Robotics ');- await act(async () => button(el, 'Create workspace').click());- await settle();-- expect(create).toHaveBeenCalledWith('srv-1', 'Weekend Robotics');- expect(setActiveWorkspace).toHaveBeenCalledWith('ws-9');- expect(onSuccess).toHaveBeenCalledWith(made);- });-- it('does not ask which server when there is only one to ask about', async () => {- addServer('srv-1', 'Acme prod', 'signedIn');-- const el = await render('srv-1');-- expect(hasLabel(el, 'Server')).toBe(false);- expect(el.textContent).toContain('Acme prod');- });-- it('asks which server once there are two you are signed in to', async () => {- addServer('srv-1', 'Acme prod', 'signedIn');- addServer('srv-2', 'Acme staging', 'signedIn');-- const el = await render('srv-1');-- expect(hasLabel(el, 'Server')).toBe(true);- });-- // The failure would otherwise arrive as an authentication error on Create,- // which reads as the name being refused.- it('refuses to ask a server you are not signed in to', async () => {- addServer('srv-1', 'Acme prod', 'signedOut');-- const el = await render('srv-1');- await typeName(el, 'Weekend Robotics');-- expect(el.textContent).toContain('not signed in to Acme prod');- expect(button(el, 'Create workspace').disabled).toBe(true);- });-- it('will not create a workspace with no name', async () => {- addServer('srv-1', 'Acme prod', 'signedIn');-- const el = await render('srv-1');- await typeName(el, ' ');-- expect(button(el, 'Create workspace').disabled).toBe(true);- });-- it('keeps the form and says why when the server refuses the name', async () => {- addServer('srv-1', 'Acme prod', 'signedIn');- create.mockRejectedValue(new Error('A workspace with that name already exists.'));-- const el = await render('srv-1');- await typeName(el, 'Weekend Robotics');- await act(async () => button(el, 'Create workspace').click());- await settle();-- expect(el.textContent).toContain('already exists');- expect(onSuccess).not.toHaveBeenCalled();- expect(button(el, 'Create workspace').disabled).toBe(false);- });-- /**- * The refusal the gateway actually sends, rather than a plain Error. Its- * words are `Slug already taken: weekend-robotics` — no terminal punctuation,- * so the shared description does not read it as a sentence and demotes it to- * diagnostics. What reached the user was a status code and a slug they never- * typed, for the likeliest failure of this form and the only one they can fix.- */- it('blames the name for a name conflict, not the status code and the slug', async () => {- addServer('srv-1', 'Acme prod', 'signedIn');- create.mockRejectedValue(- new RpcError({- __switchConsoleRpcError: true,- code: 'GatewayError',- message: 'Gateway returned 409: Slug already taken: weekend-robotics',- data: { kind: 'http', status: 409, detail: 'Slug already taken: weekend-robotics' },- } as unknown as ConstructorParameters<typeof RpcError>[0])- );-- const el = await render('srv-1');- await typeName(el, 'Weekend Robotics');- await act(async () => button(el, 'Create workspace').click());- await settle();-- expect(el.textContent).toContain('already goes by that name');- expect(el.textContent).not.toContain('weekend-robotics');- expect(el.textContent).not.toContain('409');- // Still typeable: a different name is the whole of the remedy.- expect(el.querySelector('input')!.disabled).toBe(false);- });-- /**- * "Not signed in" and "cannot be reached" want different things from the- * user, and only one of them is a password. Sending someone to re-authenticate- * for a network outage is the same misattribution this modal exists to avoid,- * pointing the other way.- */- it('says a server is unreachable rather than telling you to sign in again', async () => {- addServer('srv-1', 'Acme prod', 'unreachable');-- const el = await render('srv-1');-- expect(el.textContent).toContain('can’t be reached');- expect(el.textContent).not.toContain('not signed in');- });-- it('does not claim you are signed out before it has looked', async () => {- addServer('srv-1', 'Acme prod', 'unknown');-- const el = await render('srv-1');-- expect(el.textContent).toContain('Checking whether you’re signed in');- expect(el.textContent).not.toContain('not signed in to');- // Nothing else on screen is watching this server, so the modal has to ask- // or the sentence above is what it says forever.- expect(refreshStatus).toHaveBeenCalledWith('srv-1');- });-- /**- * The hidden default was the window's own server, which may be the one that- * cannot be asked — leaving Create permanently off with the usable server- * offered nowhere.- */- it('opens on a server it can ask when the window’s own cannot be', async () => {- addServer('srv-1', 'Acme prod', 'signedOut');- addServer('srv-2', 'Acme staging', 'signedIn');- create.mockResolvedValue(workspace('ws-9', 'srv-2'));-- const el = await render('srv-1');- await typeName(el, 'Weekend Robotics');- await act(async () => button(el, 'Create workspace').click());- await settle();-- expect(el.textContent).toContain('Acme staging');- expect(create).toHaveBeenCalledWith('srv-2', 'Weekend Robotics');- });-- /**- * `dismissOnOutsideClick: false` stops the backdrop but not Escape, so- * without the guard a keypress mid-create leaves the window re-scoped and- * `onSuccess` firing on a modal the user believed they had cancelled.- */- it('holds itself shut while the create is in flight', async () => {- addServer('srv-1', 'Acme prod', 'signedIn');- const creating = deferred<ReturnType<typeof workspace>>();- create.mockReturnValue(creating.promise);-- const el = await render('srv-1');- await typeName(el, 'Weekend Robotics');- await act(async () => button(el, 'Create workspace').click());-- expect(modalStore.closeGuardActive).toBe(true);-- creating.resolve(workspace('ws-9', 'srv-1'));- await settle();-- expect(modalStore.closeGuardActive).toBe(false);- });-- /**- * The workspace exists on the server from the moment Create returns.- * Offering Create again would send the same name back and earn a conflict- * that reads as the name being refused — on the first-run page with no way- * back, that is the end of the road.- */- it('offers to open the workspace it already made rather than creating it twice', async () => {- addServer('srv-1', 'Acme prod', 'signedIn');- create.mockResolvedValue(workspace('ws-9', 'srv-1'));- setActiveWorkspace.mockRejectedValueOnce(new Error('could not switch'));-- const el = await render('srv-1');- await typeName(el, 'Weekend Robotics');- await act(async () => button(el, 'Create workspace').click());- await settle();-- expect(el.textContent).toContain('could not be moved into it');-- await act(async () => button(el, 'Open workspace').click());- await settle();-- expect(create).toHaveBeenCalledTimes(1);- expect(onSuccess).toHaveBeenCalledWith(expect.objectContaining({ id: 'ws-9' }));- });-- // Creating it and then leaving the window in the old workspace would look- // like nothing happened, so a switch that fails is not reported as success.- it('does not report success when the new workspace cannot be entered', async () => {- addServer('srv-1', 'Acme prod', 'signedIn');- create.mockResolvedValue(workspace('ws-9', 'srv-1'));- setActiveWorkspace.mockRejectedValue(new Error('could not switch'));-- const el = await render('srv-1');- await typeName(el, 'Weekend Robotics');- await act(async () => button(el, 'Create workspace').click());- await settle();-- expect(onSuccess).not.toHaveBeenCalled();- expect(el.textContent).toContain('could not switch');- });-});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/messaging-app-row.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/messaging-app-row.test.tsxindex 430ecf91b..b5acc042d 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/messaging-app-row.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/messaging-app-row.test.tsx@@ -79,7 +79,6 @@ function row() {return (<MessagingAppRow- workspaceId="ws-1"serverId="srv-1"bridge={overrides.bridge ?? bridge()}identities={overrides.identities === undefined ? [] : overrides.identities}diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/onboarding-flow.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/onboarding-flow.test.tsxdeleted file mode 100644index 9995ef23b..000000000--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/onboarding-flow.test.tsx+++ /dev/null@@ -1,395 +0,0 @@-/**- * The path a fresh install takes to its first server.- *- * The flow is the add-server wizard drawn full window, so what is worth testing- * is not the wizard again but the joins: that the welcome page leads into the- * question rather than a dialog, that each page can be backed out of, and that- * the one thing the first-run form does differently — not asking for a name —- * still produces a server with a name on it.- */-import { act } from 'react';-import { createRoot, type Root } from 'react-dom/client';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--const addServer = vi.hoisted(() => vi.fn());-const setActive = vi.hoisted(() => vi.fn());-const navigate = vi.hoisted(() => vi.fn());-const listHosts = vi.hoisted(() => vi.fn());-const servers = vi.hoisted(() => [] as { id: string; name: string }[]);--vi.hoisted(() => {- window.electronAPI ??= {- invoke: () => Promise.resolve(undefined),- eventOn: () => () => {},- eventSend: () => {},- } as unknown as typeof window.electronAPI;-});--vi.mock('@renderer/lib/ipc', () => ({- events: { on: () => () => {} },- rpc: { remoteHosts: { listHosts } },-}));--vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({- switchServersStore: {- addServer,- setActive,- serverById: (id: string | null) => servers.find((s) => s.id === id) ?? null,- errorText: null,- ensureAuthConfig: () => Promise.resolve(),- authConfigFor: () => ({- passwordLoginEnabled: true,- oidcEnabled: false,- oidcProviderLabel: null,- }),- authConfigCheckFailed: () => false,- authConfigChecking: () => false,- passwordLogin: () => Promise.resolve(true),- oidcLogin: () => Promise.resolve(true),- },-}));--vi.mock('@renderer/lib/layout/navigation-provider', () => ({- useNavigate: () => ({ navigate }),-}));--/**- * The local-server supervisor as the page sees it. Stands in for the real- * singleton so a test can put the page in the middle of an install without a- * Docker daemon anywhere near it.- */-const localServer = vi.hoisted(() => ({- status: null as { serverId: string | null; version: string } | null,- docker: { available: true } as { available: boolean } | null,- isRunning: false,- isTransitioning: false,- phase: 'stopped',- message: null as string | null,- error: null as string | null,- errorDetail: null as string | null,- logs: [] as string[],- init: vi.fn(() => Promise.resolve()),- checkDocker: vi.fn(() => Promise.resolve()),- start: vi.fn(),-}));--vi.mock('@renderer/features/switch-servers/local-server-store', () => ({- localServerStore: localServer,-}));--vi.mock('@renderer/lib/telemetry/report', () => ({ report: vi.fn() }));--import { OnboardingFlow } from '@renderer/features/onboarding/onboarding-flow';-import { onboardingStore } from '@renderer/features/onboarding/onboarding-store';--let container: HTMLDivElement | null = null;-let root: Root | null = null;--beforeEach(() => {- addServer.mockReset();- setActive.mockReset();- navigate.mockReset();- listHosts.mockReset();- listHosts.mockResolvedValue([]);- servers.length = 0;- onboardingStore.reset();- Object.assign(localServer, {- status: null,- docker: { available: true },- isRunning: false,- isTransitioning: false,- phase: 'stopped',- message: null,- error: null,- errorDetail: null,- logs: [],- });-});--/** Register a server the way the connect page does, list and all. */-function serverAdded(id: string) {- const server = {- id,- name: 'switch.example.com',- gatewayUrl: 'https://switch.example.com',- apiUrl: 'https://switch.example.com:8000',- };- servers.push(server);- addServer.mockResolvedValue(server);- return server;-}--/** Walk the connect page to the point where the server exists. */-async function addFromConnectPage(el: HTMLElement) {- await act(async () => button(el, 'Continue with your own server').click());- await choose(el, "It's already running");- await type(field(el, 'Gateway URL')!, 'https://switch.example.com');- await type(field(el, 'API URL')!, 'https://switch.example.com:8000');- await choose(el, 'Sign in to this server');-}--afterEach(async () => {- if (root) await act(async () => root!.unmount());- container?.remove();- container = null;- root = null;-});--async function renderFlow(): Promise<HTMLDivElement> {- container = document.createElement('div');- document.body.appendChild(container);- root = createRoot(container);- await act(async () => root!.render(<OnboardingFlow />));- return container;-}--function button(el: HTMLElement, label: string): HTMLButtonElement {- const found = [...el.querySelectorAll<HTMLButtonElement>('button')].find(- (b) => b.textContent?.trim() === label- );- expect(found, `no ${label} button`).toBeDefined();- return found!;-}--/** Every button's label, for asserting that one is not among them. */-function labels(el: HTMLElement): (string | null)[] {- return [...el.querySelectorAll('button')].map((b) => b.textContent);-}--/** A card or button whose text contains this, wherever it sits in the page. */-async function choose(el: HTMLElement, text: string): Promise<void> {- const found = [...el.querySelectorAll<HTMLButtonElement>('button')].find((b) =>- b.textContent?.includes(text)- );- expect(found, `nothing to click named ${text}`).toBeDefined();- await act(async () => found!.click());-}--function field(el: HTMLElement, label: string): HTMLInputElement | null {- const labels = [...el.querySelectorAll<HTMLElement>('label')];- const match = labels.find((l) => l.textContent?.trim() === label);- if (!match) return null;- const input = match.parentElement?.querySelector('input');- expect(input, `no input under ${label}`).not.toBeNull();- return input as HTMLInputElement;-}--async function type(input: HTMLInputElement, value: string): Promise<void> {- const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;- await act(async () => {- setter.call(input, value);- input.dispatchEvent(new Event('input', { bubbles: true }));- });-}--describe('the first-run flow', () => {- it('asks who runs the server once you continue past the welcome', async () => {- const el = await renderFlow();-- await act(async () => button(el, 'Continue with your own server').click());-- expect(el.textContent).toContain('Who runs the server?');- expect(el.textContent).toContain('Set it up for me');- expect(el.textContent).toContain("It's already running");- });-- it('leaves the managed host path out when there is no host to offer', async () => {- // A fresh install has onboarded none, and the card would lead to an empty- // list every time it was taken.- const el = await renderFlow();-- await act(async () => button(el, 'Continue with your own server').click());-- expect(el.textContent).not.toContain('one of my hosts');- });-- it('offers the managed host path once a host exists', async () => {- // Onboarding a host needs no server, so someone who deleted their last- // server arrives here with hosts already set up — and this is the only- // place the managed path can be reached from.- listHosts.mockResolvedValue([{ sshHost: 'build-box' }]);- const el = await renderFlow();-- await act(async () => button(el, 'Continue with your own server').click());-- expect(el.textContent).toContain('one of my hosts');- });-- it('paints no cards until it knows whether there are hosts to offer', async () => {- // The set waits as a whole. Painting two and inserting a third between them- // a round trip later moves the answer out from under a cursor already on- // its way to one.- let answer!: (list: { sshHost: string }[]) => void;- listHosts.mockReturnValue(- new Promise<{ sshHost: string }[]>((resolve) => {- answer = resolve;- })- );- const el = await renderFlow();-- await act(async () => button(el, 'Continue with your own server').click());-- expect(el.textContent).toContain('Looking for onboarded hosts');- expect(el.textContent).not.toContain('Set it up for me');-- await act(async () => answer([{ sshHost: 'build-box' }]));-- expect(el.textContent).toContain('Set it up for me');- expect(el.textContent).toContain('one of my hosts');- });-- it('says the host check failed instead of reporting no hosts', async () => {- // A read that never answered is not an empty list. Reading it as one hides- // a path the user has already set up, and says nothing about why.- listHosts.mockRejectedValue(new Error('could not read the ssh config'));- const el = await renderFlow();-- await act(async () => button(el, 'Continue with your own server').click());-- expect(el.textContent).toContain('Could not check for onboarded hosts');- expect(el.textContent).not.toContain('one of my hosts');- // The two paths that need no such check are still offered: not knowing- // about hosts is no reason to hold the whole question hostage.- expect(el.textContent).toContain('Set it up for me');- expect(el.textContent).toContain("It's already running");- });-- it('offers the host path when a retry of the check answers', async () => {- listHosts.mockRejectedValueOnce(new Error('could not read the ssh config'));- const el = await renderFlow();- await act(async () => button(el, 'Continue with your own server').click());-- listHosts.mockResolvedValue([{ sshHost: 'build-box' }]);- await act(async () => button(el, 'Try again').click());-- expect(el.textContent).toContain('one of my hosts');- });-- it('can be left while the local stack is installing, and says so', async () => {- // A first run pulls a few gigabytes. Full window, with Back shut and the- // primary disabled, that was minutes of a page with no live control at all- // — while the same page in the dialog could still be dismissed.- localServer.isTransitioning = true;- localServer.phase = 'starting';- localServer.message = 'Pulling images…';- const el = await renderFlow();- await act(async () => button(el, 'Continue with your own server').click());- await choose(el, 'Set it up for me');-- expect(button(el, 'Back').disabled).toBe(false);- expect(el.textContent).toContain('keeps running if you leave the page');-- await act(async () => button(el, 'Back').click());-- expect(el.textContent).toContain('Who runs the server?');- });-- it('goes back from the question to the welcome, by a button and not only a chevron', async () => {- // The chevron is unlabelled, so it may repeat the way back but never be the- // only one.- const el = await renderFlow();-- await act(async () => button(el, 'Continue with your own server').click());- await act(async () => button(el, 'Back').click());-- expect(el.textContent).toContain('Welcome to Switch');- });-- it('asks for the addresses, and not for a name, on the connect page', async () => {- // Someone connecting their only server has nothing to tell it apart from,- // so the field is a question asked for the list's benefit rather than- // theirs.- const el = await renderFlow();-- await act(async () => button(el, 'Continue with your own server').click());- await choose(el, "It's already running");-- expect(el.textContent).toContain('Connect to your server');- expect(field(el, 'Gateway URL')).not.toBeNull();- expect(field(el, 'API URL')).not.toBeNull();- expect(field(el, 'Name')).toBeNull();- });-- it('names the server after its gateway, having never asked', async () => {- // The page that skips the question still has to produce a name: an- // unnamed row in the sidebar would be the cost of the shortcut.- serverAdded('srv-1');- const el = await renderFlow();-- await addFromConnectPage(el);-- expect(addServer).toHaveBeenCalledWith(- 'switch.example.com',- 'https://switch.example.com',- 'https://switch.example.com:8000'- );- });-- it('keeps the flow on screen after the server is added, for the sign-in still to come', async () => {- // The server exists from here on, which is exactly when the window would- // otherwise decide onboarding is over and take the remaining pages away.- serverAdded('srv-1');- const el = await renderFlow();-- await addFromConnectPage(el);-- expect(onboardingStore.inProgress).toBe(true);- expect(onboardingStore.page).toBe('signIn');- });-- it('offers a way out by name once the server exists', async () => {- // Sign-in can fail for good — a server that is down, a password that is- // refused — and pressing Back until the window changes shape is not an- // exit anyone finds.- serverAdded('srv-1');- const el = await renderFlow();-- await addFromConnectPage(el);- await act(async () => button(el, 'Finish later').click());-- expect(onboardingStore.inProgress).toBe(false);- expect(navigate).toHaveBeenCalledWith('server', { serverId: 'srv-1' });- });-- it('offers nothing to finish later before a server has been registered', async () => {- const el = await renderFlow();-- await act(async () => button(el, 'Continue with your own server').click());-- expect([...el.querySelectorAll('button')].map((b) => b.textContent)).not.toContain(- 'Finish later'- );- });-- it('offers no way out to a server the page on screen did not set up', async () => {- // Connect to one, walk back, take the local path instead: the exit read a- // single remembered server, so it still pointed at the abandoned attempt —- // and pressing it left for a server this page had nothing to do with.- serverAdded('srv-1');- const el = await renderFlow();- await addFromConnectPage(el);- expect(labels(el)).toContain('Finish later');-- await act(async () => button(el, 'Back').click());- await act(async () => button(el, 'Back').click());- await choose(el, 'Set it up for me');-- expect(el.textContent).toContain('Set up a server on this computer');- expect(labels(el)).not.toContain('Finish later');- });-- it('forgets a server it registered when the user walks back to the start', async () => {- // Everything after the connect page edits that row, and the user is free to- // delete it the moment it exists — the window is the workspace again for- // anything that does not need a server. A remembered id would aim the next- // attempt's save at a row that is gone.- serverAdded('srv-1');- const el = await renderFlow();-- await addFromConnectPage(el);- onboardingStore.goTo('welcome');-- expect(onboardingStore.server).toBeNull();- expect(el).toBeDefined();- });-});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.tsxdeleted file mode 100644index 9fcab9ad5..000000000--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/onboarding-workspaces.test.tsx+++ /dev/null@@ -1,316 +0,0 @@-/**- * Choosing a workspace on a server you have just signed in to.- *- * The interesting behaviour is not the list — it is what the pages do with the- * three answers the server can give. None, one and several each lead somewhere- * different, being asked and failing is not the same as being asked and told- * "none", and the sections the server cannot answer for at all are absent- * rather than drawn empty.- */-import { QueryClient, QueryClientProvider } from '@tanstack/react-query';-import { act } from 'react';-import { createRoot, type Root } from 'react-dom/client';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--const resolveWorkspaces = vi.hoisted(() => vi.fn());-const createWorkspace = vi.hoisted(() => vi.fn());-const setActiveWorkspace = vi.hoisted(() => vi.fn());--vi.hoisted(() => {- window.electronAPI ??= {- invoke: () => Promise.resolve(undefined),- eventOn: () => () => {},- eventSend: () => {},- } as unknown as typeof window.electronAPI;-});--vi.mock('@renderer/lib/ipc', () => ({- rpc: { switchServers: { resolveWorkspaces } },- events: { on: () => () => {}, emit: () => {} },-}));--vi.mock('@renderer/features/workspaces/workspaces-store', () => ({- workspacesStore: {- setActive: setActiveWorkspace,- create: createWorkspace,- idOnServerInScope: () => 'ws-1',- },-}));--const SERVER = vi.hoisted(() => ({- id: 'srv-1',- name: 'switch.example.com',- gatewayUrl: 'https://switch.example.com',- apiUrl: 'https://switch.example.com:8000',-}));--vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({- switchServersStore: {- setActive: vi.fn(),- errorText: null,- serverById: (id: string | null) => (id === SERVER.id ? SERVER : null),- // Stepping back off the picker draws the sign-in page, which reads these.- ensureAuthConfig: () => Promise.resolve(),- authConfigFor: () => ({- passwordLoginEnabled: true,- oidcEnabled: false,- oidcProviderLabel: null,- }),- authConfigCheckFailed: () => false,- authConfigChecking: () => false,- passwordLogin: () => Promise.resolve(true),- oidcLogin: () => Promise.resolve(true),- },-}));--// The last page of the flow, and not what these tests are about — stubbed so-// reaching it is a fact the test can assert without dragging in the bridge-// reads behind it.-vi.mock('@renderer/features/switch-servers/link-accounts-step', () => ({- LinkAccountsStep: () => <div>Link your messaging accounts</div>,-}));--vi.mock('@renderer/lib/layout/navigation-provider', () => ({- useNavigate: () => ({ navigate: vi.fn() }),-}));--vi.mock('@renderer/lib/telemetry/report', () => ({ report: vi.fn() }));--import { OnboardingFlow } from '@renderer/features/onboarding/onboarding-flow';-import { onboardingStore } from '@renderer/features/onboarding/onboarding-store';--function workspace(id: string, name: string) {- return {- id,- serverId: 'srv-1',- name,- tenantId: `tenant-${id}`,- slug: name.toLowerCase(),- role: 'member' as const,- createdAt: '2026-01-01T00:00:00Z',- updatedAt: '2026-01-01T00:00:00Z',- };-}--let container: HTMLDivElement | null = null;-let root: Root | null = null;--beforeEach(() => {- resolveWorkspaces.mockReset();- createWorkspace.mockReset();- setActiveWorkspace.mockReset().mockResolvedValue(undefined);- onboardingStore.reset();-});--afterEach(async () => {- if (root) await act(async () => root!.unmount());- container?.remove();- container = null;- root = null;-});--/** The flow, opened at the page that follows a successful sign-in. */-async function renderAtPickWorkspace(): Promise<HTMLDivElement> {- onboardingStore.connected(SERVER as never);- onboardingStore.goTo('pickWorkspace');-- container = document.createElement('div');- document.body.appendChild(container);- root = createRoot(container);- const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });- await act(async () =>- root!.render(- <QueryClientProvider client={client}>- <OnboardingFlow />- </QueryClientProvider>- )- );- await settle();- return container;-}--function deferred<T>() {- let resolve!: (value: T) => void;- const promise = new Promise<T>((res) => {- resolve = res;- });- return { promise, resolve };-}--async function settle(): Promise<void> {- for (let i = 0; i < 8; i++) await act(async () => await Promise.resolve());-}--async function click(el: HTMLElement, text: string): Promise<void> {- const found = [...el.querySelectorAll<HTMLButtonElement>('button')].find((b) =>- b.textContent?.includes(text)- );- expect(found, `nothing to click named ${text}`).toBeDefined();- await act(async () => found!.click());- await settle();-}--async function typeName(el: HTMLElement, value: string): Promise<void> {- const input = el.querySelector('input');- expect(input, 'no name field').not.toBeNull();- const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;- await act(async () => {- setter.call(input, value);- input!.dispatchEvent(new Event('input', { bubbles: true }));- });-}--describe('picking a workspace after signing in', () => {- it('lists the workspaces the account is a member of', async () => {- resolveWorkspaces.mockResolvedValue([- workspace('ws-1', 'Acme'),- workspace('ws-2', 'Skunkworks'),- ]);-- const el = await renderAtPickWorkspace();-- expect(resolveWorkspaces).toHaveBeenCalledWith('srv-1');- expect(el.textContent).toContain('Pick a workspace');- expect(el.textContent).toContain('Acme');- expect(el.textContent).toContain('Skunkworks');- expect(el.textContent).toContain('Create a new workspace');- });-- it('leaves out the join and invite rows the server cannot answer for', async () => {- // The design offers workspaces open to you by email domain, and invitations- // waiting for your address. A Switch server records neither, so an empty- // section would be a claim it never made.- resolveWorkspaces.mockResolvedValue([- workspace('ws-1', 'Acme'),- workspace('ws-2', 'Skunkworks'),- ]);-- const el = await renderAtPickWorkspace();-- expect(el.textContent).not.toContain('Join');- expect(el.textContent).not.toContain('Accept');- expect(el.textContent).not.toContain('invited you');- expect(el.textContent).not.toContain('domain');- });-- it('does not ask a question with one answer', async () => {- resolveWorkspaces.mockResolvedValue([workspace('ws-1', 'Acme')]);-- const el = await renderAtPickWorkspace();-- expect(setActiveWorkspace).toHaveBeenCalledWith('ws-1');- expect(onboardingStore.page).toBe('linkAccounts');- expect(el.textContent).toContain('Link your messaging accounts');- });-- it('goes straight to creating one when the account is in none', async () => {- resolveWorkspaces.mockResolvedValue([]);-- const el = await renderAtPickWorkspace();-- expect(onboardingStore.page).toBe('createWorkspace');- expect(el.textContent).toContain('Create your workspace');- // Nothing behind it: the picker had no list to return to. The arrow stays- // in the tab order and says as much in its own label, so it is matched on- // the start of one.- const back = el.querySelector<HTMLButtonElement>('[aria-label^="Previous page"]')!;- expect(back.getAttribute('aria-disabled')).toBe('true');- expect([...el.querySelectorAll('button')].map((b) => b.textContent)).not.toContain('Back');- });-- it('goes back by a button and not only by a chevron', async () => {- // The chevron is unlabelled, so it may repeat the way back but never be the- // only one — the same invariant the who-runs page keeps.- resolveWorkspaces.mockResolvedValue([workspace('ws-1', 'Acme'), workspace('ws-2', 'Skunk')]);-- const el = await renderAtPickWorkspace();- await click(el, 'Back');-- expect(onboardingStore.page).toBe('signIn');- });-- /**- * Leaving while a workspace is being entered lands the user two pages on when- * it resolves — back on the sign-in, and then thrown forward out of it.- */- it('holds the way back shut while a workspace is being opened', async () => {- resolveWorkspaces.mockResolvedValue([workspace('ws-1', 'Acme'), workspace('ws-2', 'Skunk')]);- const opening = deferred<void>();- setActiveWorkspace.mockReturnValue(opening.promise);-- const el = await renderAtPickWorkspace();- await click(el, 'Acme');-- const back = [...el.querySelectorAll<HTMLButtonElement>('button')].find(- (b) => b.textContent?.trim() === 'Back'- )!;- expect(back.disabled).toBe(true);- const chevron = el.querySelector<HTMLButtonElement>('[aria-label^="Previous page"]')!;- expect(chevron.getAttribute('aria-disabled')).toBe('true');-- opening.resolve();- await settle();- });-- it('says the server could not be asked, rather than treating it as no workspaces', async () => {- // Conflating the two would offer to create a second workspace to someone- // who already has one.- resolveWorkspaces.mockRejectedValue(new Error('gateway unreachable'));-- const el = await renderAtPickWorkspace();-- expect(el.textContent).toContain('switch.example.com');- expect(el.textContent).toContain('Retry');- expect(onboardingStore.page).toBe('pickWorkspace');- expect(el.textContent).not.toContain('Create your workspace');- });-- it('creates a workspace and carries on into it', async () => {- resolveWorkspaces.mockResolvedValue([]);- createWorkspace.mockResolvedValue(workspace('ws-9', 'Acme'));-- const el = await renderAtPickWorkspace();- await typeName(el, ' Acme ');- await click(el, 'Create workspace');-- expect(createWorkspace).toHaveBeenCalledWith('srv-1', 'Acme');- expect(setActiveWorkspace).toHaveBeenCalledWith('ws-9');- expect(onboardingStore.page).toBe('linkAccounts');- });-- /**- * The workspace exists on the server from the moment Create returns. Asking- * again would send back a name it has just taken and earn a conflict that- * reads as the name being refused — and on this page, reached because the- * account is in no workspace at all, there is no Back either.- */- it('offers to open the workspace it already made rather than creating it twice', async () => {- resolveWorkspaces.mockResolvedValue([]);- createWorkspace.mockResolvedValue(workspace('ws-9', 'Acme'));- setActiveWorkspace.mockRejectedValueOnce(new Error('could not switch'));-- const el = await renderAtPickWorkspace();- await typeName(el, 'Acme');- await click(el, 'Create workspace');-- expect(el.textContent).toContain('could not be moved into it');-- setActiveWorkspace.mockResolvedValue(undefined);- await click(el, 'Open workspace');-- expect(createWorkspace).toHaveBeenCalledTimes(1);- expect(onboardingStore.page).toBe('linkAccounts');- });-- it('keeps the form and says why when the name is refused', async () => {- resolveWorkspaces.mockResolvedValue([]);- createWorkspace.mockRejectedValue(new Error('That name is already taken.'));-- const el = await renderAtPickWorkspace();- await typeName(el, 'Acme');- await click(el, 'Create workspace');-- expect(el.textContent).toContain('already taken');- expect(onboardingStore.page).toBe('createWorkspace');- });-});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/palette-agent-icon.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/palette-agent-icon.test.tsxindex 44be7df70..59b5e5d75 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/palette-agent-icon.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/palette-agent-icon.test.tsx@@ -16,14 +16,13 @@ import { PaletteAgentItem } from '@renderer/features/command-palette/palette-ageimport { agentsStore } from '@renderer/features/locations/stores/agents-store';import { ThemeContext } from '@renderer/lib/providers/theme-provider';import { AGENTS_METADATA_QUERY_KEY } from '@renderer/lib/stores/use-agents';-import { workspaceAgentsQueryKey } from '@renderer/lib/stores/use-workspace-agents';+import { remoteAgentsQueryKey } from '@renderer/lib/stores/use-remote-agents';import type { Agent } from '@shared/core/agents/agents';import type { SearchItem } from '@shared/core/search';import type { RemoteAgentSummary } from '@shared/core/switch-servers/switch-servers';const LOCATION_ID = 'loc-1';const SERVER_ID = 'server-1';-const WORKSPACE_ID = 'workspace-1';const SWITCH_AGENT_ID = 'switch-agent-1';const AGENT_NAME = 'reviewer';@@ -34,7 +33,6 @@ const AGENT: Agent = {providerId: 'claude',switchAgentId: SWITCH_AGENT_ID,apiEndpoint: 'https://switch.example',- workspaceId: WORKSPACE_ID,serverId: SERVER_ID,status: null,autoApprove: false,@@ -105,7 +103,7 @@ async function rowAvatarSrc(options: {// test has no main process to answer.defaultOptions: { queries: { retry: false, gcTime: 0, staleTime: Infinity } },});- client.setQueryData(workspaceAgentsQueryKey(WORKSPACE_ID), [remoteAgent(options.iconUrl)]);+ client.setQueryData(remoteAgentsQueryKey(SERVER_ID), [remoteAgent(options.iconUrl)]);// The provider mark beside the name reads its artwork from here. Seeded empty// so it resolves to nothing rather than reaching for a main process the test// does not have; the mark itself is the sidebar's, already covered there.diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/room-configuration-save.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/room-configuration-save.test.tsxindex 395dfe9a7..4cbc59f23 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/room-configuration-save.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/room-configuration-save.test.tsx@@ -27,10 +27,10 @@ vi.hoisted(() => {vi.mock('@renderer/lib/ipc', () => ({events: { on: vi.fn() },rpc: {- workspaces: {+ switchServers: {updateRoom,getRoomDetail,- listAgents: vi.fn(() => Promise.resolve([])),+ listRemoteAgents: vi.fn(() => Promise.resolve([])),},agents: { getAgents: vi.fn(() => Promise.resolve([])) },},@@ -38,8 +38,7 @@ vi.mock('@renderer/lib/ipc', () => ({vi.mock('@renderer/features/switch-servers/switch-rooms-store', () => ({switchRoomsStore: {- roomWorkspaceId: () => 'ws-1',- roomServerId: () => 'server-1',+ roomServerId: () => 'srv-1',canDeleteRoom: () => false,},}));@@ -157,7 +156,7 @@ describe('a room’s description and instructions', () => {expect(updateRoom).toHaveBeenCalledTimes(1);expect(updateRoom).toHaveBeenCalledWith({- workspaceId: 'ws-1',+ serverId: 'srv-1',roomId: 'room-1',description: 'The original description',instructions: 'Be brief',diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/step-pager.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/step-pager.test.tsxdeleted file mode 100644index de75c58b0..000000000--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/step-pager.test.tsx+++ /dev/null@@ -1,106 +0,0 @@-import { act } from 'react';-import { createRoot, type Root } from 'react-dom/client';-import { afterEach, describe, expect, it, vi } from 'vitest';-import { StepPager } from '@renderer/lib/ui/step-pager';--/**- * The pager is the only thing on a wizard page that says where you are, and its- * arrows are unlabelled. So what matters is that an arrow with nowhere to go- * cannot be pressed: a page that is mid-install passes no way back, and a- * chevron that fired anyway would abandon the install with nothing watching it.- */--let container: HTMLDivElement | null = null;-let root: Root | null = null;--afterEach(async () => {- if (root) await act(async () => root!.unmount());- container?.remove();- container = null;- root = null;-});--async function render(node: React.ReactNode): Promise<HTMLDivElement> {- container = document.createElement('div');- document.body.appendChild(container);- root = createRoot(container);- await act(async () => root!.render(node));- return container;-}--// Matched on the start of the label, because an arrow leading nowhere appends-// the reason to its own.-function arrow(el: HTMLElement, label: string): HTMLButtonElement {- const found = el.querySelector<HTMLButtonElement>(`[aria-label^="${label}"]`);- expect(found).not.toBeNull();- return found!;-}--describe('the pager on a wizard page', () => {- it('names the page and moves either way when both are open', async () => {- const onBack = vi.fn();- const onNext = vi.fn();- const el = await render(- <StepPager pageName="Connect to a server" onBack={onBack} onNext={onNext} />- );-- expect(el.textContent).toContain('Connect to a server');-- await act(async () => arrow(el, 'Previous page').click());- await act(async () => arrow(el, 'Next page').click());-- expect(onBack).toHaveBeenCalledOnce();- expect(onNext).toHaveBeenCalledOnce();- });-- // Shown rather than hidden: the bar keeps the same shape from page to page,- // so the name does not move as the flow advances.- it('keeps an arrow with nowhere to go on screen and dead', async () => {- const el = await render(<StepPager pageName="Sign in" onBack={vi.fn()} onNext={null} />);-- const next = arrow(el, 'Next page');- // However the button primitive spells it, it has to reach a screen reader- // as unavailable — the chevron itself says nothing about where it leads.- expect(next.matches(':disabled, [aria-disabled="true"], [data-disabled]')).toBe(true);- });-- /**- * The same arrow, the same handler, closed and then open.- *- * `aria-disabled` leaves the button clickable — that is the price of keeping- * it in the tab order — so nothing but the missing handler stops it firing,- * and a page whose way on commits an install would be committed by a chevron- * labelled "next". Driving one button through both states is what makes this- * a test: asserting on a separate always-dead arrow would pass against an- * implementation that fires whatever it is given.- */- it('fires nothing while the way on is closed, and fires once when it opens', async () => {- const onNext = vi.fn();- const page = (open: boolean) => (- <StepPager pageName="Sign in" onBack={null} onNext={open ? onNext : null} />- );- const el = await render(page(false));-- await act(async () => arrow(el, 'Next page').click());- expect(onNext).not.toHaveBeenCalled();-- await act(async () => root!.render(page(true)));- await act(async () => arrow(el, 'Next page').click());-- expect(onNext).toHaveBeenCalledOnce();- });-- it('leaves the dead arrow reachable, with the reason in its label', async () => {- // `disabled` would take it out of the tab order, and the label is the only- // place the reason is written — so the people who cannot see the greyed-out- // chevron would be the ones who never hear why it leads nowhere.- const el = await render(<StepPager pageName="Sign in" onBack={null} onNext={null} />);-- for (const label of ['Previous page', 'Next page']) {- const button = arrow(el, label);- expect(button.hasAttribute('disabled')).toBe(false);- expect(button.tabIndex).toBeGreaterThanOrEqual(0);- expect(button.getAttribute('aria-label')!.length).toBeGreaterThan(label.length);- }- });-});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/views-without-server.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/views-without-server.test.tsxdeleted file mode 100644index 01fcb8ed1..000000000--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/views-without-server.test.tsx+++ /dev/null@@ -1,27 +0,0 @@-import { describe, expect, it } from 'vitest';-import { views, viewWorksWithoutServer, type ViewId } from '@renderer/app/view-registry';--/**- * Which views may be drawn with nothing registered, named once.- *- * The flag lives on each view so the next one of its kind is not missed, and- * that is the right place for it — but it also means no single file says what- * the set is, and dropping the flag from Settings breaks ⌘, on a fresh install- * while every other test stays green. This is the file that notices.- *- * Deliberately a whole-set comparison rather than a per-view assertion: the- * failure worth catching is a flag that quietly appeared or disappeared, and- * only the set catches both.- *- * A browser test because importing the registry pulls in every view, which- * wants the preload bridge this project installs before a module evaluates.- */-const CAN_BE_DRAWN_WITHOUT_A_SERVER = ['remoteHost', 'remoteHosts', 'settings'];--describe('the views that need no Switch server', () => {- it('are these three and no others', () => {- const ids = (Object.keys(views) as ViewId[]).filter(viewWorksWithoutServer).sort();-- expect(ids).toEqual(CAN_BE_DRAWN_WITHOUT_A_SERVER);- });-});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/welcome-page.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/welcome-page.test.tsxdeleted file mode 100644index dc6b9bf44..000000000--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/welcome-page.test.tsx+++ /dev/null@@ -1,114 +0,0 @@-/**- * The first page of a fresh install.- *- * Its whole job is to say where Switch can run and get on with the one place it- * can. So what matters is that the place nobody can use yet — Switch Cloud has- * no endpoint behind it — says so in words rather than only in grey, that- * nothing on the page pretends to be a choice, and that the place that does- * work leads somewhere rather than sitting there.- */-import { act } from 'react';-import { createRoot, type Root } from 'react-dom/client';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--const onContinue = vi.hoisted(() => vi.fn());--vi.hoisted(() => {- window.electronAPI ??= {- invoke: () => Promise.resolve(undefined),- eventOn: () => () => {},- eventSend: () => {},- } as unknown as typeof window.electronAPI;-});--import { WelcomePage } from '@renderer/features/onboarding/welcome-page';--let container: HTMLDivElement | null = null;-let root: Root | null = null;--beforeEach(() => {- onContinue.mockReset();-});--afterEach(async () => {- if (root) await act(async () => root!.unmount());- container?.remove();- container = null;- root = null;-});--async function renderPage(): Promise<HTMLDivElement> {- container = document.createElement('div');- document.body.appendChild(container);- root = createRoot(container);- await act(async () => root!.render(<WelcomePage onContinue={onContinue} />));- return container;-}--function choice(el: HTMLElement, title: string): HTMLElement {- const found = [...el.querySelectorAll<HTMLElement>('li')].find((c) =>- c.textContent?.includes(title)- );- expect(found, `no option named ${title}`).toBeDefined();- return found!;-}--function button(el: HTMLElement, label: string): HTMLButtonElement {- const found = [...el.querySelectorAll<HTMLButtonElement>('button')].find(- (b) => b.textContent?.trim() === label- );- expect(found, `no ${label} button`).toBeDefined();- return found!;-}--describe('the welcome page', () => {- it('asks where Switch should run and offers both places', async () => {- const el = await renderPage();-- expect(el.textContent).toContain('Welcome to Switch');- expect(el.textContent).toContain('Where should it run?');- expect(choice(el, 'Switch Cloud')).toBeDefined();- expect(choice(el, 'Your own server')).toBeDefined();- });-- it('says in words that Switch Cloud is not ready, not only in grey', async () => {- // Nothing hosts it yet. Shown anyway, because "where should it run" has two- // answers and one of them is not ready — but the reason has to be legible- // to someone who cannot see the card is dimmed.- const el = await renderPage();- const cloud = choice(el, 'Switch Cloud');-- expect(cloud.textContent).toContain('Coming soon');- expect(cloud.textContent).toContain('there is nothing to sign in to');- });-- it('offers nothing to pick between, since only one answer can be had', async () => {- // A radiogroup here was a widget with no working option in it: two- // `role="radio"` divs, no click handler, no key handler. Announcing a- // choice and then answering neither the keyboard nor the mouse is worse- // than a list that never claimed to be one.- const el = await renderPage();-- expect(el.querySelectorAll('[role="radiogroup"], [role="radio"]')).toHaveLength(0);- // The one control on the page, and it names which of the two it takes.- expect(button(el, 'Continue with your own server')).toBeDefined();- });-- it('moves the flow on from Continue', async () => {- const el = await renderPage();-- await act(async () => button(el, 'Continue with your own server').click());-- expect(onContinue).toHaveBeenCalled();- });-- it('sends the pager forward to the same place as Continue', async () => {- // The arrow is unlabelled, so it may only repeat a move the page already- // offers — never introduce one of its own.- const el = await renderPage();-- await act(async () => el.querySelector<HTMLButtonElement>('[aria-label="Next page"]')!.click());-- expect(onContinue).toHaveBeenCalled();- });-});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.tsxdeleted file mode 100644index e0462ff50..000000000--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/workspace-switcher.test.tsx+++ /dev/null@@ -1,295 +0,0 @@-import { act } from 'react';-import { createRoot, type Root } from 'react-dom/client';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';-import type { Workspace, WorkspaceRole } from '@shared/core/workspaces/workspaces';--vi.hoisted(() => {- window.electronAPI ??= {- invoke: () => Promise.resolve(undefined),- eventOn: () => () => {},- eventSend: () => {},- } as unknown as typeof window.electronAPI;-});--const state = vi.hoisted(() => ({- servers: [] as { id: string; name: string }[],- workspaces: [] as {- id: string;- serverId: string;- name: string;- tenantId: string | null;- role: string | null;- }[],- activeId: null as string | null,- setActive: vi.fn(),- navigate: vi.fn(),-}));--vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({- switchServersStore: {- init: () => Promise.resolve(),- recoverStale: () => Promise.resolve(),- get servers() {- return state.servers;- },- serverById: (id: string) => state.servers.find((s) => s.id === id) ?? null,- },-}));--vi.mock('@renderer/features/workspaces/workspaces-store', () => ({- workspacesStore: {- get activeId() {- return state.activeId;- },- get active() {- return state.workspaces.find((w) => w.id === state.activeId) ?? null;- },- onServer: (serverId: string) => state.workspaces.filter((w) => w.serverId === serverId),- setActive: state.setActive,- },-}));--vi.mock('@renderer/features/switch-servers/local-server-store', () => ({- localServerStore: { init: () => Promise.resolve(), dispose: () => {}, phase: 'stopped' },-}));--vi.mock('@renderer/features/switch-servers/remote-server-store', () => ({- remoteServerStore: { init: () => Promise.resolve(), dispose: () => {} },-}));--// Presentation of a server — its avatar, icon, status words and drift — is the-// server's business and tested with it. Stubbed so this test is about which-// workspaces the switcher offers and which it refuses.-vi.mock('@renderer/features/switch-servers/server-presentation', () => ({- ServerAvatar: () => null,- ServerDriftIndicator: () => null,- ServerStatusDot: () => null,- serverDrift: () => null,- serverPlacementLabel: () => null,- serverStatusLabel: (server: SwitchServer) => `${server.name} status`,- serverSubtitleLabel: (server: SwitchServer) => `${server.name} status`,-}));--vi.mock('@renderer/features/switch-servers/server-icon', () => ({- serverIcon: () => () => null,-}));--vi.mock('@renderer/lib/layout/navigation-provider', () => ({- useNavigate: () => ({ navigate: state.navigate }),-}));--vi.mock('@renderer/lib/modal/modal-provider', () => ({- useShowModal: () => () => {},-}));--vi.mock('@renderer/lib/hooks/use-toast', () => ({- useToast: () => ({ toast: () => {} }),-}));--import { WorkspaceSwitcher } from '@renderer/features/switch-servers/workspace-switcher';--let container: HTMLDivElement | null = null;-let root: Root | null = null;--function server(id: string, name: string): SwitchServer {- return {- id,- name,- gatewayUrl: `https://${id}.example.invalid`,- apiUrl: `https://${id}.example.invalid/api`,- managed: false,- managementKind: null,- sshHost: null,- createdAt: '2026-01-01T00:00:00Z',- updatedAt: '2026-01-01T00:00:00Z',- };-}--function workspace(- id: string,- serverId: string,- patch: { tenantId?: string | null; role?: WorkspaceRole | null } = {}-): Workspace {- const tenantId = patch.tenantId === undefined ? `tenant-${id}` : patch.tenantId;- return {- id,- serverId,- name: id,- tenantId,- slug: tenantId === null ? null : id,- role: patch.role === undefined ? 'member' : patch.role,- createdAt: '2026-01-01T00:00:00Z',- updatedAt: '2026-01-01T00:00:00Z',- };-}--/** Mount the switcher on the given servers and workspaces, and open its menu. */-async function openSwitcher(- servers: SwitchServer[],- workspaces: Workspace[],- activeId: string-): Promise<void> {- state.servers = servers;- state.workspaces = workspaces;- state.activeId = activeId;-- container = document.createElement('div');- document.body.appendChild(container);- root = createRoot(container);- await act(async () => root!.render(<WorkspaceSwitcher />));-- const trigger = container.querySelector<HTMLElement>('[aria-label="Switch workspace"]');- expect(trigger, 'the switcher did not render its trigger').not.toBeNull();- await act(async () => trigger!.click());-}--/** The menu row offering a workspace, by the name shown on it. */-function row(name: string): HTMLElement {- const found = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find((item) =>- item.textContent?.startsWith(name)- );- expect(found, `no row for ${name}`).toBeDefined();- return found!;-}--beforeEach(() => {- state.setActive.mockReset().mockResolvedValue(undefined);- state.navigate.mockReset();-});--afterEach(async () => {- if (root) await act(async () => root!.unmount());- container?.remove();- container = null;- root = null;-});--describe('the workspaces the switcher offers', () => {- // A workspace only means anything on its server — two servers can each have a- // "Default" — so a flat list would offer two rows that read identically.- it('lists the workspaces on a server under that server', async () => {- await openSwitcher(- [server('srv-1', 'Acme'), server('srv-2', 'Local dev')],- [workspace('ws-a', 'srv-1'), workspace('ws-b', 'srv-1'), workspace('ws-c', 'srv-2')],- 'ws-a'- );-- const groups = [...document.querySelectorAll<HTMLElement>('[data-slot="dropdown-menu-group"]')];- const listed = groups.map((group) => [- group.querySelector('[data-slot="dropdown-menu-label"]')?.textContent,- // The first span on a row is its name; a second one, where there is one,- // is the role or the reason it cannot be opened.- [...group.querySelectorAll('[role="menuitem"]')].map(- (item) => item.querySelector('span')?.textContent- ),- ]);-- expect(listed[0]?.[0]).toContain('Acme');- expect(listed[0]?.[1]).toEqual(['ws-a', 'ws-b']);- expect(listed[1]?.[0]).toContain('Local dev');- expect(listed[1]?.[1]).toEqual(['ws-c']);- });-- it('marks the one the window is scoped to', async () => {- await openSwitcher(- [server('srv-1', 'Acme')],- [workspace('ws-a', 'srv-1'), workspace('ws-b', 'srv-1')],- 'ws-b'- );-- expect(row('ws-a').getAttribute('aria-current')).toBeNull();- expect(row('ws-b').getAttribute('aria-current')).toBe('true');- });-- it('switches to the one clicked', async () => {- await openSwitcher(- [server('srv-1', 'Acme')],- [workspace('ws-a', 'srv-1'), workspace('ws-b', 'srv-1')],- 'ws-a'- );-- await act(async () => row('ws-b').click());-- expect(state.setActive).toHaveBeenCalledWith('ws-b');- });-});--/**- * Two rows the gateway will refuse every call scoped to. Both are kept in the- * list rather than hidden, because their agents are still here and the row is- * the only thing that says where they went — so both have to be unclickable and- * both have to say why, or the app turns a fact it already knows into an error- * after the click.- */-describe('a workspace that cannot be opened', () => {- it('refuses one this account is no longer a member of', async () => {- await openSwitcher(- [server('srv-1', 'Acme')],- [workspace('ws-a', 'srv-1'), workspace('ws-gone', 'srv-1', { role: null })],- 'ws-a'- );-- const gone = row('ws-gone');- expect(gone.getAttribute('aria-disabled')).toBe('true');- expect(gone.textContent).toContain('No longer a member');- expect(gone.title).toContain('no longer a member');- });-- /**- * The row every server is registered with, before the gateway has been asked- * which workspaces the account has. Once the account turns out to have more- * than one, nothing can say which this row meant — and a call scoped to it- * selects no tenant at all, so the gateway answers under whichever workspace- * the session last selected.- */- it('refuses a placeholder the reconcile could not match', async () => {- await openSwitcher(- [server('srv-1', 'Acme')],- [- workspace('ws-placeholder', 'srv-1', { tenantId: null, role: null }),- workspace('ws-a', 'srv-1'),- ],- 'ws-a'- );-- const placeholder = row('ws-placeholder');- expect(placeholder.getAttribute('aria-disabled')).toBe('true');- expect(placeholder.textContent).toContain('Not matched');- });-- /**- * The same state on a server holding one workspace is ordinary rather than- * broken: there is nothing to confuse it with, and the gateway resolves the- * account's sole membership to exactly that row. Refusing it would lock the- * window out of a freshly registered server until a reconcile had run.- */- it('still offers a lone workspace that has no tenant yet', async () => {- await openSwitcher(- [server('srv-1', 'Acme')],- [workspace('ws-only', 'srv-1', { tenantId: null, role: null })],- 'ws-only'- );-- const only = row('ws-only');- expect(only.getAttribute('aria-disabled')).toBeNull();- expect(only.textContent).toBe('ws-only');- });-- it('says what to do instead of sending you back through sign-in', async () => {- await openSwitcher(- [server('srv-1', 'Acme')],- [- workspace('ws-placeholder', 'srv-1', { tenantId: null, role: null }),- workspace('ws-a', 'srv-1'),- ],- 'ws-a'- );-- // Signing in re-runs the reconcile, which is what left the row unmatched and- // would do so again — so the row must not offer it as the way out.- const reason = row('ws-placeholder').title;- expect(reason).toContain('Open one of the others');- expect(reason).not.toMatch(/sign in/i);- });-});diff --git a/console/apps/switch-console-desktop/src/shared/core/agents/agents.ts b/console/apps/switch-console-desktop/src/shared/core/agents/agents.tsindex 89bb53a83..58d073034 100644--- a/console/apps/switch-console-desktop/src/shared/core/agents/agents.ts+++ b/console/apps/switch-console-desktop/src/shared/core/agents/agents.ts@@ -6,8 +6,9 @@ import type { AgentProviderId } from '@shared/core/providers/agent-provider-regi* location (a working directory on this machine or an SSH host). Many agents* may share a location. `switchAgentId` / `apiEndpoint` carry the Switch* identity detected from the location dir's `.claude/settings.local.json`.- * `workspaceId` is the workspace the agent belongs to; null means unlinked —- * the workspace it was in is no longer registered in this app.+ * `serverId` is the registered Switch server the agent belongs to (resolved+ * from `apiEndpoint`); null means unlinked — the server it points at is not+ * registered in this app.*/export type Agent = {id: string;@@ -19,12 +20,6 @@ export type Agent = {providerId: AgentProviderId;switchAgentId: string | null;apiEndpoint: string | null;- workspaceId: string | null;- /**- * The server hosting `workspaceId`, denormalised onto the agent: null exactly- * when `workspaceId` is. Reaching an agent's gateway means reaching its- * workspace's server, and this saves every caller repeating that one hop.- */serverId: string | null;status: string | null;/** When true, Switch Console launches this agent's CLI with its auto-approve /@@ -48,10 +43,10 @@ export type CreateAgentParams = {providerId: AgentProviderId;switchAgentId: string | null;apiEndpoint: string | null;- /** The workspace this agent belongs to. Every agent must have one — it is+ /** The Switch server this agent belongs to. Every agent must have one — it is* chosen and verified at onboarding (legacy rows may still be null until the* user assigns one). */- workspaceId: string;+ serverId: string;/** Seed for the per-agent bypass-permissions flag: false for local agents,* true for remote agents. */autoApprove: boolean;diff --git a/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.tsindex 5c39045f8..655892b4f 100644--- a/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts+++ b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts@@ -265,7 +265,7 @@ export type RemoteRoomDetail = RemoteRoomSummary & {/** The room fields Switch Console can change. Anything omitted is left alone;* an empty string clears the field rather than leaving it. */export type UpdateRoomParams = {- workspaceId: string;+ serverId: string;roomId: string;description?: string;instructions?: string;@@ -414,7 +414,7 @@ export type RemoteBridgeType = {* never logged, and never sent back to the renderer.*/export type CreateBridgeParams = {- workspaceId: string;+ serverId: string;bridgeType: string;displayName: string;connectionConfig: Record<string, string | boolean>;@@ -450,7 +450,7 @@ export type CreateBridgeResult =* own partial-update contract.*/export type UpdateBridgeParams = {- workspaceId: string;+ serverId: string;bridgeId: string;channelCreationEnabled?: boolean;};@@ -468,7 +468,7 @@ export type UpdateBridgeResult =/** Parameters for disconnecting a bridge from a server* (`DELETE /collaborations/{id}`). */export type DeleteBridgeParams = {- workspaceId: string;+ serverId: string;bridgeId: string;};@@ -555,7 +555,7 @@ export type BridgeDirectorySearchResult =/** Claim a platform identity for the signed-in Switch user (CHOO-2137). */export type ClaimIdentityParams = {- workspaceId: string;+ serverId: string;bridgeId: string;/** The platform's own id, not an `ExternalUser` row id — the row may not* exist yet, and the server creates it on demand. */@@ -669,7 +669,7 @@ export type AgentProviderKind = 'anthropic' | 'third-party';* its credentials into the directory's `.claude/settings.local.json`.*/export type ProvisionAgentParams = {- workspaceId: string;+ serverId: string;/** The agent's working directory; the settings file is written here and used* as `repo_dir` so an offline-session command can `cd` into it. */dir: string;@@ -688,7 +688,7 @@ export type ProvisionAgentParams = {* is no local directory: the agent's config lives entirely on the host.*/export type ProvisionRemoteAgentParams = {- workspaceId: string;+ serverId: string;/** SSH alias of the onboarded host the agent runs on. */sshHost: string;/** The agent's working directory on the host; the settings file is written@@ -741,7 +741,7 @@ export type ProvisionAgentResult =* useful room, so there is no internal-only path here.*/export type CreateRoomParams = {- workspaceId: string;+ serverId: string;name: string;description: string;/** Room-specific system prompt shown to agents on connect. Optional. */diff --git a/console/apps/switch-console-desktop/src/shared/core/telemetry/renderer-events.ts b/console/apps/switch-console-desktop/src/shared/core/telemetry/renderer-events.tsindex 6aa013d4b..c4302d099 100644--- a/console/apps/switch-console-desktop/src/shared/core/telemetry/renderer-events.ts+++ b/console/apps/switch-console-desktop/src/shared/core/telemetry/renderer-events.ts@@ -46,15 +46,8 @@ export type RendererTelemetryEvents = {onboarding_checklist_dismissed: Record<never, never>;/** Every step of the checklist is done. */onboarding_completed: Record<never, never>;- /**- * The add-server wizard reached a step. Where people stop is the question.- *- * `first_run` separates the two places the same steps are drawn: the wizard- * in a dialog, and the full-window pages a fresh install opens on. Giving up- * before you have any server at all is a different answer from giving up- * adding your second, and one funnel covering both could not tell them apart.- */- add_server_step: { step: AddServerStepName; choice: AddServerChoiceName; first_run: boolean };+ /** The add-server wizard reached a step. Where people stop is the question. */+ add_server_step: { step: AddServerStepName; choice: AddServerChoiceName };/** A screen failed and the error boundary caught it. */renderer_crashed: Record<never, never>;};diff --git a/console/apps/switch-console-desktop/src/shared/core/workspaces/workspaceEvents.ts b/console/apps/switch-console-desktop/src/shared/core/workspaces/workspaceEvents.tsdeleted file mode 100644index 6591daeb3..000000000--- a/console/apps/switch-console-desktop/src/shared/core/workspaces/workspaceEvents.ts+++ /dev/null@@ -1,13 +0,0 @@-import { defineEvent } from '@shared/lib/ipc/events';--/**- * The set of workspaces this install holds changed in the main process.- *- * Fired by the reconcile, which is the one thing that adds, matches and drops- * workspace rows without a window having asked for it — the boot sweep, and- * every sign-in. Without it a membership added or withdrawn since the last- * launch stays invisible for the whole session, and a placeholder the sweep- * deleted goes on being offered in the switcher by a renderer holding the list- * it read at startup.- */-export const workspacesChangedChannel = defineEvent<void>('workspaces:changed');diff --git a/console/apps/switch-console-desktop/src/shared/core/workspaces/workspaces.ts b/console/apps/switch-console-desktop/src/shared/core/workspaces/workspaces.tsdeleted file mode 100644index 3c97fe80f..000000000--- a/console/apps/switch-console-desktop/src/shared/core/workspaces/workspaces.ts+++ /dev/null@@ -1,84 +0,0 @@-/**- * Shared types for workspaces: what a Switch Console window is scoped to, and- * the thing agents belong to.- *- * A workspace sits one level below a registered server. On a server with- * tenancy it mirrors a tenant the signed-in user is a member of; the server's- * own identity (its URLs, its session cookie, its auth method) stays at the- * server, because one session cookie covers every workspace on it.- */--/** The caller's standing in a workspace, as the gateway reports it. */-export type WorkspaceRole = 'owner' | 'admin' | 'member';--/** A workspace on a registered Switch server. */-export type Workspace = {- id: string;- serverId: string;- name: string;- /**- * The workspace's tenant id on the gateway.- *- * Null means the workspace has not been matched to a tenant yet — the state- * every workspace starts in, since one is created locally the moment a server- * is registered and the gateway is only asked afterwards. It is a transient- * "not reconciled yet", not a description of the server.- */- tenantId: string | null;- /** The gateway's slug for the workspace; null alongside a null `tenantId`. */- slug: string | null;- /**- * Null alongside a null `tenantId`, where the notion does not apply yet — and- * null beside a tenant id once the membership has been withdrawn, which is- * what {@link isWithdrawnWorkspace} reads.- */- role: WorkspaceRole | null;- createdAt: string;- updatedAt: string;-};--/**- * Whether this account has lost its membership of a workspace still held here.- *- * The row is kept so the agents registered through it stay attached to- * something, but nothing scoped to it can be answered any more: the gateway- * refuses a session selecting a tenant the account does not belong to. Views- * say so rather than offering it, so the refusal is read before the click- * rather than after it.- */-export function isWithdrawnWorkspace(workspace: Workspace): boolean {- return workspace.tenantId !== null && workspace.role === null;-}--/**- * Whether a row that names no tenant is one nothing can answer for.- *- * Every server's first workspace is created tenant-less and matched to a- * membership by the reconcile, so on a server holding one workspace this state- * is ordinary: there is nothing to confuse it with, and the gateway resolves- * the account's sole membership to exactly that row. Beside siblings it is the- * placeholder the reconcile could not match, kept only because it holds agents- * — and a call scoped to it selects no tenant, so the gateway answers with- * whichever workspace the session last selected, under this one's name.- *- * `onSameServer` is every workspace on the server, this one included.- */-export function isUnmatchedWorkspace(workspace: Workspace, onSameServer: number): boolean {- return workspace.tenantId === null && onSameServer > 1;-}--/** Why a workspace cannot be opened, or null when it can. */-export type WorkspaceUnavailability = 'withdrawn' | 'unmatched';--/**- * The two ways a workspace held here can be one nothing scoped to it will be- * answered for, as one question — so a view offering workspaces cannot rule out- * the first and go on offering the second.- */-export function workspaceUnavailability(- workspace: Workspace,- onSameServer: number-): WorkspaceUnavailability | null {- if (isWithdrawnWorkspace(workspace)) return 'withdrawn';- return isUnmatchedWorkspace(workspace, onSameServer) ? 'unmatched' : null;-}diff --git a/console/apps/switch-console-desktop/tooling/fixtures/baseline.db b/console/apps/switch-console-desktop/tooling/fixtures/baseline.dbindex c1759e17b..23caa2637 100644Binary files a/console/apps/switch-console-desktop/tooling/fixtures/baseline.db and b/console/apps/switch-console-desktop/tooling/fixtures/baseline.db differdiff --git a/console/apps/switch-console-desktop/tooling/fixtures/baseline.db-shm b/console/apps/switch-console-desktop/tooling/fixtures/baseline.db-shmdeleted file mode 100644index fe9ac2845..000000000Binary files a/console/apps/switch-console-desktop/tooling/fixtures/baseline.db-shm and /dev/null differdiff --git a/console/apps/switch-console-desktop/tooling/fixtures/baseline.db-wal b/console/apps/switch-console-desktop/tooling/fixtures/baseline.db-waldeleted file mode 100644index e69de29bb..000000000diff --git a/console/apps/switch-console-desktop/tooling/fixtures/empty.db b/console/apps/switch-console-desktop/tooling/fixtures/empty.dbindex ef513691c..3bf798903 100644Binary files a/console/apps/switch-console-desktop/tooling/fixtures/empty.db and b/console/apps/switch-console-desktop/tooling/fixtures/empty.db differdiff --git a/console/apps/switch-console-desktop/tooling/fixtures/empty.db-shm b/console/apps/switch-console-desktop/tooling/fixtures/empty.db-shmdeleted file mode 100644index fe9ac2845..000000000Binary files a/console/apps/switch-console-desktop/tooling/fixtures/empty.db-shm and /dev/null differdiff --git a/console/apps/switch-console-desktop/tooling/fixtures/empty.db-wal b/console/apps/switch-console-desktop/tooling/fixtures/empty.db-waldeleted file mode 100644index e69de29bb..000000000diff --git a/console/packages/core/src/agents/plugins/capabilities/repo-agents.ts b/console/packages/core/src/agents/plugins/capabilities/repo-agents.tsindex 9ff5b50c2..5bfc7052f 100644--- a/console/packages/core/src/agents/plugins/capabilities/repo-agents.ts+++ b/console/packages/core/src/agents/plugins/capabilities/repo-agents.ts@@ -127,19 +127,19 @@ export type RepoAgentAttributes = Record<string, RepoAgentAttributeValue>;* provider's business and lives behind this behavior; the main process supplies a* `PluginFs` for the IO and owns the provider-neutral gateway reconciliation.*- * `workdirFs` is rooted at the agent's working directory; `homeFs` at the user's+ * `workspaceFs` is rooted at the agent's working directory; `homeFs` at the user's* home — definitions may resolve in either scope.*/export type IRepoAgentsBehavior = {/** Runnable agents, from the working dir's on-disk credentials + definitions. */- discoverLocal(workdirFs: PluginFs, homeFs: PluginFs): Promise<LocalRepoAgent[]>;+ discoverLocal(workspaceFs: PluginFs, homeFs: PluginFs): Promise<LocalRepoAgent[]>;/** Agent definitions in the working dir, for onboarding (project scope). */- discoverDefinitions(workdirFs: PluginFs): Promise<RepoAgentDefinition[]>;+ discoverDefinitions(workspaceFs: PluginFs): Promise<RepoAgentDefinition[]>;/** Provider-specific CLI args that run the CLI as the named agent. Pure — the* caller passes them to `buildCommand` as `agentArgs` (not user extra args). */launchArgs(workingDir: string, agentName: string): string[];/** The named agent's Switch credentials as env vars, for the launched session. */- readLaunchEnv(workdirFs: PluginFs, agentName: string): Promise<Record<string, string>>;+ readLaunchEnv(workspaceFs: PluginFs, agentName: string): Promise<Record<string, string>>;/** The attribute fields this provider supports, in display order. Drives the* create/edit form; the first two are always `name` and `description`. */attributeFields(): RepoAgentField[];@@ -155,16 +155,16 @@ export type IRepoAgentsBehavior = {/** The definition file's path, relative to the working directory. */definitionPath(name: string): string;/** Create or overwrite a named agent's on-disk definition from its attributes- * (workdir scope). `attributes.name` selects the agent. */- writeDefinition(workdirFs: PluginFs, attributes: RepoAgentAttributes): Promise<void>;+ * (workspace scope). `attributes.name` selects the agent. */+ writeDefinition(workspaceFs: PluginFs, attributes: RepoAgentAttributes): Promise<void>;/** The current attribute values for an existing agent definition, keyed to* {@link attributeFields}, or null if no definition exists. */- readDefinition(workdirFs: PluginFs, name: string): Promise<RepoAgentAttributes | null>;+ readDefinition(workspaceFs: PluginFs, name: string): Promise<RepoAgentAttributes | null>;/** Remove a named agent's provider-specific files — its definition and any- * legacy per-agent settings (workdir scope). The provider-neutral Switch+ * legacy per-agent settings (workspace scope). The provider-neutral Switch* credentials are not this hook's to remove: they are written for every* provider, so they are torn down by the caller for every provider too. */- removeLocal(workdirFs: PluginFs, name: string): Promise<void>;+ removeLocal(workspaceFs: PluginFs, name: string): Promise<void>;};/**diff --git a/console/packages/plugins/src/agents/impl/claude/subagents.test.ts b/console/packages/plugins/src/agents/impl/claude/subagents.test.tsindex c333c4261..785b787db 100644--- a/console/packages/plugins/src/agents/impl/claude/subagents.test.ts+++ b/console/packages/plugins/src/agents/impl/claude/subagents.test.ts@@ -56,7 +56,7 @@ describe('claudeRepoAgentsBehavior.launchArgs', () => {describe('claudeRepoAgentsBehavior.discoverDefinitions', () => {it('parses definitions, eligibility, and registered state', async () => {- const workdirFs = fakeFs({+ const workspaceFs = fakeFs({[defRel('reviewer')]:'---\nname: reviewer\ndescription: Reviews code\nmodel: opus\n---\nbody',// No `tools` line → eligible (inherits all tools), and registered (creds exist).@@ -65,7 +65,7 @@ describe('claudeRepoAgentsBehavior.discoverDefinitions', () => {[defRel('linter')]: '---\ndescription: Lints\ntools: Read, Edit\n---\n',});- const defs = await claudeRepoAgentsBehavior.discoverDefinitions(workdirFs);+ const defs = await claudeRepoAgentsBehavior.discoverDefinitions(workspaceFs);expect(defs).toEqual([{ name: 'linter', description: 'Lints', model: null, eligible: false, registered: false },@@ -82,7 +82,7 @@ describe('claudeRepoAgentsBehavior.discoverDefinitions', () => {describe('claudeRepoAgentsBehavior.discoverLocal', () => {it('reads creds env and definition meta, project scope then home', async () => {- const workdirFs = fakeFs({+ const workspaceFs = fakeFs({[settingsRel('reviewer')]:'{"env":{"SWITCH_AGENT_ID":"a1","SWITCH_API_ENDPOINT":"https://s"}}',[defRel('reviewer')]: '---\ndescription: Reviews\nmodel: opus\n---\n',@@ -92,7 +92,7 @@ describe('claudeRepoAgentsBehavior.discoverLocal', () => {[defRel('helper')]: '---\ndescription: From home\n---\n',});- const local = await claudeRepoAgentsBehavior.discoverLocal(workdirFs, homeFs);+ const local = await claudeRepoAgentsBehavior.discoverLocal(workspaceFs, homeFs);expect(local).toEqual([{@@ -115,12 +115,12 @@ describe('claudeRepoAgentsBehavior.discoverLocal', () => {describe('claudeRepoAgentsBehavior.readLaunchEnv', () => {it('returns only non-empty SWITCH_* keys', async () => {- const workdirFs = fakeFs({+ const workspaceFs = fakeFs({[settingsRel('reviewer')]:'{"env":{"SWITCH_AGENT_ID":"a1","SWITCH_API_TOKEN":"t","SWITCH_API_ENDPOINT":" ","OTHER":"x"}}',});- expect(await claudeRepoAgentsBehavior.readLaunchEnv(workdirFs, 'reviewer')).toEqual({+ expect(await claudeRepoAgentsBehavior.readLaunchEnv(workspaceFs, 'reviewer')).toEqual({SWITCH_AGENT_ID: 'a1',SWITCH_API_TOKEN: 't',});@@ -133,22 +133,22 @@ describe('claudeRepoAgentsBehavior.readLaunchEnv', () => {describe('claudeRepoAgentsBehavior.writeDefinition / readDefinition', () => {it('writes frontmatter + body without a tools line, and round-trips attributes', async () => {- const workdirFs = fakeFs({});- await claudeRepoAgentsBehavior.writeDefinition(workdirFs, {+ const workspaceFs = fakeFs({});+ await claudeRepoAgentsBehavior.writeDefinition(workspaceFs, {name: 'reviewer',description: 'Reviews diffs',model: 'opus',instructions: 'You are a careful reviewer.',});- const raw = await workdirFs.read(defRel('reviewer'));+ const raw = await workspaceFs.read(defRel('reviewer'));expect(raw).toBe('---\nname: reviewer\ndescription: Reviews diffs\nmodel: opus\n---\n\nYou are a careful reviewer.\n');// No `tools:` line → the subagent inherits all tools and is Switch-eligible.expect(raw).not.toContain('tools:');- const attrs = await claudeRepoAgentsBehavior.readDefinition(workdirFs, 'reviewer');+ const attrs = await claudeRepoAgentsBehavior.readDefinition(workspaceFs, 'reviewer');expect(attrs).toMatchObject({name: 'reviewer',description: 'Reviews diffs',@@ -159,14 +159,14 @@ describe('claudeRepoAgentsBehavior.writeDefinition / readDefinition', () => {});it('falls back to the description for the body when there are no instructions', async () => {- const workdirFs = fakeFs({});- await claudeRepoAgentsBehavior.writeDefinition(workdirFs, {+ const workspaceFs = fakeFs({});+ await claudeRepoAgentsBehavior.writeDefinition(workspaceFs, {name: 'reviewer',description: 'Reviews diffs',});// Claude Code reads the body as the system prompt, so it cannot be empty.- expect(await workdirFs.read(defRel('reviewer'))).toBe(+ expect(await workspaceFs.read(defRel('reviewer'))).toBe('---\nname: reviewer\ndescription: Reviews diffs\n---\n\nReviews diffs\n');});@@ -174,13 +174,13 @@ describe('claudeRepoAgentsBehavior.writeDefinition / readDefinition', () => {it('does not read the description stand-in back as instructions', async () => {// Otherwise the round trip invents a prompt the user never wrote, and the// next write pins it as if they had.- const workdirFs = fakeFs({});- await claudeRepoAgentsBehavior.writeDefinition(workdirFs, {+ const workspaceFs = fakeFs({});+ await claudeRepoAgentsBehavior.writeDefinition(workspaceFs, {name: 'reviewer',description: 'Reviews diffs',});- const attrs = await claudeRepoAgentsBehavior.readDefinition(workdirFs, 'reviewer');+ const attrs = await claudeRepoAgentsBehavior.readDefinition(workspaceFs, 'reviewer');expect(attrs?.instructions).toBe('');});@@ -204,24 +204,24 @@ describe('claudeRepoAgentsBehavior.writeDefinition / readDefinition', () => {});it('always merges the Switch tools into a non-empty tools list', async () => {- const workdirFs = fakeFs({});- await claudeRepoAgentsBehavior.writeDefinition(workdirFs, {+ const workspaceFs = fakeFs({});+ await claudeRepoAgentsBehavior.writeDefinition(workspaceFs, {name: 'reviewer',description: 'Reviews diffs',tools: ['Read', 'Grep'],instructions: 'body',});- const raw = (await workdirFs.read(defRel('reviewer'))) ?? '';+ const raw = (await workspaceFs.read(defRel('reviewer'))) ?? '';expect(raw).toContain('tools: Read, Grep, mcp__switch');// Read-back strips the Switch rules so the form shows only the user's tools.- const attrs = await claudeRepoAgentsBehavior.readDefinition(workdirFs, 'reviewer');+ const attrs = await claudeRepoAgentsBehavior.readDefinition(workspaceFs, 'reviewer');expect(attrs?.tools).toEqual(['Read', 'Grep']);});it('strips the retired connector-plugin rules an older Switch Console wrote', async () => {- const workdirFs = fakeFs({+ const workspaceFs = fakeFs({[defRel('reviewer')]: ['---','name: reviewer',@@ -233,20 +233,20 @@ describe('claudeRepoAgentsBehavior.writeDefinition / readDefinition', () => {].join('\n'),});- const attrs = await claudeRepoAgentsBehavior.readDefinition(workdirFs, 'reviewer');+ const attrs = await claudeRepoAgentsBehavior.readDefinition(workspaceFs, 'reviewer');expect(attrs?.tools).toEqual(['Read']);// And it is not written back: only the rule Switch Console still authors is.- await claudeRepoAgentsBehavior.writeDefinition(workdirFs, attrs ?? {});- const raw = (await workdirFs.read(defRel('reviewer'))) ?? '';+ await claudeRepoAgentsBehavior.writeDefinition(workspaceFs, attrs ?? {});+ const raw = (await workspaceFs.read(defRel('reviewer'))) ?? '';expect(raw).toContain('tools: Read, mcp__switch\n');expect(raw).not.toContain('switch-connector');expect(raw).not.toContain('switch-channel');});it('serialises optional scalar, number, and boolean fields and omits empty ones', async () => {- const workdirFs = fakeFs({});- await claudeRepoAgentsBehavior.writeDefinition(workdirFs, {+ const workspaceFs = fakeFs({});+ await claudeRepoAgentsBehavior.writeDefinition(workspaceFs, {name: 'worker',description: 'line one\nline two',model: '',@@ -257,7 +257,7 @@ describe('claudeRepoAgentsBehavior.writeDefinition / readDefinition', () => {instructions: 'do work',});- const raw = (await workdirFs.read(defRel('worker'))) ?? '';+ const raw = (await workspaceFs.read(defRel('worker'))) ?? '';expect(raw).toContain('description: line one line two');expect(raw).toContain('color: blue');expect(raw).toContain('maxTurns: 5');@@ -265,7 +265,7 @@ describe('claudeRepoAgentsBehavior.writeDefinition / readDefinition', () => {expect(raw).not.toContain('model:');expect(raw).not.toContain('permissionMode:');- const attrs = await claudeRepoAgentsBehavior.readDefinition(workdirFs, 'worker');+ const attrs = await claudeRepoAgentsBehavior.readDefinition(workspaceFs, 'worker');expect(attrs).toMatchObject({ color: 'blue', maxTurns: 5, background: true, model: '' });});@@ -285,26 +285,26 @@ describe('claudeRepoAgentsBehavior.attributeFields', () => {describe('claudeRepoAgentsBehavior.removeLocal', () => {it('deletes the definition and the legacy per-agent settings', async () => {- const workdirFs = fakeFs({+ const workspaceFs = fakeFs({[defRel('reviewer')]: '---\nname: reviewer\ndescription: x\n---\n',[settingsRel('reviewer')]: '{"env":{}}',});- await claudeRepoAgentsBehavior.removeLocal(workdirFs, 'reviewer');+ await claudeRepoAgentsBehavior.removeLocal(workspaceFs, 'reviewer');- expect(await workdirFs.exists(defRel('reviewer'))).toBe(false);- expect(await workdirFs.exists(settingsRel('reviewer'))).toBe(false);+ expect(await workspaceFs.exists(defRel('reviewer'))).toBe(false);+ expect(await workspaceFs.exists(settingsRel('reviewer'))).toBe(false);});it('leaves the provider-neutral credentials to the caller, which removes them for every provider', async () => {const neutralRel = '.switch/agents/reviewer.json';- const workdirFs = fakeFs({+ const workspaceFs = fakeFs({[defRel('reviewer')]: '---\nname: reviewer\ndescription: x\n---\n',[neutralRel]: '{"env":{}}',});- await claudeRepoAgentsBehavior.removeLocal(workdirFs, 'reviewer');+ await claudeRepoAgentsBehavior.removeLocal(workspaceFs, 'reviewer');- expect(await workdirFs.exists(neutralRel)).toBe(true);+ expect(await workspaceFs.exists(neutralRel)).toBe(true);});});diff --git a/console/packages/plugins/src/agents/impl/claude/subagents.ts b/console/packages/plugins/src/agents/impl/claude/subagents.tsindex d623b86ed..c15828049 100644--- a/console/packages/plugins/src/agents/impl/claude/subagents.ts+++ b/console/packages/plugins/src/agents/impl/claude/subagents.ts@@ -356,12 +356,12 @@ function neutralSettingsRelPath(name: string): string {* yet migrated (CHOO-1440).*/async function readCredsObject(- workdirFs: PluginFs,+ workspaceFs: PluginFs,name: string): Promise<Record<string, unknown>> {- const neutral = await workdirFs.read(neutralSettingsRelPath(name));+ const neutral = await workspaceFs.read(neutralSettingsRelPath(name));if (neutral !== null) return parseSettingsObject(neutral);- return parseSettingsObject(await workdirFs.read(settingsRelPath(name)));+ return parseSettingsObject(await workspaceFs.read(settingsRelPath(name)));}function definitionRelPath(name: string): string {@@ -370,11 +370,11 @@ function definitionRelPath(name: string): string {/** Description/model from a subagent's definition, project scope then user scope. */async function readDefinitionMeta(- workdirFs: PluginFs,+ workspaceFs: PluginFs,homeFs: PluginFs,name: string): Promise<{ description: string | null; model: string | null }> {- const project = await workdirFs.read(definitionRelPath(name));+ const project = await workspaceFs.read(definitionRelPath(name));if (project !== null) {const fm = parseFrontmatter(project);return { description: fm.description, model: fm.model };@@ -388,27 +388,27 @@ async function readDefinitionMeta(}export const claudeRepoAgentsBehavior: IRepoAgentsBehavior = {- async discoverLocal(workdirFs, homeFs): Promise<LocalRepoAgent[]> {+ async discoverLocal(workspaceFs, homeFs): Promise<LocalRepoAgent[]> {// Names come from either credentials location — the neutral `.switch/agents`// dir and the legacy `.claude/switch-subagents` dir — so both migrated and// un-migrated installs are discovered (CHOO-1440). Plain agents' creds files// live in the neutral dir too (keyed by agent id, no `.claude/agents/<name>.md`// definition); a neutral file counts as a subagent only when it has a// definition, so those are filtered out here.- const neutralCandidates = (await workdirFs.list(SWITCH_AGENT_SETTINGS_DIR))+ const neutralCandidates = (await workspaceFs.list(SWITCH_AGENT_SETTINGS_DIR)).filter((entry) => entry.endsWith('.json')).map((entry) => entry.slice(0, -'.json'.length)).filter((name) => name.length > 0);const neutralNames: string[] = [];for (const name of neutralCandidates) {if (- (await workdirFs.exists(definitionRelPath(name))) ||+ (await workspaceFs.exists(definitionRelPath(name))) ||(await homeFs.exists(definitionRelPath(name)))) {neutralNames.push(name);}}- const legacyNames = (await workdirFs.list(CLAUDE_SUBAGENTS.dirRelative))+ const legacyNames = (await workspaceFs.list(CLAUDE_SUBAGENTS.dirRelative)).filter((entry) => entry.endsWith(CLAUDE_SUBAGENTS.settingsSuffix)).map((entry) => entry.slice(0, -CLAUDE_SUBAGENTS.settingsSuffix.length));const names = [...new Set([...neutralNames, ...legacyNames])]@@ -417,9 +417,9 @@ export const claudeRepoAgentsBehavior: IRepoAgentsBehavior = {return Promise.all(names.map(async (name) => {- const settings = await readCredsObject(workdirFs, name);+ const settings = await readCredsObject(workspaceFs, name);const env = (settings.env ?? {}) as Record<string, unknown>;- const { description, model } = await readDefinitionMeta(workdirFs, homeFs, name);+ const { description, model } = await readDefinitionMeta(workspaceFs, homeFs, name);return {name,description,@@ -431,8 +431,8 @@ export const claudeRepoAgentsBehavior: IRepoAgentsBehavior = {);},- async discoverDefinitions(workdirFs): Promise<RepoAgentDefinition[]> {- const entries = await workdirFs.list(CLAUDE_SUBAGENTS.definitionsDirRelative);+ async discoverDefinitions(workspaceFs): Promise<RepoAgentDefinition[]> {+ const entries = await workspaceFs.list(CLAUDE_SUBAGENTS.definitionsDirRelative);const files = entries.filter((entry) => entry.endsWith(MD_SUFFIX)).sort((a, b) => a.localeCompare(b));@@ -440,10 +440,10 @@ export const claudeRepoAgentsBehavior: IRepoAgentsBehavior = {return Promise.all(files.map(async (file) => {const content =- (await workdirFs.read(`${CLAUDE_SUBAGENTS.definitionsDirRelative}/${file}`)) ?? '';+ (await workspaceFs.read(`${CLAUDE_SUBAGENTS.definitionsDirRelative}/${file}`)) ?? '';const fm = parseFrontmatter(content);const name = fm.name ?? file.slice(0, -MD_SUFFIX.length);- const registered = await workdirFs.exists(settingsRelPath(name));+ const registered = await workspaceFs.exists(settingsRelPath(name));return {name,description: fm.description,@@ -468,8 +468,8 @@ export const claudeRepoAgentsBehavior: IRepoAgentsBehavior = {];},- async readLaunchEnv(workdirFs, agentName): Promise<Record<string, string>> {- const settings = await readCredsObject(workdirFs, agentName);+ async readLaunchEnv(workspaceFs, agentName): Promise<Record<string, string>> {+ const settings = await readCredsObject(workspaceFs, agentName);const env = (settings.env ?? {}) as Record<string, unknown>;const result: Record<string, string> = {};for (const key of SWITCH_ENV_KEYS) {@@ -491,13 +491,13 @@ export const claudeRepoAgentsBehavior: IRepoAgentsBehavior = {return definitionRelPath(name);},- async writeDefinition(workdirFs, attributes: RepoAgentAttributes): Promise<void> {+ async writeDefinition(workspaceFs, attributes: RepoAgentAttributes): Promise<void> {const name = toScalar(attributes.name);- await workdirFs.write(definitionRelPath(name), serializeDefinition(attributes));+ await workspaceFs.write(definitionRelPath(name), serializeDefinition(attributes));},- async readDefinition(workdirFs, name): Promise<RepoAgentAttributes | null> {- const content = await workdirFs.read(definitionRelPath(name));+ async readDefinition(workspaceFs, name): Promise<RepoAgentAttributes | null> {+ const content = await workspaceFs.read(definitionRelPath(name));if (content === null) return null;const fields = parseFrontmatterFields(content);@@ -529,8 +529,8 @@ export const claudeRepoAgentsBehavior: IRepoAgentsBehavior = {return attributes;},- async removeLocal(workdirFs, name): Promise<void> {- await workdirFs.delete(definitionRelPath(name));- await workdirFs.delete(settingsRelPath(name));+ async removeLocal(workspaceFs, name): Promise<void> {+ await workspaceFs.delete(definitionRelPath(name));+ await workspaceFs.delete(settingsRelPath(name));},};diff --git a/docs/TELEMETRY.md b/docs/TELEMETRY.mdindex dca2677a7..56a8f2f61 100644--- a/docs/TELEMETRY.md+++ b/docs/TELEMETRY.md@@ -118,7 +118,7 @@ id, no IP field, no Switch identity.| `onboarding_step_started` | `step_id`, one of exactly 4: `addServer`, `agentProviders`, `onboardAgents`, `createRoom` || `onboarding_checklist_dismissed` | *(no fields)* || `onboarding_completed` | *(no fields)* |-| `add_server_step` | `step`: `choose` / `local` / `remoteHost` / `external` / `signIn` / `linkAccounts` · `choice`: `none` / `local` / `remoteHost` / `external` · `first_run`: `true` / `false` — whether the same step was reached on a fresh install rather than from the Add server dialog |+| `add_server_step` | `step`: `choose` / `local` / `remoteHost` / `external` / `signIn` / `linkAccounts` · `choice`: `none` / `local` / `remoteHost` / `external` |**Agents and sessions**