Skip to content

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

fix(switchdash): stop a destroyed server's agents from polling forever (CHOO-1802 follow-up) (#95)

Louis Amaudruz46697e9128fb
diff --git a/dash/agents/architecture/data-model.md b/dash/agents/architecture/data-model.md
index 033ee94b9..70ae9a48f 100644
--- a/dash/agents/architecture/data-model.md
+++ b/dash/agents/architecture/data-model.md
@@ -32,9 +32,16 @@ The schema is defined in `apps/switchdash-desktop/src/main/db/schema.ts`.
project (directory on disk)
└─ agent (Switch identity; one provider each; many per dir)
└─ session (a run/instantiation; was "conversation")
- └─ message
+ ├─ message
+ └─ session_room_connection (0..1 — the Switch room it is attending)
```
+A session's room connection is a row keyed by `session_id` with
+`ON DELETE CASCADE`, so it cannot outlive the session (or the agent above it).
+It was previously a JSON blob in `app_settings`, which referenced nothing and so
+survived both — leaving switchdash restoring sessions, on every launch, for
+agents whose Switch server had been destroyed.
+
## What we deliberately dropped from upstream, and why
- **The `workspaces` table and the workspace abstraction.** Upstream modelled
diff --git a/dash/apps/switchdash-desktop/drizzle/0044_session_room_connections.sql b/dash/apps/switchdash-desktop/drizzle/0044_session_room_connections.sql
new file mode 100644
index 000000000..3eff70d1d
--- /dev/null
+++ b/dash/apps/switchdash-desktop/drizzle/0044_session_room_connections.sql
@@ -0,0 +1,39 @@
+/*
+ Move each session's Switch room connection out of the `switchRoomConnections`
+ JSON blob in `app_settings` and into a table keyed by session.
+
+ The blob referenced nothing, so nothing ever cleaned it up: entries outlived the
+ sessions they described, and the boot sweep re-armed a poller for every one of
+ them. A connection whose Switch server had since been destroyed then hammered a
+ dead endpoint for the lifetime of the app. Keying the row on `session_id` with
+ ON DELETE CASCADE makes that state unrepresentable — the row goes when the
+ session does, and sessions already cascade from `agents`.
+
+ Live connections are carried over; leaked ones are dropped. A connection is
+ live iff its session still exists (an agent's removal already cascaded its
+ sessions away, so this one condition covers both). The blob is deleted
+ afterwards: the table is the only home now, and leaving it would let a future
+ reader resurrect exactly the rows this migration filtered out.
+*/
+CREATE TABLE `session_room_connections` (
+ `session_id` text PRIMARY KEY NOT NULL,
+ `room_id` text NOT NULL,
+ `room_name` text,
+ `switch_agent_id` text,
+ `updated_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
+ FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE cascade
+);
+--> statement-breakpoint
+INSERT INTO `session_room_connections` (`session_id`, `room_id`, `room_name`, `switch_agent_id`)
+SELECT
+ `entry`.`key`,
+ json_extract(`entry`.`value`, '$.roomId'),
+ json_extract(`entry`.`value`, '$.roomName'),
+ json_extract(`entry`.`value`, '$.agentId')
+FROM `app_settings`, json_each(`app_settings`.`value`) AS `entry`
+WHERE `app_settings`.`key` = 'switchRoomConnections'
+ AND json_valid(`app_settings`.`value`)
+ AND json_extract(`entry`.`value`, '$.roomId') IS NOT NULL
+ AND `entry`.`key` IN (SELECT `id` FROM `sessions`);
+--> statement-breakpoint
+DELETE FROM `app_settings` WHERE `key` = 'switchRoomConnections';
diff --git a/dash/apps/switchdash-desktop/drizzle/meta/0044_snapshot.json b/dash/apps/switchdash-desktop/drizzle/meta/0044_snapshot.json
new file mode 100644
index 000000000..75f5e6ebc
--- /dev/null
+++ b/dash/apps/switchdash-desktop/drizzle/meta/0044_snapshot.json
@@ -0,0 +1,829 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "0accfa68-741f-4f75-9b40-7a47c434091e",
+ "prevId": "24ca41c8-3ae9-4b92-976a-08a6a6d4ab4c",
+ "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
+ },
+ "server_id": {
+ "name": "server_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
+ },
+ "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_server_id": {
+ "name": "idx_agents_server_id",
+ "columns": ["server_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_server_id_switch_servers_id_fk": {
+ "name": "agents_server_id_switch_servers_id_fk",
+ "tableFrom": "agents",
+ "tableTo": "switch_servers",
+ "columnsFrom": ["server_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_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": {}
+ },
+ "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
+ },
+ "shell_id": {
+ "name": "shell_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'system'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_session_id": {
+ "name": "agent_session_id",
+ "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": {}
+ },
+ "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": {}
+ }
+ },
+ "views": {},
+ "enums": {},
+ "_meta": {
+ "schemas": {},
+ "tables": {},
+ "columns": {}
+ },
+ "internal": {
+ "indexes": {}
+ }
+}
diff --git a/dash/apps/switchdash-desktop/drizzle/meta/_journal.json b/dash/apps/switchdash-desktop/drizzle/meta/_journal.json
index bf8cac704..5ce5ca53e 100644
--- a/dash/apps/switchdash-desktop/drizzle/meta/_journal.json
+++ b/dash/apps/switchdash-desktop/drizzle/meta/_journal.json
@@ -309,6 +309,13 @@
"when": 1785224611278,
"tag": "0043_furry_maggott",
"breakpoints": true
+ },
+ {
+ "idx": 44,
+ "version": "6",
+ "when": 1785224671278,
+ "tag": "0044_session_room_connections",
+ "breakpoints": true
}
]
}
diff --git a/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/local-server-service.ts b/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/local-server-service.ts
index a99ad8c7f..b41443d5d 100644
--- a/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/local-server-service.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/local-server-service.ts
@@ -1,3 +1,4 @@
+import { deleteAgentsForServer } from '@main/core/switch-servers/delete-server-agents';
import { getManagedServer } from '@main/core/switch-servers/servers-store';
import { events } from '@main/lib/events';
import { log } from '@main/lib/logger';
@@ -123,14 +124,20 @@ class LocalServerService {
}
/** Destroy the stack AND its data volumes, and drop the stored secrets so the
- * next start is a clean install. Irreversible — the caller must confirm. The
- * caller (renderer) removes the managed server's agents first, since their
- * server-side identity is wiped here. */
+ * next start is a clean install. Irreversible — the caller must confirm.
+ *
+ * The stack's agents are deleted first, here rather than in the caller: the
+ * wipe destroys their server-side identity, and an agent that outlives it
+ * keeps a dead endpoint and a token for nobody. Doing it behind the reset is
+ * what stops a second caller from forgetting. */
async reset(): Promise<void> {
if (this.busy) throw new Error('A local-server operation is already in progress.');
this.busy = true;
const host: ServerHost = new LocalServerHost();
try {
+ this.setStatus({ phase: 'stopping', message: 'Removing agents…' });
+ const server = await getManagedServer();
+ if (server) await deleteAgentsForServer(server.id);
this.setStatus({ phase: 'stopping', message: 'Destroying containers and data…' });
await resetStack(host);
this.setStatus({ phase: 'stopped', message: null, error: null });
diff --git a/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/remote-server-service.ts b/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/remote-server-service.ts
index 57607c61c..f4adf68cb 100644
--- a/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/remote-server-service.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/remote-server-service.ts
@@ -1,6 +1,10 @@
import type { HostReachabilityChange } from '@main/core/remote-hosts/host-reachability-service';
import { hostReachabilityService } from '@main/core/remote-hosts/production-host-reachability';
-import { listManagedServers } from '@main/core/switch-servers/servers-store';
+import { deleteAgentsForServer } from '@main/core/switch-servers/delete-server-agents';
+import {
+ getRemoteManagedServer,
+ listManagedServers,
+} from '@main/core/switch-servers/servers-store';
import { events } from '@main/lib/events';
import { log } from '@main/lib/logger';
import { COMPATIBLE_SWITCH_VERSION } from '@shared/app-identity';
@@ -206,8 +210,11 @@ class RemoteServerService {
}
}
- /** Destroy the remote stack, its data volumes, and stored secrets. The caller
- * removes the server's agents first (their server-side identity is wiped). */
+ /** Destroy the remote stack, its data volumes, and stored secrets.
+ *
+ * The stack's agents are deleted first, here rather than in the caller — the
+ * wipe destroys their server-side identity, so leaving them behind strands a
+ * dead endpoint and a token for nobody (see {@link deleteAgentsForServer}). */
async reset(sshHost: string): Promise<void> {
if (this.busy.has(sshHost))
throw new Error(`An operation is already in progress for ${sshHost}.`);
@@ -215,6 +222,9 @@ class RemoteServerService {
this.busy.add(sshHost);
const host = this.hosts.get(sshHost) ?? (await createRemoteServerHost(sshHost));
try {
+ this.setStatus(sshHost, { phase: 'stopping', message: 'Removing agents…' });
+ const server = await getRemoteManagedServer(sshHost);
+ if (server) await deleteAgentsForServer(server.id);
this.setStatus(sshHost, { phase: 'stopping', message: 'Destroying containers and data…' });
await resetStack(host);
this.setStatus(sshHost, { phase: 'stopped', message: null, error: null });
diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/session-join.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/session-join.ts
index cf8037840..21ab50987 100644
--- a/dash/apps/switchdash-desktop/src/main/core/sessions/session-join.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/session-join.ts
@@ -10,6 +10,10 @@ export type SessionWithAgent = {
/** The owning agent's `name` — the session's identity source. The creds slug
* and `--agent` launch name derive from it, read live, not from a frozen tag. */
name: string;
+ /** The registered Switch server the agent belongs to; null once that server
+ * has been removed, which leaves the agent's endpoint and token pointing at
+ * something that no longer exists. */
+ serverId: string | null;
};
/**
@@ -25,6 +29,7 @@ export async function loadSessionWithAgent(
locationId: agents.locationId,
providerId: agents.providerId,
name: agents.name,
+ serverId: agents.serverId,
})
.from(sessions)
.innerJoin(agents, eq(sessions.agentId, agents.id))
@@ -36,5 +41,6 @@ export async function loadSessionWithAgent(
locationId: joined.locationId,
providerId: joined.providerId,
name: joined.name,
+ serverId: joined.serverId,
};
}
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/restore-sessions.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/restore-sessions.ts
index 79019e87a..9d0fed5b2 100644
--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/restore-sessions.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/restore-sessions.ts
@@ -24,6 +24,7 @@ export async function restoreSwitchRoomSessions(): Promise<void> {
const stale: string[] = [];
let launched = 0;
+ let orphaned = 0;
for (const sessionId of sessionIds) {
try {
@@ -33,6 +34,22 @@ export async function restoreSwitchRoomSessions(): Promise<void> {
continue;
}
+ // An agent whose server has been removed still carries that server's
+ // endpoint and token, both of which now point at nothing. Launching it
+ // would spawn an agent process that can never reach its room, so say so
+ // rather than starting a poller that fails forever. The session is left
+ // intact and can still be opened by hand.
+ if (loaded.serverId === null) {
+ orphaned += 1;
+ log.warn('restoreSwitchRoomSessions: agent has no Switch server; not restoring session', {
+ event: 'switch_room_restore_skipped',
+ reason: 'agent_server_removed',
+ sessionId,
+ agentName: loaded.name,
+ });
+ continue;
+ }
+
const location = await getLocationById(loaded.locationId);
if (!location) {
stale.push(sessionId);
@@ -67,5 +84,6 @@ export async function restoreSwitchRoomSessions(): Promise<void> {
log.info('restoreSwitchRoomSessions: launched room-connected sessions at startup', {
launched,
pruned: stale.length,
+ orphaned,
});
}
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.test.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.test.ts
index 6c564fc27..e5fbe8a7b 100644
--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.test.ts
@@ -573,4 +573,110 @@ describe('RoomConnection', () => {
expect((leaseCalls[0][1] as RequestInit).method).toBe('POST');
conn.stop();
});
+
+ /**
+ * An endpoint that is simply gone — a managed server's port after the stack
+ * was destroyed — used to produce an unbounded stream of warnings: two renew
+ * loops retrying every 2s with no backoff, plus a watchdog announcing the
+ * staleness they were already reporting.
+ */
+ describe('renew against a dead endpoint', () => {
+ /** Fails every renew; parks the poll loop so only renews are under test. */
+ function makeFailingFetch(shouldFail: () => boolean) {
+ return vi.fn(async (url: string) => {
+ const u = String(url);
+ if (u.includes('/renew')) {
+ if (shouldFail()) throw new TypeError('fetch failed');
+ return { ok: true, status: 200, json: async () => ({}), text: async () => '' };
+ }
+ if (u.includes('/events')) return new Promise(() => {});
+ return { ok: true, status: 200, json: async () => ({}), text: async () => '' };
+ });
+ }
+
+ function connectWith(fetchMock: ReturnType<typeof makeFailingFetch>) {
+ vi.stubGlobal('fetch', fetchMock);
+ const conn = new RoomConnection({
+ creds,
+ roomId: 'room-1',
+ roomName: 'Room One',
+ sessionId: 'session-1',
+ sink: { acquire: () => ({ write: vi.fn() }) },
+ injector,
+ control,
+ deeplinkScheme: 'switchdash',
+ isHumanTyping: () => false,
+ mediaDir,
+ log: silentLog,
+ });
+ conn.start();
+ return conn;
+ }
+
+ function warnings(match: string): unknown[][] {
+ return silentLog.warn.mock.calls.filter((call) => String(call[0]).includes(match));
+ }
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('backs off instead of retrying every two seconds forever', async () => {
+ vi.useFakeTimers();
+ const fetchMock = makeFailingFetch(() => true);
+ const conn = connectWith(fetchMock);
+
+ await vi.advanceTimersByTimeAsync(120_000);
+ const attempts = fetchMock.mock.calls.filter((c) =>
+ String(c[0]).includes('/connection/renew')
+ ).length;
+
+ // Unbounded retries at the 2s heartbeat would be ~60 in two minutes; with
+ // the backoff capped at 30s it settles near a tenth of that.
+ expect(attempts).toBeLessThan(15);
+ conn.stop();
+ });
+
+ it('reports the outage on a curve rather than once per attempt', async () => {
+ vi.useFakeTimers();
+ const conn = connectWith(makeFailingFetch(() => true));
+
+ await vi.advanceTimersByTimeAsync(120_000);
+
+ const reported = warnings('connection renew error');
+ expect(reported.length).toBeGreaterThan(0);
+ expect(reported.length).toBeLessThan(8);
+ // The first failure is always reported, with the endpoint that failed.
+ expect(reported[0][1]).toMatchObject({
+ endpoint: 'https://switch.test',
+ failures: 1,
+ });
+ conn.stop();
+ });
+
+ it('stays quiet about staleness while the loop is failing loudly', async () => {
+ vi.useFakeTimers();
+ const conn = connectWith(makeFailingFetch(() => true));
+
+ await vi.advanceTimersByTimeAsync(120_000);
+
+ expect(warnings('renew stale')).toHaveLength(0);
+ conn.stop();
+ });
+
+ it('says so when the endpoint comes back', async () => {
+ vi.useFakeTimers();
+ let failing = true;
+ const conn = connectWith(makeFailingFetch(() => failing));
+
+ await vi.advanceTimersByTimeAsync(30_000);
+ failing = false;
+ await vi.advanceTimersByTimeAsync(60_000);
+
+ const recovered = warnings('connection renew recovered');
+ expect(recovered).toHaveLength(1);
+ expect(recovered[0][1]).toMatchObject({ event: 'room_renew_recovered' });
+ conn.stop();
+ });
+ });
});
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.ts
index 510ea6da3..2204595a6 100644
--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.ts
@@ -35,8 +35,21 @@ const MEDIA_REQUEST_TIMEOUT_MS = 30_000;
// past its own timeout, or the loop otherwise stopped making progress): abort the
// in-flight renew to force an immediate fresh attempt, and warn loudly so a
// silently-dropped room is visible rather than mysterious.
+//
+// "Wedged" specifically means *not making progress*. A renew that fails fast —
+// a refused connection to an endpoint that is simply gone — is progress: the
+// loop is running, retrying, and reporting for itself. Firing the watchdog then
+// would abort a request that is not in flight and warn about a stall that is not
+// happening, which is how a single dead endpoint used to produce a third of a
+// warning line per second, forever.
const RENEW_WATCHDOG_INTERVAL_MS = 2_000;
const RENEW_STALE_THRESHOLD_MS = 8_000;
+// Backoff for the renew loops. Renews are a heartbeat, so the healthy cadence is
+// fixed and short; failures back off geometrically up to this cap. Once the
+// heartbeat has missed its TTL the session is already dropped server-side, so
+// retrying every 2s buys nothing but noise — `renew` is an upsert, so the
+// session re-establishes on the first success whenever that comes.
+const RENEW_MAX_BACKOFF_MS = 30_000;
// Safety net for the dialog gate: if a blocking prompt (permission/elicitation)
// never reports resolution, release the gate after this long so queued messages
// can't get permanently stuck. Normal turns are never gated.
@@ -225,6 +238,9 @@ export class RoomConnection {
private humanGateTimer: ReturnType<typeof setTimeout> | null = null;
/** Monotonic timestamp of the last renew that succeeded — drives the watchdog. */
private lastRenewOkAt = 0;
+ /** Consecutive connection-renew failures; 0 while healthy. Tells the watchdog
+ * a loop that is failing loudly apart from one that has gone quiet. */
+ private renewFailures = 0;
/** Aborts just the in-flight renew request (independent of the loop's own
* per-request timeout) so the watchdog can force an immediate retry. */
private renewRequestAbort: AbortController | null = null;
@@ -415,22 +431,74 @@ export class RoomConnection {
private async connectionRenewLoop(): Promise<void> {
// Seed the watchdog clock so a wedge before the first success is still caught.
this.lastRenewOkAt = Date.now();
- while (!this.abort.signal.aborted) {
+ await this.renewLoop('connection', CONNECTION_RENEW_INTERVAL_MS, async () => {
const requestAbort = new AbortController();
this.renewRequestAbort = requestAbort;
try {
await this.postConnectionRenew(requestAbort);
this.lastRenewOkAt = Date.now();
- } catch (error) {
- if (this.abort.signal.aborted) return;
- this.log.warn('RoomConnection: connection renew error', {
- roomId: this.roomId,
- error: String(error),
- });
} finally {
if (this.renewRequestAbort === requestAbort) this.renewRequestAbort = null;
}
- await new Promise((r) => setTimeout(r, CONNECTION_RENEW_INTERVAL_MS));
+ });
+ }
+
+ /**
+ * Drive one renew heartbeat until the connection stops.
+ *
+ * While renews succeed the cadence is fixed — this is a liveness signal and the
+ * server drops the session without it. While they fail it backs off to
+ * RENEW_MAX_BACKOFF_MS, and reports on a curve rather than per attempt: the
+ * first failure, then at exponentially sparser counts, then a line when it
+ * recovers. An endpoint that is permanently gone therefore costs a handful of
+ * lines rather than one every couple of seconds for the life of the app, while
+ * a failure that matters is still reported the moment it happens.
+ */
+ private async renewLoop(
+ kind: 'connection' | 'lease',
+ intervalMs: number,
+ attempt: () => Promise<void>
+ ): Promise<void> {
+ let failures = 0;
+ let failingSince = 0;
+
+ while (!this.abort.signal.aborted) {
+ try {
+ await attempt();
+ if (failures > 0) {
+ this.log.warn(`RoomConnection: ${kind} renew recovered`, {
+ event: 'room_renew_recovered',
+ roomId: this.roomId,
+ failures,
+ outageMs: Date.now() - failingSince,
+ });
+ }
+ failures = 0;
+ if (kind === 'connection') this.renewFailures = 0;
+ } catch (error) {
+ if (this.abort.signal.aborted) return;
+ if (failures === 0) failingSince = Date.now();
+ failures += 1;
+ if (kind === 'connection') this.renewFailures = failures;
+ // Powers of two: 1st, 2nd, 4th, 8th … failure. Dense enough to catch a
+ // blip as it starts, sparse enough that an outage cannot flood the log.
+ if ((failures & (failures - 1)) === 0) {
+ this.log.warn(`RoomConnection: ${kind} renew error`, {
+ event: 'room_renew_failed',
+ roomId: this.roomId,
+ endpoint: this.creds.apiEndpoint,
+ failures,
+ failingForMs: Date.now() - failingSince,
+ error: String(error),
+ });
+ }
+ }
+
+ const delay =
+ failures === 0
+ ? intervalMs
+ : Math.min(intervalMs * 2 ** (failures - 1), RENEW_MAX_BACKOFF_MS);
+ await new Promise((r) => setTimeout(r, delay));
}
}
@@ -448,18 +516,7 @@ export class RoomConnection {
* role auto-release shortly after the connection stops.
*/
private async leaseRenewLoop(): Promise<void> {
- while (!this.abort.signal.aborted) {
- try {
- await this.postLeaseRenew();
- } catch (error) {
- if (this.abort.signal.aborted) return;
- this.log.warn('RoomConnection: lease renew error', {
- roomId: this.roomId,
- error: String(error),
- });
- }
- await new Promise((r) => setTimeout(r, LEASE_RENEW_INTERVAL_MS));
- }
+ await this.renewLoop('lease', LEASE_RENEW_INTERVAL_MS, () => this.postLeaseRenew());
}
/**
@@ -467,12 +524,19 @@ export class RoomConnection {
* within RENEW_STALE_THRESHOLD_MS. Abort the in-flight request so the loop
* retries immediately instead of waiting out a stall, and warn loudly: a
* silently-dropped room should be visible, not mysterious.
+ *
+ * A loop that is failing outright is not stalled: it is looping, backing off
+ * and reporting on its own schedule, and there is no in-flight request to
+ * abort. Leave it to speak for itself — this watchdog exists for the case it
+ * cannot report, where a request neither returns nor rejects.
*/
private checkRenewStale(): void {
if (this.abort.signal.aborted) return;
+ if (this.renewFailures > 0) return;
const staleMs = Date.now() - this.lastRenewOkAt;
if (staleMs <= RENEW_STALE_THRESHOLD_MS) return;
this.log.warn('RoomConnection: renew stale — forcing retry', {
+ event: 'room_renew_stalled',
roomId: this.roomId,
staleMs,
});
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/session-room-store.db.test.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/session-room-store.db.test.ts
new file mode 100644
index 000000000..df50aebf5
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/session-room-store.db.test.ts
@@ -0,0 +1,143 @@
+import { openFixture } from '@tooling/utils/db';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { AppDb } from '@main/db/client';
+import { agents, locations, sessionRoomConnections, sessions } from '@main/db/schema';
+
+const mocks = vi.hoisted(() => ({
+ db: undefined as AppDb | undefined,
+}));
+
+vi.mock('@main/db/client', () => ({
+ get db() {
+ if (!mocks.db) throw new Error('Test database not initialized');
+ return mocks.db;
+ },
+}));
+
+const {
+ forgetRoomConnections,
+ getPersistedRoomConnection,
+ listPersistedRoomSessionIds,
+ persistRoomConnection,
+} = await import('./session-room-store');
+
+describe('session-room-store', () => {
+ let fixture: Awaited<ReturnType<typeof openFixture>>;
+
+ beforeEach(async () => {
+ fixture = await openFixture('empty');
+ mocks.db = fixture.db;
+
+ await fixture.db
+ .insert(locations)
+ .values({ id: 'loc-1', name: 'repo', sshHost: '', dir: '/tmp/repo' });
+ await fixture.db
+ .insert(agents)
+ .values({ id: 'agent-1', locationId: 'loc-1', name: 'agent-one', providerId: 'claude' });
+ await fixture.db
+ .insert(sessions)
+ .values({ id: 'session-1', agentId: 'agent-1', title: 'Session' });
+ });
+
+ afterEach(() => {
+ fixture.close();
+ mocks.db = undefined;
+ });
+
+ it('round-trips a connection and upserts on a room switch', async () => {
+ await persistRoomConnection('session-1', {
+ roomId: 'room-1',
+ roomName: 'First room',
+ switchAgentId: 'switch-agent-1',
+ });
+ await expect(getPersistedRoomConnection('session-1')).resolves.toEqual({
+ roomId: 'room-1',
+ roomName: 'First room',
+ switchAgentId: 'switch-agent-1',
+ });
+
+ await persistRoomConnection('session-1', {
+ roomId: 'room-2',
+ roomName: 'Second room',
+ switchAgentId: 'switch-agent-1',
+ });
+
+ // A session holds at most one room, so the switch replaces rather than adds.
+ await expect(listPersistedRoomSessionIds()).resolves.toEqual(['session-1']);
+ await expect(getPersistedRoomConnection('session-1')).resolves.toMatchObject({
+ roomId: 'room-2',
+ });
+ });
+
+ it('returns null for a session that never connected', async () => {
+ await expect(getPersistedRoomConnection('session-unknown')).resolves.toBeNull();
+ });
+
+ it('forgets the named sessions and leaves the rest', async () => {
+ await fixture.db
+ .insert(sessions)
+ .values({ id: 'session-2', agentId: 'agent-1', title: 'Other' });
+ await persistRoomConnection('session-1', {
+ roomId: 'room-1',
+ roomName: null,
+ switchAgentId: null,
+ });
+ await persistRoomConnection('session-2', {
+ roomId: 'room-2',
+ roomName: null,
+ switchAgentId: null,
+ });
+
+ await forgetRoomConnections(['session-1']);
+
+ await expect(listPersistedRoomSessionIds()).resolves.toEqual(['session-2']);
+ });
+
+ it('does nothing when asked to forget nothing', async () => {
+ await persistRoomConnection('session-1', {
+ roomId: 'room-1',
+ roomName: null,
+ switchAgentId: null,
+ });
+
+ await forgetRoomConnections([]);
+
+ await expect(listPersistedRoomSessionIds()).resolves.toEqual(['session-1']);
+ });
+
+ // The cascade is the reason this table exists: it is what makes a connection
+ // that outlives its session — and so a poller hammering a server that no
+ // longer exists — unrepresentable. It only holds if foreign keys are actually
+ // enforced on the runtime connection, so assert the enforcement too.
+ describe('foreign-key cascade', () => {
+ it('enforces foreign keys on a connection opened the way the app opens one', () => {
+ expect(fixture.sqlite.pragma('foreign_keys', { simple: true })).toBe(1);
+ });
+
+ it('drops the connection when its session is deleted', async () => {
+ await persistRoomConnection('session-1', {
+ roomId: 'room-1',
+ roomName: null,
+ switchAgentId: null,
+ });
+
+ await fixture.db.delete(sessions).where(eq(sessions.id, 'session-1'));
+
+ await expect(listPersistedRoomSessionIds()).resolves.toEqual([]);
+ });
+
+ it('drops the connection when the agent above the session is deleted', async () => {
+ await persistRoomConnection('session-1', {
+ roomId: 'room-1',
+ roomName: null,
+ switchAgentId: null,
+ });
+
+ await fixture.db.delete(agents).where(eq(agents.id, 'agent-1'));
+
+ await expect(listPersistedRoomSessionIds()).resolves.toEqual([]);
+ await expect(fixture.db.select().from(sessionRoomConnections)).resolves.toEqual([]);
+ });
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/session-room-store.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/session-room-store.ts
new file mode 100644
index 000000000..8b86541ae
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/session-room-store.ts
@@ -0,0 +1,78 @@
+import { inArray, sql } from 'drizzle-orm';
+import { eq } from 'drizzle-orm';
+import { db } from '@main/db/client';
+import { sessionRoomConnections } from '@main/db/schema';
+
+/**
+ * The durable half of a session's room connection: enough to re-arm the poller
+ * after a restart. Runtime state (the live `RoomConnection`, its queue and
+ * gates) stays in memory — only what must survive the process is stored.
+ */
+export type PersistedRoomConnection = {
+ roomId: string;
+ roomName: string | null;
+ /** The Switch-side agent identity (`SWITCH_AGENT_ID`), not `agents.id`. */
+ switchAgentId: string | null;
+};
+
+export async function getPersistedRoomConnection(
+ sessionId: string
+): Promise<PersistedRoomConnection | null> {
+ const [row] = await db
+ .select()
+ .from(sessionRoomConnections)
+ .where(eq(sessionRoomConnections.sessionId, sessionId))
+ .limit(1);
+ if (!row) return null;
+ return { roomId: row.roomId, roomName: row.roomName, switchAgentId: row.switchAgentId };
+}
+
+/**
+ * Record the room a session is attending. A session holds at most one room, so
+ * this is an upsert on the session id rather than an insert.
+ */
+export async function persistRoomConnection(
+ sessionId: string,
+ connection: PersistedRoomConnection
+): Promise<void> {
+ await db
+ .insert(sessionRoomConnections)
+ .values({
+ sessionId,
+ roomId: connection.roomId,
+ roomName: connection.roomName,
+ switchAgentId: connection.switchAgentId,
+ updatedAt: sql`CURRENT_TIMESTAMP`,
+ })
+ .onConflictDoUpdate({
+ target: sessionRoomConnections.sessionId,
+ set: {
+ roomId: connection.roomId,
+ roomName: connection.roomName,
+ switchAgentId: connection.switchAgentId,
+ updatedAt: sql`CURRENT_TIMESTAMP`,
+ },
+ });
+}
+
+/** Sessions that held a room connection before the last shutdown. */
+export async function listPersistedRoomSessionIds(): Promise<string[]> {
+ const rows = await db
+ .select({ sessionId: sessionRoomConnections.sessionId })
+ .from(sessionRoomConnections);
+ return rows.map((row) => row.sessionId);
+}
+
+/**
+ * Forget connections for sessions that can no longer be restored.
+ *
+ * A deleted session takes its row with it through the foreign key, so this
+ * exists for what the cascade cannot see: a session whose *location* has gone,
+ * which leaves the session row intact but unlaunchable.
+ */
+export async function forgetRoomConnections(sessionIds: string[]): Promise<void> {
+ if (sessionIds.length === 0) return;
+ await db
+ .delete(sessionRoomConnections)
+ .where(inArray(sessionRoomConnections.sessionId, sessionIds));
+}
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-notification-poller.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-notification-poller.ts
index 74b062720..4244a781c 100644
--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-notification-poller.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-notification-poller.ts
@@ -5,6 +5,8 @@ import { agentSettingsPath, subagentSettingsPath } from '@main/core/agents/switc
import { getLocationById } from '@main/core/locations/store';
import { isHumanInputRecent } from '@main/core/pty/human-activity';
import { loadSessionWithAgent } from '@main/core/sessions/session-join';
+import { runWithLogContext } from '@main/lib/log-context';
+import { noteAgentName, noteSessionTitle } from '@main/lib/log-name-cache';
import { log } from '@main/lib/logger';
import type { AgentStatus, NotificationType } from '@shared/core/providers/agentEvents';
import { makeAgentPtySessionId } from '@shared/core/pty/ptySessionId';
@@ -118,6 +120,11 @@ class SwitchNotificationPoller {
return;
}
+ // Names for the ids these logs carry. The poller holds the joined row
+ // already, so hand them over rather than making the log path look them up.
+ noteSessionTitle(ctx.sessionId, loaded.row.title);
+ noteAgentName(creds.agentId, slug);
+
const ptySessionId = makeAgentPtySessionId(location.id, ctx.sessionId);
const connection = new RoomConnection({
creds,
@@ -141,7 +148,19 @@ class SwitchNotificationPoller {
agentId: creds.agentId,
});
- connection.start();
+ // Open the scope the connection's loops inherit. They outlive this call and
+ // log from timers, so without it their lines could only ever name the room —
+ // which is exactly how a failing connection became hard to trace back to the
+ // session and agent behind it.
+ runWithLogContext(
+ {
+ component: 'room-connection',
+ sessionId: ctx.sessionId,
+ agentId: creds.agentId,
+ agentName: slug,
+ },
+ () => connection.start()
+ );
}
/**
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-room-service.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-room-service.ts
index 0cdc81556..19bee2715 100644
--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-room-service.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-room-service.ts
@@ -1,11 +1,14 @@
import type { IDisposable } from '@switchdash/shared';
-import { eq } from 'drizzle-orm';
-import { db } from '@main/db/client';
-import { appSettings } from '@main/db/schema';
import { events } from '@main/lib/events';
import { log } from '@main/lib/logger';
import type { SessionRoomConnection } from '@shared/core/switch-rooms/switch-rooms';
import { sessionRoomChangedChannel } from '@shared/core/switch-rooms/switchRoomEvents';
+import {
+ forgetRoomConnections,
+ getPersistedRoomConnection,
+ listPersistedRoomSessionIds,
+ persistRoomConnection,
+} from './session-room-store';
import { switchNotificationPoller } from './switch-notification-poller';
export type SessionRoomContext = {
@@ -20,11 +23,6 @@ type ConnectionState = SessionRoomConnection & {
ptyId: string;
};
-/** Persisted across app restarts so a resumed session re-polls its room. */
-type PersistedConnection = { roomId: string; agentId: string; roomName: string | null };
-
-const PERSIST_KEY = 'switchRoomConnections';
-
/**
* Tracks which Switch room each live switchdash session is connected to.
*
@@ -49,7 +47,7 @@ class SwitchRoomService implements IDisposable {
setSessionRoom(
ctx: SessionRoomContext,
roomId: string,
- agentId: string,
+ agentId: string | null,
roomName: string | null
): void {
const previous = this.connections.get(ctx.sessionId);
@@ -66,7 +64,11 @@ class SwitchRoomService implements IDisposable {
// Persist so a resumed session re-polls this room after an app restart,
// even though the connect_to_room hook only fires on a live tool call.
- void this.persistConnection(ctx.sessionId, { roomId, agentId, roomName }).catch((error) => {
+ void persistRoomConnection(ctx.sessionId, {
+ roomId,
+ roomName,
+ switchAgentId: agentId,
+ }).catch((error) => {
log.warn('SwitchRoomService: failed to persist connection', {
sessionId: ctx.sessionId,
error: String(error),
@@ -92,7 +94,7 @@ class SwitchRoomService implements IDisposable {
* Mirror the room a remote session is attending, as reported by the on-VM
* sidecar's `/sessions` snapshot. Unlike setSessionRoom (the local
* connect_to_room hook path) this records the association for DISPLAY only: it
- * does not persist to the restore blob and does not start switchdash's
+ * does not persist the connection and does not start switchdash's
* notification poller — the sidecar owns polling and injection on the VM, and
* the reconciler re-derives the room from the live snapshot every tick, so
* there is nothing to restore across restarts. The unchanged-guard keeps the
@@ -132,7 +134,7 @@ class SwitchRoomService implements IDisposable {
* connect_to_room again. No-op when the session has no persisted room.
*/
async restorePoller(ctx: SessionRoomContext): Promise<void> {
- const persisted = await this.getPersisted(ctx.sessionId);
+ const persisted = await getPersistedRoomConnection(ctx.sessionId);
if (!persisted) return;
log.info('SwitchRoomService: restoring room poller for resumed session', {
@@ -140,27 +142,18 @@ class SwitchRoomService implements IDisposable {
roomId: persisted.roomId,
});
- this.setSessionRoom(ctx, persisted.roomId, persisted.agentId, persisted.roomName);
+ this.setSessionRoom(ctx, persisted.roomId, persisted.switchAgentId, persisted.roomName);
switchNotificationPoller.connect(ctx, persisted.roomId, persisted.roomName);
}
/** Session ids that had a live room connection before the last shutdown. */
async listPersistedSessionIds(): Promise<string[]> {
- return Object.keys(await this.readPersisted());
+ return listPersistedRoomSessionIds();
}
- /** Forget persisted connections whose sessions no longer exist. */
+ /** Forget persisted connections for sessions that can no longer be restored. */
async prunePersisted(sessionIds: string[]): Promise<void> {
- if (sessionIds.length === 0) return;
- const map = await this.readPersisted();
- let changed = false;
- for (const id of sessionIds) {
- if (id in map) {
- delete map[id];
- changed = true;
- }
- }
- if (changed) await this.writePersisted(map);
+ await forgetRoomConnections(sessionIds);
}
/** Drop a session's connection (on room switch-away or session exit). */
@@ -203,41 +196,6 @@ class SwitchRoomService implements IDisposable {
}));
}
- private async getPersisted(sessionId: string): Promise<PersistedConnection | null> {
- const map = await this.readPersisted();
- return map[sessionId] ?? null;
- }
-
- private async readPersisted(): Promise<Record<string, PersistedConnection>> {
- const [row] = await db
- .select({ value: appSettings.value })
- .from(appSettings)
- .where(eq(appSettings.key, PERSIST_KEY));
- if (!row) return {};
- try {
- return JSON.parse(row.value) as Record<string, PersistedConnection>;
- } catch {
- return {};
- }
- }
-
- private async persistConnection(
- sessionId: string,
- connection: PersistedConnection
- ): Promise<void> {
- const map = await this.readPersisted();
- map[sessionId] = connection;
- await this.writePersisted(map);
- }
-
- private async writePersisted(map: Record<string, PersistedConnection>): Promise<void> {
- const serialized = JSON.stringify(map);
- await db
- .insert(appSettings)
- .values({ key: PERSIST_KEY, value: serialized })
- .onConflictDoUpdate({ target: appSettings.key, set: { value: serialized } });
- }
-
dispose(): void {
this.connections.clear();
}
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-servers/delete-server-agents.db.test.ts b/dash/apps/switchdash-desktop/src/main/core/switch-servers/delete-server-agents.db.test.ts
new file mode 100644
index 000000000..5243a6514
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-servers/delete-server-agents.db.test.ts
@@ -0,0 +1,120 @@
+import { openFixture } from '@tooling/utils/db';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { AppDb } from '@main/db/client';
+import { agents, locations, switchServers } from '@main/db/schema';
+
+const mocks = vi.hoisted(() => ({
+ db: undefined as AppDb | undefined,
+ deleteAgent: vi.fn(async (_agentId: string, _options: { deleteInSwitch: boolean }) => {}),
+}));
+
+vi.mock('@main/db/client', () => ({
+ get db() {
+ if (!mocks.db) throw new Error('Test database not initialized');
+ return mocks.db;
+ },
+}));
+
+// The real deleteAgent tears down runtimes, watchers, sidecars and on-disk
+// files; this suite is about *which* agents it is asked to delete, and with
+// what options.
+vi.mock('@main/core/agents/deleteAgent', () => ({
+ deleteAgent: mocks.deleteAgent,
+}));
+
+const { deleteAgentsForServer } = await import('./delete-server-agents');
+
+describe('deleteAgentsForServer', () => {
+ let fixture: Awaited<ReturnType<typeof openFixture>>;
+
+ beforeEach(async () => {
+ fixture = await openFixture('empty');
+ mocks.db = fixture.db;
+ mocks.deleteAgent.mockReset();
+ mocks.deleteAgent.mockResolvedValue(undefined);
+
+ await fixture.db
+ .insert(locations)
+ .values({ id: 'loc-1', name: 'repo', sshHost: '', dir: '/tmp/repo' });
+ for (const id of ['managed-1', 'other-1']) {
+ await fixture.db.insert(switchServers).values({
+ id,
+ name: id,
+ gatewayUrl: `https://${id}.example.com`,
+ apiUrl: `https://api-${id}.example.com`,
+ });
+ }
+ });
+
+ afterEach(() => {
+ fixture.close();
+ mocks.db = undefined;
+ });
+
+ async function seedAgent(id: string, serverId: string | null): Promise<void> {
+ await fixture.db
+ .insert(agents)
+ .values({ id, locationId: 'loc-1', name: id, providerId: 'claude', serverId });
+ }
+
+ it('deletes only the agents belonging to the given server', async () => {
+ await seedAgent('agent-a', 'managed-1');
+ await seedAgent('agent-b', 'managed-1');
+ await seedAgent('agent-other', 'other-1');
+ await seedAgent('agent-unlinked', null);
+
+ const result = await deleteAgentsForServer('managed-1');
+
+ expect(result.deleted.sort()).toEqual(['agent-a', 'agent-b']);
+ expect(mocks.deleteAgent.mock.calls.map(([agentId]) => agentId).sort()).toEqual([
+ 'agent-a',
+ 'agent-b',
+ ]);
+ });
+
+ // The stack's own records are about to be destroyed wholesale, and the
+ // gateway call would be made against a server that is going away.
+ it('does not ask the gateway to delete each agent', async () => {
+ await seedAgent('agent-a', 'managed-1');
+
+ await deleteAgentsForServer('managed-1');
+
+ expect(mocks.deleteAgent).toHaveBeenCalledWith('agent-a', { deleteInSwitch: false });
+ });
+
+ it('reports a failed agent instead of stranding the rest', async () => {
+ await seedAgent('agent-a', 'managed-1');
+ await seedAgent('agent-b', 'managed-1');
+ mocks.deleteAgent.mockImplementation(async (agentId: string) => {
+ if (agentId === 'agent-a') throw new Error('pty teardown exploded');
+ });
+
+ const result = await deleteAgentsForServer('managed-1');
+
+ expect(result.failed).toEqual([{ agentId: 'agent-a', error: 'Error: pty teardown exploded' }]);
+ expect(result.deleted).toEqual(['agent-b']);
+ });
+
+ it('is a no-op for a server with no agents', async () => {
+ await seedAgent('agent-other', 'other-1');
+
+ const result = await deleteAgentsForServer('managed-1');
+
+ expect(result).toEqual({ deleted: [], failed: [] });
+ expect(mocks.deleteAgent).not.toHaveBeenCalled();
+ });
+
+ it('leaves other servers’ agent rows in place', async () => {
+ await seedAgent('agent-a', 'managed-1');
+ await seedAgent('agent-other', 'other-1');
+
+ await deleteAgentsForServer('managed-1');
+
+ const remaining = await fixture.db
+ .select({ id: agents.id })
+ .from(agents)
+ .where(eq(agents.serverId, 'other-1'));
+ expect(remaining).toEqual([{ id: 'agent-other' }]);
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-servers/delete-server-agents.ts b/dash/apps/switchdash-desktop/src/main/core/switch-servers/delete-server-agents.ts
new file mode 100644
index 000000000..b670aeb32
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-servers/delete-server-agents.ts
@@ -0,0 +1,67 @@
+import { eq } from 'drizzle-orm';
+import { deleteAgent } from '@main/core/agents/deleteAgent';
+import { db } from '@main/db/client';
+import { agents } from '@main/db/schema';
+import { log } from '@main/lib/logger';
+
+/**
+ * Delete every agent that belongs to a managed Switch server, as part of
+ * destroying that server's stack.
+ *
+ * Wiping a managed stack destroys the server-side identity behind each of its
+ * agents: the token in the agent's on-disk Switch settings authenticates
+ * nothing, and its API endpoint is a port that will never be listened on again.
+ * An agent left in that state is not merely idle — switchdash restores its
+ * room-connected sessions on every launch, and each one polls a dead endpoint
+ * for as long as the app runs.
+ *
+ * Deliberately scoped to *managed* servers. De-registering an external server
+ * destroys nothing: that switch-core keeps running and its agents keep working,
+ * so those agents are unlinked and kept (see `removeServer`).
+ *
+ * `deleteInSwitch` is false — the server-side records are about to be destroyed
+ * wholesale by the reset, and a per-agent gateway call would fail against a
+ * stack that is already going away.
+ *
+ * Each agent is deleted independently so one failure cannot strand the rest;
+ * the failures are returned rather than thrown, since the reset that follows is
+ * what the caller is really waiting on.
+ */
+export async function deleteAgentsForServer(
+ serverId: string
+): Promise<{ deleted: string[]; failed: { agentId: string; error: string }[] }> {
+ const rows = await db
+ .select({ id: agents.id, name: agents.name })
+ .from(agents)
+ .where(eq(agents.serverId, serverId));
+
+ const deleted: string[] = [];
+ const failed: { agentId: string; error: string }[] = [];
+
+ for (const row of rows) {
+ try {
+ await deleteAgent(row.id, { deleteInSwitch: false });
+ deleted.push(row.id);
+ } catch (error) {
+ failed.push({ agentId: row.id, error: String(error) });
+ log.error('deleteAgentsForServer: failed to delete agent of a destroyed server', {
+ event: 'server_teardown_agent_failed',
+ serverId,
+ agentId: row.id,
+ agentName: row.name,
+ error: String(error),
+ });
+ }
+ }
+
+ if (rows.length > 0) {
+ log.info('deleteAgentsForServer: removed agents belonging to a destroyed server', {
+ event: 'server_teardown_agents_removed',
+ serverId,
+ deleted: deleted.length,
+ failed: failed.length,
+ });
+ }
+
+ return { deleted, failed };
+}
diff --git a/dash/apps/switchdash-desktop/src/main/db/drizzle.gen.config.ts b/dash/apps/switchdash-desktop/src/main/db/drizzle.gen.config.ts
new file mode 100644
index 000000000..e69de29bb
diff --git a/dash/apps/switchdash-desktop/src/main/db/schema.ts b/dash/apps/switchdash-desktop/src/main/db/schema.ts
index 3b9c90b89..1d6f697e9 100644
--- a/dash/apps/switchdash-desktop/src/main/db/schema.ts
+++ b/dash/apps/switchdash-desktop/src/main/db/schema.ts
@@ -255,6 +255,33 @@ export const sessions = sqliteTable(
})
);
+/**
+ * The Switch room a session is attending, durable across restarts so a resumed
+ * session re-polls its room without waiting for the agent to call
+ * `connect_to_room` again.
+ *
+ * Keyed by session and cascaded from it: a session (or the agent above it)
+ * going away takes its room connection with it. That cascade is the point of
+ * the table — the previous storage, a single JSON blob in `app_settings`,
+ * referenced nothing and so outlived the sessions it described, resurrecting
+ * pollers for agents whose Switch server had been destroyed.
+ *
+ * `switchAgentId` is the identity on the Switch side (an agent's
+ * `SWITCH_AGENT_ID`), not `agents.id` — it is reported by the connecting agent
+ * and carried for display, so it is deliberately not a foreign key.
+ */
+export const sessionRoomConnections = sqliteTable('session_room_connections', {
+ sessionId: text('session_id')
+ .primaryKey()
+ .references(() => sessions.id, { onDelete: 'cascade' }),
+ roomId: text('room_id').notNull(),
+ roomName: text('room_name'),
+ switchAgentId: text('switch_agent_id'),
+ updatedAt: text('updated_at')
+ .notNull()
+ .default(sql`CURRENT_TIMESTAMP`),
+});
+
export const messages = sqliteTable(
'messages',
{
diff --git a/dash/apps/switchdash-desktop/src/main/db/tests/migrations/0044-session-room-connections.test.ts b/dash/apps/switchdash-desktop/src/main/db/tests/migrations/0044-session-room-connections.test.ts
new file mode 100644
index 000000000..8c856c526
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/db/tests/migrations/0044-session-room-connections.test.ts
@@ -0,0 +1,142 @@
+/**
+ * Migration 0044 — moves session→room connections out of the
+ * `switchRoomConnections` JSON blob in `app_settings` into their own table.
+ *
+ * The interesting behaviour is the filter: connections whose session still
+ * exists are carried over, leaked ones (the session, and so the agent above it,
+ * are long gone) are dropped, and the blob is deleted so nothing can resurrect
+ * them. Applying the committed SQL against a minimal schema keeps the test on
+ * exactly the statements that ship — `openFixture` would have already created
+ * the table, so the migration cannot be replayed against 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/0044_session_room_connections.sql'
+ ),
+ 'utf8'
+);
+
+function applyMigration(db: Database.Database): void {
+ for (const stmt of MIGRATION_SQL.split('--> statement-breakpoint')) {
+ const trimmed = stmt.trim();
+ if (trimmed) db.exec(trimmed);
+ }
+}
+
+type BlobEntry = { roomId: string; agentId: string; roomName: string | null };
+
+describe('migration 0044: session room connections', () => {
+ let db: Database.Database;
+
+ beforeEach(() => {
+ db = new Database(':memory:');
+ db.exec(`
+ CREATE TABLE sessions (
+ id TEXT PRIMARY KEY,
+ agent_id TEXT NOT NULL,
+ title TEXT NOT NULL
+ );
+ CREATE TABLE app_settings (
+ key TEXT PRIMARY KEY,
+ value TEXT NOT NULL
+ );
+ `);
+ });
+
+ afterEach(() => {
+ db.close();
+ });
+
+ function seedSession(id: string): void {
+ db.prepare(`INSERT INTO sessions (id, agent_id, title) VALUES (?, 'agent-1', 'Session')`).run(
+ id
+ );
+ }
+
+ function seedBlob(entries: Record<string, BlobEntry>): void {
+ db.prepare(`INSERT INTO app_settings (key, value) VALUES ('switchRoomConnections', ?)`).run(
+ JSON.stringify(entries)
+ );
+ }
+
+ function connectionRows(): { session_id: string; room_id: string; room_name: string | null }[] {
+ return db
+ .prepare(
+ `SELECT session_id, room_id, room_name, switch_agent_id FROM session_room_connections`
+ )
+ .all() as { session_id: string; room_id: string; room_name: string | null }[];
+ }
+
+ it('carries over a live connection with its room and agent identity', () => {
+ seedSession('session-live');
+ seedBlob({
+ 'session-live': { roomId: 'room-1', agentId: 'switch-agent-1', roomName: 'Design' },
+ });
+
+ applyMigration(db);
+
+ expect(connectionRows()).toEqual([
+ {
+ session_id: 'session-live',
+ room_id: 'room-1',
+ room_name: 'Design',
+ switch_agent_id: 'switch-agent-1',
+ },
+ ]);
+ });
+
+ it('drops connections whose session no longer exists', () => {
+ seedSession('session-live');
+ seedBlob({
+ 'session-live': { roomId: 'room-1', agentId: 'switch-agent-1', roomName: 'Design' },
+ 'session-gone': { roomId: 'room-2', agentId: 'switch-agent-2', roomName: 'Leaked' },
+ });
+
+ applyMigration(db);
+
+ expect(connectionRows().map((row) => row.session_id)).toEqual(['session-live']);
+ });
+
+ it('deletes the blob so the dropped connections cannot be resurrected', () => {
+ seedSession('session-live');
+ seedBlob({
+ 'session-live': { roomId: 'room-1', agentId: 'switch-agent-1', roomName: null },
+ });
+
+ applyMigration(db);
+
+ const remaining = db
+ .prepare(`SELECT count(*) AS n FROM app_settings WHERE key = 'switchRoomConnections'`)
+ .get() as { n: number };
+ expect(remaining.n).toBe(0);
+ });
+
+ it('tolerates a missing blob, an unparseable one, and entries without a room', () => {
+ seedSession('session-live');
+
+ applyMigration(db);
+ expect(connectionRows()).toEqual([]);
+
+ db.exec(`DROP TABLE session_room_connections`);
+ db.prepare(`INSERT INTO app_settings (key, value) VALUES ('switchRoomConnections', ?)`).run(
+ 'not json'
+ );
+ applyMigration(db);
+ expect(connectionRows()).toEqual([]);
+
+ db.exec(`DROP TABLE session_room_connections`);
+ db.prepare(`INSERT INTO app_settings (key, value) VALUES ('switchRoomConnections', ?)`).run(
+ JSON.stringify({ 'session-live': { agentId: 'switch-agent-1' } })
+ );
+ applyMigration(db);
+ expect(connectionRows()).toEqual([]);
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/RemoteServerControls.tsx b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/RemoteServerControls.tsx
index 952bd5fcf..671f4e464 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/RemoteServerControls.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/RemoteServerControls.tsx
@@ -25,11 +25,9 @@ const card = 'rounded-lg border border-border bg-card p-4';
*/
export const RemoteServerControls = observer(function RemoteServerControls({
sshHost,
- serverId,
name,
}: {
sshHost: string;
- serverId: string;
/** The registered server's name, reused when restarting so the record's name
* is preserved (not blanked). */
name: string;
@@ -142,7 +140,7 @@ export const RemoteServerControls = observer(function RemoteServerControls({
disabled={transitioning}
onConfirm={() => {
setResetOpen(false);
- void store.reset(sshHost, serverId);
+ void store.reset(sshHost);
}}
/>
</div>
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/local-server-store.ts b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/local-server-store.ts
index 1cc838aa3..6f0e97a9b 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/local-server-store.ts
+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/local-server-store.ts
@@ -1,6 +1,5 @@
import { makeAutoObservable, runInAction } from 'mobx';
import { agentsStore } from '@renderer/features/locations/stores/agents-store';
-import { getLocationManagerStore } from '@renderer/features/locations/stores/location-selectors';
import { events, rpc } from '@renderer/lib/ipc';
import type {
DockerAvailability,
@@ -150,12 +149,11 @@ export class LocalServerStore {
this.error = null;
});
try {
- // Delete the managed server's agents first (same path as the sidebar's
- // "Remove agent", so they drop out of the tree), then wipe the stack —
- // the wipe destroys their server-side identity, so leaving them would
- // strand them as "Unnamed agent" rows.
- await this.removeManagedAgents();
+ // The reset deletes the stack's agents itself — their server-side
+ // identity dies with it — so this only has to refresh what the deletion
+ // changed underneath the UI.
await rpc.localSwitchServer.reset();
+ await agentsStore.load();
await switchServersStore.init();
} catch (cause) {
this.setError(cause);
@@ -166,22 +164,6 @@ export class LocalServerStore {
}
}
- /** Remove every location whose agent belongs to the managed local server. */
- private async removeManagedAgents(): Promise<void> {
- const managedId = switchServersStore.servers.find((s) => s.managed)?.id;
- if (!managedId) return;
- await agentsStore.load();
- const locationIds = new Set<string>();
- for (const [locationId, agents] of agentsStore.byLocation) {
- if (agents.some((a) => a.serverId === managedId)) locationIds.add(locationId);
- }
- const manager = getLocationManagerStore();
- for (const locationId of locationIds) {
- await manager.removeLocation(locationId);
- }
- await agentsStore.load();
- }
-
private setError(cause: unknown): void {
runInAction(() => {
this.error = cause instanceof Error ? cause.message : String(cause);
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/remote-server-store.ts b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/remote-server-store.ts
index ba9b8d04d..503f22881 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/remote-server-store.ts
+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/remote-server-store.ts
@@ -1,6 +1,5 @@
import { makeAutoObservable, runInAction } from 'mobx';
import { agentsStore } from '@renderer/features/locations/stores/agents-store';
-import { getLocationManagerStore } from '@renderer/features/locations/stores/location-selectors';
import { hostReachabilityStore } from '@renderer/features/remote-hosts/host-reachability-store';
import { events, rpc } from '@renderer/lib/ipc';
import type { DockerAvailability } from '@shared/core/managed-switch-server/managed-switch-server';
@@ -163,16 +162,17 @@ export class RemoteServerStore {
}
}
- async reset(sshHost: string, serverId: string): Promise<void> {
+ async reset(sshHost: string): Promise<void> {
runInAction(() => {
this.busyHosts.add(sshHost);
this.error = null;
});
try {
- // Remove the server's agents first (their server-side identity is wiped by
- // the reset), then destroy the stack.
- await this.removeManagedAgents(serverId);
+ // The reset deletes the stack's agents itself — their server-side
+ // identity dies with it — so this only has to refresh what the deletion
+ // changed underneath the UI.
await rpc.remoteSwitchServer.reset(sshHost);
+ await agentsStore.load();
await switchServersStore.init();
} catch (cause) {
this.setError(cause);
@@ -181,19 +181,6 @@ export class RemoteServerStore {
}
}
- private async removeManagedAgents(serverId: string): Promise<void> {
- await agentsStore.load();
- const locationIds = new Set<string>();
- for (const [locationId, agents] of agentsStore.byLocation) {
- if (agents.some((a) => a.serverId === serverId)) locationIds.add(locationId);
- }
- const manager = getLocationManagerStore();
- for (const locationId of locationIds) {
- await manager.removeLocation(locationId);
- }
- await agentsStore.load();
- }
-
private setError(cause: unknown): void {
runInAction(() => {
this.error = cause instanceof Error ? cause.message : String(cause);
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-servers-store.ts b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-servers-store.ts
index e1787daf5..e091667c7 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-servers-store.ts
+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-servers-store.ts
@@ -197,10 +197,12 @@ export class SwitchServersStore {
/**
* Delete a server. For a managed server this first tears down its stack (the
* Docker/SSH reset — stops containers and destroys the stack's data), since
- * removing the record while the stack keeps running would strand it. External
- * servers have no stack, so this is a plain de-register. In both cases the
- * server's agents are unlinked but kept (see {@link removeServer}), never
- * deleted. Returns false if the teardown or de-register failed.
+ * removing the record while the stack keeps running would strand it. That
+ * teardown also deletes the stack's agents, whose identity it destroys.
+ *
+ * External servers have no stack: de-registering one destroys nothing, so its
+ * agents keep working and are merely unlinked (see {@link removeServer}).
+ * Returns false if the teardown or de-register failed.
*/
async deleteServer(serverId: string): Promise<boolean> {
this.clearError();
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/view.tsx b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/view.tsx
index 9a2b26ae5..145aa2d75 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/view.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/view.tsx
@@ -190,11 +190,7 @@ const ServerMainPanel = observer(function ServerMainPanel() {
{server.managed &&
(server.managementKind === 'remote' && server.sshHost ? (
- <RemoteServerControls
- sshHost={server.sshHost}
- serverId={server.id}
- name={server.name}
- />
+ <RemoteServerControls sshHost={server.sshHost} name={server.name} />
) : (
<LocalServerControls />
))}
diff --git a/dash/apps/switchdash-desktop/src/shared/core/switch-rooms/switch-rooms.ts b/dash/apps/switchdash-desktop/src/shared/core/switch-rooms/switch-rooms.ts
index 482ed28f1..cac6d8404 100644
--- a/dash/apps/switchdash-desktop/src/shared/core/switch-rooms/switch-rooms.ts
+++ b/dash/apps/switchdash-desktop/src/shared/core/switch-rooms/switch-rooms.ts
@@ -9,6 +9,9 @@ export interface SessionRoomConnection {
sessionId: string;
/** The Switch room the session is currently connected to. */
roomId: string;
- /** The Switch agent id that connected (from the agent's SWITCH_AGENT_ID). */
- agentId: string;
+ /** The Switch agent id that connected (from the agent's SWITCH_AGENT_ID).
+ * Null when a restored connection predates the identity being recorded — the
+ * field is for display, so an unknown one is reported as unknown rather than
+ * invented. */
+ agentId: string | null;
}
diff --git a/dash/apps/switchdash-desktop/tooling/fixtures/baseline.db b/dash/apps/switchdash-desktop/tooling/fixtures/baseline.db
index 23f9fa3ff..c11b06ed3 100644
Binary files a/dash/apps/switchdash-desktop/tooling/fixtures/baseline.db and b/dash/apps/switchdash-desktop/tooling/fixtures/baseline.db differ
diff --git a/dash/apps/switchdash-desktop/tooling/fixtures/empty.db b/dash/apps/switchdash-desktop/tooling/fixtures/empty.db
index c8fa0866d..5f86d6ba0 100644
Binary files a/dash/apps/switchdash-desktop/tooling/fixtures/empty.db and b/dash/apps/switchdash-desktop/tooling/fixtures/empty.db differ