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
Show organizations in Switch Console's workspace switcher
Petr Bauch5efccc31ada5
diff --git a/console/apps/switch-console-desktop/drizzle/0054_workspace_organizations.sql b/console/apps/switch-console-desktop/drizzle/0054_workspace_organizations.sqlnew file mode 100644index 000000000..34831c6cd--- /dev/null+++ b/console/apps/switch-console-desktop/drizzle/0054_workspace_organizations.sql@@ -0,0 +1,3 @@+ALTER TABLE `workspaces` ADD `organization_id` text;--> statement-breakpoint+ALTER TABLE `workspaces` ADD `organization_name` text;--> statement-breakpoint+ALTER TABLE `workspaces` ADD `organization_role` text;\ No newline at end of filediff --git a/console/apps/switch-console-desktop/drizzle/meta/0054_snapshot.json b/console/apps/switch-console-desktop/drizzle/meta/0054_snapshot.jsonnew file mode 100644index 000000000..eef65d3bb--- /dev/null+++ b/console/apps/switch-console-desktop/drizzle/meta/0054_snapshot.json@@ -0,0 +1,1001 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "7ceb4de2-57c5-4b17-a4fd-1c067f13f3e7",+ "prevId": "485dc9e4-c576-47fd-814c-4c8d61bddbc3",+ "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+ },+ "auto_mode": {+ "name": "auto_mode",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "owner_name": {+ "name": "owner_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "provider_config": {+ "name": "provider_config",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "idx_agents_location_id": {+ "name": "idx_agents_location_id",+ "columns": ["location_id"],+ "isUnique": false+ },+ "idx_agents_workspace_id": {+ "name": "idx_agents_workspace_id",+ "columns": ["workspace_id"],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "agents_location_id_locations_id_fk": {+ "name": "agents_location_id_locations_id_fk",+ "tableFrom": "agents",+ "tableTo": "locations",+ "columnsFrom": ["location_id"],+ "columnsTo": ["id"],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "agents_workspace_id_workspaces_id_fk": {+ "name": "agents_workspace_id_workspaces_id_fk",+ "tableFrom": "agents",+ "tableTo": "workspaces",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "app_secrets": {+ "name": "app_secrets",+ "columns": {+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "secret": {+ "name": "secret",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_app_secrets_key": {+ "name": "idx_app_secrets_key",+ "columns": ["key"],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "app_settings": {+ "name": "app_settings",+ "columns": {+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "idx_app_settings_key": {+ "name": "idx_app_settings_key",+ "columns": ["key"],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "kv": {+ "name": "kv",+ "columns": {+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "idx_kv_key": {+ "name": "idx_kv_key",+ "columns": ["key"],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "location_settings": {+ "name": "location_settings",+ "columns": {+ "location_id": {+ "name": "location_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "base_settings_json": {+ "name": "base_settings_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "shareable_settings_json": {+ "name": "shareable_settings_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "legacy_config_migrated_at": {+ "name": "legacy_config_migrated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "location_settings_location_id_locations_id_fk": {+ "name": "location_settings_location_id_locations_id_fk",+ "tableFrom": "location_settings",+ "tableTo": "locations",+ "columnsFrom": ["location_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "locations": {+ "name": "locations",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ssh_host": {+ "name": "ssh_host",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "dir": {+ "name": "dir",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "idx_locations_host_dir": {+ "name": "idx_locations_host_dir",+ "columns": ["ssh_host", "dir"],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "messages": {+ "name": "messages",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "sender": {+ "name": "sender",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "timestamp": {+ "name": "timestamp",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_messages_session_id": {+ "name": "idx_messages_session_id",+ "columns": ["session_id"],+ "isUnique": false+ },+ "idx_messages_timestamp": {+ "name": "idx_messages_timestamp",+ "columns": ["timestamp"],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "messages_session_id_sessions_id_fk": {+ "name": "messages_session_id_sessions_id_fk",+ "tableFrom": "messages",+ "tableTo": "sessions",+ "columnsFrom": ["session_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "remote_host_reachability": {+ "name": "remote_host_reachability",+ "columns": {+ "ssh_host": {+ "name": "ssh_host",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'unknown'"+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_checked_at": {+ "name": "last_checked_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_reachable_at": {+ "name": "last_reachable_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "consecutive_failures": {+ "name": "consecutive_failures",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "remote_host_setup_plans": {+ "name": "remote_host_setup_plans",+ "columns": {+ "ssh_host": {+ "name": "ssh_host",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'idle'"+ },+ "steps": {+ "name": "steps",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "current_step_id": {+ "name": "current_step_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "remote_hosts": {+ "name": "remote_hosts",+ "columns": {+ "ssh_host": {+ "name": "ssh_host",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "session_room_connections": {+ "name": "session_room_connections",+ "columns": {+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "room_id": {+ "name": "room_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "room_name": {+ "name": "room_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "switch_agent_id": {+ "name": "switch_agent_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "session_room_connections_session_id_sessions_id_fk": {+ "name": "session_room_connections_session_id_sessions_id_fk",+ "tableFrom": "session_room_connections",+ "tableTo": "sessions",+ "columnsFrom": ["session_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "sessions": {+ "name": "sessions",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "agent_id": {+ "name": "agent_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "config": {+ "name": "config",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "agent_status": {+ "name": "agent_status",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "agent_status_seen": {+ "name": "agent_status_seen",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": 1+ },+ "is_initial_session": {+ "name": "is_initial_session",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "is_pinned": {+ "name": "is_pinned",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "archived_at": {+ "name": "archived_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_interacted_at": {+ "name": "last_interacted_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "status_changed_at": {+ "name": "status_changed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "idx_sessions_agent_id": {+ "name": "idx_sessions_agent_id",+ "columns": ["agent_id"],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "sessions_agent_id_agents_id_fk": {+ "name": "sessions_agent_id_agents_id_fk",+ "tableFrom": "sessions",+ "tableTo": "agents",+ "columnsFrom": ["agent_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "switch_servers": {+ "name": "switch_servers",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "dashboard_url": {+ "name": "dashboard_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "managed": {+ "name": "managed",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "management_kind": {+ "name": "management_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "ssh_host": {+ "name": "ssh_host",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "workspaces": {+ "name": "workspaces",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "server_id": {+ "name": "server_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "tenant_id": {+ "name": "tenant_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "organization_name": {+ "name": "organization_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "organization_role": {+ "name": "organization_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 c37fd6265..c3f57a7ac 100644--- a/console/apps/switch-console-desktop/drizzle/meta/_journal.json+++ b/console/apps/switch-console-desktop/drizzle/meta/_journal.json@@ -379,6 +379,13 @@"when": 1792510951310,"tag": "0053_agent_auto_mode","breakpoints": true+ },+ {+ "idx": 54,+ "version": "6",+ "when": 1793302509244,+ "tag": "0054_workspace_organizations",+ "breakpoints": true}]}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 f01d17f2a..fe0fdfd4f 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@@ -17,7 +17,11 @@ const passwordLogin = vi.hoisted(() => vi.fn());const signup = vi.hoisted(() => vi.fn());const reconcileServerWorkspaces = vi.hoisted(() => vi.fn());const listWorkspacesForServer = vi.hoisted(() => vi.fn());-const createTenant = vi.hoisted(() => vi.fn());+const createOrganization = vi.hoisted(() => vi.fn());+const createOrganizationWorkspace = vi.hoisted(() => vi.fn());+const fetchWorkspaceCreation = vi.hoisted(() => vi.fn());+const requireWorkspaceForServer = vi.hoisted(() => vi.fn());+const sessionScopes = vi.hoisted(() => [] as string[]);const acceptInvitation = vi.hoisted(() => vi.fn());// Stubbed rather than reimplemented: what the tests below assert is that the// kind reaches the event, not how a row is read as one.@@ -54,7 +58,10 @@ vi.mock('@main/core/managed-switch-server/managed-server-status', () => ({vi.mock('@main/core/workspaces/reconcile-workspaces', () => ({reconcileServerWorkspaces,}));-vi.mock('@main/core/workspaces/workspaces-store', () => ({ listWorkspacesForServer }));+vi.mock('@main/core/workspaces/workspaces-store', () => ({+ listWorkspacesForServer,+ requireWorkspaceForServer,+}));// 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() },@@ -75,6 +82,15 @@ vi.mock('@main/core/workspaces/workspace-session', async (importOriginal) => ({fn({ id: serverId, name: 'S' }),withReachableServerWorkspaceSession: async (serverId: string, fn: (s: unknown) => unknown) =>fn({ id: serverId, name: 'S' }),+ withWorkspaceSession: async (workspaceId: string, fn: (s: unknown) => unknown) => {+ sessionScopes.push(workspaceId);+ return fn({ id: 'srv', name: 'S' });+ },+ withReachableWorkspaceSession: async (workspaceId: string, fn: (s: unknown) => unknown) => {+ sessionScopes.push(workspaceId);+ return fn({ id: 'srv', name: 'S' });+ },+ workspaceServer: async () => ({ id: 'srv', name: 'S' }),}));vi.mock('./gateway-client', () => ({fetchMe,@@ -85,7 +101,9 @@ vi.mock('./gateway-client', () => ({fetchAgentRooms: vi.fn(),fetchAgents: vi.fn(),fetchAuthConfig,- createTenant,+ createOrganization,+ createOrganizationWorkspace,+ fetchWorkspaceCreation,acceptInvitation,fetchRoomRoles: vi.fn(),fetchRooms: vi.fn(),@@ -476,7 +494,7 @@ describe('createWorkspace', () => {});it('returns the local row for the workspace the gateway minted', async () => {- createTenant.mockResolvedValue({ id: 't9', slug: 'acme', name: 'Acme', role: 'owner' });+ createOrganization.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' }),@@ -487,7 +505,7 @@ describe('createWorkspace', () => {name: 'Acme',});- expect(createTenant).toHaveBeenCalledWith(expect.objectContaining({ id: 'srv' }), 'Acme');+ expect(createOrganization).toHaveBeenCalledWith(expect.objectContaining({ id: 'srv' }), 'Acme');expect(created.id).toBe('ws-9');});@@ -498,7 +516,7 @@ describe('createWorkspace', () => {* 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' });+ createOrganization.mockResolvedValue({ id: 't9', slug: 'acme', name: 'Acme', role: 'owner' });reconcileServerWorkspaces.mockRejectedValue(new Error('the gateway stopped answering'));await expect(@@ -511,7 +529,7 @@ describe('createWorkspace', () => {// 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' });+ createOrganization.mockResolvedValue({ id: 't9', slug: 'acme', name: 'Acme', role: 'owner' });listWorkspacesForServer.mockResolvedValue([workspaceRow({ id: 'ws-1', tenantId: 't1' })]);await expect(@@ -526,7 +544,67 @@ describe('createWorkspace', () => {await expect(switchServersController.createWorkspace({ serverId: 'srv', name: 'Acme' })).rejects.toThrow();- expect(createTenant).not.toHaveBeenCalled();+ expect(createOrganization).not.toHaveBeenCalled();+ });+});++describe('addOrganizationWorkspace', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ sessionScopes.length = 0;+ reconcileServerWorkspaces.mockReset().mockResolvedValue(undefined);+ });++ it('asks through the workspace named, and returns the local row for the new one', async () => {+ createOrganizationWorkspace.mockResolvedValue({+ id: 't9',+ slug: 'labs',+ name: 'Labs',+ role: 'owner',+ organizationId: 'o1',+ organizationRole: 'org_admin',+ });+ listWorkspacesForServer.mockResolvedValue([+ workspaceRow({ id: 'ws-1', tenantId: 't1' }),+ workspaceRow({ id: 'ws-9', tenantId: 't9', name: 'Labs', role: 'owner' }),+ ]);++ const created = await switchServersController.addOrganizationWorkspace({+ workspaceId: 'ws-1',+ name: 'Labs',+ });++ expect(sessionScopes).toEqual(['ws-1']);+ expect(createOrganizationWorkspace).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'srv' }),+ 'Labs'+ );+ expect(reconcileServerWorkspaces).toHaveBeenCalledWith('srv');+ expect(created.id).toBe('ws-9');+ });+});++describe('workspaceCreation', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ sessionScopes.length = 0;+ });++ it('answers for the workspace a call about the server is scoped to, and names it', async () => {+ requireWorkspaceForServer.mockResolvedValue(workspaceRow({ id: 'ws-2' }));+ fetchWorkspaceCreation.mockResolvedValue({+ canCreate: true,+ canAddWorkspace: false,+ organizations: true,+ });++ await expect(switchServersController.workspaceCreation('srv')).resolves.toEqual({+ canCreate: true,+ canAddWorkspace: false,+ organizations: true,+ workspaceId: 'ws-2',+ });+ expect(sessionScopes).toEqual(['ws-2']);});});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 122eab96b..ad57a62bf 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@@ -11,9 +11,15 @@ import { trackEvent } from '@main/core/telemetry/telemetry-service';import { reconcileServerWorkspaces } from '@main/core/workspaces/reconcile-workspaces';import {withReachableServerWorkspaceSession,+ withReachableWorkspaceSession,withServerWorkspaceSession,+ withWorkspaceSession,+ workspaceServer,} from '@main/core/workspaces/workspace-session';-import { listWorkspacesForServer } from '@main/core/workspaces/workspaces-store';+import {+ listWorkspacesForServer,+ requireWorkspaceForServer,+} from '@main/core/workspaces/workspaces-store';import { log } from '@main/lib/logger';import type {SaveConnectorAppInput,@@ -68,9 +74,9 @@ import {acceptInvitation,acceptPendingInvitation,joinWorkspaceByDomain,- createTenant,+ createOrganization,+ createOrganizationWorkspace,fetchAuthConfig,- fetchCanCreateWorkspace,deleteMyAccount,fetchMe,fetchJoinableWorkspaces,@@ -83,6 +89,8 @@ import {importConnectorApp,removeConnectorApp,saveConnectorApp,+ fetchWorkspaceCreation,+ type WorkspaceCreation,} from './gateway-client';import { openAuthenticatedGatewayPage } from './gateway-web';import {@@ -172,6 +180,19 @@ async function adoptWorkspaces(server: SwitchServer): Promise<void> {* Reconciled rather than inserted here, the same as `createWorkspace`: which* local row a membership belongs to is decided in one place.*/+/** The local row for a workspace the account has just created on a server. */+async function recordCreated(server: SwitchServer, tenant: RemoteTenant): Promise<Workspace> {+ await reconcileServerWorkspaces(server.id);+ const workspaces = await listWorkspacesForServer(server.id);+ 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;+}+async function recordJoined(server: SwitchServer, tenant: RemoteTenant): Promise<Workspace> {await reconcileServerWorkspaces(server.id);const workspaces = await listWorkspacesForServer(server.id);@@ -237,9 +258,20 @@ export const switchServersController = createRPCController({withReachableServerWorkspaceSession(params.serverId, (server) =>fetchAgentIconChoices(server, params.name, params.page)),- /** Whether the signed-in account may create a workspace on the server. */- canCreateWorkspace: (serverId: string) =>- withServerWorkspaceSession(serverId, (server) => fetchCanCreateWorkspace(server)),+ /**+ * What the signed-in account may create on the server, answered for the+ * workspace a call about the server is scoped to, which is named alongside:+ * adding a workspace is a question about that workspace's organization.+ */+ workspaceCreation: async (+ serverId: string+ ): Promise<WorkspaceCreation & { workspaceId: string }> => {+ const workspace = await requireWorkspaceForServer(serverId);+ const answer = await withWorkspaceSession(workspace.id, (server) =>+ fetchWorkspaceCreation(server)+ );+ return { ...answer, workspaceId: workspace.id };+ },/** Whether this server allows a third-party avatar URL (DiceBear, ui-avatars.com)* to be generated or sent anywhere. */avatarSettings: (serverId: string) =>@@ -410,7 +442,9 @@ export const switchServersController = createRPCController({},/**- * Create a workspace on a server, owned by the signed-in user.+ * Create an organization on a server, with a first workspace of the same+ * name, owned by the signed-in user, and return that workspace. A server+ * from before organizations creates the workspace alone.** Addressed by server rather than by workspace — the exception the split* allows itself, because the thing being created is the workspace: there is@@ -428,17 +462,22 @@ export const switchServersController = createRPCController({*/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;+ return recordCreated(server, await createOrganization(server, params.name));+ },++ /**+ * Add a workspace to the organization `workspaceId` belongs to, owned by the+ * signed-in user, and return it. The gateway reads the organization from the+ * workspace the session selects, so the call is scoped to that one.+ */+ addOrganizationWorkspace: async (params: {+ workspaceId: string;+ name: string;+ }): Promise<Workspace> => {+ const tenant = await withReachableWorkspaceSession(params.workspaceId, (server) =>+ createOrganizationWorkspace(server, params.name)+ );+ return recordCreated(await workspaceServer(params.workspaceId), tenant);},/**diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.tsindex c49bfb437..ee632e8f0 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts@@ -88,7 +88,11 @@ const {removeBridgeTeam,createInvitation,fetchInvitations,- fetchCanCreateWorkspace,+ createOrganization,+ createOrganizationWorkspace,+ fetchOrganizationNames,+ fetchTenants,+ fetchWorkspaceCreation,fetchInviteEmailEnabled,createRoom,deleteBridge,@@ -2336,6 +2340,147 @@ describe('messaging-app installs', () => {});});+describe('organizations', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.stubGlobal('fetch', fetchMock);+ getSessionCookie.mockResolvedValue(makeJwt(24 * 60 * 60));+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ const WORKSPACE_JSON = {+ id: 't1',+ slug: 'acme',+ name: 'Acme',+ role: 'owner',+ organization_id: 'o1',+ organization_role: 'org_admin',+ };+ const WORKSPACE = {+ id: 't1',+ slug: 'acme',+ name: 'Acme',+ role: 'owner',+ organizationId: 'o1',+ organizationRole: 'org_admin',+ };++ function requests(): Array<{ url: string; method: string; body: unknown }> {+ return (+ fetchMock.mock.calls as unknown as Array<[string, { method?: string; body?: string }]>+ ).map(([url, init]) => ({+ url,+ method: init.method ?? 'GET',+ body: init.body === undefined ? undefined : JSON.parse(init.body),+ }));+ }++ it('reads each membership’s organization and the caller’s role in it', async () => {+ fetchMock.mockResolvedValue(+ jsonResponse([+ WORKSPACE_JSON,+ { id: 't2', slug: 'old', name: 'Old', role: 'member' },+ ]) as never+ );++ await expect(fetchTenants(SERVER)).resolves.toEqual([+ WORKSPACE,+ {+ id: 't2',+ slug: 'old',+ name: 'Old',+ role: 'member',+ organizationId: null,+ organizationRole: null,+ },+ ]);+ });++ it('refuses an organization role it does not know', async () => {+ fetchMock.mockResolvedValue(+ jsonResponse([{ ...WORKSPACE_JSON, organization_role: 'billing' }]) as never+ );+ await expect(fetchTenants(SERVER)).rejects.toThrow(/unknown organization role: billing/);+ });++ it('names the organizations by id, and says when the server has none', async () => {+ fetchMock.mockResolvedValue(+ jsonResponse([{ id: 'o1', slug: 'acme', name: 'Acme Inc', role: 'org_admin' }]) as never+ );+ await expect(fetchOrganizationNames(SERVER)).resolves.toEqual(new Map([['o1', 'Acme Inc']]));++ fetchMock.mockResolvedValue(errorResponse(404, '{"detail":"Not Found"}') as never);+ await expect(fetchOrganizationNames(SERVER)).resolves.toBeNull();+ });++ it('creates an organization and answers with its first workspace', async () => {+ fetchMock.mockResolvedValue(+ jsonResponse({+ organization: { id: 'o1', slug: 'acme', name: 'Acme', role: 'org_admin' },+ workspace: WORKSPACE_JSON,+ }) as never+ );++ await expect(createOrganization(SERVER, 'Acme')).resolves.toEqual(WORKSPACE);+ expect(requests()).toEqual([+ {+ url: 'https://switch.example.com/gateway/organizations',+ method: 'POST',+ body: { name: 'Acme' },+ },+ ]);+ });++ it('creates a workspace on a server from before organizations', async () => {+ fetchMock+ .mockResolvedValueOnce(errorResponse(404, '{"detail":"Not Found"}') as never)+ .mockResolvedValueOnce(+ jsonResponse({ id: 't1', slug: 'acme', name: 'Acme', role: 'owner' }) as never+ );++ await expect(createOrganization(SERVER, 'Acme')).resolves.toEqual({+ id: 't1',+ slug: 'acme',+ name: 'Acme',+ role: 'owner',+ organizationId: null,+ organizationRole: null,+ });+ expect(requests().map((r) => r.url)).toEqual([+ 'https://switch.example.com/gateway/organizations',+ 'https://switch.example.com/gateway/tenants',+ ]);+ });++ it('passes on a refusal rather than retrying under the old route', async () => {+ fetchMock.mockResolvedValue(+ errorResponse(403, '{"detail":"Creating organizations is turned off"}') as never+ );++ await expect(createOrganization(SERVER, 'Acme')).rejects.toMatchObject({ status: 403 });+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it('adds a workspace to the selected workspace’s organization', async () => {+ fetchMock.mockResolvedValue(jsonResponse({ ...WORKSPACE_JSON, id: 't3' }) as never);++ await expect(createOrganizationWorkspace(SERVER, 'Labs')).resolves.toEqual({+ ...WORKSPACE,+ id: 't3',+ });+ expect(requests()).toEqual([+ {+ url: 'https://switch.example.com/gateway/organizations/current/workspaces',+ method: 'POST',+ body: { name: 'Labs' },+ },+ ]);+ });+});+describe('acceptInvitation', () => {beforeEach(() => {vi.clearAllMocks();@@ -2372,7 +2517,14 @@ describe('acceptInvitation', () => {expect(init.method).toBe('POST');expect(JSON.parse(init.body)).toEqual({ token: 'tok-1' });expect(setSessionCookie).toHaveBeenCalledExactlyOnceWith('srv-1', 'scoped');- expect(tenant).toEqual({ id: 't1', slug: 'cryo', name: 'Cryo Team', role: 'member' });+ expect(tenant).toEqual({+ id: 't1',+ slug: 'cryo',+ name: 'Cryo Team',+ role: 'member',+ organizationId: null,+ organizationRole: null,+ });});it('raises when the server joins the workspace but sends no cookie', async () => {@@ -2616,7 +2768,14 @@ describe('invitations addressed to the signed-in account', () => {expect(init.method).toBe('POST');expect(JSON.parse(init.body)).toEqual({ tenant_id: 't1', invitation_id: 'inv-1' });expect(setSessionCookie).toHaveBeenCalledExactlyOnceWith('srv-1', 'scoped');- expect(tenant).toEqual({ id: 't1', slug: 'cryo', name: 'Cryo Team', role: 'member' });+ expect(tenant).toEqual({+ id: 't1',+ slug: 'cryo',+ name: 'Cryo Team',+ role: 'member',+ organizationId: null,+ organizationRole: null,+ });});});@@ -2665,7 +2824,14 @@ describe('joining a workspace by e-mail domain', () => {fetchMock.mockResolvedValue({status: 200,ok: true,- json: async () => ({ id: 't9', slug: 'skunk', name: 'Skunkworks', role: 'member' }),+ json: async () => ({+ id: 't9',+ slug: 'skunk',+ name: 'Skunkworks',+ role: 'member',+ organization_id: 'o1',+ organization_role: 'member',+ }),headers: { get: () => null, getSetCookie: () => ['switch_auth=scoped; Path=/; HttpOnly'] },text: async () => '',} as never);@@ -2676,7 +2842,14 @@ describe('joining a workspace by e-mail domain', () => {expect(url).toBe('https://switch.example.com/gateway/joinable-tenants/t9/join');expect(init.method).toBe('POST');expect(setSessionCookie).toHaveBeenCalledExactlyOnceWith('srv-1', 'scoped');- expect(tenant).toEqual({ id: 't9', slug: 'skunk', name: 'Skunkworks', role: 'member' });+ expect(tenant).toEqual({+ id: 't9',+ slug: 'skunk',+ name: 'Skunkworks',+ role: 'member',+ organizationId: 'o1',+ organizationRole: 'member',+ });});it("reads a workspace's domains and the admin's own", async () => {@@ -2825,18 +2998,41 @@ describe('workspace invitations', () => {await expect(fetchInviteEmailEnabled(SERVER)).resolves.toBeNull();});- it('reads whether the server lets the account create a workspace', async () => {- fetchMock.mockResolvedValue(jsonResponse({ can_create_workspace: false }) as never);- await expect(fetchCanCreateWorkspace(SERVER)).resolves.toBe(false);+ it('reads what the server lets the account create', async () => {+ fetchMock.mockResolvedValue(+ jsonResponse({ can_create_workspace: false, can_add_workspace: true }) as never+ );+ await expect(fetchWorkspaceCreation(SERVER)).resolves.toEqual({+ canCreate: false,+ canAddWorkspace: true,+ organizations: true,+ });+ // Older servers refused nothing up front, so nothing is hidden on them, and+ // have no organizations to add to.fetchMock.mockResolvedValue(jsonResponse({ can_create_workspace: true }) as never);- await expect(fetchCanCreateWorkspace(SERVER)).resolves.toBe(true);-- // Older servers refused nothing up front, so nothing is hidden on them.+ await expect(fetchWorkspaceCreation(SERVER)).resolves.toEqual({+ canCreate: true,+ canAddWorkspace: false,+ organizations: false,+ });fetchMock.mockResolvedValue(jsonResponse({ state: 'ready' }) as never);- await expect(fetchCanCreateWorkspace(SERVER)).resolves.toBe(true);+ await expect(fetchWorkspaceCreation(SERVER)).resolves.toEqual({+ canCreate: true,+ canAddWorkspace: false,+ organizations: false,+ });fetchMock.mockResolvedValue(errorResponse(404, '{"detail":"Not Found"}') as never);- await expect(fetchCanCreateWorkspace(SERVER)).resolves.toBe(true);+ await expect(fetchWorkspaceCreation(SERVER)).resolves.toEqual({+ canCreate: true,+ canAddWorkspace: false,+ organizations: false,+ });+ });++ it('refuses an unreadable answer about adding a workspace', async () => {+ fetchMock.mockResolvedValue(jsonResponse({ can_add_workspace: 'yes' }) as never);+ await expect(fetchWorkspaceCreation(SERVER)).rejects.toThrow(/can_add_workspace/);});it('keeps the link when an older server says nothing about the e-mail', async () => {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 ddc4d7dad..15afdf2fc 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@@ -111,7 +111,7 @@ import type {PendingInvitations,WorkspaceJoinDomains,} from '@shared/core/workspaces/invitations';-import type { WorkspaceRole } from '@shared/core/workspaces/workspaces';+import type { OrganizationRole, WorkspaceRole } from '@shared/core/workspaces/workspaces';import { extractAuthCookie, reauthenticateManagedServer, refreshSession } from './auth';import { consoleIdentityHeaders } from './console-identity';import { NoManagementApiError } from './server-address';@@ -612,6 +612,18 @@ export type RemoteTenant = {slug: string;name: string;role: WorkspaceRole;+ /** Null on a server from before organizations, which reports none. */+ organizationId: string | null;+ organizationRole: OrganizationRole | null;+};++type TenantJson = {+ id: string;+ slug: string;+ name: string;+ role: string;+ organization_id?: string | null;+ organization_role?: string | null;};function mapRole(raw: unknown): WorkspaceRole {@@ -619,6 +631,23 @@ function mapRole(raw: unknown): WorkspaceRole {throw new GatewayError('http', `Switch server reported an unknown workspace role: ${raw}`);}+function mapOrganizationRole(raw: unknown): OrganizationRole | null {+ if (raw === undefined || raw === null) return null;+ if (raw === 'org_admin' || raw === 'member') return raw;+ throw new GatewayError('http', `Switch server reported an unknown organization role: ${raw}`);+}++function mapTenant(json: TenantJson): RemoteTenant {+ return {+ id: json.id,+ slug: json.slug,+ name: json.name,+ role: mapRole(json.role),+ organizationId: json.organization_id ?? null,+ organizationRole: mapOrganizationRole(json.organization_role),+ };+}+/*** 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@@ -626,30 +655,82 @@ function mapRole(raw: unknown): WorkspaceRole {*/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) }));+ return ((await res.json()) as TenantJson[]).map(mapTenant);}/**- * Create a workspace on this server, owned by the signed-in user.+ * The names of the organizations the signed-in user belongs to, by id. Like+ * `GET /tenants` it needs no tenant selected.+ *+ * Null on a server from before organizations, which has no such route.+ */+export async function fetchOrganizationNames(+ server: SwitchServer+): Promise<Map<string, string> | null> {+ let res: Response;+ try {+ res = await gatewayFetch(server, '/organizations', { authenticated: true });+ } catch (cause) {+ if (cause instanceof GatewayError && cause.status === 404) return null;+ throw cause;+ }+ const json = (await res.json()) as Array<{ id: string; name: string }>;+ return new Map(json.map((o) => [o.id, o.name]));+}++/**+ * Create an organization on this server, with a first workspace of the same+ * name, owned by the signed-in user. Answers with that workspace.+ *+ * A server from before organizations has no `POST /organizations`, and is+ * asked for a workspace through `POST /tenants` instead, as it always was.** 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', {+export async function createOrganization(+ server: SwitchServer,+ name: string+): Promise<RemoteTenant> {+ let res: Response;+ try {+ res = await gatewayFetch(server, '/organizations', {+ authenticated: true,+ method: 'POST',+ body: { name },+ });+ } catch (cause) {+ if (!(cause instanceof GatewayError && cause.status === 404)) throw cause;+ const legacy = await gatewayFetch(server, '/tenants', {+ authenticated: true,+ method: 'POST',+ body: { name },+ });+ return mapTenant((await legacy.json()) as TenantJson);+ }+ const json = (await res.json()) as { workspace: TenantJson };+ return mapTenant(json.workspace);+}++/**+ * Add a workspace to the organization of the workspace the session selects,+ * owned by the signed-in user. The gateway allows it to an `org_admin` only,+ * and leaves the session's selection where it was.+ *+ * Call it through the session seam scoped to a workspace of that organization:+ * the organization is read from the selection, not named in the call.+ */+export async function createOrganizationWorkspace(+ server: SwitchServer,+ name: string+): Promise<RemoteTenant> {+ const res = await gatewayFetch(server, '/organizations/current/workspaces', {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) };+ return mapTenant((await res.json()) as TenantJson);}/**@@ -757,7 +838,7 @@ export async function fetchPendingInvitations(server: SwitchServer): Promise<Pen}async function joinedTenant(server: SwitchServer, res: Response): Promise<RemoteTenant> {- const json = (await res.json()) as { id: string; slug: string; name: string; role: string };+ const json = (await res.json()) as TenantJson;const cookie = extractAuthCookie(res.headers.getSetCookie());if (!cookie) {throw new GatewayError(@@ -766,7 +847,7 @@ async function joinedTenant(server: SwitchServer, res: Response): Promise<Remote);}await setSessionCookie(server.id, cookie);- return { id: json.id, slug: json.slug, name: json.name, role: mapRole(json.role) };+ return mapTenant(json);}type InvitationJson = {@@ -997,30 +1078,68 @@ export async function fetchInviteEmailEnabled(server: SwitchServer): Promise<boo}/**- * Whether the signed-in account may create a workspace on this server: the- * server's own answer, which covers its sign-up mode, the per-person cap, and- * a deployment that keeps to one workspace because it is not isolating them.+ * What the signed-in account may create on this server, as the server answers+ * it for the workspace the session selects.+ *+ * - `canCreate`: a new organization with its first workspace — or, on a server+ * from before organizations, a workspace. The answer covers the server's+ * sign-up mode, the per-person cap, and a deployment that keeps to one+ * workspace because it is not isolating them.+ * - `canAddWorkspace`: another workspace in the selected workspace's+ * organization, which only its `org_admin` may do.+ * - `organizations`: whether the server has organizations at all, which is+ * what `canCreate` creates.+ */+export type WorkspaceCreation = {+ canCreate: boolean;+ canAddWorkspace: boolean;+ organizations: boolean;+};++/**+ * {@link WorkspaceCreation} for the session's workspace.*- * True on a server older than the answer (no session route, or no field): it- * refused nothing up front either.+ * On a server older than either answer (no session route, or no field) creating+ * is allowed, since it refused nothing up front either, and adding to an+ * organization is not, since there are none.*/-export async function fetchCanCreateWorkspace(server: SwitchServer): Promise<boolean> {+export async function fetchWorkspaceCreation(server: SwitchServer): Promise<WorkspaceCreation> {let res: Response;try {res = await gatewayFetch(server, '/auth/session', { authenticated: true });} catch (cause) {- if (cause instanceof GatewayError && cause.status === 404) return true;+ if (cause instanceof GatewayError && cause.status === 404) {+ return { canCreate: true, canAddWorkspace: false, organizations: false };+ }throw cause;}- const json = (await res.json()) as { can_create_workspace?: unknown };- if (json.can_create_workspace === undefined) return true;- if (typeof json.can_create_workspace !== 'boolean') {+ const json = (await res.json()) as {+ can_create_workspace?: unknown;+ can_add_workspace?: unknown;+ };+ return {+ canCreate: optionalFlag(server, json, 'can_create_workspace', true),+ canAddWorkspace: optionalFlag(server, json, 'can_add_workspace', false),+ // Answered by the same release that added organizations.+ organizations: json.can_add_workspace !== undefined,+ };+}++function optionalFlag(+ server: SwitchServer,+ json: Record<string, unknown>,+ field: string,+ absent: boolean+): boolean {+ const value = json[field];+ if (value === undefined) return absent;+ if (typeof value !== 'boolean') {throw new GatewayError('http',- `${server.name} reported an unreadable can_create_workspace: ${String(json.can_create_workspace)}`+ `${server.name} reported an unreadable ${field}: ${String(value)}`);}- return json.can_create_workspace;+ return value;}/** Options for `registerKnownAgent`, matching the gateway'sdiff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.db.test.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.db.test.tsindex 9efe105d1..db58fdc5d 100644--- a/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.db.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.db.test.ts@@ -10,6 +10,7 @@ const mocks = vi.hoisted(() => ({}));const fetchTenants = vi.hoisted(() => vi.fn());+const fetchOrganizationNames = 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 }[]> => []));@@ -25,7 +26,11 @@ vi.mock('@main/db/client', () => ({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/gateway-client', () => ({+ decodeJwtTenantId,+ fetchOrganizationNames,+ fetchTenants,+}));vi.mock('@main/core/switch-servers/require-server', () => ({requireServer: async (id: string) => ({ id, name: id }),}));@@ -49,8 +54,20 @@ const {setActiveWorkspaceId,} = await import('./workspaces-store');-function tenant(id: string, name: string, role = 'member') {- return { id, slug: id, name, role };+function tenant(+ id: string,+ name: string,+ role = 'member',+ organization: { id: string; role: string } | null = null+) {+ return {+ id,+ slug: id,+ name,+ role,+ organizationId: organization?.id ?? null,+ organizationRole: organization?.role ?? null,+ };}describe('reconcile-workspaces', () => {@@ -111,6 +128,85 @@ describe('reconcile-workspaces', () => {expect(found[0]!.role).toBe('owner');});+ it('records each workspace’s organization, its name and the account’s role in it', async () => {+ await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });+ fetchTenants.mockResolvedValue([+ tenant('t-1', 'Default', 'owner', { id: 'o-1', role: 'org_admin' }),+ tenant('t-2', 'Research', 'member', { id: 'o-2', role: 'member' }),+ ]);+ fetchOrganizationNames.mockResolvedValue(+ new Map([+ ['o-1', 'Acme'],+ ['o-2', 'Globex'],+ ])+ );++ await reconcileServerWorkspaces('srv-1');++ const found = await listWorkspacesForServer('srv-1');+ expect(+ found.map((w) => [w.tenantId, w.organizationId, w.organizationName, w.organizationRole])+ ).toEqual(+ expect.arrayContaining([+ ['t-1', 'o-1', 'Acme', 'org_admin'],+ ['t-2', 'o-2', 'Globex', 'member'],+ ])+ );+ });++ it('does not ask a server from before organizations to name any', async () => {+ await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });+ fetchTenants.mockResolvedValue([tenant('t-1', 'Default', 'owner')]);++ await reconcileServerWorkspaces('srv-1');++ expect(fetchOrganizationNames).not.toHaveBeenCalled();+ const [found] = await listWorkspacesForServer('srv-1');+ expect([found!.organizationId, found!.organizationName, found!.organizationRole]).toEqual([+ null,+ null,+ null,+ ]);+ });++ it('keeps the organization without a name, and says so, where the server cannot name it', async () => {+ await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });+ fetchTenants.mockResolvedValue([+ tenant('t-1', 'Default', 'owner', { id: 'o-1', role: 'org_admin' }),+ ]);+ fetchOrganizationNames.mockResolvedValue(null);++ await reconcileServerWorkspaces('srv-1');++ const [found] = await listWorkspacesForServer('srv-1');+ expect([found!.organizationId, found!.organizationName]).toEqual(['o-1', null]);+ expect(warn).toHaveBeenCalledWith(+ 'workspaces: the server reports organizations but could not name them',+ { server: 'srv-1' }+ );+ });++ it('forgets the organization role along with the workspace role when a membership goes', async () => {+ await createTenantWorkspace('srv-1', {+ id: 't-1',+ slug: 't-1',+ name: 'Default',+ role: 'owner',+ organizationId: 'o-1',+ organizationName: 'Acme',+ organizationRole: 'org_admin',+ });+ fetchTenants.mockResolvedValue([+ tenant('t-2', 'Research', 'member', { id: 'o-2', role: 'member' }),+ ]);+ fetchOrganizationNames.mockResolvedValue(new Map([['o-2', 'Globex']]));++ await reconcileServerWorkspaces('srv-1');++ const withdrawn = (await listWorkspacesForServer('srv-1')).find((w) => w.tenantId === 't-1');+ expect([withdrawn!.role, withdrawn!.organizationRole]).toEqual([null, null]);+ });+it('remembers a server whose account belongs to no workspace, until it joins one', async () => {const placeholder = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });fetchTenants.mockResolvedValue([]);@@ -263,12 +359,18 @@ describe('reconcile-workspaces', () => {slug: 't-1',name: 'Default',role: 'owner',+ organizationId: null,+ organizationName: null,+ organizationRole: null,});await createTenantWorkspace('srv-1', {id: 't-2',slug: 't-2',name: 'Research',role: 'member',+ organizationId: null,+ organizationName: null,+ organizationRole: null,});fetchTenants.mockResolvedValue([tenant('t-1', 'Default'), tenant('t-2', 'Research')]);@@ -328,6 +430,9 @@ describe('reconcile-workspaces', () => {slug: 't-1',name: 'Research',role: 'member',+ organizationId: null,+ organizationName: null,+ organizationRole: null,});fetchTenants.mockResolvedValue([tenant('t-1', 'Research', 'admin')]);@@ -349,6 +454,9 @@ describe('reconcile-workspaces', () => {slug: 't-gone',name: 'Research',role: 'member',+ organizationId: null,+ organizationName: null,+ organizationRole: null,});fetchTenants.mockResolvedValue([tenant('t-1', 'Default')]);@@ -373,6 +481,9 @@ describe('reconcile-workspaces', () => {slug: 't-back',name: 'Research',role: 'admin',+ organizationId: null,+ organizationName: null,+ organizationRole: null,});fetchTenants.mockResolvedValue([tenant('t-1', 'Default')]);await reconcileServerWorkspaces('srv-1');@@ -394,6 +505,9 @@ describe('reconcile-workspaces', () => {slug: 't-previous',name: 'Previous account’s',role: 'owner',+ organizationId: null,+ organizationName: null,+ organizationRole: null,});await setActiveWorkspaceId(previous.id);fetchTenants.mockResolvedValue([tenant('t-1', 'Default', 'owner')]);@@ -410,6 +524,9 @@ describe('reconcile-workspaces', () => {slug: 't-gone',name: 'Research',role: 'member',+ organizationId: null,+ organizationName: null,+ organizationRole: null,});await setActiveWorkspaceId(held.id);fetchTenants.mockResolvedValue([]);@@ -444,6 +561,9 @@ describe('reconcile-workspaces', () => {slug: 't-gone',name: 'Research',role: 'member',+ organizationId: null,+ organizationName: null,+ organizationRole: null,});fetchTenants.mockResolvedValue([]);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.tsindex efe139fd9..dd90f3718 100644--- 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.ts@@ -1,6 +1,7 @@import { isManagedServerRunning } from '@main/core/managed-switch-server/managed-server-status';import {decodeJwtTenantId,+ fetchOrganizationNames,fetchTenants,type RemoteTenant,} from '@main/core/switch-servers/gateway-client';@@ -18,9 +19,42 @@ import {leaveUnavailableActiveWorkspace,listWorkspacesForServer,setWorkspaceTenant,+ type TenantRecord,workspaceHasAgents,} from './workspaces-store';+/**+ * The account's memberships on `server`, each with its organization's name.+ *+ * The names are asked for only where a membership names an organization, so a+ * server from before organizations is not asked about a route it lacks. One+ * that reports organization ids but cannot list them leaves the names null,+ * with a warning: the switcher then lists those workspaces without grouping+ * them, which is what it did before organizations.+ */+async function fetchTenantRecords(server: SwitchServer): Promise<TenantRecord[]> {+ const tenants = await fetchTenants(server);+ const organized = tenants.some((tenant) => tenant.organizationId !== null);+ const names = organized ? await fetchOrganizationNames(server) : null;+ if (organized && names === null) {+ log.warn('workspaces: the server reports organizations but could not name them', {+ server: server.id,+ });+ }+ return tenants.map((tenant) => withOrganizationName(tenant, names));+}++function withOrganizationName(+ tenant: RemoteTenant,+ names: Map<string, string> | null+): TenantRecord {+ return {+ ...tenant,+ organizationName:+ tenant.organizationId === null ? null : (names?.get(tenant.organizationId) ?? null),+ };+}+/*** The tenant this server's session resolves to — the one whose data every call* made against it so far has actually reached.@@ -33,8 +67,8 @@ import {*/async function resolvedTenant(server: SwitchServer,- tenants: RemoteTenant[]-): Promise<RemoteTenant | null> {+ tenants: TenantRecord[]+): Promise<TenantRecord | 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@@ -60,9 +94,9 @@ async function resolvedTenant(async function tenantToAdopt(server: SwitchServer,unclaimed: Workspace,- tenants: RemoteTenant[],- unmatched: RemoteTenant[]-): Promise<RemoteTenant | null> {+ tenants: TenantRecord[],+ unmatched: TenantRecord[]+): Promise<TenantRecord | 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);@@ -89,7 +123,7 @@ async function tenantToAdopt(async function markWithdrawnMemberships(serverId: string,local: Workspace[],- tenants: RemoteTenant[]+ tenants: TenantRecord[]): Promise<void> {for (const workspace of local) {if (!workspace.tenantId) continue;@@ -161,7 +195,7 @@ export function listServersWithoutMembership(): string[] {async function reconcileOneServer(serverId: string): Promise<void> {const server = await requireServer(serverId);- const tenants = await fetchTenants(server);+ const tenants = await fetchTenantRecords(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 casediff --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.tsindex b8a1fc5fd..f90ae9f8b 100644--- 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.ts@@ -3,6 +3,7 @@ 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 OrganizationRole,type Workspace,type WorkspaceRole,workspaceUnavailability,@@ -10,6 +11,29 @@ import {const ACTIVE_WORKSPACE_KV_KEY = 'activeWorkspaceId';+/** What the gateway owns about a tenant the account belongs to. */+export type TenantRecord = {+ id: string;+ slug: string;+ name: string;+ role: WorkspaceRole;+ organizationId: string | null;+ organizationName: string | null;+ organizationRole: OrganizationRole | null;+};++function tenantColumns(tenant: TenantRecord) {+ return {+ tenantId: tenant.id,+ slug: tenant.slug,+ name: tenant.name,+ role: tenant.role,+ organizationId: tenant.organizationId,+ organizationName: tenant.organizationName,+ organizationRole: tenant.organizationRole,+ };+}+function mapRow(row: WorkspaceRow): Workspace {return {id: row.id,@@ -18,6 +42,9 @@ function mapRow(row: WorkspaceRow): Workspace {tenantId: row.tenantId ?? null,slug: row.slug ?? null,role: row.role ?? null,+ organizationId: row.organizationId ?? null,+ organizationName: row.organizationName ?? null,+ organizationRole: row.organizationRole ?? null,createdAt: row.createdAt,updatedAt: row.updatedAt,};@@ -156,17 +183,11 @@ export function insertServerWorkspace(* 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> {+export async function setWorkspaceTenant(workspaceId: string, tenant: TenantRecord): Promise<void> {await db.update(workspaces).set({- tenantId: tenant.id,- slug: tenant.slug,- name: tenant.name,- role: tenant.role,+ ...tenantColumns(tenant),updatedAt: sql`CURRENT_TIMESTAMP`,}).where(eq(workspaces.id, workspaceId));@@ -184,7 +205,7 @@ export async function setWorkspaceTenant(export async function clearWorkspaceRole(workspaceId: string): Promise<void> {await db.update(workspaces)- .set({ role: null, updatedAt: sql`CURRENT_TIMESTAMP` })+ .set({ role: null, organizationRole: null, updatedAt: sql`CURRENT_TIMESTAMP` }).where(eq(workspaces.id, workspaceId));}@@ -229,17 +250,14 @@ export async function discardEmptyWorkspace(workspaceId: string): Promise<void>/** 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 }+ tenant: TenantRecord): Promise<Workspace> {const [row] = await db.insert(workspaces).values({id: randomUUID(),serverId,- name: tenant.name,- tenantId: tenant.id,- slug: tenant.slug,- role: tenant.role,+ ...tenantColumns(tenant),updatedAt: sql`CURRENT_TIMESTAMP`,}).returning();diff --git a/console/apps/switch-console-desktop/src/main/db/schema.ts b/console/apps/switch-console-desktop/src/main/db/schema.tsindex 6ea79ac57..853c01274 100644--- a/console/apps/switch-console-desktop/src/main/db/schema.ts+++ b/console/apps/switch-console-desktop/src/main/db/schema.ts@@ -4,7 +4,7 @@ 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';+import type { OrganizationRole, WorkspaceRole } from '@shared/core/workspaces/workspaces';// ---------------------------------------------------------------------------// Data model (Switch Console rework — diverges from upstream; see@@ -171,6 +171,13 @@ export const workspaces = sqliteTable(* the notion does not apply.*/role: text('role').$type<WorkspaceRole>(),+ /**+ * The workspace's organization on the gateway, its name, and the caller's+ * role in it, as last reported. Null on a server from before organizations.+ */+ organizationId: text('organization_id'),+ organizationName: text('organization_name'),+ organizationRole: text('organization_role').$type<OrganizationRole>(),createdAt: text('created_at').notNull().default(sql`CURRENT_TIMESTAMP`),diff --git a/console/apps/switch-console-desktop/src/main/db/tests/migrations/0054-workspace-organizations.test.ts b/console/apps/switch-console-desktop/src/main/db/tests/migrations/0054-workspace-organizations.test.tsnew file mode 100644index 000000000..e1b4b4720--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/db/tests/migrations/0054-workspace-organizations.test.ts@@ -0,0 +1,77 @@+/**+ * Migration 0054 — the organization each workspace belongs to.+ *+ * Runs the real migration runner over `pre-0054.db` (the baseline fixture at+ * 0053), and the SQL over a hand-built table holding workspaces, which the+ * baseline has none of.+ *+ * Workspaces that already exist read as belonging to no organization until the+ * next reconcile asks the server, which is what a server from before+ * organizations would answer too.+ */++import { readFileSync } from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { openFixture } from '@tooling/utils/db';+import Database from 'better-sqlite3';+import { describe, expect, it } from 'vitest';++const MIGRATION_SQL = readFileSync(+ path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ '../../../../../drizzle/0054_workspace_organizations.sql'+ ),+ 'utf8'+);++describe('migration 0054: workspace organizations', () => {+ it('adds the organization columns to the baseline', async () => {+ const fixture = await openFixture('pre-0054');+ try {+ const columns = (+ fixture.sqlite.prepare(`PRAGMA table_info(workspaces)`).all() as { name: string }[]+ ).map((c) => c.name);+ expect(columns).toEqual(+ expect.arrayContaining(['organization_id', 'organization_name', 'organization_role'])+ );+ } finally {+ fixture.close();+ }+ });++ it('leaves existing workspaces in no organization, as they were', () => {+ const db = new Database(':memory:');+ try {+ db.exec(`+ CREATE TABLE workspaces (+ id TEXT PRIMARY KEY NOT NULL,+ name TEXT NOT NULL,+ tenant_id TEXT,+ role TEXT+ );+ INSERT INTO workspaces (id, name, tenant_id, role) VALUES ('ws-1', 'Default', 't-1', 'owner');+ `);+ for (const statement of MIGRATION_SQL.split('--> statement-breakpoint')) db.exec(statement);++ expect(+ db+ .prepare(+ 'SELECT id, tenant_id, role, organization_id, organization_name, organization_role FROM workspaces'+ )+ .all()+ ).toEqual([+ {+ id: 'ws-1',+ tenant_id: 't-1',+ role: 'owner',+ organization_id: null,+ organization_name: null,+ organization_role: null,+ },+ ]);+ } finally {+ db.close();+ }+ });+});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 e3961da80..463b8ca0b 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,14 @@import { useQuery, useQueryClient } from '@tanstack/react-query';import { Check, ChevronsUpDown, Plus, Search, Server, UserPlus } from 'lucide-react';import { observer } from 'mobx-react-lite';-import { useEffect, useState } from 'react';+import { Fragment, useEffect, useState } from 'react';import { ChatsOfflineNote } from '@renderer/features/chats/components/chats-offline-note';+import type { CreateTarget } from '@renderer/features/workspaces/create-workspace-modal';+import {+ addWorkspaceThrough,+ type CreationAnswer,+ groupByOrganization,+} from '@renderer/features/workspaces/organization-groups';import {InvitedBadge,invitationSummary,@@ -392,8 +398,9 @@ const WorkspaceMenu = observer(function WorkspaceMenu({</div>)}<DropdownMenuSeparator className="mx-1 my-1.5 h-[0.5px] bg-[var(--hair)]" />- {/* New workspace and Invite live with the server and the workspace- they act on, so only what belongs to no server is left here. */}+ {/* Create organization and Invite live with the server and the+ workspace they act on, so only what belongs to no server is left+ here. */}<DropdownMenuItem className={ACTION_ROW} onClick={() => showAddServerModal({})}><Server className="size-4" />Add server…@@ -489,7 +496,7 @@ const ServerWorkspaceGroup = observer(function ServerWorkspaceGroup({<ServerWorkspaceGroupBodyserver={server}query={query}- canCreateWorkspace={false}+ creation={NO_CREATION}invitations={NO_OFFERS.invitations}joinable={NO_OFFERS.joinable}invitationsFailed={false}@@ -503,22 +510,47 @@ const NO_OFFERS: { invitations: PendingInvitation[]; joinable: JoinableWorkspacejoinable: [],};+/**+ * What the switcher offers to create on a server.+ *+ * `answer` is the server's own, for the workspace it was asked about; null+ * until it has answered, or where it could not be asked.+ */+type Creation = {+ canCreate: boolean;+ organizations: boolean;+ answer: CreationAnswer | null;+};++const NO_CREATION: Creation = { canCreate: false, organizations: false, answer: null };+function AvailableServerWorkspaceGroup({ server, query }: { server: SwitchServer; query: string }) {const invitations = usePendingInvitations(server.id);const joinable = useJoinableWorkspaces(server.id);- // The server's own answer, so New workspace is not offered where creating- // one is refused: a deployment that keeps to one workspace, invite-only- // sign-up, or a spent allowance. Offered until it has said no.- const canCreate = useQuery({- queryKey: ['can-create-workspace', server.id],- queryFn: () => rpc.switchServers.canCreateWorkspace(server.id),+ // The server's own answer, so Create organization is not offered where+ // creating one is refused: a deployment that keeps to one workspace,+ // invite-only sign-up, or a spent allowance. Offered until it has said no.+ const answer = useQuery({+ queryKey: ['workspace-creation', server.id],+ queryFn: () => rpc.switchServers.workspaceCreation(server.id),staleTime: 60_000,});+ const creation: Creation = answer.data+ ? {+ canCreate: answer.data.canCreate,+ organizations: answer.data.organizations,+ answer: answer.data,+ }+ : {+ canCreate: true,+ organizations: workspacesStore.onServer(server.id).some((w) => w.organizationId !== null),+ answer: null,+ };return (<ServerWorkspaceGroupBodyserver={server}query={query}- canCreateWorkspace={canCreate.data !== false}+ creation={creation}invitations={listedInvitations(invitations.data)}joinable={listedJoinable(joinable.data)}invitationsFailed={invitations.isError}@@ -530,7 +562,7 @@ function AvailableServerWorkspaceGroup({ server, query }: { server: SwitchServerconst ServerWorkspaceGroupBody = observer(function ServerWorkspaceGroupBody({server,query,- canCreateWorkspace,+ creation,invitations,joinable,invitationsFailed,@@ -538,7 +570,7 @@ const ServerWorkspaceGroupBody = observer(function ServerWorkspaceGroupBody({}: {server: SwitchServer;query: string;- canCreateWorkspace: boolean;+ creation: Creation;invitations: PendingInvitation[];joinable: JoinableWorkspace[];invitationsFailed: boolean;@@ -597,11 +629,15 @@ const ServerWorkspaceGroupBody = observer(function ServerWorkspaceGroupBody({return null;}const available = availability === 'available';- const createWorkspace = () =>+ const create = (target: CreateTarget) =>showCreateWorkspaceModal({serverId: server.id,+ target,onSuccess: (workspace) => navigate('server', { serverId: workspace.serverId }),});+ const groups = groupByOrganization(workspaces);+ // Headed only where there is more than one to tell apart.+ const headed = groups.length > 1;return (<DropdownMenuGroup>@@ -639,8 +675,10 @@ const ServerWorkspaceGroupBody = observer(function ServerWorkspaceGroupBody({<>{noMembership && whole && (<div className="px-2 py-1.5 text-xs text-foreground-muted">- {canCreateWorkspace- ? 'No workspace yet — create one, or accept an invitation below.'+ {creation.canCreate+ ? creation.organizations+ ? 'No workspace yet — create an organization, or accept an invitation below.'+ : 'No workspace yet — create one, or accept an invitation below.': 'No workspace yet — accept an invitation below.'}</div>)}@@ -652,15 +690,47 @@ const ServerWorkspaceGroupBody = observer(function ServerWorkspaceGroupBody({No workspace yet — this server has not finished being set up.</div>) : (- workspaces.map((workspace) => (- <WorkspaceMenuItem- key={workspace.id}- workspace={workspace}- server={server}- onServerCount={all.length}- dormant={false}- />- ))+ groups.map((group) => {+ const through = whole ? addWorkspaceThrough(group, all, creation.answer) : null;+ return (+ <Fragment key={group.organizationId ?? 'none'}>+ {headed && (+ <div+ data-org-heading+ className="truncate px-[9px] pt-1.5 pb-0.5 text-[11px] font-medium text-[var(--fg-dim)]"+ >+ {group.name ?? 'Other workspaces'}+ </div>+ )}+ {group.workspaces.map((workspace) => (+ <WorkspaceMenuItem+ key={workspace.id}+ workspace={workspace}+ server={server}+ onServerCount={all.length}+ dormant={false}+ />+ ))}+ {through && (+ <DropdownMenuItem+ onClick={() =>+ create({+ kind: 'organization-workspace',+ through: through.id,+ organizationName: group.name,+ })+ }+ className={cn(ACTION_ROW, 'text-[var(--fg-dim)]')}+ >+ <Plus className="size-4" />+ {headed || group.name === null+ ? 'Add workspace'+ : `Add workspace to ${group.name}`}+ </DropdownMenuItem>+ )}+ </Fragment>+ );+ }))}{invitationsFailed && (<div className="px-2 py-1.5 text-xs text-foreground-muted">@@ -682,13 +752,15 @@ const ServerWorkspaceGroupBody = observer(function ServerWorkspaceGroupBody({{shownJoinable.map((offer) => (<JoinableWorkspaceMenuItem key={offer.tenantId} offer={offer} server={server} />))}- {whole && canCreateWorkspace && (+ {whole && creation.canCreate && (<DropdownMenuItem- onClick={createWorkspace}+ onClick={() =>+ create({ kind: creation.organizations ? 'organization' : 'workspace' })+ }className={cn(ACTION_ROW, 'text-[var(--fg-dim)]')}><Plus className="size-4" />- New workspace+ {creation.organizations ? 'Create organization' : 'New workspace'}</DropdownMenuItem>)}</>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.tsxindex f87a30165..0912ebc0f 100644--- 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.tsx@@ -17,13 +17,58 @@ import { Input } from '@renderer/lib/ui/input';import type { Workspace } from '@shared/core/workspaces/workspaces';import { createWorkspaceFailureText } from './describe-create-failure';+/**+ * What is being created.+ *+ * - `organization`: an organization with a first workspace of the same name,+ * which is what creating means on a server with organizations.+ * - `workspace`: a workspace on its own, on a server from before them.+ * - `organization-workspace`: another workspace in an organization the account+ * is an `org_admin` of, asked for through `through`, one of its workspaces.+ */+export type CreateTarget =+ | { kind: 'organization' }+ | { kind: 'workspace' }+ | { kind: 'organization-workspace'; through: string; organizationName: string | null };+type CreateWorkspaceModalArgs = {- /** The server to create it on: the one whose "New workspace" was chosen. */+ /** The server to create it on: the one whose group the action was chosen in. */serverId: string;+ target: CreateTarget;};+function title(target: CreateTarget, serverName: string | null): string {+ switch (target.kind) {+ case 'organization':+ return serverName ? `Create an organization on ${serverName}` : 'Create an organization';+ case 'workspace':+ return serverName ? `Create a workspace on ${serverName}` : 'Create a workspace';+ case 'organization-workspace':+ return target.organizationName+ ? `Add a workspace to ${target.organizationName}`+ : 'Add a workspace to your organization';+ }+}++function placement(target: CreateTarget, serverName: string): string {+ switch (target.kind) {+ case 'organization':+ return `It will live on ${serverName}, with a first workspace of the same name for its rooms and agents. You can add more workspaces to it later.`;+ case 'workspace':+ return `It will live on ${serverName}, along with its rooms and agents.`;+ case 'organization-workspace':+ return `You will own it, and every admin of ${target.organizationName ?? 'the organization'} can manage it.`;+ }+}+type Props = BaseModalProps<Workspace> & CreateWorkspaceModalArgs;+const CONFIRM_LABEL: Record<CreateTarget['kind'], string> = {+ organization: 'Create organization',+ workspace: 'Create workspace',+ 'organization-workspace': 'Add workspace',+};+/*** Why a server cannot be asked to create a workspace, or null when it can.*@@ -49,11 +94,12 @@ function whyNotReady(serverId: string): string | null {}/**- * Make a workspace from the switcher.+ * Make an organization, or a workspace in one, from the switcher.*- * A workspace belongs to a server, and the switcher has already said which:- * each server's group ends with its own New workspace, so the server is the- * one whose row was chosen and this asks only for the name.+ * Both belong to a server, and the switcher has already said which: each+ * server's group ends with its own Create organization, and each organization+ * an `org_admin` runs with its own Add workspace, so this asks only for the+ * name.** 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@@ -67,6 +113,7 @@ function whyNotReady(serverId: string): string | null {*/export const CreateWorkspaceModal = observer(function CreateWorkspaceModal({serverId,+ target: creating,onSuccess,onClose,}: Props) {@@ -102,7 +149,11 @@ export const CreateWorkspaceModal = observer(function CreateWorkspaceModal({setCloseGuard(true);setError(null);try {- const workspace = created ?? (await workspacesStore.create(where, trimmed));+ const workspace =+ created ??+ (creating.kind === 'organization-workspace'+ ? await workspacesStore.addToOrganization(creating.through, trimmed)+ : 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.@@ -131,9 +182,7 @@ export const CreateWorkspaceModal = observer(function CreateWorkspaceModal({return (<><DialogHeader showCloseButton={false}>- <DialogTitle>- {target ? `Create a workspace on ${target.name}` : 'Create a workspace'}- </DialogTitle>+ <DialogTitle>{title(creating, target?.name ?? null)}</DialogTitle></DialogHeader><DialogContentArea className="pt-0"><FieldGroup>@@ -162,24 +211,24 @@ export const CreateWorkspaceModal = observer(function CreateWorkspaceModal({) : notReady !== null ? (<p className="text-xs text-destructive">{notReady}</p>) : target !== null ? (- <p className="text-xs text-foreground-muted">- It will live on {target.name}, along with its rooms and agents.- </p>+ <p className="text-xs text-foreground-muted">{placement(creating, target.name)}</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>+ {creating.kind !== 'organization-workspace' && (+ <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>@@ -198,7 +247,7 @@ export const CreateWorkspaceModal = observer(function CreateWorkspaceModal({: 'Open workspace': submitting? 'Creating…'- : 'Create workspace'}+ : CONFIRM_LABEL[creating.kind]}</ConfirmButton></DialogFooter></>diff --git a/console/apps/switch-console-desktop/src/renderer/features/workspaces/organization-groups.test.ts b/console/apps/switch-console-desktop/src/renderer/features/workspaces/organization-groups.test.tsnew file mode 100644index 000000000..5ef29cbc9--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/workspaces/organization-groups.test.ts@@ -0,0 +1,93 @@+import { describe, expect, it } from 'vitest';+import type { OrganizationRole, Workspace } from '@shared/core/workspaces/workspaces';+import { addWorkspaceThrough, groupByOrganization } from './organization-groups';++function workspace(+ id: string,+ organization: { id: string; name: string | null; role: OrganizationRole } | null,+ patch: Partial<Workspace> = {}+): Workspace {+ return {+ id,+ serverId: 'srv-1',+ name: id,+ tenantId: `tenant-${id}`,+ slug: id,+ role: 'member',+ organizationId: organization?.id ?? null,+ organizationName: organization?.name ?? null,+ organizationRole: organization?.role ?? null,+ createdAt: '',+ updatedAt: '',+ ...patch,+ };+}++const ACME_ADMIN = { id: 'o-1', name: 'Acme', role: 'org_admin' } as const;+const GLOBEX_MEMBER = { id: 'o-2', name: 'Globex', role: 'member' } as const;++describe('groupByOrganization', () => {+ it('groups by organization, in the order each first appears', () => {+ const groups = groupByOrganization([+ workspace('a', ACME_ADMIN),+ workspace('b', GLOBEX_MEMBER),+ workspace('c', ACME_ADMIN),+ ]);++ expect(groups.map((g) => [g.name, g.workspaces.map((w) => w.id)])).toEqual([+ ['Acme', ['a', 'c']],+ ['Globex', ['b']],+ ]);+ });++ it('keeps a server from before organizations as one unnamed group', () => {+ const groups = groupByOrganization([workspace('a', null), workspace('b', null)]);++ expect(groups).toEqual([+ { organizationId: null, name: null, workspaces: [expect.anything(), expect.anything()] },+ ]);+ });+});++describe('addWorkspaceThrough', () => {+ it('offers it to an org admin, through one of the organization’s workspaces', () => {+ const all = [workspace('a', ACME_ADMIN), workspace('b', GLOBEX_MEMBER)];+ const [acme, globex] = groupByOrganization(all);++ expect(addWorkspaceThrough(acme!, all, null)?.id).toBe('a');+ expect(addWorkspaceThrough(globex!, all, null)).toBeNull();+ });++ it('does not ask through a workspace the account has lost', () => {+ const all = [workspace('a', ACME_ADMIN, { role: null }), workspace('b', ACME_ADMIN)];+ const [acme] = groupByOrganization(all);++ expect(addWorkspaceThrough(acme!, all, null)?.id).toBe('b');+ });++ it('takes a refusal given for an organization the account runs as holding everywhere', () => {+ const otherAdmin = { id: 'o-3', name: 'Initech', role: 'org_admin' } as const;+ const all = [workspace('a', ACME_ADMIN), workspace('c', otherAdmin)];+ const [, initech] = groupByOrganization(all);++ expect(+ addWorkspaceThrough(initech!, all, { canAddWorkspace: false, workspaceId: 'a' })+ ).toBeNull();+ });++ it('ignores a refusal given for an organization the account does not run', () => {+ const all = [workspace('a', ACME_ADMIN), workspace('b', GLOBEX_MEMBER)];+ const [acme] = groupByOrganization(all);++ expect(addWorkspaceThrough(acme!, all, { canAddWorkspace: false, workspaceId: 'b' })?.id).toBe(+ 'a'+ );+ });++ it('offers nothing on a server from before organizations', () => {+ const all = [workspace('a', null, { role: 'owner' })];+ const [group] = groupByOrganization(all);++ expect(addWorkspaceThrough(group!, all, null)).toBeNull();+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/workspaces/organization-groups.ts b/console/apps/switch-console-desktop/src/renderer/features/workspaces/organization-groups.tsnew file mode 100644index 000000000..5a00ffcac--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/workspaces/organization-groups.ts@@ -0,0 +1,68 @@+import {+ administersOrganization,+ type Workspace,+ workspaceUnavailability,+} from '@shared/core/workspaces/workspaces';++/** A server's workspaces in one organization, in the order they were listed. */+export type OrganizationGroup = {+ /** Null for the workspaces that name no organization. */+ organizationId: string | null;+ name: string | null;+ workspaces: Workspace[];+};++/**+ * `workspaces` grouped by the organization each belongs to, the groups in the+ * order their first workspace appears.+ *+ * Every workspace names an organization on a server that has them, and none+ * does on one from before them, so a server's list is one group there.+ */+export function groupByOrganization(workspaces: Workspace[]): OrganizationGroup[] {+ const groups = new Map<string | null, OrganizationGroup>();+ for (const workspace of workspaces) {+ const key = workspace.organizationId;+ let group = groups.get(key);+ if (!group) {+ group = { organizationId: key, name: workspace.organizationName, workspaces: [] };+ groups.set(key, group);+ }+ group.name ??= workspace.organizationName;+ group.workspaces.push(workspace);+ }+ return [...groups.values()];+}++/** What a server answered about creating, for the workspace it was asked about. */+export type CreationAnswer = { canAddWorkspace: boolean; workspaceId: string };++/**+ * The workspace to add another to `group`'s organization through, or null when+ * the account may not.+ *+ * The workspace is any one the account can open there as its `org_admin`: the+ * gateway reads the organization from the workspace the call is scoped to.+ *+ * The server's answer was given for one workspace. Where the account is an+ * `org_admin` there, a refusal is about the account — its allowance spent, or+ * a deployment that keeps to one workspace — and holds in every organization;+ * anywhere else it says nothing about this one, and the role decides until the+ * server refuses.+ */+export function addWorkspaceThrough(+ group: OrganizationGroup,+ onServer: Workspace[],+ answer: CreationAnswer | null+): Workspace | null {+ if (group.organizationId === null) return null;+ const through = group.workspaces.find(+ (workspace) =>+ administersOrganization(workspace) &&+ workspaceUnavailability(workspace, onServer.length) === null+ );+ if (!through || answer === null) return through ?? null;+ const asked = onServer.find((workspace) => workspace.id === answer.workspaceId);+ if (asked && administersOrganization(asked) && !answer.canAddWorkspace) return null;+ return through;+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspace-title.test.ts b/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspace-title.test.tsindex 893d46707..88b476623 100644--- a/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspace-title.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspace-title.test.ts@@ -26,6 +26,9 @@ function workspace(name: string, tenantId: string | null): Workspace {tenantId,slug: null,role: null,+ organizationId: null,+ organizationName: null,+ organizationRole: null,createdAt: '',updatedAt: '',};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.tsindex 86ca0077c..1117e5526 100644--- 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.ts@@ -28,6 +28,9 @@ function workspace(id: string, serverId: string, name = id): Workspace {tenantId: `tenant-${id}`,slug: id,role: 'member',+ organizationId: null,+ organizationName: null,+ organizationRole: null,createdAt: '2026-01-01T00:00:00Z',updatedAt: '2026-01-01T00:00:00Z',};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.tsindex c0dac6d8b..d5cb47c19 100644--- 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.ts@@ -79,7 +79,9 @@ export class WorkspacesStore {}/**- * Create a workspace on a server and return it.+ * Create an organization on a server, with a first workspace of the same+ * name, and return that workspace. A server from before organizations+ * creates the workspace alone.** 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.@@ -92,6 +94,16 @@ export class WorkspacesStore {return workspace;}+ /**+ * Add a workspace to the organization `workspaceId` belongs to, and return+ * it. Refreshes before returning, for the same reason as {@link create}.+ */+ async addToOrganization(workspaceId: string, name: string): Promise<Workspace> {+ const workspace = await rpc.switchServers.addOrganizationWorkspace({ workspaceId, name });+ await this.refresh();+ return workspace;+ }+/*** Accept an invitation on a server and return the workspace it admits to.*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.tsxindex 99e4a414c..3455d4d3a 100644--- 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.tsx@@ -10,6 +10,7 @@ import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const create = vi.hoisted(() => vi.fn());+const addToOrganization = 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. */@@ -40,10 +41,13 @@ vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({}));vi.mock('@renderer/features/workspaces/workspaces-store', () => ({- workspacesStore: { create, setActive: setActiveWorkspace },+ workspacesStore: { create, addToOrganization, setActive: setActiveWorkspace },}));-import { CreateWorkspaceModal } from '@renderer/features/workspaces/create-workspace-modal';+import {+ type CreateTarget,+ 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';@@ -69,6 +73,7 @@ function workspace(id: string, serverId: string) {beforeEach(() => {create.mockReset();+ addToOrganization.mockReset();setActiveWorkspace.mockReset().mockResolvedValue(undefined);refreshStatus.mockReset();onSuccess.mockReset();@@ -116,7 +121,10 @@ afterEach(async () => {root = null;});-async function render(serverId: string): Promise<HTMLDivElement> {+async function render(+ serverId: string,+ target: CreateTarget = { kind: 'workspace' }+): Promise<HTMLDivElement> {container = document.createElement('div');document.body.appendChild(container);root = createRoot(container);@@ -125,7 +133,12 @@ async function render(serverId: string): Promise<HTMLDivElement> {await act(async () =>root!.render(<Dialog open onOpenChange={() => {}}>- <CreateWorkspaceModal serverId={serverId} onSuccess={onSuccess} onClose={onClose} />+ <CreateWorkspaceModal+ serverId={serverId}+ target={target}+ onSuccess={onSuccess}+ onClose={onClose}+ /></Dialog>));@@ -160,6 +173,44 @@ function hasLabel(el: HTMLElement, text: string): boolean {}describe('the create-workspace modal', () => {+ it('creates an organization on a server that has them', async () => {+ addServer('srv-1', 'Acme prod', 'signedIn');+ const made = workspace('ws-9', 'srv-1');+ create.mockResolvedValue(made);++ const el = await render('srv-1', { kind: 'organization' });+ expect(el.textContent).toContain('Create an organization on Acme prod');+ await typeName(el, 'Weekend Robotics');+ await act(async () => button(el, 'Create organization').click());+ await settle();++ expect(create).toHaveBeenCalledWith('srv-1', 'Weekend Robotics');+ expect(onSuccess).toHaveBeenCalledWith(made);+ });++ it('adds a workspace to an organization through one of its workspaces', async () => {+ addServer('srv-1', 'Acme prod', 'signedIn');+ const made = workspace('ws-9', 'srv-1');+ addToOrganization.mockResolvedValue(made);++ const el = await render('srv-1', {+ kind: 'organization-workspace',+ through: 'ws-1',+ organizationName: 'Acme',+ });+ expect(el.textContent).toContain('Add a workspace to Acme');+ // Its place is the organization's, so there is no other server to offer.+ expect(el.textContent).not.toContain('Add a server');+ await typeName(el, 'Labs');+ await act(async () => button(el, 'Add workspace').click());+ await settle();++ expect(addToOrganization).toHaveBeenCalledWith('ws-1', 'Labs');+ expect(create).not.toHaveBeenCalled();+ expect(setActiveWorkspace).toHaveBeenCalledWith('ws-9');+ expect(onSuccess).toHaveBeenCalledWith(made);+ });+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');diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/workspace-switcher.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/workspace-switcher.test.tsxindex df5c359c6..9ffec01fb 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/workspace-switcher.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/workspace-switcher.test.tsx@@ -3,7 +3,11 @@ 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';+import type {+ OrganizationRole,+ Workspace,+ WorkspaceRole,+} from '@shared/core/workspaces/workspaces';vi.hoisted(() => {window.electronAPI ??= {@@ -29,6 +33,10 @@ const state = vi.hoisted(() => ({unavailable: new Set<string>(),noMembership: new Set<string>(),noCreate: new Set<string>(),+ /** Servers that have organizations, and the ones that refuse adding a workspace. */+ organizations: new Set<string>(),+ noAdd: new Set<string>(),+ showModal: vi.fn(),listPendingInvitations: vi.fn(),acceptPendingInvitation: vi.fn(),listJoinableWorkspaces: vi.fn(),@@ -41,7 +49,13 @@ vi.mock('@renderer/lib/ipc', () => ({switchServers: {listPendingInvitations: state.listPendingInvitations,listJoinableWorkspaces: state.listJoinableWorkspaces,- canCreateWorkspace: (serverId: string) => Promise.resolve(!state.noCreate.has(serverId)),+ workspaceCreation: (serverId: string) =>+ Promise.resolve({+ canCreate: !state.noCreate.has(serverId),+ canAddWorkspace: !state.noAdd.has(serverId),+ organizations: state.organizations.has(serverId),+ workspaceId: state.activeId,+ }),},},events: { on: () => () => {}, emit: () => {} },@@ -132,7 +146,7 @@ vi.mock('@renderer/lib/layout/navigation-provider', () => ({}));vi.mock('@renderer/lib/modal/modal-provider', () => ({- useShowModal: () => () => {},+ useShowModal: () => state.showModal,}));vi.mock('@renderer/lib/hooks/use-toast', () => ({@@ -165,7 +179,11 @@ function server(id: string, name: string): SwitchServer {function workspace(id: string,serverId: string,- patch: { tenantId?: string | null; role?: WorkspaceRole | null } = {}+ patch: {+ tenantId?: string | null;+ role?: WorkspaceRole | null;+ organization?: { id: string; name: string; role: OrganizationRole };+ } = {}): Workspace {const tenantId = patch.tenantId === undefined ? `tenant-${id}` : patch.tenantId;return {@@ -175,6 +193,9 @@ function workspace(tenantId,slug: tenantId === null ? null : id,role: patch.role === undefined ? 'member' : patch.role,+ organizationId: patch.organization?.id ?? null,+ organizationName: patch.organization?.name ?? null,+ organizationRole: patch.organization?.role ?? null,createdAt: '2026-01-01T00:00:00Z',updatedAt: '2026-01-01T00:00:00Z',};@@ -230,6 +251,9 @@ beforeEach(() => {state.unavailable.clear();state.noMembership.clear();state.noCreate.clear();+ state.organizations.clear();+ state.noAdd.clear();+ state.showModal.mockReset();state.listPendingInvitations.mockReset().mockResolvedValue({ kind: 'listed', invitations: [] });state.acceptPendingInvitation.mockReset();state.listJoinableWorkspaces.mockReset().mockResolvedValue({ kind: 'listed', workspaces: [] });@@ -440,6 +464,109 @@ describe('new workspaces from the switcher', () => {});});+describe('organizations in the switcher', () => {+ const ACME = { id: 'o-1', name: 'Acme', role: 'org_admin' } as const;+ const GLOBEX = { id: 'o-2', name: 'Globex', role: 'member' } as const;++ function menuRows(): string[] {+ return [...document.querySelectorAll('[role="menuitem"], [data-org-heading]')].map(+ (item) => item.textContent ?? ''+ );+ }++ it('heads each organization’s workspaces with its name where there are several', async () => {+ state.organizations.add('srv-1');+ await openSwitcher(+ [server('srv-1', 'Cloud')],+ [+ workspace('ws-a', 'srv-1', { organization: ACME, role: 'owner' }),+ workspace('ws-b', 'srv-1', { organization: GLOBEX }),+ workspace('ws-c', 'srv-1', { organization: ACME }),+ ],+ 'ws-a'+ );+ await settle();++ const text = menuRows().join(' | ');+ expect(text.indexOf('Acme')).toBeLessThan(text.indexOf('ws-c'));+ expect(text.indexOf('ws-c')).toBeLessThan(text.indexOf('Globex'));+ expect(text.indexOf('Globex')).toBeLessThan(text.indexOf('ws-b'));+ });++ it('offers an org admin Add workspace in their organization only', async () => {+ state.organizations.add('srv-1');+ await openSwitcher(+ [server('srv-1', 'Cloud')],+ [+ workspace('ws-a', 'srv-1', { organization: ACME, role: 'owner' }),+ workspace('ws-b', 'srv-1', { organization: GLOBEX }),+ ],+ 'ws-a'+ );+ await settle();++ const adds = menuRows().filter((text) => text.startsWith('Add workspace'));+ expect(adds).toEqual(['Add workspace']);+ const add = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find(+ (item) => item.textContent === 'Add workspace'+ )!;+ await act(async () => add.click());++ expect(state.showModal).toHaveBeenCalledWith(+ expect.objectContaining({+ serverId: 'srv-1',+ target: { kind: 'organization-workspace', through: 'ws-a', organizationName: 'Acme' },+ })+ );+ });++ it('names the organization on Add workspace when there is only one', async () => {+ state.organizations.add('srv-1');+ await openSwitcher(+ [server('srv-1', 'Cloud')],+ [workspace('ws-a', 'srv-1', { organization: ACME, role: 'owner' })],+ 'ws-a'+ );+ await settle();++ expect(menuRows()).toContain('Add workspace to Acme');+ });++ it('does not offer Add workspace where the server refuses it', async () => {+ state.organizations.add('srv-1');+ state.noAdd.add('srv-1');+ await openSwitcher(+ [server('srv-1', 'Cloud')],+ [workspace('ws-a', 'srv-1', { organization: ACME, role: 'owner' })],+ 'ws-a'+ );+ await settle();++ expect(menuRows().some((text) => text.startsWith('Add workspace'))).toBe(false);+ });++ it('says Create organization where the server has organizations', async () => {+ state.organizations.add('srv-1');+ await openSwitcher(+ [server('srv-1', 'Cloud'), server('srv-2', 'Old')],+ [workspace('ws-a', 'srv-1', { organization: GLOBEX }), workspace('ws-b', 'srv-2')],+ 'ws-a'+ );+ await settle();++ const rows = menuRows();+ expect(rows).toContain('Create organization');+ expect(rows).toContain('New workspace');+ const create = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find(+ (item) => item.textContent === 'Create organization'+ )!;+ await act(async () => create.click());+ expect(state.showModal).toHaveBeenCalledWith(+ expect.objectContaining({ serverId: 'srv-1', target: { kind: 'organization' } })+ );+ });+});+describe('invitations to your address in the switcher', () => {function invitation(id: string, workspaceName: string) {return {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.tsindex 6fb5eec85..692cb07bc 100644--- a/console/apps/switch-console-desktop/src/shared/core/workspaces/workspaces.ts+++ b/console/apps/switch-console-desktop/src/shared/core/workspaces/workspaces.ts@@ -11,6 +11,12 @@/** The caller's standing in a workspace, as the gateway reports it. */export type WorkspaceRole = 'owner' | 'admin' | 'member';+/**+ * The caller's standing in the organization a workspace belongs to. An+ * `org_admin` administers every workspace in it, and may add more.+ */+export type OrganizationRole = 'org_admin' | 'member';+/** A workspace on a registered Switch server. */export type Workspace = {id: string;@@ -33,6 +39,18 @@ export type Workspace = {* what {@link isWithdrawnWorkspace} reads.*/role: WorkspaceRole | null;+ /**+ * The organization the workspace belongs to on the gateway. Null on a server+ * from before organizations, and alongside a null `tenantId`.+ */+ organizationId: string | null;+ /**+ * The organization's name. Null where `organizationId` is, and on a server+ * that reports the id but cannot yet list organizations by name.+ */+ organizationName: string | null;+ /** The caller's role in that organization; null where `organizationId` is. */+ organizationRole: OrganizationRole | null;createdAt: string;updatedAt: string;};@@ -45,6 +63,15 @@ export function administersWorkspace(workspace: Workspace): boolean {return workspace.role === 'owner' || workspace.role === 'admin';}+/**+ * Whether this account may add workspaces to the organization `workspace`+ * belongs to. Whether the server allows it right now (its allowance) is the+ * server's to say; this is only the role.+ */+export function administersOrganization(workspace: Workspace): boolean {+ return workspace.organizationRole === 'org_admin' && !isWithdrawnWorkspace(workspace);+}+/*** Whether this account has lost its membership of a workspace still held here.*diff --git a/console/apps/switch-console-desktop/tooling/fixtures/baseline.db b/console/apps/switch-console-desktop/tooling/fixtures/baseline.dbindex 3584fe45d..dca16c279 100644Binary files a/console/apps/switch-console-desktop/tooling/fixtures/baseline.db and b/console/apps/switch-console-desktop/tooling/fixtures/baseline.db differdiff --git a/console/apps/switch-console-desktop/tooling/fixtures/empty.db b/console/apps/switch-console-desktop/tooling/fixtures/empty.dbindex a5ef9fae0..602460a46 100644Binary files a/console/apps/switch-console-desktop/tooling/fixtures/empty.db and b/console/apps/switch-console-desktop/tooling/fixtures/empty.db differdiff --git a/console/apps/switch-console-desktop/tooling/fixtures/pre-0054.db b/console/apps/switch-console-desktop/tooling/fixtures/pre-0054.dbnew file mode 100644index 000000000..3584fe45dBinary files /dev/null and b/console/apps/switch-console-desktop/tooling/fixtures/pre-0054.db differ