Skip to content

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

feat(console): workspaces as the unit the window is scoped to (CHOO-2702)

Louis Amaudruz9c46138334b3
diff --git a/console/apps/switch-console-desktop/drizzle/0051_workspaces.sql b/console/apps/switch-console-desktop/drizzle/0051_workspaces.sql
new file mode 100644
index 000000000..ef9534803
--- /dev/null
+++ b/console/apps/switch-console-desktop/drizzle/0051_workspaces.sql
@@ -0,0 +1,62 @@
+-- Workspaces: what the window is scoped to, one level below a server.
+--
+-- Each existing server gets exactly one workspace, and that workspace REUSES
+-- THE SERVER'S ID. That is what makes the upgrade invisible: every server id
+-- already persisted elsewhere — agents.server_id, the active-server kv value,
+-- and the opaque navigation snapshots under `view-state:` — stays valid when
+-- read as a workspace id, so nothing has to be rewritten or reconciled. New
+-- workspaces discovered from a gateway get fresh ids.
+--
+-- tenant_id stays NULL for these rows: the server reported no tenancy, so the
+-- workspace IS the whole server. A later reconcile fills it in if that changes.
+CREATE TABLE `workspaces` (
+ `id` text PRIMARY KEY NOT NULL,
+ `server_id` text NOT NULL,
+ `name` text NOT NULL,
+ `tenant_id` text,
+ `slug` text,
+ `role` text,
+ `created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
+ `updated_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
+ FOREIGN KEY (`server_id`) REFERENCES `switch_servers`(`id`) ON UPDATE no action ON DELETE cascade
+);
+--> statement-breakpoint
+CREATE INDEX `idx_workspaces_server_id` ON `workspaces` (`server_id`);--> statement-breakpoint
+CREATE UNIQUE INDEX `idx_workspaces_server_tenant` ON `workspaces` (`server_id`,`tenant_id`);--> statement-breakpoint
+INSERT INTO `workspaces` (`id`, `server_id`, `name`, `tenant_id`, `slug`, `role`)
+ SELECT `id`, `id`, `name`, NULL, NULL, NULL FROM `switch_servers`;
+--> statement-breakpoint
+-- Re-point agents at workspaces via the SQLite table-recreation dance rather
+-- than DROP COLUMN: `server_id` carries a foreign key, and SQLite refuses to
+-- drop a column named in one. Runs with foreign_keys=OFF inside the migration
+-- transaction, so dropping and renaming does not disturb the sessions FK, which
+-- tracks the table name. The workspace id equals the old server id, so the
+-- carry-over is a straight copy.
+CREATE TABLE `__new_agents` (
+ `id` text PRIMARY KEY NOT NULL,
+ `location_id` text NOT NULL,
+ `name` text NOT NULL,
+ `provider_id` text NOT NULL,
+ `switch_agent_id` text,
+ `api_endpoint` text,
+ `workspace_id` text,
+ `status` text,
+ `auto_approve` integer DEFAULT false NOT NULL,
+ `owner_name` text,
+ `provider_config` text,
+ `created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
+ `updated_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
+ FOREIGN KEY (`location_id`) REFERENCES `locations`(`id`) ON UPDATE no action ON DELETE no action,
+ FOREIGN KEY (`workspace_id`) REFERENCES `workspaces`(`id`) ON UPDATE no action ON DELETE set null
+);--> statement-breakpoint
+INSERT INTO `__new_agents` (`id`, `location_id`, `name`, `provider_id`, `switch_agent_id`, `api_endpoint`, `workspace_id`, `status`, `auto_approve`, `owner_name`, `provider_config`, `created_at`, `updated_at`)
+ SELECT `id`, `location_id`, `name`, `provider_id`, `switch_agent_id`, `api_endpoint`, `server_id`, `status`, `auto_approve`, `owner_name`, `provider_config`, `created_at`, `updated_at` FROM `agents`;
+--> statement-breakpoint
+DROP TABLE `agents`;--> statement-breakpoint
+ALTER TABLE `__new_agents` RENAME TO `agents`;--> statement-breakpoint
+CREATE INDEX `idx_agents_location_id` ON `agents` (`location_id`);--> statement-breakpoint
+CREATE INDEX `idx_agents_workspace_id` ON `agents` (`workspace_id`);--> statement-breakpoint
+INSERT INTO `kv` (`key`, `value`)
+ SELECT 'activeWorkspaceId', `value` FROM `kv` WHERE `key` = 'activeSwitchServerId';
+--> statement-breakpoint
+DELETE FROM `kv` WHERE `key` = 'activeSwitchServerId';
diff --git a/console/apps/switch-console-desktop/drizzle/meta/0051_snapshot.json b/console/apps/switch-console-desktop/drizzle/meta/0051_snapshot.json
new file mode 100644
index 000000000..9e52e7a19
--- /dev/null
+++ b/console/apps/switch-console-desktop/drizzle/meta/0051_snapshot.json
@@ -0,0 +1,972 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "a44f0db7-1021-46dc-90e6-810d28551f3a",
+ "prevId": "9bf29a0b-5aea-41b1-8394-0475326b97f7",
+ "tables": {
+ "agents": {
+ "name": "agents",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "location_id": {
+ "name": "location_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "switch_agent_id": {
+ "name": "switch_agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "api_endpoint": {
+ "name": "api_endpoint",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "auto_approve": {
+ "name": "auto_approve",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "owner_name": {
+ "name": "owner_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "provider_config": {
+ "name": "provider_config",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "idx_agents_location_id": {
+ "name": "idx_agents_location_id",
+ "columns": ["location_id"],
+ "isUnique": false
+ },
+ "idx_agents_workspace_id": {
+ "name": "idx_agents_workspace_id",
+ "columns": ["workspace_id"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "agents_location_id_locations_id_fk": {
+ "name": "agents_location_id_locations_id_fk",
+ "tableFrom": "agents",
+ "tableTo": "locations",
+ "columnsFrom": ["location_id"],
+ "columnsTo": ["id"],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "agents_workspace_id_workspaces_id_fk": {
+ "name": "agents_workspace_id_workspaces_id_fk",
+ "tableFrom": "agents",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "app_secrets": {
+ "name": "app_secrets",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "secret": {
+ "name": "secret",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_app_secrets_key": {
+ "name": "idx_app_secrets_key",
+ "columns": ["key"],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "app_settings": {
+ "name": "app_settings",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "idx_app_settings_key": {
+ "name": "idx_app_settings_key",
+ "columns": ["key"],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "kv": {
+ "name": "kv",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "idx_kv_key": {
+ "name": "idx_kv_key",
+ "columns": ["key"],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "location_settings": {
+ "name": "location_settings",
+ "columns": {
+ "location_id": {
+ "name": "location_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "base_settings_json": {
+ "name": "base_settings_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "shareable_settings_json": {
+ "name": "shareable_settings_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "legacy_config_migrated_at": {
+ "name": "legacy_config_migrated_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "location_settings_location_id_locations_id_fk": {
+ "name": "location_settings_location_id_locations_id_fk",
+ "tableFrom": "location_settings",
+ "tableTo": "locations",
+ "columnsFrom": ["location_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "locations": {
+ "name": "locations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ssh_host": {
+ "name": "ssh_host",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "dir": {
+ "name": "dir",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "idx_locations_host_dir": {
+ "name": "idx_locations_host_dir",
+ "columns": ["ssh_host", "dir"],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "messages": {
+ "name": "messages",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sender": {
+ "name": "sender",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "timestamp": {
+ "name": "timestamp",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_messages_session_id": {
+ "name": "idx_messages_session_id",
+ "columns": ["session_id"],
+ "isUnique": false
+ },
+ "idx_messages_timestamp": {
+ "name": "idx_messages_timestamp",
+ "columns": ["timestamp"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "messages_session_id_sessions_id_fk": {
+ "name": "messages_session_id_sessions_id_fk",
+ "tableFrom": "messages",
+ "tableTo": "sessions",
+ "columnsFrom": ["session_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "remote_host_reachability": {
+ "name": "remote_host_reachability",
+ "columns": {
+ "ssh_host": {
+ "name": "ssh_host",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'unknown'"
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_checked_at": {
+ "name": "last_checked_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_reachable_at": {
+ "name": "last_reachable_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "consecutive_failures": {
+ "name": "consecutive_failures",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "remote_host_setup_plans": {
+ "name": "remote_host_setup_plans",
+ "columns": {
+ "ssh_host": {
+ "name": "ssh_host",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'idle'"
+ },
+ "steps": {
+ "name": "steps",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "current_step_id": {
+ "name": "current_step_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "remote_hosts": {
+ "name": "remote_hosts",
+ "columns": {
+ "ssh_host": {
+ "name": "ssh_host",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "session_room_connections": {
+ "name": "session_room_connections",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "room_id": {
+ "name": "room_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "room_name": {
+ "name": "room_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "switch_agent_id": {
+ "name": "switch_agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "session_room_connections_session_id_sessions_id_fk": {
+ "name": "session_room_connections_session_id_sessions_id_fk",
+ "tableFrom": "session_room_connections",
+ "tableTo": "sessions",
+ "columnsFrom": ["session_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "sessions": {
+ "name": "sessions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "config": {
+ "name": "config",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_status": {
+ "name": "agent_status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_status_seen": {
+ "name": "agent_status_seen",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": 1
+ },
+ "is_initial_session": {
+ "name": "is_initial_session",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "is_pinned": {
+ "name": "is_pinned",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "archived_at": {
+ "name": "archived_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_interacted_at": {
+ "name": "last_interacted_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status_changed_at": {
+ "name": "status_changed_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "idx_sessions_agent_id": {
+ "name": "idx_sessions_agent_id",
+ "columns": ["agent_id"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "sessions_agent_id_agents_id_fk": {
+ "name": "sessions_agent_id_agents_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "agents",
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "switch_servers": {
+ "name": "switch_servers",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "gateway_url": {
+ "name": "gateway_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "api_url": {
+ "name": "api_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "managed": {
+ "name": "managed",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "management_kind": {
+ "name": "management_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "ssh_host": {
+ "name": "ssh_host",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "idx_switch_servers_gateway_url": {
+ "name": "idx_switch_servers_gateway_url",
+ "columns": ["gateway_url"],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "workspaces": {
+ "name": "workspaces",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "server_id": {
+ "name": "server_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tenant_id": {
+ "name": "tenant_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "slug": {
+ "name": "slug",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "idx_workspaces_server_id": {
+ "name": "idx_workspaces_server_id",
+ "columns": ["server_id"],
+ "isUnique": false
+ },
+ "idx_workspaces_server_tenant": {
+ "name": "idx_workspaces_server_tenant",
+ "columns": ["server_id", "tenant_id"],
+ "isUnique": true
+ }
+ },
+ "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.json
index dd2dfb96e..cb8a8591c 100644
--- a/console/apps/switch-console-desktop/drizzle/meta/_journal.json
+++ b/console/apps/switch-console-desktop/drizzle/meta/_journal.json
@@ -358,6 +358,13 @@
"when": 1790248865722,
"tag": "0050_drop_session_shell_id",
"breakpoints": true
+ },
+ {
+ "idx": 51,
+ "version": "6",
+ "when": 1790300000000,
+ "tag": "0051_workspaces",
+ "breakpoints": true
}
]
}
diff --git a/console/apps/switch-console-desktop/src/main/db/schema.ts b/console/apps/switch-console-desktop/src/main/db/schema.ts
index 05e3586f2..97855199a 100644
--- a/console/apps/switch-console-desktop/src/main/db/schema.ts
+++ b/console/apps/switch-console-desktop/src/main/db/schema.ts
@@ -9,9 +9,12 @@ import { sessionConfig } from '@shared/core/sessions/session-config';
// Data model (Switch Console rework — diverges from upstream; see
// agents/architecture/data-model.md for the full map):
//
+// switch_servers — a registered Switch gateway
+// └─ workspaces — what the window is scoped to; one active at a time
+//
// locations — a working directory on a host (this machine or an SSH host)
// └─ agents — a Switch agent identity (one provider each; many per
-// │ location)
+// │ location; belongs to one workspace)
// └─ sessions — an instantiation/run of an agent (was "conversation";
// │ one session == one terminal, folded in)
// └─ messages
@@ -82,10 +85,11 @@ export const appSettings = sqliteTable(
/**
* A Switch server: a gateway Switch Console can connect to. Switch Console is
* multi-server — many gateways (a local dev one, a deployed pilot one) can be
- * registered, and the UI works against one "active" server at a time (the
- * active id is tracked in `kv` under `activeSwitchServerId`). The session JWT
- * minted by the gateway is NOT stored here — it lives in the encrypted secrets
- * store keyed by server id — so this table holds only non-secret connection
+ * registered. What the window is scoped to is a workspace on one of them, not
+ * the server itself, so the active selection names a workspace (`kv`,
+ * `activeWorkspaceId`) and the server is read from it. The session JWT minted
+ * by the gateway is NOT stored here — it lives in the encrypted secrets store
+ * keyed by server id — so this table holds only non-secret connection
* metadata.
*/
export const switchServers = sqliteTable(
@@ -125,6 +129,55 @@ export const switchServers = sqliteTable(
})
);
+/**
+ * A workspace: the unit everything in the window is scoped to. A server hosts
+ * one or more of them, and exactly one workspace is active at a time (tracked
+ * in `kv` under `activeWorkspaceId`). Switching workspace swaps the whole
+ * window — agents, rooms, sidebar — the way switching server used to.
+ *
+ * `tenantId` is the workspace's id on the gateway, and is null when the server
+ * reports no tenancy: there the workspace *is* the whole server, which is every
+ * server registered before multi-tenancy and every self-hosted install that
+ * never turns it on. Workspaces are discovered from the gateway rather than
+ * created by hand, so a server that gains tenancy later fills in the ids on its
+ * next reconcile without the user doing anything.
+ *
+ * `slug` is the gateway's handle for the workspace; null alongside a null
+ * `tenantId`. The (server, tenant) pair is unique so a reconcile can upsert on
+ * it, with tenant-less rows excluded from the index — SQLite treats NULLs as
+ * distinct, which is what lets the one-per-server legacy row coexist.
+ */
+export const workspaces = sqliteTable(
+ 'workspaces',
+ {
+ id: text('id').primaryKey(),
+ serverId: text('server_id')
+ .notNull()
+ .references(() => switchServers.id, { onDelete: 'cascade' }),
+ name: text('name').notNull(),
+ /** The workspace's id on the gateway; null when the server has no tenancy. */
+ tenantId: text('tenant_id'),
+ /** The gateway's slug for the workspace; null when it has no tenancy. */
+ slug: text('slug'),
+ /**
+ * The caller's role in the workspace as the gateway last reported it
+ * (`owner` / `admin` / `member`). Null for a tenant-less workspace, where
+ * the notion does not apply.
+ */
+ role: text('role'),
+ createdAt: text('created_at')
+ .notNull()
+ .default(sql`CURRENT_TIMESTAMP`),
+ updatedAt: text('updated_at')
+ .notNull()
+ .default(sql`CURRENT_TIMESTAMP`),
+ },
+ (table) => ({
+ serverIdIdx: index('idx_workspaces_server_id').on(table.serverId),
+ serverTenantIdx: uniqueIndex('idx_workspaces_server_tenant').on(table.serverId, table.tenantId),
+ })
+);
+
/**
* A Switch agent: an agent identity bound to a single provider, living at a
* location. Many agents may share a location (e.g. a Claude Code and a Codex
@@ -132,11 +185,12 @@ export const switchServers = sqliteTable(
* the location dir is configured as a Switch agent (detected from
* `.claude/settings.local.json`); they are null for a plain local agent.
*
- * `serverId` binds the agent to the one registered Switch server it belongs to.
- * It is resolved by matching the detected `apiEndpoint` against the registered
- * servers' origins. It is nullable: an agent whose server is not (or no longer)
- * registered is shown as "unlinked" rather than guessed, and removing a server
- * sets its agents' `serverId` to null instead of deleting them.
+ * `workspaceId` binds the agent to the one workspace it belongs to. It is
+ * resolved by matching the detected `apiEndpoint` against the registered
+ * servers' origins and then the server's active workspace. It is nullable: an
+ * agent whose workspace is not (or no longer) registered is shown as "unlinked"
+ * rather than guessed, and removing a workspace sets its agents' `workspaceId`
+ * to null instead of deleting them.
*/
export const agents = sqliteTable(
'agents',
@@ -153,7 +207,7 @@ export const agents = sqliteTable(
providerId: text('provider_id').$type<AgentProviderId>().notNull(),
switchAgentId: text('switch_agent_id'),
apiEndpoint: text('api_endpoint'),
- serverId: text('server_id').references(() => switchServers.id, { onDelete: 'set null' }),
+ workspaceId: text('workspace_id').references(() => workspaces.id, { onDelete: 'set null' }),
status: text('status'),
// When set, Switch Console launches this agent's CLI with its auto-approve /
// "bypass permissions" flag (e.g. `--dangerously-skip-permissions`).
@@ -175,7 +229,7 @@ export const agents = sqliteTable(
},
(table) => ({
locationIdIdx: index('idx_agents_location_id').on(table.locationId),
- serverIdIdx: index('idx_agents_server_id').on(table.serverId),
+ workspaceIdIdx: index('idx_agents_workspace_id').on(table.workspaceId),
})
);
@@ -379,6 +433,8 @@ export type AppSecretRow = typeof appSecrets.$inferSelect;
export type AppSecretInsert = typeof appSecrets.$inferInsert;
export type SwitchServerRow = typeof switchServers.$inferSelect;
export type SwitchServerInsert = typeof switchServers.$inferInsert;
+export type WorkspaceRow = typeof workspaces.$inferSelect;
+export type WorkspaceInsert = typeof workspaces.$inferInsert;
export type RemoteHostRow = typeof remoteHosts.$inferSelect;
export type RemoteHostInsert = typeof remoteHosts.$inferInsert;
export type RemoteHostReachabilityRow = typeof remoteHostReachability.$inferSelect;
diff --git a/console/apps/switch-console-desktop/src/main/db/tests/migrations/0051-workspaces.test.ts b/console/apps/switch-console-desktop/src/main/db/tests/migrations/0051-workspaces.test.ts
new file mode 100644
index 000000000..dd6d49361
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/db/tests/migrations/0051-workspaces.test.ts
@@ -0,0 +1,314 @@
+/**
+ * Migration 0051 — introduces workspaces, the unit the window is scoped to, and
+ * moves agents from being owned by a server to being owned by a workspace.
+ *
+ * The upgrade has to be invisible: everyone currently has servers and no
+ * workspaces, so each server gets exactly one workspace reusing the server's id.
+ * That reuse is the whole backward-compatibility story — agent rows, the active
+ * selection in `kv`, and the opaque navigation snapshots all keep referring to
+ * the same string — so these tests pin it rather than just checking the table
+ * exists.
+ *
+ * The SQL is applied to a hand-built pre-0051 schema (the same approach as the
+ * 0047 test) because the committed fixtures have already been migrated past it.
+ */
+
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import Database from 'better-sqlite3';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+const MIGRATION_SQL = readFileSync(
+ path.resolve(
+ path.dirname(fileURLToPath(import.meta.url)),
+ '../../../../../drizzle/0051_workspaces.sql'
+ ),
+ 'utf8'
+);
+
+type WorkspaceRow = {
+ id: string;
+ server_id: string;
+ name: string;
+ tenant_id: string | null;
+ slug: string | null;
+ role: string | null;
+};
+
+describe('migration 0051: workspaces', () => {
+ let db: Database.Database;
+
+ beforeEach(() => {
+ db = new Database(':memory:');
+ db.exec(`
+ CREATE TABLE switch_servers (
+ id TEXT PRIMARY KEY NOT NULL,
+ name TEXT NOT NULL,
+ gateway_url TEXT NOT NULL,
+ api_url TEXT NOT NULL,
+ managed INTEGER NOT NULL DEFAULT 0,
+ management_kind TEXT,
+ ssh_host TEXT,
+ created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
+ );
+ CREATE TABLE locations (
+ id TEXT PRIMARY KEY NOT NULL,
+ name TEXT NOT NULL
+ );
+ INSERT INTO locations (id, name) VALUES ('loc-1', 'repo');
+ -- Mirrors the real pre-0051 agents DDL, foreign keys included. The
+ -- columns are not incidental: server_id carrying an FK is exactly why the
+ -- migration has to recreate the table instead of dropping the column.
+ CREATE TABLE agents (
+ id TEXT PRIMARY KEY NOT NULL,
+ location_id TEXT NOT NULL,
+ name TEXT NOT NULL,
+ provider_id TEXT NOT NULL,
+ switch_agent_id TEXT,
+ api_endpoint TEXT,
+ server_id TEXT,
+ status TEXT,
+ auto_approve INTEGER DEFAULT false NOT NULL,
+ owner_name TEXT,
+ provider_config TEXT,
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP NOT NULL,
+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP NOT NULL,
+ FOREIGN KEY (location_id) REFERENCES locations(id),
+ FOREIGN KEY (server_id) REFERENCES switch_servers(id) ON DELETE SET NULL
+ );
+ CREATE INDEX idx_agents_location_id ON agents (location_id);
+ CREATE INDEX idx_agents_server_id ON agents (server_id);
+ CREATE TABLE kv (
+ key TEXT PRIMARY KEY NOT NULL,
+ value TEXT NOT NULL,
+ updated_at INTEGER NOT NULL DEFAULT 0
+ );
+ `);
+ });
+
+ afterEach(() => {
+ db.close();
+ });
+
+ function seedServer(id: string, name: string): void {
+ db.prepare(
+ `INSERT INTO switch_servers (id, name, gateway_url, api_url) VALUES (?, ?, ?, ?)`
+ ).run(id, name, `https://${id}.example`, `https://${id}.example:8000`);
+ }
+
+ function seedAgent(id: string, serverId: string | null): void {
+ db.prepare(
+ `INSERT INTO agents (id, location_id, name, provider_id, server_id) VALUES (?, 'loc-1', ?, 'claude', ?)`
+ ).run(id, id, serverId);
+ }
+
+ function applyMigration(): void {
+ for (const stmt of MIGRATION_SQL.split('--> statement-breakpoint')) {
+ const trimmed = stmt.trim();
+ if (trimmed) db.exec(trimmed);
+ }
+ }
+
+ function workspaces(): WorkspaceRow[] {
+ return db.prepare(`SELECT * FROM workspaces ORDER BY name`).all() as WorkspaceRow[];
+ }
+
+ it('gives every existing server exactly one workspace, named after it', () => {
+ seedServer('srv-local', 'Local dev');
+ seedServer('srv-cloud', 'Switch Cloud');
+
+ applyMigration();
+
+ expect(workspaces().map((w) => [w.server_id, w.name])).toEqual([
+ ['srv-local', 'Local dev'],
+ ['srv-cloud', 'Switch Cloud'],
+ ]);
+ });
+
+ it('reuses the server id as the workspace id, so persisted ids stay valid', () => {
+ seedServer('srv-local', 'Local dev');
+
+ applyMigration();
+
+ const [workspace] = workspaces();
+ expect(workspace!.id).toBe('srv-local');
+ });
+
+ it('leaves the migrated workspaces tenant-less, since the server reported no tenancy', () => {
+ seedServer('srv-local', 'Local dev');
+
+ applyMigration();
+
+ const [workspace] = workspaces();
+ expect(workspace!.tenant_id).toBeNull();
+ expect(workspace!.slug).toBeNull();
+ expect(workspace!.role).toBeNull();
+ });
+
+ it("moves each agent onto its server's workspace", () => {
+ seedServer('srv-local', 'Local dev');
+ seedServer('srv-cloud', 'Switch Cloud');
+ seedAgent('agent-a', 'srv-local');
+ seedAgent('agent-b', 'srv-cloud');
+
+ applyMigration();
+
+ const rows = db.prepare(`SELECT id, workspace_id FROM agents ORDER BY id`).all() as {
+ id: string;
+ workspace_id: string | null;
+ }[];
+ expect(rows).toEqual([
+ { id: 'agent-a', workspace_id: 'srv-local' },
+ { id: 'agent-b', workspace_id: 'srv-cloud' },
+ ]);
+ });
+
+ it('keeps an unlinked agent unlinked rather than guessing a workspace for it', () => {
+ seedServer('srv-local', 'Local dev');
+ seedAgent('agent-unlinked', null);
+
+ applyMigration();
+
+ const row = db
+ .prepare(`SELECT workspace_id FROM agents WHERE id = ?`)
+ .get('agent-unlinked') as {
+ workspace_id: string | null;
+ };
+ expect(row.workspace_id).toBeNull();
+ });
+
+ it('carries every other agent column through the table rebuild', () => {
+ seedServer('srv-local', 'Local dev');
+ db.prepare(
+ `INSERT INTO agents (id, location_id, name, provider_id, switch_agent_id, api_endpoint, server_id, status, auto_approve, owner_name, provider_config)
+ VALUES ('agent-a', 'loc-1', 'Worker', 'codex', 'switch-123', 'https://api.example', 'srv-local', 'live', 1, 'owner-1', '{"v":1}')`
+ ).run();
+
+ applyMigration();
+
+ const row = db.prepare(`SELECT * FROM agents WHERE id = 'agent-a'`).get() as Record<
+ string,
+ unknown
+ >;
+ expect(row).toMatchObject({
+ location_id: 'loc-1',
+ name: 'Worker',
+ provider_id: 'codex',
+ switch_agent_id: 'switch-123',
+ api_endpoint: 'https://api.example',
+ workspace_id: 'srv-local',
+ status: 'live',
+ auto_approve: 1,
+ owner_name: 'owner-1',
+ provider_config: '{"v":1}',
+ });
+ });
+
+ it('keeps the location foreign key working after the rebuild', () => {
+ seedServer('srv-local', 'Local dev');
+ seedAgent('agent-a', 'srv-local');
+
+ applyMigration();
+ db.exec('PRAGMA foreign_keys = ON');
+
+ expect(() =>
+ db
+ .prepare(`INSERT INTO agents (id, location_id, name, provider_id) VALUES (?, ?, ?, ?)`)
+ .run('agent-b', 'loc-missing', 'B', 'claude')
+ ).toThrow(/FOREIGN KEY/);
+ });
+
+ it('drops the old server column so nothing can keep reading it', () => {
+ seedServer('srv-local', 'Local dev');
+
+ applyMigration();
+
+ const columns = (db.prepare(`PRAGMA table_info('agents')`).all() as { name: string }[]).map(
+ (c) => c.name
+ );
+ expect(columns).toContain('workspace_id');
+ expect(columns).not.toContain('server_id');
+ });
+
+ it('carries the active selection over, so the app opens where it was left', () => {
+ seedServer('srv-local', 'Local dev');
+ db.prepare(`INSERT INTO kv (key, value) VALUES ('activeSwitchServerId', 'srv-local')`).run();
+
+ applyMigration();
+
+ const active = db.prepare(`SELECT value FROM kv WHERE key = 'activeWorkspaceId'`).get() as
+ | { value: string }
+ | undefined;
+ expect(active?.value).toBe('srv-local');
+
+ const stale = db.prepare(`SELECT value FROM kv WHERE key = 'activeSwitchServerId'`).get();
+ expect(stale).toBeUndefined();
+ });
+
+ it('survives an install that had no active selection recorded', () => {
+ seedServer('srv-local', 'Local dev');
+
+ applyMigration();
+
+ const active = db.prepare(`SELECT value FROM kv WHERE key = 'activeWorkspaceId'`).get();
+ expect(active).toBeUndefined();
+ });
+
+ it('survives a fresh install with no servers at all', () => {
+ applyMigration();
+
+ expect(workspaces()).toEqual([]);
+ });
+
+ it('removes a server’s workspaces with it', () => {
+ seedServer('srv-local', 'Local dev');
+ applyMigration();
+ db.exec('PRAGMA foreign_keys = ON');
+
+ db.prepare(`DELETE FROM switch_servers WHERE id = ?`).run('srv-local');
+
+ expect(workspaces()).toEqual([]);
+ });
+
+ it('lets two servers each keep a tenant-less workspace', () => {
+ seedServer('srv-a', 'A');
+ seedServer('srv-b', 'B');
+
+ applyMigration();
+
+ expect(workspaces()).toHaveLength(2);
+ });
+
+ it('refuses two workspaces with the same tenant on one server', () => {
+ seedServer('srv-cloud', 'Switch Cloud');
+ applyMigration();
+
+ const insert = (id: string, tenantId: string) =>
+ db
+ .prepare(`INSERT INTO workspaces (id, server_id, name, tenant_id) VALUES (?, ?, ?, ?)`)
+ .run(id, 'srv-cloud', id, tenantId);
+
+ insert('ws-1', 'tenant-1');
+ expect(() => insert('ws-2', 'tenant-1')).toThrow(/UNIQUE/);
+ });
+
+ it('allows the same tenant id on two different servers', () => {
+ seedServer('srv-a', 'A');
+ seedServer('srv-b', 'B');
+ applyMigration();
+
+ db.prepare(`INSERT INTO workspaces (id, server_id, name, tenant_id) VALUES (?, ?, ?, ?)`).run(
+ 'ws-a',
+ 'srv-a',
+ 'Shared',
+ 'tenant-1'
+ );
+ expect(() =>
+ db
+ .prepare(`INSERT INTO workspaces (id, server_id, name, tenant_id) VALUES (?, ?, ?, ?)`)
+ .run('ws-b', 'srv-b', 'Shared', 'tenant-1')
+ ).not.toThrow();
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/main/db/tests/migrations/journal-registration.test.ts b/console/apps/switch-console-desktop/src/main/db/tests/migrations/journal-registration.test.ts
index 75ea22dd6..ab2311463 100644
--- a/console/apps/switch-console-desktop/src/main/db/tests/migrations/journal-registration.test.ts
+++ b/console/apps/switch-console-desktop/src/main/db/tests/migrations/journal-registration.test.ts
@@ -25,6 +25,10 @@ const journalTags = journal.entries.map((entry) => entry.tag);
const sqlTags = readdirSync(drizzleDir)
.filter((name) => name.endsWith('.sql'))
.map((name) => name.replace(/\.sql$/, ''));
+const snapshotIndices = readdirSync(`${drizzleDir}/meta`)
+ .map((name) => /^(\d+)_snapshot\.json$/.exec(name))
+ .filter((match) => match !== null)
+ .map((match) => Number(match[1]));
describe('migration journal registration', () => {
it('finds the migration files at all, so the checks below are not vacuous', () => {
@@ -42,6 +46,23 @@ describe('migration journal registration', () => {
expect(missing).toEqual([]);
});
+ /**
+ * A hand-written migration is easy to commit without one, and nothing at
+ * runtime notices: the runner reads the journal and the `.sql`, never `meta/`.
+ *
+ * drizzle-kit does, and it takes the *highest-numbered snapshot file* as the
+ * state to diff against rather than the last journal entry — a gap is not an
+ * error it reports. So the next `db:generate` diffs the schema against the
+ * last snapshot before the gap and re-emits everything since as one new
+ * migration. On any machine that already ran the missing one, that lands as
+ * `table workspaces already exists`, and it takes `db:fixtures` with it.
+ */
+ it('has a meta snapshot for every journal entry', () => {
+ const missing = journal.entries.filter((entry) => !snapshotIndices.includes(entry.idx));
+
+ expect(missing.map((entry) => entry.tag)).toEqual([]);
+ });
+
it('numbers journal entries contiguously from zero', () => {
// A gap means an entry was hand-edited out; a duplicate means two branches
// claimed the same number and the merge kept both.