Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
feat(switchdash): sidecar lifecycle, versioning & resiliency (CHOO-1425) (#74)
Louis Amaudruz3015c70428e2
diff --git a/dash/apps/switchdash-desktop/drizzle/0041_delete_leaked_tagged_sessions.sql b/dash/apps/switchdash-desktop/drizzle/0041_delete_leaked_tagged_sessions.sqlnew file mode 100644index 000000000..217285b77--- /dev/null+++ b/dash/apps/switchdash-desktop/drizzle/0041_delete_leaked_tagged_sessions.sql@@ -0,0 +1,31 @@+/*+ Collapse agent identity onto `agents.name`, then delete leaked / misidentified+ sessions (CHOO-1440 follow-up).++ The authoritative identity value has been carried by `agents.definition_name`+ (the `.claude/agents/<name>` stem, the `--agent` value, the creds-file key);+ `name` was a second, sometimes-stale copy. We are collapsing to a single+ `agents.name`, so first backfill it from the authoritative `definition_name`+ wherever that is set. `definition_name` itself is dropped by the next migration.++ A session used to freeze its agent identity as a name tag in `config`+ (`agentName`, legacy `subagentName`) while its `agent_id` was written to the+ wrong agent — the location's representative agent instead of the one it actually+ ran as. Identity now resolves from `session.agent_id -> agents.name` (the+ sidebar groups by agent_id; the notification poller reads credentials from the+ joined agent row), so a session whose frozen tag disagrees with its owning+ agent's (now-authoritative) `name` points at the wrong agent and cannot be+ repaired from the tag alone. Some point at a name whose agent row no longer+ exists at all — the invisible "ghosts".++ Delete exactly those diverged rows: a tag that does NOT equal the owning agent's+ `name` (compared AFTER the backfill, so `name` already holds the proper value).+ A healthy session whose tag matches its agent's name is kept, so live+ auto-started sessions are not churned; untagged sessions are kept. The wiped+ rows recreate under the correct agent id on next launch / auto-start.+*/+UPDATE `agents` SET `name` = `definition_name` WHERE `definition_name` IS NOT NULL;--> statement-breakpoint+DELETE FROM `sessions`+WHERE COALESCE(json_extract(`config`, '$.agentName'), json_extract(`config`, '$.subagentName')) IS NOT NULL+ AND COALESCE(json_extract(`config`, '$.agentName'), json_extract(`config`, '$.subagentName'))+ IS NOT (SELECT `name` FROM `agents` WHERE `agents`.`id` = `sessions`.`agent_id`);diff --git a/dash/apps/switchdash-desktop/drizzle/0042_drop_agent_definition_name.sql b/dash/apps/switchdash-desktop/drizzle/0042_drop_agent_definition_name.sqlnew file mode 100644index 000000000..9c6153516--- /dev/null+++ b/dash/apps/switchdash-desktop/drizzle/0042_drop_agent_definition_name.sql@@ -0,0 +1 @@+ALTER TABLE `agents` DROP COLUMN `definition_name`;\ No newline at end of filediff --git a/dash/apps/switchdash-desktop/drizzle/meta/0041_snapshot.json b/dash/apps/switchdash-desktop/drizzle/meta/0041_snapshot.jsonnew file mode 100644index 000000000..fb71319f5--- /dev/null+++ b/dash/apps/switchdash-desktop/drizzle/meta/0041_snapshot.json@@ -0,0 +1,718 @@+{+ "id": "d9df5e5d-e959-440a-afa3-d4b78886c9a1",+ "prevId": "42cda662-cb01-492f-b667-cc190d511d8f",+ "version": "6",+ "dialect": "sqlite",+ "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+ },+ "definition_name": {+ "name": "definition_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "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",+ "columnsFrom": ["location_id"],+ "tableTo": "locations",+ "columnsTo": ["id"],+ "onUpdate": "no action",+ "onDelete": "no action"+ },+ "agents_server_id_switch_servers_id_fk": {+ "name": "agents_server_id_switch_servers_id_fk",+ "tableFrom": "agents",+ "columnsFrom": ["server_id"],+ "tableTo": "switch_servers",+ "columnsTo": ["id"],+ "onUpdate": "no action",+ "onDelete": "set null"+ }+ },+ "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",+ "columnsFrom": ["location_id"],+ "tableTo": "locations",+ "columnsTo": ["id"],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "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",+ "columnsFrom": ["session_id"],+ "tableTo": "sessions",+ "columnsTo": ["id"],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "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",+ "columnsFrom": ["agent_id"],+ "tableTo": "agents",+ "columnsTo": ["id"],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "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": {}+ }+ },+ "views": {},+ "enums": {},+ "_meta": {+ "columns": {},+ "schemas": {},+ "tables": {}+ },+ "internal": {+ "indexes": {}+ }+}diff --git a/dash/apps/switchdash-desktop/drizzle/meta/0042_snapshot.json b/dash/apps/switchdash-desktop/drizzle/meta/0042_snapshot.jsonnew file mode 100644index 000000000..d326b6b92--- /dev/null+++ b/dash/apps/switchdash-desktop/drizzle/meta/0042_snapshot.json@@ -0,0 +1,711 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "4744931c-4640-42c4-9ac3-6b1b0946a0b4",+ "prevId": "d9df5e5d-e959-440a-afa3-d4b78886c9a1",+ "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_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": {}+ }+ },+ "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.jsonindex 94e6de660..6ae857a92 100644--- a/dash/apps/switchdash-desktop/drizzle/meta/_journal.json+++ b/dash/apps/switchdash-desktop/drizzle/meta/_journal.json@@ -288,6 +288,20 @@"when": 1784989270502,"tag": "0040_massive_dreadnoughts","breakpoints": true+ },+ {+ "idx": 41,+ "version": "6",+ "when": 1785162743556,+ "tag": "0041_delete_leaked_tagged_sessions",+ "breakpoints": true+ },+ {+ "idx": 42,+ "version": "6",+ "when": 1785164441913,+ "tag": "0042_drop_agent_definition_name",+ "breakpoints": true}]}diff --git a/dash/apps/switchdash-desktop/scripts/build-sidecar.mjs b/dash/apps/switchdash-desktop/scripts/build-sidecar.mjsindex 263f839bb..606ec621d 100644--- a/dash/apps/switchdash-desktop/scripts/build-sidecar.mjs+++ b/dash/apps/switchdash-desktop/scripts/build-sidecar.mjs@@ -1,3 +1,4 @@+import { readFile } from 'node:fs/promises';import { build } from 'esbuild';/**@@ -34,14 +35,34 @@ const guardForbiddenImports = {},};+const OUTFILE = 'dist-sidecar/sidecar.mjs';+await build({entryPoints: ['src/sidecar/index.ts'],bundle: true,platform: 'node',format: 'esm',target: 'node20',- outfile: 'dist-sidecar/sidecar.mjs',+ outfile: OUTFILE,tsconfig: 'tsconfig.json',logLevel: 'info',plugins: [guardForbiddenImports],});++/**+ * The sidecar runs under raw Node, where `import.meta.env` is undefined — unlike+ * the Vite-built renderer/main (and unlike Vitest, which defines it, so a unit+ * test cannot catch this). An UNGUARDED `import.meta.env.X` read therefore+ * crashes the sidecar on boot; the guarded `import.meta.env?.X` is fine. Shared+ * code the sidecar bundles must use the optional-chained form (see+ * `src/shared/logger.ts`). Fail the build loudly if an unguarded read slips in,+ * rather than shipping a bundle that dies on the VM (CHOO-1425).+ */+const bundle = await readFile(OUTFILE, 'utf8');+const unguarded = bundle.match(/import\.meta\.env\.[A-Za-z_]/g);+if (unguarded) {+ throw new Error(+ `sidecar bundle contains unguarded import.meta.env access (${[...new Set(unguarded)].join(', ')}) — ` ++ 'use import.meta.env?.X in shared code; it is undefined under raw Node and crashes the sidecar on boot'+ );+}diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/hook-server.ts b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/hook-server.tsindex 1a2015f82..371e6c01c 100644--- a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/hook-server.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/hook-server.ts@@ -29,7 +29,17 @@ export class HookEventLog {private seq = 0;private waiters: Array<() => void> = [];- constructor(private readonly capacity = 256) {}+ /**+ * Identifies this log's incarnation. Sequence numbers restart at zero when+ * the process does, so a consumer holding a cursor from a previous life would+ * otherwise treat the new, lower sequence as "already seen" and silently+ * ignore every event. Callers pass the sidecar's persisted epoch; the default+ * suits the local hook server, which dies with its consumers anyway.+ */+ constructor(+ private readonly capacity = 256,+ readonly epoch = 0+ ) {}append(raw: RawHookRequest): void {this.seq += 1;@@ -49,15 +59,26 @@ export class HookEventLog {poll(since: number,timeoutMs: number- ): Promise<{ events: RelayedHookEvent[]; oldestSeq: number; latestSeq: number }> {+ ): Promise<{+ events: RelayedHookEvent[];+ oldestSeq: number;+ latestSeq: number;+ epoch: number;+ }> {const snapshot = () => ({events: this.buffer.filter((e) => e.seq > since),oldestSeq: this.buffer.length > 0 ? this.buffer[0]!.seq : 0,latestSeq: this.seq,+ epoch: this.epoch,});const immediate = snapshot();if (immediate.events.length > 0) return Promise.resolve(immediate);+ // A cursor beyond our highest seq cannot belong to this stream — the caller+ // is holding one from a previous incarnation. Answer now instead of parking+ // it on the long poll, so it sees the epoch and resyncs promptly rather+ // than after a full timeout per attempt.+ if (since > this.seq) return Promise.resolve(immediate);return new Promise((resolve) => {const wake = (): void => {diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ensure-agent-sidecar.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ensure-agent-sidecar.tsindex a5f6795e3..a00d3f600 100644--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ensure-agent-sidecar.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ensure-agent-sidecar.ts@@ -6,61 +6,65 @@ import {RemoteSidecarLauncher,type SidecarEndpoint,type SidecarHost,+ type SidecarRunStatus,} from './remote-sidecar-launcher';import { resolveSidecarBundlePath } from './resolve-sidecar-bundle';/**- * Deploy + launch (or reattach to) the one agent-scoped remote sidecar and- * return its hook endpoint. Shared by the SSH agent runtime (which- * points a UI-started session's hook env at the endpoint) and the auto-session- * setup path (which just needs the sidecar — and its watcher — running). One- * sidecar per remote repo dir, so both callers reattach to the same instance.+ * The parameters every sidecar operation shares: enough to identify the agent's+ * sidecar on the host and (re)generate its launch recipe.*/-export async function ensureAgentSidecar(params: {+export interface AgentSidecarParams {providerId: string;/** Absolute remote repo dir; the agent's Switch creds + bundle live under it. */repoDir: string;deeplinkScheme: string;/** The agent's bypass-permissions setting, baked into the auto-start launch spec. */autoApprove: boolean;- /** Per-agent creds slug (definition name, else agent id) — selects the sidecar's+ /** Per-agent creds slug (the agent's name) — selects the sidecar's* `.switch/agents/<slug>.json` identity file (CHOO-1440). */credsSlug: string;- /** The agent's definition name (null if none) — so auto-started sessions launch- * as the definition with its own identity. */- definitionName: string | null;+ /** The agent's name — so auto-started sessions launch as it with its own+ * identity (a definitions-capable provider passes it as `--agent <name>`). */+ agentName: string | null;ctx: IExecutionContext;connectionId: string;host: SidecarHost;-}): Promise<SidecarEndpoint> {- const {- providerId,- repoDir,- deeplinkScheme,- autoApprove,- credsSlug,- definitionName,- ctx,- connectionId,- host,- } = params;+}++async function buildLauncher(params: AgentSidecarParams): Promise<RemoteSidecarLauncher> {const launchSpec = await generateAgentLaunchSpec({- providerId,- remoteRepoDir: repoDir,- deeplinkScheme,- autoApprove,- agentName: definitionName,- ctx,- connectionId,+ providerId: params.providerId,+ remoteRepoDir: params.repoDir,+ deeplinkScheme: params.deeplinkScheme,+ autoApprove: params.autoApprove,+ agentName: params.agentName,+ ctx: params.ctx,+ connectionId: params.connectionId,});- const launcher = new RemoteSidecarLauncher({- host,+ return new RemoteSidecarLauncher({+ host: params.host,bundlePath: resolveSidecarBundlePath(),- sidecarTmuxName: agentSidecarTmuxName(repoDir, credsSlug),- config: { repoDir, deeplinkScheme, launchSpec, credsSlug },+ sidecarTmuxName: agentSidecarTmuxName(params.repoDir, params.credsSlug),+ config: {+ repoDir: params.repoDir,+ deeplinkScheme: params.deeplinkScheme,+ launchSpec,+ credsSlug: params.credsSlug,+ },log,});- return launcher.deployAndLaunch();+}++/**+ * Deploy + launch (or reattach to) the one agent-scoped remote sidecar and+ * return its hook endpoint. Shared by the SSH agent runtime (which points a+ * UI-started session's hook env at the endpoint) and the auto-session setup path+ * (which just needs the sidecar — and its watcher — running). One sidecar per+ * remote repo dir, so both callers reattach to the same instance.+ */+export async function ensureAgentSidecar(params: AgentSidecarParams): Promise<SidecarEndpoint> {+ return (await buildLauncher(params)).deployAndLaunch();}/**@@ -70,49 +74,54 @@ export async function ensureAgentSidecar(params: {* just to poll. When no sidecar is up there is nothing to discover, so callers* treat null as "no sessions this tick".*/-export async function probeAgentSidecar(params: {- providerId: string;- repoDir: string;- deeplinkScheme: string;- /** The agent's bypass-permissions setting. Probe never writes the spec, so this- * only shapes the (unused) config; pass the real value for consistency. */- autoApprove: boolean;- /** Per-agent creds slug (definition name, else agent id). Probe never launches,- * so this only shapes the (unused) config; pass the real value for consistency. */- credsSlug: string;- /** The agent's definition name (null if none). Probe never launches; passed for- * consistency with ensureAgentSidecar. */- definitionName: string | null;- ctx: IExecutionContext;- connectionId: string;- host: SidecarHost;-}): Promise<SidecarEndpoint | null> {- const {- providerId,- repoDir,- deeplinkScheme,- autoApprove,- credsSlug,- definitionName,- ctx,- connectionId,- host,- } = params;- const launchSpec = await generateAgentLaunchSpec({- providerId,- remoteRepoDir: repoDir,- deeplinkScheme,- autoApprove,- agentName: definitionName,- ctx,- connectionId,- });- const launcher = new RemoteSidecarLauncher({- host,- bundlePath: resolveSidecarBundlePath(),- sidecarTmuxName: agentSidecarTmuxName(repoDir, credsSlug),- config: { repoDir, deeplinkScheme, launchSpec, credsSlug },- log,- });- return launcher.probeExisting();+export async function probeAgentSidecar(+ params: AgentSidecarParams+): Promise<SidecarEndpoint | null> {+ return (await buildLauncher(params)).probeExisting();+}++/**+ * Read-only status of an agent's sidecar for the UI (running? which build/+ * protocol/epoch/pid? how many live sessions?), plus this client's own bundle+ * hash so the caller can render the client-vs-host verdict. Never launches.+ */+export async function readAgentSidecarStatus(+ params: AgentSidecarParams+): Promise<{ status: SidecarRunStatus; clientHash: string }> {+ const launcher = await buildLauncher(params);+ const [status, clientHash] = await Promise.all([+ launcher.readStatus(),+ launcher.localBundleHash(),+ ]);+ return { status, clientHash };+}++/**+ * Stop an agent's sidecar (kills its tmux session). Sessions keep running in+ * their own panes; they simply lose room injection until a sidecar is back.+ */+export async function stopAgentSidecar(params: AgentSidecarParams): Promise<void> {+ await (await buildLauncher(params)).stop();+}++/**+ * Force a fresh sidecar process: stop the running one, then deploy + launch.+ *+ * `ensureAgentSidecar` alone reattaches to a same-build sidecar and defers an+ * upgrade while sessions are live, so it is not a restart. This is the explicit+ * "restart / force upgrade now" the UI offers — safe because sessions follow+ * the new process via the endpoint file.+ */+export async function restartAgentSidecar(params: AgentSidecarParams): Promise<SidecarEndpoint> {+ const launcher = await buildLauncher(params);+ await launcher.stop();+ return launcher.deployAndLaunch();+}++/** Best-effort tail of an agent's sidecar log, for the UI's debug view. */+export async function readAgentSidecarLog(+ params: AgentSidecarParams,+ lines: number+): Promise<string> {+ return (await buildLauncher(params)).logTail(lines);}diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-hook-event-relay.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-hook-event-relay.test.tsindex a0fce64bf..5905b59e1 100644--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-hook-event-relay.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-hook-event-relay.test.ts@@ -130,6 +130,69 @@ describe('RemoteHookEventRelay', () => {expect(attempt).toBeGreaterThan(1);expect(seen.map((r) => r.ptyId)).toEqual(['pty-1']);});++ it('follows the sidecar to a new port and token after repeated failures', async () => {+ // A restarted sidecar binds a fresh ephemeral port and mints a fresh token,+ // so the values the relay launched with are stale, not merely unreachable.+ // Without re-resolution it polls the dead port until the app quits.+ const eventLog = new HookEventLog();+ eventLog.append(raw(1));+ server = new HookServer(serverLog);+ await server.start(async () => {}, { eventLog });+ const livePort = server.getPort();+ const liveToken = server.getToken();++ const seen: RawHookRequest[] = [];+ const relay = new RemoteHookEventRelay({+ opener: localOpener,+ port: 1, // dead: nothing listening+ token: 'stale-token',+ resolveEndpoint: async () => ({ port: livePort, token: liveToken }),+ sink: async (r) => {+ seen.push(r);+ },+ log: noopLog,+ sleep: async () => {},+ });+ relay.start();++ await waitFor(() => seen.length >= 1);+ relay.stop();++ expect(relay.endpoint).toEqual({ port: livePort, token: liveToken });+ expect(seen.map((r) => r.ptyId)).toEqual(['pty-1']);+ });++ it('resets its cursor when the sidecar epoch changes, so a lower seq still lands', async () => {+ // Epoch 2's sequence numbers restart at 1, below the cursor the relay holds+ // from epoch 1 — without the epoch reset every new event looks already-seen.+ const restarted = new HookEventLog(256, 2);+ restarted.append(raw(42));+ server = new HookServer(serverLog);+ await server.start(async () => {}, { eventLog: restarted });++ const seen: RawHookRequest[] = [];+ const relay = new RemoteHookEventRelay({+ opener: localOpener,+ port: server.getPort(),+ token: server.getToken(),+ sink: async (r) => {+ seen.push(r);+ },+ log: noopLog,+ sleep: async () => {},+ });+ // Simulate having consumed epoch 1 up to seq 9.+ const internals = relay as unknown as { cursor: number; epoch: number | null };+ internals.cursor = 9;+ internals.epoch = 1;+ relay.start();++ await waitFor(() => seen.length >= 1);+ relay.stop();++ expect(seen.map((r) => r.ptyId)).toEqual(['pty-42']);+ });});function httpResponse(payload: unknown): string {diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-hook-event-relay.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-hook-event-relay.tsindex 6651822a2..9470612d2 100644--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-hook-event-relay.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-hook-event-relay.ts@@ -25,8 +25,13 @@ interface EventsResponse {events: RelayedHookEvent[];oldestSeq: number;latestSeq: number;+ /** The sidecar's incarnation. Absent from a pre-CHOO-1425 sidecar. */+ epoch?: number;}+/** Re-resolves the sidecar's current port and token. */+export type EndpointResolver = () => Promise<{ port: number; token: string } | null>;+/** Opens a duplex stream connected to `127.0.0.1:<port>` on the remote host. */export type RelayChannelOpener = SidecarChannelOpener;@@ -50,10 +55,16 @@ function getEventsOverChannel(});}+/** Failed polls before we suspect the endpoint itself moved and re-resolve it. */+const RESOLVE_AFTER_FAILURES = 2;+export class RemoteHookEventRelay {private cursor = 0;+ private epoch: number | null = null;private stopped = false;private channel: Duplex | null = null;+ private port: number;+ private token: string;private readonly sleep: (ms: number) => Promise<void>;constructor(@@ -61,15 +72,29 @@ export class RemoteHookEventRelay {opener: RelayChannelOpener;port: number;token: string;+ /**+ * Re-resolves the sidecar's endpoint after repeated failures. The port and+ * token are regenerated every time the sidecar starts, so without this a+ * relay outlives exactly one incarnation and then polls a dead port until+ * the app quits — taking `/disconnect` down with it.+ */+ resolveEndpoint?: EndpointResolver;/** Replays one relayed event through switchdash's hook path. */sink: (raw: RawHookRequest) => Promise<void>;log: RemoteHookEventRelayLogger;sleep?: (ms: number) => Promise<void>;}) {+ this.port = deps.port;+ this.token = deps.token;this.sleep = deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));}+ /** The endpoint currently in use — moves when the sidecar is re-resolved. */+ get endpoint(): { port: number; token: string } {+ return { port: this.port, token: this.token };+ }+start(): void {void this.loop();}@@ -93,32 +118,76 @@ export class RemoteHookEventRelay {failureStreak += 1;const delayMs = RETRY_DELAYS_MS[Math.min(failureStreak, RETRY_DELAYS_MS.length) - 1]!;this.deps.log.warn('RemoteHookEventRelay: poll failed, retrying', {- port: this.deps.port,+ port: this.port,failureStreak,retryInMs: delayMs,error: String(error),});+ if (failureStreak >= RESOLVE_AFTER_FAILURES) await this.reresolve();await this.sleep(delayMs);}}}private async pollOnce(since: number): Promise<EventsResponse> {- const channel = await this.deps.opener.openChannel(this.deps.port);+ const channel = await this.deps.opener.openChannel(this.port);this.channel = channel;try {- return await getEventsOverChannel(channel, this.deps.port, this.deps.token, since);+ return await getEventsOverChannel(channel, this.port, this.token, since);} finally {channel.destroy();if (this.channel === channel) this.channel = null;}}+ /**+ * Ask for the sidecar's current endpoint and adopt it if it moved. A restarted+ * sidecar binds a fresh ephemeral port and mints a fresh token, so the values+ * this relay was constructed with are stale rather than merely unreachable.+ */+ private async reresolve(): Promise<void> {+ const resolve = this.deps.resolveEndpoint;+ if (!resolve) return;+ let next: { port: number; token: string } | null;+ try {+ next = await resolve();+ } catch (error) {+ this.deps.log.debug('RemoteHookEventRelay: endpoint re-resolve failed', {+ error: String(error),+ });+ return;+ }+ if (!next) return;+ if (next.port === this.port && next.token === this.token) return;+ this.deps.log.info('RemoteHookEventRelay: sidecar endpoint moved — following it', {+ from: this.port,+ to: next.port,+ });+ this.port = next.port;+ this.token = next.token;+ }+private consume(result: EventsResponse): void {+ if (this.epoch === null) this.epoch = result.epoch ?? null;+ // A changed epoch means this is a different incarnation of the sidecar; its+ // sequence numbers restarted, so a cursor from the previous life would sit+ // above every new seq and silently suppress the lot. Reset instead of+ // comparing cursors across two unrelated streams.+ else if (result.epoch !== undefined && result.epoch !== this.epoch) {+ this.deps.log.info('RemoteHookEventRelay: sidecar restarted — re-anchoring event cursor', {+ port: this.port,+ previousEpoch: this.epoch,+ epoch: result.epoch,+ previousCursor: this.cursor,+ });+ this.epoch = result.epoch;+ this.cursor = 0;+ }+const fresh = result.events.filter((e) => e.seq > this.cursor);if (fresh.length > 0) {this.deps.log.info('RemoteHookEventRelay: received events from sidecar', {- port: this.deps.port,+ port: this.port,count: fresh.length,cursor: this.cursor,oldestSeq: result.oldestSeq,@@ -127,7 +196,7 @@ export class RemoteHookEventRelay {});} else {this.deps.log.debug('RemoteHookEventRelay: poll returned no new events', {- port: this.deps.port,+ port: this.port,cursor: this.cursor,latestSeq: result.latestSeq,});@@ -136,7 +205,7 @@ export class RemoteHookEventRelay {this.deps.log.warn('RemoteHookEventRelay: dropped events (consumer fell behind ring buffer)',{- port: this.deps.port,+ port: this.port,cursor: this.cursor,oldestSeq: result.oldestSeq,dropped: result.oldestSeq - this.cursor - 1,diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.test.tsindex f4192add7..ac97ff2b5 100644--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.test.ts@@ -1,5 +1,7 @@import { describe, expect, it, vi } from 'vitest';import type { AgentLaunchSpec } from '../../../../sidecar/agent-launch-spec';+import { SIDECAR_BUNDLE_REL_PATH } from '../../../../sidecar/sidecar-paths';+import { SIDECAR_VERSION } from '../../../../sidecar/sidecar-version';import {agentSidecarTmuxName,killSidecarSession,@@ -26,8 +28,24 @@ const CONFIG: SidecarLaunchConfig = {credsSlug: 'claude-code.repo.me',};-const readyLine = (hash: string | undefined = 'hash-v1'): string =>- `${JSON.stringify({ event: 'ready', port: 4321, token: 'tok-abc', hash })}\n`;+/** The endpoint the launcher derives for CONFIG — sessions are pointed at this+ * path rather than at the port/token, so it must track repoDir + credsSlug. */+const ENDPOINT_FILE = '/home/dev/repo/.switchdash/agents/claude-code.repo.me/endpoint';+const ENDPOINT = { port: 4321, token: 'tok-abc', endpointFile: ENDPOINT_FILE };++const readyLine = (+ hash: string | undefined = 'hash-v1',+ epoch = 1,+ version: string | undefined = SIDECAR_VERSION+): string =>+ `${JSON.stringify({+ event: 'ready',+ port: 4321,+ token: 'tok-abc',+ hash,+ epoch,+ version,+ })}\n`;const noopLog = { debug: vi.fn(), warn: vi.fn() };interface ExecCall {@@ -38,8 +56,16 @@ interface ExecCall {function isLaunchSpecWrite(script: string): boolean {return script.includes('base64 -d');}-function isBundleHashWrite(script: string): boolean {- return script.includes('printf %s') && script.includes('.sha256');+function isDeployLock(script: string): boolean {+ return script.includes('deploy.lock') && script.includes('mkdir');+}+function isLockRelease(script: string): boolean {+ // The acquire script also contains an `rm -rf` (its stale-break branch), so+ // match only the standalone release.+ return script.startsWith('rm -rf') && script.includes('deploy.lock');+}+function isBundleRename(script: string): boolean {+ return script.startsWith('mv ');}function makeHost(@@ -48,6 +74,12 @@ function makeHost(readyAfter?: number;diesAfter?: number;remoteBundleHash?: string;+ /** Simulates another client holding the host-side deploy lock. */+ lockHeld?: boolean;+ /** Version the running sidecar reports (undefined = predates the field). */+ readyVersion?: string;+ /** Sessions recorded in the running sidecar's durable state. */+ liveSessions?: number;/** Bundle hash the (already-running) sidecar's ready line reports. */readyHash?: string;/** What `tail` of the sidecar log returns after a startup crash. */@@ -55,7 +87,8 @@ function makeHost(} = {}): { host: SidecarHost; calls: ExecCall[]; puts: Array<{ local: string; remote: string }> } {const existingSidecar = opts.existingSidecar ?? false;- const readyLineOut = readyLine(opts.readyHash ?? 'hash-v1');+ const readyHash = opts.readyHash ?? 'hash-v1';+ const readyVersion = 'readyVersion' in opts ? opts.readyVersion : SIDECAR_VERSION;const readyAfter = opts.readyAfter ?? 0;const diesAfter = opts.diesAfter ?? Infinity;const calls: ExecCall[] = [];@@ -63,18 +96,29 @@ function makeHost(let sidecarExists = existingSidecar;let catReads = 0;let aliveChecks = 0;+ // The real sidecar bumps its epoch on every start; the launcher relies on+ // that to tell a freshly-launched process from the one it just killed.+ let epoch = 1;const host: SidecarHost = {async exec(command, args) {calls.push({ command, args });if (command === 'sh') {const script = args[1] ?? '';- if (isLaunchSpecWrite(script) || isBundleHashWrite(script))+ if (isDeployLock(script)) {+ // `mkdir` succeeds unless another client holds the lock.+ return { stdout: opts.lockHeld ? 'busy' : 'acquired', stderr: '' };+ }+ if (isLaunchSpecWrite(script) || isLockRelease(script) || isBundleRename(script)) {return { stdout: '', stderr: '' };- return { stdout: opts.remoteBundleHash ?? '', stderr: '' }; // prepareDir hash read+ }+ // prepareDir: `sha256sum <bundle>` output is "<hash> <path>".+ const remote = opts.remoteBundleHash;+ return { stdout: remote ? `${remote} ${SIDECAR_BUNDLE_REL_PATH}` : '', stderr: '' };}if (command === 'tmux' && args[0] === 'new-session') {sidecarExists = true;+ epoch += 1;return { stdout: '', stderr: '' };}if (command === 'tmux' && args[0] === 'kill-session') {@@ -88,10 +132,18 @@ function makeHost(return { stdout: '', stderr: '' };}if (command === 'cat') {- if (existingSidecar) return { stdout: readyLineOut, stderr: '' };+ // The launcher reads two different files through `cat`.+ if ((args[0] ?? '').endsWith('state.json')) {+ const sessions = Array.from({ length: opts.liveSessions ?? 0 }, (_, i) => ({+ sessionId: `s${i}`,+ }));+ return { stdout: JSON.stringify({ version: '1', epoch, sessions }), stderr: '' };+ }+ const line = readyLine(readyHash, epoch, readyVersion);+ if (existingSidecar) return { stdout: line, stderr: '' };const n = catReads++;if (n < readyAfter) throw new Error('no such file');- return { stdout: readyLineOut, stderr: '' };+ return { stdout: line, stderr: '' };}if (command === 'tail') {return { stdout: opts.logTail ?? '', stderr: '' };@@ -122,10 +174,15 @@ describe('RemoteSidecarLauncher', () => {const { host, calls, puts } = makeHost();const endpoint = await makeLauncher(host).deployAndLaunch();- expect(endpoint).toEqual({ port: 4321, token: 'tok-abc' });- expect(puts).toEqual([- { local: '/local/dist-sidecar/sidecar.mjs', remote: '.switchdash/sidecar.mjs' },- ]);+ expect(endpoint).toEqual(ENDPOINT);+ // The bundle lands on a temp path and is renamed into place: an SFTP+ // overwrite of the live file is observable half-written, and node loading+ // it mid-transfer dies on a SyntaxError.+ expect(puts).toHaveLength(1);+ expect(puts[0]!.local).toBe('/local/dist-sidecar/sidecar.mjs');+ expect(puts[0]!.remote).toMatch(/^\.switchdash\/sidecar\.mjs\.\d+\.tmp$/);+ const rename = calls.find((c) => c.command === 'sh' && isBundleRename(c.args[1] ?? ''));+ expect(rename!.args[1]).toContain(`mv '${puts[0]!.remote}' '.switchdash/sidecar.mjs'`);const specWrite = calls.find((c) => c.command === 'sh' && isLaunchSpecWrite(c.args[1] ?? ''));// Per-agent state path (keyed by the creds slug), not the shared per-dir path.expect(specWrite!.args[1]).toContain(@@ -139,7 +196,7 @@ describe('RemoteSidecarLauncher', () => {it('skips the bundle upload when the host already holds an identical bundle', async () => {const { host, puts } = makeHost({ remoteBundleHash: 'hash-v1' });const endpoint = await makeLauncher(host).deployAndLaunch();- expect(endpoint).toEqual({ port: 4321, token: 'tok-abc' });+ expect(endpoint).toEqual(ENDPOINT);expect(puts).toHaveLength(0);});@@ -166,7 +223,7 @@ describe('RemoteSidecarLauncher', () => {it('polls the ready file until the sidecar reports its endpoint', async () => {const { host } = makeHost({ readyAfter: 3 });- expect(await makeLauncher(host).deployAndLaunch()).toEqual({ port: 4321, token: 'tok-abc' });+ expect(await makeLauncher(host).deployAndLaunch()).toEqual(ENDPOINT);});it('fails loud if the sidecar tmux session dies during startup', async () => {@@ -189,7 +246,7 @@ describe('RemoteSidecarLauncher', () => {const { host, calls, puts } = makeHost({ existingSidecar: true });const endpoint = await makeLauncher(host).deployAndLaunch();- expect(endpoint).toEqual({ port: 4321, token: 'tok-abc' });+ expect(endpoint).toEqual(ENDPOINT);expect(puts).toHaveLength(0);expect(calls.find((c) => c.command === 'tmux' && c.args[0] === 'new-session')).toBeUndefined();expect(@@ -197,6 +254,61 @@ describe('RemoteSidecarLauncher', () => {).toBeDefined();});+ it('does not delete the ready file, so a healthy sidecar stays discoverable', async () => {+ // Clearing it up front made a running sidecar invisible to every other+ // client for the length of the deploy — and permanently if the deploy died.+ const { host, calls } = makeHost();+ await makeLauncher(host).deployAndLaunch();++ const removedReady = calls.some(+ (c) =>+ c.command === 'sh' &&+ (c.args[1] ?? '').includes('rm -f') &&+ (c.args[1] ?? '').includes('sidecar.ready')+ );+ expect(removedReady).toBe(false);+ });++ it('takes the deploy lock before replacing the sidecar, and releases it after', async () => {+ const { host, calls } = makeHost();+ await makeLauncher(host).deployAndLaunch();++ const lockIdx = calls.findIndex((c) => c.command === 'sh' && isDeployLock(c.args[1] ?? ''));+ const killIdx = calls.findIndex((c) => c.command === 'tmux' && c.args[0] === 'kill-session');+ const releaseIdx = calls.findIndex((c) => c.command === 'sh' && isLockRelease(c.args[1] ?? ''));++ expect(lockIdx).toBeGreaterThanOrEqual(0);+ expect(lockIdx).toBeLessThan(killIdx);+ expect(releaseIdx).toBeGreaterThan(killIdx);+ });++ it('refuses to replace the sidecar while another client holds the deploy lock', async () => {+ // Better to fail loudly than to race a concurrent deploy: both clients+ // would overwrite the bundle under each other and kill each other's process.+ const { host, calls } = makeHost({ lockHeld: true });++ await expect(makeLauncher(host).deployAndLaunch()).rejects.toThrow(/another client/i);+ expect(calls.some((c) => c.command === 'tmux' && c.args[0] === 'kill-session')).toBe(false);+ });++ it('releases the deploy lock even when the launch fails', async () => {+ const { host, calls } = makeHost({ diesAfter: 1 });++ await expect(makeLauncher(host).deployAndLaunch()).rejects.toThrow();+ expect(calls.some((c) => c.command === 'sh' && isLockRelease(c.args[1] ?? ''))).toBe(true);+ });++ it('hashes the deployed bundle on the host instead of trusting a sidecar hash file', async () => {+ const { host, calls, puts } = makeHost({ remoteBundleHash: 'hash-v1' });+ await makeLauncher(host).deployAndLaunch();++ expect(calls.some((c) => c.command === 'sh' && (c.args[1] ?? '').includes('sha256sum'))).toBe(+ true+ );+ // Identical bundle already on the host — no re-upload.+ expect(puts).toHaveLength(0);+ });+it('relaunches a running sidecar whose bundle hash is stale (upgrade takes effect)', async () => {// A sidecar left over from an older bundle reports a different hash in its// ready line — it must be killed and relaunched, not reattached to, or the@@ -204,7 +316,7 @@ describe('RemoteSidecarLauncher', () => {const { host, calls, puts } = makeHost({ existingSidecar: true, readyHash: 'hash-OLD' });const endpoint = await makeLauncher(host).deployAndLaunch();- expect(endpoint).toEqual({ port: 4321, token: 'tok-abc' });+ expect(endpoint).toEqual(ENDPOINT);expect(puts).toHaveLength(1); // new bundle uploadedexpect(calls.find((c) => c.command === 'tmux' && c.args[0] === 'kill-session')).toBeDefined();expect(calls.find((c) => c.command === 'tmux' && c.args[0] === 'new-session')).toBeDefined();@@ -227,6 +339,74 @@ describe('RemoteSidecarLauncher', () => {});});+describe('RemoteSidecarLauncher versioning', () => {+ it('probes a running sidecar of a DIFFERENT build — a build difference is not an incompatibility', async () => {+ // The two-client kill-loop: each client judged the other's sidecar unusable+ // purely because its bundle hash differed, killed it, relaunched, and+ // reported zero sessions in between — pruning live rows on both sides.+ const { host, calls } = makeHost({ existingSidecar: true, readyHash: 'hash-other' });++ const endpoint = await makeLauncher(host).probeExisting();++ expect(endpoint).toEqual(ENDPOINT);+ expect(calls.some((c) => c.command === 'tmux' && c.args[0] === 'kill-session')).toBe(false);+ });++ it('refuses to probe a sidecar speaking a protocol it cannot support', async () => {+ const { host } = makeHost({+ existingSidecar: true,+ readyVersion: '2.0',+ });++ expect(await makeLauncher(host).probeExisting()).toBeNull();+ });++ it('treats a sidecar predating the version field as major 0, still usable', async () => {+ const { host } = makeHost({ existingSidecar: true, readyVersion: undefined });++ expect(await makeLauncher(host).probeExisting()).toEqual(ENDPOINT);+ });++ it('defers an available upgrade while the sidecar has live sessions', async () => {+ const { host, calls } = makeHost({+ existingSidecar: true,+ readyHash: 'hash-old',+ liveSessions: 2,+ });++ const endpoint = await makeLauncher(host).deployAndLaunch();++ expect(endpoint).toEqual(ENDPOINT);+ expect(calls.some((c) => c.command === 'tmux' && c.args[0] === 'kill-session')).toBe(false);+ });++ it('takes the upgrade once the sidecar is idle', async () => {+ const { host, calls } = makeHost({+ existingSidecar: true,+ readyHash: 'hash-old',+ liveSessions: 0,+ });++ await makeLauncher(host).deployAndLaunch();++ expect(calls.some((c) => c.command === 'tmux' && c.args[0] === 'kill-session')).toBe(true);+ });++ it('replaces an incompatible sidecar even when sessions are live', async () => {+ // Compatibility is the one reason worth interrupting work for: we cannot+ // talk to it at all, so deferring would mean never recovering.+ const { host, calls } = makeHost({+ existingSidecar: true,+ readyVersion: '2.0',+ liveSessions: 3,+ });++ await makeLauncher(host).deployAndLaunch();++ expect(calls.some((c) => c.command === 'tmux' && c.args[0] === 'kill-session')).toBe(true);+ });+});+describe('agentSidecarTmuxName', () => {it('is deterministic per repo dir + slug and does not end in -sidecar', () => {const a = agentSidecarTmuxName('/home/dev/repo', 'agent-a');diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.tsindex acefd9c5d..fbe9e8bed 100644--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.ts@@ -4,14 +4,21 @@ import { exactTmuxTarget } from '@main/core/pty/tmux-session-name';import { quoteShellArg } from '@main/utils/shellEscape';import type { AgentLaunchSpec } from '../../../../sidecar/agent-launch-spec';import {- SIDECAR_BUNDLE_HASH_REL_PATH,SIDECAR_BUNDLE_REL_PATH,sidecarAgentDir,+ sidecarDeployLockRelPath,sidecarLaunchSpecRelPath,+ sidecarEndpointRelPath,sidecarLogRelPath,sidecarReadyRelPath,+ sidecarStateRelPath,sidecarWatchEnabledRelPath,} from '../../../../sidecar/sidecar-paths';+import {+ MIN_SUPPORTED_SIDECAR_MAJOR,+ SIDECAR_CLIENT_MAJOR,+ sidecarMajor,+} from '../../../../sidecar/sidecar-version';/*** Deploys and launches the switchdash remote runtime sidecar on the agent's VM@@ -21,15 +28,28 @@ import {* the VM (the one switchdash starts over SSH and any it auto-starts) plus the* notification watcher. It must outlive the switchdash UI — that is the whole* point — so it runs inside its own detached tmux session rather than on the- * launching SSH channel (which dies when switchdash disconnects). It prints- * `{event:"ready",port,token}` to stdout, redirected to a ready file; the- * launcher polls that file until the endpoint appears, then returns it so the- * caller can point its remote sessions' hook env at the VM-local server.+ * launching SSH channel (which dies when switchdash disconnects). It writes+ * `{event:"ready",port,token,hash,epoch,pid}` to its ready file atomically once+ * bound; the launcher polls that file until a line from the incarnation it just+ * started appears, then returns the endpoint so the caller can point its remote+ * sessions' hook env at the VM-local server. The ready line also carries the+ * sidecar's `version` (human-readable `x.y`) and build `hash`.+ *+ * Replacing a running sidecar is serialised across clients by a host-side deploy+ * lock: two clients deploying at once would overwrite the bundle under each+ * other and each kill the other's freshly started process.*/const SIDECAR_TMUX_SUFFIX = '-sidecar';const READY_POLL_INTERVAL_MS = 250;const READY_MAX_ATTEMPTS = 80; // ~20s+const DEPLOY_LOCK_POLL_MS = 500;+const DEPLOY_LOCK_MAX_ATTEMPTS = 60; // ~30s waiting on another client's deploy+/** `find -mmin` granularity is minutes; 2 comfortably exceeds a real deploy. */+const DEPLOY_LOCK_STALE_MIN = 2;+/** Trim the append-only sidecar log at launch once it passes this size. */+const SIDECAR_LOG_MAX_BYTES = 8 * 1024 * 1024;+const SIDECAR_LOG_KEEP_BYTES = 1024 * 1024;export interface SidecarLaunchConfig {/** Absolute remote repo dir; the bundle, spec, ready file, and log live under .switchdash/. */@@ -46,12 +66,45 @@ export interface SidecarLaunchConfig {export interface SidecarEndpoint {port: number;token: string;+ /** Absolute on-VM path of the sidecar's endpoint file. Sessions are launched+ * pointing at this rather than at `port`/`token` directly, so they survive the+ * sidecar restarting on a fresh port with a fresh token. */+ endpointFile: string;}-/** The ready line the sidecar prints, plus the bundle hash the running process- * was launched with (absent for a pre-CHOO-1085 sidecar). */-interface ReadyLine extends SidecarEndpoint {+/** The ready line the sidecar prints. `hash` is absent for a pre-CHOO-1085+ * sidecar; the endpoint file path is derived locally, not carried on the wire. */+interface ReadyLine {+ port: number;+ token: string;hash: string | null;+ /** Monotonic per-start counter from the sidecar's durable state. Absent from+ * a pre-CHOO-1425 sidecar. */+ epoch: number | null;+ /** Human-readable `x.y` version; the major governs compatibility. Absent from+ * a sidecar predating versioning, which is treated as major 0. */+ version: string | null;+ /** OS process id of the running sidecar, for display. Absent from an older one. */+ pid: number | null;+}++/**+ * Read-only view of the sidecar running on the host, for the UI. Independent of+ * whether this client's bundle matches — that comparison (the verdict) is the+ * caller's to make, since it needs the client's own hash and version.+ */+export interface SidecarRunStatus {+ running: boolean;+ /** Whether this client can speak to it (its major is in the supported range). */+ compatible: boolean;+ /** Build fingerprint the running sidecar reports for itself. */+ hash: string | null;+ /** Human-readable `x.y` version the running sidecar reports. */+ version: string | null;+ epoch: number | null;+ pid: number | null;+ /** Sessions the running sidecar currently owns, from its durable state. */+ liveSessions: number;}/** Narrow remote seam the launcher needs — satisfied by IExecutionContext + ssh-fs. */@@ -97,7 +150,11 @@ function parseReady(raw: string): ReadyLine | null {typeof parsed.token === 'string') {const hash = 'hash' in parsed && typeof parsed.hash === 'string' ? parsed.hash : null;- return { port: parsed.port, token: parsed.token, hash };+ const epoch = 'epoch' in parsed && typeof parsed.epoch === 'number' ? parsed.epoch : null;+ const version =+ 'version' in parsed && typeof parsed.version === 'string' ? parsed.version : null;+ const pid = 'pid' in parsed && typeof parsed.pid === 'number' ? parsed.pid : null;+ return { port: parsed.port, token: parsed.token, hash, epoch, version, pid };}return null;}@@ -168,6 +225,21 @@ export class RemoteSidecarLauncher {private get logPath(): string {return sidecarLogRelPath(this.config.credsSlug);}+ private get statePath(): string {+ return sidecarStateRelPath(this.config.credsSlug);+ }+ private get deployLockPath(): string {+ return sidecarDeployLockRelPath(this.config.credsSlug);+ }+ /** Absolute, because it is baked into spawned sessions' env and read by hooks+ * whose working directory is not guaranteed to be the repo dir. */+ private get endpointFile(): string {+ return `${this.config.repoDir}/${sidecarEndpointRelPath(this.config.credsSlug)}`;+ }++ private toEndpoint(ready: ReadyLine): SidecarEndpoint {+ return { port: ready.port, token: ready.token, endpointFile: this.endpointFile };+ }/*** Reconcile-or-launch. The sidecar is designed to outlive the switchdash UI,@@ -182,7 +254,7 @@ export class RemoteSidecarLauncher {await this.writeLaunchSpec();const localHash = await this.hashBundle();- const existing = await this.reattachExisting(localHash);+ const existing = await this.decideExisting(localHash);if (existing) {this.log.debug('RemoteSidecarLauncher: reattached to running sidecar', {sidecarTmuxName: this.sidecarTmuxName,@@ -191,34 +263,127 @@ export class RemoteSidecarLauncher {return existing;}- const remoteHash = await this.prepareDir();- if (remoteHash === localHash) {- this.log.debug('RemoteSidecarLauncher: bundle unchanged on host — skipping upload', {- sidecarTmuxName: this.sidecarTmuxName,- });- } else {- await this.host.putFile(this.bundlePath, SIDECAR_BUNDLE_REL_PATH);- await this.writeBundleHash(localHash);- }- await this.killSidecar();- await this.startDetached(localHash);- return this.awaitReady();+ // Replacing the sidecar is not safe to do concurrently: two clients would+ // overwrite the bundle under each other and each kill the other's freshly+ // started process. Serialise it across clients, then re-check — whoever+ // waited may find the holder already started exactly what it wanted.+ return this.withDeployLock(async () => {+ const reattach = await this.decideExisting(localHash);+ if (reattach) {+ this.log.debug('RemoteSidecarLauncher: another client deployed a matching sidecar', {+ sidecarTmuxName: this.sidecarTmuxName,+ port: reattach.port,+ });+ return reattach;+ }++ const previousEpoch = await this.runningEpoch();+ const remoteHash = await this.prepareDir();+ if (remoteHash === localHash) {+ this.log.debug('RemoteSidecarLauncher: bundle unchanged on host — skipping upload', {+ sidecarTmuxName: this.sidecarTmuxName,+ });+ } else {+ await this.uploadBundle();+ }+ await this.killSidecar();+ await this.startDetached(localHash);+ return this.awaitReady(previousEpoch);+ });}/**- * Create the sidecar dir, clear any stale ready file, and return the hash of- * the bundle already on the host (empty when absent) — one round-trip, so the- * 1.2MB bundle SFTP is skipped whenever an identical copy is already deployed- * (the common case: a new session reusing a prior session's bundle).+ * Create the sidecar dir and return the hash of the bundle already on the+ * host (empty when absent), so the 1.2MB SFTP is skipped whenever an identical+ * copy is already deployed (the common case: a new session reusing a prior+ * session's bundle).+ *+ * The hash is computed from the file itself rather than read from a sidecar+ * file kept alongside it: that file could be torn, written out of step with+ * the bundle, or simply stale, each of which silently defeats the comparison.+ *+ * Note this no longer deletes the ready file. Doing so made a healthy running+ * sidecar undiscoverable to every other client for the duration of a deploy —+ * and permanently if the deploy then failed. The sidecar replaces that file+ * atomically when it starts.*/private async prepareDir(): Promise<string> {+ const bundle = quoteShellArg(SIDECAR_BUNDLE_REL_PATH);const script = [`mkdir -p ${quoteShellArg(this.agentDir)}`,- `rm -f ${quoteShellArg(this.readyPath)}`,- `[ -f ${quoteShellArg(SIDECAR_BUNDLE_REL_PATH)} ] && cat ${quoteShellArg(SIDECAR_BUNDLE_HASH_REL_PATH)} 2>/dev/null || true`,+ `if [ -f ${bundle} ]; then sha256sum ${bundle} 2>/dev/null || shasum -a 256 ${bundle} 2>/dev/null; fi`,].join('; ');const { stdout } = await this.host.exec('sh', ['-c', script]);- return stdout.trim();+ return stdout.trim().split(/\s+/)[0] ?? '';+ }++ /**+ * Upload the bundle to a temp path and rename it into place.+ *+ * `putFile` is a direct SFTP overwrite: it truncates the destination and+ * streams into it, so for the length of the transfer the file node is about+ * to load is observably half-written. A concurrent start would fail on a+ * SyntaxError. Renaming is atomic, so a reader sees the old bundle or the new+ * one.+ */+ private async uploadBundle(): Promise<void> {+ const tmpRel = `${SIDECAR_BUNDLE_REL_PATH}.${process.pid}.tmp`;+ await this.host.putFile(this.bundlePath, tmpRel);+ await this.host.exec('sh', [+ '-c',+ `mv ${quoteShellArg(tmpRel)} ${quoteShellArg(SIDECAR_BUNDLE_REL_PATH)}`,+ ]);+ }++ /** Epoch of the sidecar currently running, or null if none/unreadable. */+ private async runningEpoch(): Promise<number | null> {+ const raw = await this.readReadyFile();+ return (raw ? parseReady(raw) : null)?.epoch ?? null;+ }++ /**+ * Run `fn` holding the host-side deploy lock for this agent.+ *+ * `mkdir` is atomic on POSIX — it fails if the directory exists — which makes+ * it a usable mutex over plain ssh, unlike a create-then-write lockfile. A+ * lock older than the timeout is broken rather than honoured: the holder may+ * have been killed mid-deploy, and refusing to ever deploy again would be a+ * worse failure than the race the lock prevents.+ */+ private async withDeployLock<T>(fn: () => Promise<T>): Promise<T> {+ const lock = quoteShellArg(this.deployLockPath);+ for (let attempt = 0; attempt < DEPLOY_LOCK_MAX_ATTEMPTS; attempt++) {+ const { stdout } = await this.host.exec('sh', [+ '-c',+ `if mkdir ${lock} 2>/dev/null; then echo acquired; else ` ++ // Break a stale lock: find returns the dir only when it is older than+ // the staleness window, so a live holder is left alone.+ `if [ -n "$(find ${lock} -maxdepth 0 -mmin +${DEPLOY_LOCK_STALE_MIN} 2>/dev/null)" ]; then ` ++ `rm -rf ${lock} && mkdir ${lock} 2>/dev/null && echo broke-stale; else echo busy; fi; fi`,+ ]);+ const outcome = stdout.trim();+ if (outcome === 'broke-stale') {+ this.log.warn('RemoteSidecarLauncher: broke a stale deploy lock', {+ sidecarTmuxName: this.sidecarTmuxName,+ });+ }+ if (outcome === 'acquired' || outcome === 'broke-stale') {+ try {+ return await fn();+ } finally {+ await this.host.exec('sh', ['-c', `rm -rf ${lock}`]).catch((error: unknown) =>+ this.log.warn('RemoteSidecarLauncher: failed to release deploy lock', {+ error: String(error),+ })+ );+ }+ }+ await this.sleep(DEPLOY_LOCK_POLL_MS);+ }+ throw new Error(+ `another client has been deploying this sidecar for over ` ++ `${(DEPLOY_LOCK_MAX_ATTEMPTS * DEPLOY_LOCK_POLL_MS) / 1000}s — not replacing it`+ );}private async writeLaunchSpec(): Promise<void> {@@ -235,13 +400,6 @@ export class RemoteSidecarLauncher {]);}- private async writeBundleHash(hash: string): Promise<void> {- await this.host.exec('sh', [- '-c',- `printf %s ${quoteShellArg(hash)} > ${quoteShellArg(SIDECAR_BUNDLE_HASH_REL_PATH)}`,- ]);- }-/*** Endpoint of an already-running sidecar for this session, or null. Reattaches* only when the running process was launched from the current bundle: its ready@@ -250,35 +408,155 @@ export class RemoteSidecarLauncher {* and relaunched — otherwise a bundle upgrade never takes effect while the old* process keeps running.*/- private async reattachExisting(localHash: string): Promise<SidecarEndpoint | null> {+ /** The running sidecar's ready line, or null when none is running. */+ private async readRunning(): Promise<ReadyLine | null> {try {await this.host.exec('tmux', ['has-session', '-t', exactTmuxTarget(this.sidecarTmuxName)]);} catch {return null; // not running}const raw = await this.readReadyFile();- const ready = raw ? parseReady(raw) : null;+ return raw ? parseReady(raw) : null;+ }++ /**+ * Whether this client can speak to the running sidecar at all.+ *+ * Deliberately independent of the bundle hash. A different build is not an+ * incompatibility — it only means an upgrade exists — and treating it as one+ * is what made two clients on different builds kill each other's sidecar in a+ * loop. A sidecar that reports no protocol predates the field and is treated+ * as version 0.+ */+ private isCompatible(ready: ReadyLine): boolean {+ const major = sidecarMajor(ready.version);+ return major >= MIN_SUPPORTED_SIDECAR_MAJOR && major <= SIDECAR_CLIENT_MAJOR;+ }++ /**+ * Endpoint of an already-running, *compatible* sidecar, or null if none is+ * running. Read-only — unlike `deployAndLaunch` it never deploys, writes, or+ * starts anything. For callers that only want to talk to a sidecar if one+ * exists (cross-client discovery), so a merely-configured agent does not cause+ * one to be launched.+ *+ * A running sidecar built from a different bundle is still returned: discovery+ * asks "can I talk to it", and answering that with the *upgrade* question made+ * every client on a different build report zero sessions and prune live rows.+ */+ /**+ * Read-only status of the sidecar on the host, for display. Never launches,+ * deploys, or writes. Returns `running: false` when none is up; otherwise the+ * running sidecar's self-reported identity plus its live-session count.+ *+ * The client-vs-host verdict is intentionally left to the caller — it needs+ * this client's own bundle hash and version, which the launcher exposes via+ * `localBundleHash()` and the shared version constant.+ */+ async readStatus(): Promise<SidecarRunStatus> {+ const ready = await this.readRunning();+ if (!ready) {+ return {+ running: false,+ compatible: false,+ hash: null,+ version: null,+ epoch: null,+ pid: null,+ liveSessions: 0,+ };+ }+ return {+ running: true,+ compatible: this.isCompatible(ready),+ hash: ready.hash,+ version: ready.version,+ epoch: ready.epoch,+ pid: ready.pid,+ liveSessions: await this.runningSessionCount(),+ };+ }++ /** This client's own bundle fingerprint, for the caller to compare against+ * `readStatus().hash`. */+ localBundleHash(): Promise<string> {+ return this.hashBundle();+ }++ async probeExisting(): Promise<SidecarEndpoint | null> {+ const ready = await this.readRunning();if (!ready) return null;- if (ready.hash !== localHash) {- this.log.debug('RemoteSidecarLauncher: running sidecar is a stale bundle — relaunching', {+ if (!this.isCompatible(ready)) {+ this.log.debug('RemoteSidecarLauncher: running sidecar speaks an unusable protocol', {sidecarTmuxName: this.sidecarTmuxName,- runningHash: ready.hash,- localHash,+ runningVersion: ready.version,+ clientVersion: `${SIDECAR_CLIENT_MAJOR}.x`,});return null;}- return { port: ready.port, token: ready.token };+ return this.toEndpoint(ready);}/**- * Endpoint of an already-running current-bundle sidecar, or null if none is- * running (or it is a stale bundle). Read-only — unlike `deployAndLaunch` it- * never deploys, writes, or starts anything. For callers that only want to- * talk to a sidecar if one already exists (e.g. cross-client discovery), so a- * merely-configured agent does not cause a sidecar to be launched.+ * Decide what to do about a sidecar that is already running.+ *+ * Replacing one is disruptive even now that sessions survive it, so it is+ * reserved for the cases that need it:+ * - incompatible protocol → must replace; we cannot talk to it at all.+ * - same build → reattach; there is nothing to gain.+ * - different build, no live sessions → upgrade, since nothing is disturbed.+ * - different build, live sessions → reattach and record that an upgrade is+ * pending, rather than interrupting work in flight for a build difference.+ * The next launch with an idle sidecar picks it up.*/- async probeExisting(): Promise<SidecarEndpoint | null> {- return this.reattachExisting(await this.hashBundle());+ private async decideExisting(localHash: string): Promise<SidecarEndpoint | null> {+ const ready = await this.readRunning();+ if (!ready) return null;++ if (!this.isCompatible(ready)) {+ this.log.warn('RemoteSidecarLauncher: replacing sidecar with an unusable protocol', {+ sidecarTmuxName: this.sidecarTmuxName,+ runningVersion: ready.version,+ clientVersion: `${SIDECAR_CLIENT_MAJOR}.x`,+ });+ return null;+ }+ if (ready.hash === localHash) return this.toEndpoint(ready);++ const liveSessions = await this.runningSessionCount();+ if (liveSessions > 0) {+ this.log.warn(+ 'RemoteSidecarLauncher: sidecar upgrade pending — deferring while sessions run',+ {+ sidecarTmuxName: this.sidecarTmuxName,+ runningHash: ready.hash,+ localHash,+ liveSessions,+ }+ );+ return this.toEndpoint(ready);+ }+ this.log.debug('RemoteSidecarLauncher: upgrading idle sidecar to the current bundle', {+ sidecarTmuxName: this.sidecarTmuxName,+ runningHash: ready.hash,+ localHash,+ });+ return null;+ }++ /**+ * How many sessions the running sidecar currently owns, read from its durable+ * state. Zero when unreadable — an unparseable state file is not grounds for+ * refusing to upgrade forever.+ */+ private async runningSessionCount(): Promise<number> {+ try {+ const { stdout } = await this.host.exec('cat', [this.statePath]);+ const parsed = JSON.parse(stdout) as { sessions?: unknown };+ return Array.isArray(parsed.sessions) ? parsed.sessions.length : 0;+ } catch {+ return 0;+ }}async stop(): Promise<void> {@@ -301,9 +579,23 @@ export class RemoteSidecarLauncher {const envPrefix = Object.entries(env).map(([key, value]) => `${key}=${quoteShellArg(value)}`).join(' ');+ // Trim the log first: it is append-only for the life of the host, and the+ // sidecar logs a line per `/events` poll per attached client. Left alone it+ // eventually fills the disk, which then breaks the very files — ready,+ // endpoint, state — that everything else depends on. A restart is the+ // natural rotation point.+ const log = quoteShellArg(this.logPath);+ await this.host.exec('sh', [+ '-c',+ `if [ -f ${log} ] && [ "$(wc -c < ${log})" -gt ${SIDECAR_LOG_MAX_BYTES} ]; then ` ++ `tail -c ${SIDECAR_LOG_KEEP_BYTES} ${log} > ${log}.tmp && mv ${log}.tmp ${log}; fi`,+ ]);+ // stdout goes to the log alongside stderr; the sidecar writes its ready file+ // itself (atomically) rather than relying on a shell redirect, which would+ // truncate it the moment the process starts.const inner =`${envPrefix} exec node ${quoteShellArg(SIDECAR_BUNDLE_REL_PATH)} ` +- `> ${quoteShellArg(this.readyPath)} 2>> ${quoteShellArg(this.logPath)}`;+ `>> ${quoteShellArg(this.logPath)} 2>&1`;await this.host.exec('tmux', ['new-session','-d',@@ -315,12 +607,23 @@ export class RemoteSidecarLauncher {]);}- private async awaitReady(): Promise<SidecarEndpoint> {+ /**+ * Wait for the sidecar we just started to publish its endpoint.+ *+ * The ready file is no longer deleted before launch, so a leftover line from+ * the process we killed would otherwise be mistaken for the new one's. The+ * epoch increments on every start, so requiring a higher one identifies the+ * new incarnation. A sidecar that reports no epoch predates this and cannot+ * be distinguished — accept it rather than hang.+ */+ private async awaitReady(previousEpoch: number | null): Promise<SidecarEndpoint> {for (let attempt = 0; attempt < READY_MAX_ATTEMPTS; attempt++) {await this.assertAlive();const raw = await this.readReadyFile();const ready = raw ? parseReady(raw) : null;- if (ready) return { port: ready.port, token: ready.token };+ const isNew =+ ready && (previousEpoch === null || ready.epoch === null || ready.epoch > previousEpoch);+ if (ready && isNew) return this.toEndpoint(ready);await this.sleep(READY_POLL_INTERVAL_MS);}throw new Error(@@ -351,15 +654,20 @@ export class RemoteSidecarLauncher {/** Best-effort tail of the sidecar log, so a startup crash surfaces its actual* error (e.g. a SyntaxError from too-old node) instead of an opaque message. */- private async readLogTail(): Promise<string> {+ private async readLogTail(lines = 20): Promise<string> {try {- const { stdout } = await this.host.exec('tail', ['-n', '20', this.logPath]);+ const { stdout } = await this.host.exec('tail', ['-n', String(lines), this.logPath]);return stdout.trim();} catch {return '';}}+ /** Public log tail for the UI's debug panel. Best-effort — empty on any error. */+ logTail(lines: number): Promise<string> {+ return this.readLogTail(lines);+ }+private async readReadyFile(): Promise<string | null> {try {const { stdout } = await this.host.exec('cat', [this.readyPath]);@@ -409,11 +717,19 @@ export async function killSidecarSession(}/**- * Kill sidecar tmux sessions on the host whose agent pane is gone. A sidecar is- * named `<agentTmux>-sidecar`; if its `<agentTmux>` session no longer exists the- * agent has exited (or its session was deleted) and the sidecar is an orphan —- * still polling Switch with nowhere to inject. Best-effort: a missing tmux- * server (no sessions at all) is a no-op, not an error.+ * Reap LEGACY per-session sidecars — those named `<agentTmux>-sidecar`, one per+ * session — whose agent pane is gone: they are still polling Switch with nowhere+ * to inject.+ *+ * This deliberately does not match today's agent-scoped sidecars+ * (`switchdash-sidecar-<hash>`, see `agentSidecarTmuxName`). Those are *supposed*+ * to outlive every pane: with no live session the notification watcher is the+ * thing that starts one when the agent is next addressed, so reaping them for+ * having no panes would quietly disable auto-start. An agent-scoped sidecar is+ * torn down explicitly instead, via `killSidecarSession`, when the agent or host+ * goes away.+ *+ * Best-effort: a missing tmux server (no sessions at all) is a no-op, not an error.*/export async function reapOrphanedSidecars(host: SidecarHost,diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.tsindex 115cf82a3..b82287f67 100644--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts@@ -9,7 +9,6 @@ import type { IExecutionContext } from '@main/core/execution-context/types';import type { FileSystemProvider } from '@main/core/fs/types';import { getPlugin } from '@main/core/providers/plugin-registry';import type { Pty } from '@main/core/pty/pty';-import { buildAgentHookEnv } from '@main/core/pty/pty-env';import { ptySessionRegistry } from '@main/core/pty/pty-session-registry';import { resolveSshCommand } from '@main/core/pty/spawn-utils';import { openSsh2Pty } from '@main/core/pty/ssh2-pty';@@ -24,14 +23,15 @@ import { events } from '@main/lib/events';import { log } from '@main/lib/logger';import type { AgentSessionConfig } from '@shared/core/providers/agent-session';import { agentSessionExitedChannel } from '@shared/core/providers/agentEvents';+import { buildAgentHookEnv } from '@shared/core/pty/hookEnv';import { makePtyId } from '@shared/core/pty/ptyId';import { makeAgentPtySessionId } from '@shared/core/pty/ptySessionId';import type { Session } from '@shared/core/sessions/sessions';-import { ensureAgentSidecar } from './ensure-agent-sidecar';+import { ensureAgentSidecar, probeAgentSidecar } from './ensure-agent-sidecar';import { scheduleInitialPromptInjection } from './keystroke-injection';import { RemoteHookEventRelay } from './remote-hook-event-relay';import { createRemotePluginFs } from './remote-plugin-fs';-import type { SidecarHost } from './remote-sidecar-launcher';+import type { SidecarEndpoint, SidecarHost } from './remote-sidecar-launcher';import { resolveAgentExecutable } from './resolve-agent-executable';import { httpPostJsonOverChannel } from './sidecar-http';@@ -54,7 +54,7 @@ export class SshAgentRuntime implements AgentRuntimeProvider {private relay: RemoteHookEventRelay | null = null;/** Last resolved sidecar endpoint (agent-scoped, shared by all sessions on the* VM), captured at launch so a delete can POST /disconnect without re-ensuring. */- private sidecarEndpoint: { port: number; token: string } | null = null;+ private sidecarEndpoint: SidecarEndpoint | null = null;private supervisor = new AgentRuntimeSupervisor();private readonly handleConnectionEvent: (evt: SshConnectionManagerEvent) => void;private readonly locationId: string;@@ -194,7 +194,7 @@ export class SshAgentRuntime implements AgentRuntimeProvider {}}- private async launchSidecar(session: Session): Promise<{ port: number; token: string }> {+ private async launchSidecar(session: Session): Promise<SidecarEndpoint> {// One agent-scoped sidecar serves every session on the VM (this one and any// the sidecar's own watcher auto-starts) — ensure it is running and point// this session's hooks at its shared hook server. Reattaches if already up.@@ -206,8 +206,8 @@ export class SshAgentRuntime implements AgentRuntimeProvider {repoDir: this.sessionPath,deeplinkScheme: DEEPLINK_SCHEME,autoApprove: agent?.autoApprove ?? false,- credsSlug: agent?.definitionName ?? session.agentName ?? session.agentId,- definitionName: agent?.definitionName ?? session.agentName ?? null,+ credsSlug: agent?.name ?? session.agentName ?? session.agentId,+ agentName: agent?.name ?? session.agentName ?? null,ctx: this.ctx,connectionId: this.connectionId,host: this.createSidecarHost(),@@ -274,13 +274,35 @@ export class SshAgentRuntime implements AgentRuntimeProvider {* local sessions, but with `startLocalPoller: false` — the sidecar already* polls and injects on the VM.*/- private startRelay(endpoint: { port: number; token: string }): void {+ private startRelay(endpoint: SidecarEndpoint): void {this.relay?.stop();const proxy = this.proxy;const relay = new RemoteHookEventRelay({opener: { openChannel: (port) => proxy.forwardOut(port) },port: endpoint.port,token: endpoint.token,+ // Follow the sidecar if it restarts on a different port with a new token,+ // instead of polling the dead one for the rest of the app's life. Probe,+ // never launch: a relay must not resurrect a sidecar the user stopped.+ resolveEndpoint: async () => {+ const session = this.session;+ if (!session) return null;+ const agent = await getAgentById(session.agentId);+ const next = await probeAgentSidecar({+ providerId: session.providerId,+ repoDir: this.sessionPath,+ deeplinkScheme: DEEPLINK_SCHEME,+ autoApprove: agent?.autoApprove ?? false,+ credsSlug: agent?.name ?? session.agentName ?? session.agentId,+ agentName: agent?.name ?? session.agentName ?? null,+ ctx: this.ctx,+ connectionId: this.connectionId,+ host: this.createSidecarHost(),+ });+ // Keep the cached endpoint used by /disconnect in step with the relay.+ if (next) this.sidecarEndpoint = next;+ return next;+ },sink: async (raw) => {if (raw.type === 'session-terminated') {this.onRemoteTerminated(raw.body);@@ -424,7 +446,12 @@ export class SshAgentRuntime implements AgentRuntimeProvider {// ensureHooksInstalled).await this.installRemoteHooks(session.providerId);const endpoint = await this.launchSidecar(session);- hookEnv = buildAgentHookEnv({ port: endpoint.port, ptyId, token: endpoint.token });+ hookEnv = buildAgentHookEnv({+ port: endpoint.port,+ ptyId,+ token: endpoint.token,+ endpointFile: endpoint.endpointFile,+ });} else {log.warn('SshAgentRuntime: tmux disabled — remote agent will not stay connected to Switch while detached',diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/add-agent.ts b/dash/apps/switchdash-desktop/src/main/core/agents/add-agent.tsindex d34e2bc8f..1515d1da4 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/add-agent.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/add-agent.ts@@ -105,9 +105,6 @@ export async function addAgent(params: AddAgentParams): Promise<AddAgentResult>locationId: location.id,name: params.name,providerId: params.providerId,- // A provider with a definitions capability launches as `--agent <name>`;- // one without has no on-disk definition, so it launches plainly.- definitionName: behavior ? params.name : null,switchAgentId: registered.id,apiEndpoint: server.apiUrl,serverId: params.serverId,diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/agent-definition.ts b/dash/apps/switchdash-desktop/src/main/core/agents/agent-definition.tsindex e2f179818..9dcc07f12 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/agent-definition.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/agent-definition.ts@@ -16,12 +16,12 @@ export async function readAgentDefinition(agentId: string): Promise<RepoAgentAttif (!agent) throw new Error(`No agent with id ${agentId}`);const behavior = getPlugin(agent.providerId).behavior.repoAgents;- if (!behavior || !agent.definitionName) return null;+ if (!behavior || !agent.name) return null;const location = await getAgentLocation(agent);const workspace = await resolveWorkspaceFsFor(location.sshHost, location.dir);try {- return await behavior.readDefinition(workspace.fs, agent.definitionName);+ return await behavior.readDefinition(workspace.fs, agent.name);} finally {workspace.close();}@@ -42,18 +42,18 @@ export async function updateAgentDefinition(params: {if (!agent) throw new Error(`No agent with id ${params.agentId}`);const behavior = getPlugin(agent.providerId).behavior.repoAgents;- if (!behavior || !agent.definitionName) {+ if (!behavior || !agent.name) {throw new Error(`Agent ${params.agentId} has no editable on-disk definition.`);}const location = await getAgentLocation(agent);const workspace = await resolveWorkspaceFsFor(location.sshHost, location.dir);try {- const current = await behavior.readDefinition(workspace.fs, agent.definitionName);+ const current = await behavior.readDefinition(workspace.fs, agent.name);const description = typeof current?.description === 'string' ? current.description : '';await behavior.writeDefinition(workspace.fs, {...params.attributes,- name: agent.definitionName,+ name: agent.name,description,});} finally {diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/createAgent.ts b/dash/apps/switchdash-desktop/src/main/core/agents/createAgent.tsindex 389fdf259..d80e27a6b 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/createAgent.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/createAgent.ts@@ -12,7 +12,6 @@ export async function createAgent(params: CreateAgentParams): Promise<Agent> {locationId: params.locationId,name: params.name,providerId: params.providerId,- definitionName: params.definitionName ?? null,switchAgentId: params.switchAgentId,apiEndpoint: params.apiEndpoint,serverId: params.serverId,diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/deleteAgent.ts b/dash/apps/switchdash-desktop/src/main/core/agents/deleteAgent.tsindex eb297185f..9b4881c84 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/deleteAgent.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/deleteAgent.ts@@ -66,11 +66,11 @@ async function removeProvisionedFiles(agent: Agent, location: Location): Promiseconst ctx = await resolveWorkspaceFsFor(location.sshHost, location.dir);try {const behavior = getPlugin(agent.providerId).behavior.repoAgents;- if (behavior && agent.definitionName) {- await behavior.removeLocal(ctx.fs, agent.definitionName).catch((error) => {+ if (behavior && agent.name) {+ await behavior.removeLocal(ctx.fs, agent.name).catch((error) => {log.warn('deleteAgent: failed to remove agent definition files', {agentId: agent.id,- definitionName: agent.definitionName,+ name: agent.name,error: String(error),});});diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/discover-location-agents.ts b/dash/apps/switchdash-desktop/src/main/core/agents/discover-location-agents.tsindex e6d954658..2b4f3adf4 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/discover-location-agents.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/discover-location-agents.ts@@ -37,11 +37,7 @@ export async function discoverLocationAgents(params: {const location = await getLocationByHostDir(params.sshHost, params.dir);const existing = location- ? new Set(- (await getAgents(location.id))- .map((a) => a.definitionName)- .filter((n): n is string => n != null)- )+ ? new Set((await getAgents(location.id)).map((a) => a.name)): new Set<string>();const workspace = await resolveWorkspaceFsFor(params.sshHost, params.dir);diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/migrate-agent-storage.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/migrate-agent-storage.test.tsindex 1f40612fb..9b907f356 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/migrate-agent-storage.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/migrate-agent-storage.test.ts@@ -72,7 +72,6 @@ const h = vi.hoisted(() => {updateAgent: vi.fn(async () => undefined),isComplete: vi.fn(async () => false),markComplete: vi.fn(async () => undefined),- backfill: vi.fn(async () => 0),};});@@ -108,9 +107,6 @@ vi.mock('./agent-storage-migration-marker', () => ({isAgentStorageMigrationComplete: h.isComplete,markAgentStorageMigrationComplete: h.markComplete,}));-vi.mock('@main/core/sessions/operations/backfillSessionAgentName', () => ({- backfillSessionAgentName: h.backfill,-}));import { migrateAgentStorage } from './migrate-agent-storage';@@ -118,8 +114,8 @@ const baseAgent = {id: 'agent-id-1',providerId: 'claude',locationId: 'loc',- name: 'hoot-main',- definitionName: 'cc-hoot-main',+ // The agent's single identity — the creds/definition stem on disk (CHOO-1440).+ name: 'cc-hoot-main',switchAgentId: 'sw-1',serverId: 'srv-1',};@@ -218,41 +214,4 @@ describe('migrateAgentStorage', () => {expect(h.markComplete).not.toHaveBeenCalled();});-- it('does not latch the marker when an agent name cannot be resolved', async () => {- h.state.agents = [{ ...baseAgent, definitionName: null }];- h.discoverLocal.mockResolvedValueOnce([]);- h.state.workspace = fakeFs({});-- await migrateAgentStorage();-- expect(h.markComplete).not.toHaveBeenCalled();- });-- it('backfills session agentName so migrated sessions stay grouped under the agent', async () => {- h.state.workspace = fakeFs({- '.switch/agents/cc-hoot-main.json': credsJson('sw-1'),- '.claude/agents/cc-hoot-main.md': '# def',- });-- await migrateAgentStorage();-- expect(h.backfill).toHaveBeenCalledWith('agent-id-1', 'cc-hoot-main');- });-- it('backfills even when definitionName was already set (repairs a prior migration)', async () => {- // definitionName is already populated (an earlier migration ran) but old- // sessions still carry no agentName — the backfill must still repair them.- h.state.agents = [{ ...baseAgent, definitionName: 'cc-hoot-main' }];- h.backfill.mockResolvedValueOnce(3);- h.state.workspace = fakeFs({- '.switch/agents/cc-hoot-main.json': credsJson('sw-1'),- '.claude/agents/cc-hoot-main.md': '# def',- });-- await migrateAgentStorage();-- expect(h.updateAgent).not.toHaveBeenCalled();- expect(h.backfill).toHaveBeenCalledWith('agent-id-1', 'cc-hoot-main');- });});diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/migrate-agent-storage.ts b/dash/apps/switchdash-desktop/src/main/core/agents/migrate-agent-storage.tsindex d3abc1521..7d2c588c2 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/migrate-agent-storage.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/migrate-agent-storage.ts@@ -1,9 +1,6 @@import { getLocationById } from '@main/core/locations/store';import { getPlugin } from '@main/core/providers/plugin-registry';-import { backfillSessionAgentName } from '@main/core/sessions/operations/backfillSessionAgentName';import { parseSwitchAgentCredentials } from '@main/core/switch-rooms/switch-credentials';-import { fetchAgentDetail } from '@main/core/switch-servers/gateway-client';-import { getServer } from '@main/core/switch-servers/servers-store';import { log } from '@main/lib/logger';import type { Agent } from '@shared/core/agents/agents';import {@@ -13,15 +10,14 @@ import {import { resolveWorkspaceFsFor } from './agent-workspace-fs';import { getAgents } from './getAgents';import { agentSettingsRelativePath, SWITCH_SETTINGS_RELATIVE_PATH } from './switch-settings-paths';-import { updateAgent } from './updateAgent';/*** Migrate existing switchdash-managed agents to the current storage/definition* layout (CHOO-1440): every agent is a repository-defined agent with a per-agent- * credentials file at `.switch/agents/<name>.json`, an on-disk definition, and a- * populated `definitionName`. Pre-CHOO-1440 installs kept credentials in the- * legacy `.claude/switch-subagents/<name>.settings.json` (or the shared- * `.claude/settings.local.json`) and left `definitionName` null.+ * credentials file at `.switch/agents/<name>.json` and an on-disk definition,+ * both keyed by the agent's single `name`. Pre-CHOO-1440 installs kept+ * credentials in the legacy `.claude/switch-subagents/<name>.settings.json` (or+ * the shared `.claude/settings.local.json`).** Runs once at boot, best-effort: each agent is migrated in isolation so one bad* directory or unreachable host never aborts the rest, and every step is@@ -77,36 +73,11 @@ async function migrateOne(agent: Agent): Promise<MigrateResult> {const workspace = await resolveWorkspaceFsFor(location.sshHost, location.dir);try {- // Resolve the agent's REAL name — the credentials/definition stem, NOT- // `agent.name` (the directory-derived display name). Prefer the row's- // definitionName; else the on-disk agent matched to this row by switchAgentId;- // else the registered Switch name from the gateway (authoritative — the same- // name new agents are created under). Never the directory name (CHOO-1440).- let name = agent.definitionName;- let description = agent.name;- if (!name) {- // No switchAgentId → nothing anchors a real name; leave for a later boot- // in case the row is still being populated.- if (!agent.switchAgentId) return { changed: false, complete: false };- const discovered = await behavior.discoverLocal(workspace.fs, workspace.homeFs);- const match = discovered.find((d) => d.switchAgentId === agent.switchAgentId);- if (match) {- name = match.name;- description = match.description ?? match.name;- } else {- const registered = await fetchRegisteredName(agent);- if (!registered) {- log.info('migrateAgentStorage: could not resolve a real name for agent; skipping', {- agentId: agent.id,- switchAgentId: agent.switchAgentId,- });- // Resolution may fail transiently (gateway down); retry next boot.- return { changed: false, complete: false };- }- name = registered.name;- description = registered.description;- }- }+ // The agent's identity is its single `name` (CHOO-1440): the creds/definition+ // stem on disk. It is authoritative — earlier migrations, and the 0041 SQL+ // backfill, have already collapsed the former `definitionName` onto it.+ const name = agent.name;+ const description = agent.name;let changed = false;@@ -158,52 +129,12 @@ async function migrateOne(agent: Agent): Promise<MigrateResult> {changed = true;}- // 3. Row: populate definitionName so sessions launch as this named agent.- if (agent.definitionName === null) {- await updateAgent({ agentId: agent.id, definitionName: name });- changed = true;- }-- // 4. Backfill this agent's own pre-existing sessions: they froze no- // `agentName` (created before it had a definitionName), so the sidebar —- // which pairs a session to its agent by `agentName === definitionName` —- // would orphan them once definitionName is set. Idempotent, and run even- // when definitionName was already populated so installs that ran an- // earlier migration (before this backfill existed) are repaired too.- const backfilled = await backfillSessionAgentName(agent.id, name);- if (backfilled > 0) {- log.info('migrateAgentStorage: backfilled session agentName for migrated agent', {- agentId: agent.id,- backfilled,- });- changed = true;- }-return { changed, complete: true };} finally {workspace.close();}}-/** The agent's registered name + description on its Switch server, or null. */-async function fetchRegisteredName(- agent: Agent-): Promise<{ name: string; description: string } | null> {- if (!agent.serverId || !agent.switchAgentId) return null;- const server = await getServer(agent.serverId);- if (!server) return null;- try {- const detail = await fetchAgentDetail(server, agent.switchAgentId);- return { name: detail.name, description: detail.description || detail.name };- } catch (error) {- log.warn('migrateAgentStorage: failed to fetch registered agent name', {- agentId: agent.id,- error: String(error),- });- return null;- }-}-/** Build credentials from a launch-env map, or null when any value is missing. */function toCreds(env: Record<string, string>diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/onboard-location-agents.ts b/dash/apps/switchdash-desktop/src/main/core/agents/onboard-location-agents.tsindex 79395dd43..7e97cdc62 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/onboard-location-agents.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/onboard-location-agents.ts@@ -173,11 +173,7 @@ export async function onboardLocationAgents(name: params.locationName ?? basenameFromAnyPath(params.dir) ?? params.providerId,});- const existing = new Set(- (await getAgents(location.id))- .map((a) => a.definitionName)- .filter((n): n is string => n != null)- );+ const existing = new Set((await getAgents(location.id)).map((a) => a.name));const workspace = await resolveWorkspaceFsFor(params.sshHost, params.dir);const created: Agent[] = [];@@ -225,7 +221,6 @@ export async function onboardLocationAgents(locationId: location.id,name: def.name,providerId: params.providerId,- definitionName: def.name,switchAgentId: resolved.identity.switchAgentId,apiEndpoint: resolved.identity.apiEndpoint,serverId: params.serverId,diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/remote-session-reconciler.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/remote-session-reconciler.test.tsindex dcdf3c82a..d55ebb734 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/remote-session-reconciler.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/remote-session-reconciler.test.ts@@ -1,4 +1,4 @@-import { afterEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const REMOTE_AGENT = {id: 'agent-1',@@ -63,7 +63,9 @@ vi.mock('@main/db/client', () => ({delete: () => ({ where: (arg: unknown) => deleteWhere(arg as never) }),},}));-vi.mock('@main/lib/logger', () => ({ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));+vi.mock('@main/lib/logger', () => ({+ log: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() },+}));const eventsEmit = vi.fn();vi.mock('@main/lib/events', () => ({events: { emit: (...args: unknown[]) => eventsEmit(...args) },@@ -97,6 +99,13 @@ function handleRemoteTerminated(sessionId: string): Promise<void> {}describe('RemoteSessionReconciler', () => {+ beforeEach(() => {+ // `clearAllMocks` clears calls but keeps implementations, so a test that+ // simulates an unreachable sidecar would otherwise leave every later test+ // probing null — and assertions like "did not prune" would pass vacuously.+ probeAgentSidecar.mockResolvedValue({ port: 4321, token: 'tok' });+ });+afterEach(() => {vi.clearAllMocks();knownRows = [];@@ -260,6 +269,49 @@ describe('RemoteSessionReconciler', () => {emitSpy.mockRestore();});+ it('never prunes when the sidecar is unreachable, however long it stays away', async () => {+ // The regression this guards: an unreachable sidecar used to be reported as+ // an empty session list, so three failed polls deleted rows for sessions+ // that were alive and healthy on the VM — and nothing ever re-adopted them.+ knownRows = [];+ httpGetJsonOverChannel.mockResolvedValue({+ sessions: [{ sessionId: 'session-unreachable', roomId: 'room-1' }],+ });+ await reconcile('agent-1'); // adopt session-unreachable+ knownRows = [{ id: 'session-unreachable' }];++ // Sidecar goes away entirely (restarting, upgrading, briefly unreachable).+ probeAgentSidecar.mockResolvedValue(null);+ httpGetJsonOverChannel.mockRejectedValue(new Error('ECONNREFUSED'));+ for (let i = 0; i < 6; i++) await reconcile('agent-1');++ expect(deleteWhere).not.toHaveBeenCalled();+ });++ it('resumes pruning once the sidecar answers again and really omits the session', async () => {+ knownRows = [];+ httpGetJsonOverChannel.mockResolvedValue({+ sessions: [{ sessionId: 'session-resume', roomId: 'room-1' }],+ });+ await reconcile('agent-1');+ knownRows = [{ id: 'session-resume' }];++ probeAgentSidecar.mockResolvedValue(null);+ await reconcile('agent-1');+ await reconcile('agent-1');+ await reconcile('agent-1');+ expect(deleteWhere).not.toHaveBeenCalled();++ // Sidecar is back and authoritatively reports no sessions.+ probeAgentSidecar.mockResolvedValue({ port: 4321, token: 'tok' });+ httpGetJsonOverChannel.mockResolvedValue({ sessions: [] });+ await reconcile('agent-1');+ await reconcile('agent-1');+ await reconcile('agent-1');++ expect(deleteWhere).toHaveBeenCalledTimes(1);+ });+it('does not prune an adopted session that keeps being reported', async () => {knownRows = [];httpGetJsonOverChannel.mockResolvedValue({diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/remote-session-reconciler.ts b/dash/apps/switchdash-desktop/src/main/core/agents/remote-session-reconciler.tsindex df2d8c801..00aca10ad 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/remote-session-reconciler.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/remote-session-reconciler.ts@@ -36,15 +36,28 @@ const TOMBSTONE_TTL_MS = 10_000;// the sidecar `/sessions` snapshot before its local row is pruned. This is the// backstop for a client that missed the `session-terminated` push (e.g. it// adopted a session but never opened it, so it has no relay polling `/events`).-// A threshold (rather than pruning on first absence) tolerates the brief empty-// window after a sidecar restart, before the agents re-post their hooks. Only-// successful polls count — a failed fetch throws and skips the pass entirely.+// A threshold (rather than pruning on first absence) absorbs a one-off odd+// snapshot. It is NOT what covers a sidecar restart: the sidecar restores its+// session registry from durable state, so a restarted sidecar reports its+// sessions immediately rather than going empty until the agents next speak.+// Only successful polls count — an unreachable sidecar skips the pass entirely+// rather than counting as an absence.const PRUNE_MISSING_THRESHOLD = 3;interface SidecarSessionsResponse {sessions: Array<{ sessionId: string; roomId: string | null }>;}+/**+ * Outcome of a poll. "The VM says it has no sessions" and "I could not ask the+ * VM" are different facts and only the first is evidence a session is gone —+ * conflating them meant an unreachable sidecar looked exactly like an empty one+ * and drove the client to delete rows for sessions that were still running.+ */+type SessionsSnapshot =+ | { ok: true; sessions: Array<{ sessionId: string; roomId: string | null }> }+ | { ok: false; reason: string };+/*** Surfaces the sessions a remote agent's on-VM sidecar started on its own (the* notification watcher auto-starting a session when the agent is addressed while@@ -239,8 +252,18 @@ class RemoteSessionReconciler {if (connectionState === 'reconnecting') return;const conn = await connectRemoteAgent(agent);- const response = await this.fetchSessions(agent, conn);- const vmSessions = response.sessions ?? [];+ const snapshot = await this.fetchSessions(agent, conn);+ // A poll we could not complete tells us nothing about what is running, so+ // this pass makes no adoptions and — crucially — no prunes. Deleting rows+ // because the VM was unreachable is how live sessions used to disappear.+ if (!snapshot.ok) {+ log.debug('RemoteSessionReconciler: sessions poll failed — skipping pass', {+ agentId,+ reason: snapshot.reason,+ });+ return;+ }+ const vmSessions = snapshot.sessions;const vmIds = new Set(vmSessions.map((s) => s.sessionId));// Check adoption candidates against ALL local sessions, not just this@@ -302,7 +325,8 @@ class RemoteSessionReconciler {* only ever adopted (never opened) has no relay to receive the `session-terminated`* push, so without this it would keep a ghost row that could re-attach into a* blank tmux session. Only prune after `PRUNE_MISSING_THRESHOLD` consecutive- * absences to ride out the empty window after a sidecar restart.+ * absences, and only on snapshots we actually got — an unreachable sidecar is+ * not evidence of anything and never reaches here.*/private async pruneVanished(agentId: string, vmIds: Set<string>): Promise<void> {const adoptedIds = this.adopted.get(agentId);@@ -335,11 +359,11 @@ class RemoteSessionReconciler {private async fetchSessions(agent: Agent,conn: Awaited<ReturnType<typeof connectRemoteAgent>>- ): Promise<SidecarSessionsResponse> {+ ): Promise<SessionsSnapshot> {const cached = this.endpoints.get(agent.id);if (cached) {try {- return await this.pollSessions(conn.proxy, cached);+ return { ok: true, sessions: (await this.pollSessions(conn.proxy, cached)).sessions ?? [] };} catch (error) {log.debug('RemoteSessionReconciler: cached endpoint poll failed — re-probing sidecar', {agentId: agent.id,@@ -356,15 +380,23 @@ class RemoteSessionReconciler {repoDir: conn.remoteRepoDir,deeplinkScheme: DEEPLINK_SCHEME,autoApprove: agent.autoApprove,- credsSlug: agent.definitionName ?? agent.id,- definitionName: agent.definitionName ?? null,+ credsSlug: agent.name ?? agent.id,+ agentName: agent.name ?? null,ctx: conn.ctx,connectionId: conn.connectionId,host: conn.host,});- if (!endpoint) return { sessions: [] };+ // No sidecar answered the probe. That is not "the agent has no sessions" —+ // it may be restarting, mid-upgrade, or briefly unreachable — so report it+ // as a failed poll and leave the local rows alone.+ if (!endpoint) return { ok: false, reason: 'no sidecar reachable' };this.endpoints.set(agent.id, endpoint);- return this.pollSessions(conn.proxy, endpoint);+ try {+ return { ok: true, sessions: (await this.pollSessions(conn.proxy, endpoint)).sessions ?? [] };+ } catch (error) {+ this.endpoints.delete(agent.id);+ return { ok: false, reason: String(error) };+ }}private async pollSessions(diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/remote-watcher.ts b/dash/apps/switchdash-desktop/src/main/core/agents/remote-watcher.tsindex 5d64a798e..9274b8fe2 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/remote-watcher.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/remote-watcher.ts@@ -114,13 +114,13 @@ export async function ensureRemoteWatcher(agentId: string): Promise<void> {repoDir: remoteRepoDir,deeplinkScheme: DEEPLINK_SCHEME,autoApprove: agent.autoApprove,- credsSlug: agent.definitionName ?? agent.id,- definitionName: agent.definitionName ?? null,+ credsSlug: agent.name ?? agent.id,+ agentName: agent.name ?? null,ctx,connectionId,host,});- await writeWatchEnabled(host, agent.definitionName ?? agent.id, true);+ await writeWatchEnabled(host, agent.name ?? agent.id, true);log.info('ensureRemoteWatcher: sidecar deployed + watching', {agentId,switchAgentId: agent.switchAgentId,@@ -142,6 +142,6 @@ export async function stopRemoteWatcher(agentId: string): Promise<void> {if (!agent || !(await getRemoteAgentLocation(agent))) return;remoteSessionReconciler.stop(agentId);const { host } = await connectRemoteAgent(agent);- await writeWatchEnabled(host, agent.definitionName ?? agent.id, false);+ await writeWatchEnabled(host, agent.name ?? agent.id, false);log.info('stopRemoteWatcher: watching disabled', { agentId });}diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/reset-remote-agent.ts b/dash/apps/switchdash-desktop/src/main/core/agents/reset-remote-agent.tsindex d12ce55ec..a908206fe 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/reset-remote-agent.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/reset-remote-agent.ts@@ -46,8 +46,8 @@ async function fetchSidecarSessionIds(agent: Agent, conn: RemoteConn): Promise<srepoDir: conn.remoteRepoDir,deeplinkScheme: DEEPLINK_SCHEME,autoApprove: agent.autoApprove,- credsSlug: agent.definitionName ?? agent.id,- definitionName: agent.definitionName ?? null,+ credsSlug: agent.name ?? agent.id,+ agentName: agent.name ?? null,ctx: conn.ctx,connectionId: conn.connectionId,host: conn.host,@@ -141,7 +141,7 @@ export async function resetRemoteAgent(agentId: string): Promise<void> {remoteSessionReconciler.stop(agentId);const conn = await connectRemoteAgent(agent);- const credsSlug = agent.definitionName ?? agent.id;+ const credsSlug = agent.name ?? agent.id;// Silence the VM watcher first so it cannot auto-start a fresh session between// the /sessions snapshot and the kill (whose pane we would then miss).diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/updateAgent.ts b/dash/apps/switchdash-desktop/src/main/core/agents/updateAgent.tsindex c30268fd9..a7d4bc59d 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/updateAgent.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/updateAgent.ts@@ -11,7 +11,6 @@ export type UpdateAgentParams = {apiEndpoint?: string | null;serverId?: string;autoApprove?: boolean;- definitionName?: string | null;};type AgentUpdateSet = Parameters<ReturnType<typeof db.update<typeof agents>>['set']>[0];@@ -23,7 +22,6 @@ export async function updateAgent(params: UpdateAgentParams): Promise<Agent | unif (params.apiEndpoint !== undefined) set.apiEndpoint = params.apiEndpoint;if (params.serverId !== undefined) set.serverId = params.serverId;if (params.autoApprove !== undefined) set.autoApprove = params.autoApprove;- if (params.definitionName !== undefined) set.definitionName = params.definitionName;const [row] = await db.update(agents).set(set).where(eq(agents.id, params.agentId)).returning();if (!row) return undefined;diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/utils.ts b/dash/apps/switchdash-desktop/src/main/core/agents/utils.tsindex cd52a1bbd..8608a249b 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/utils.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/utils.ts@@ -7,7 +7,6 @@ export function mapAgentRowToAgent(row: AgentRow): Agent {locationId: row.locationId,name: row.name,providerId: row.providerId,- definitionName: row.definitionName ?? null,switchAgentId: row.switchAgentId ?? null,apiEndpoint: row.apiEndpoint ?? null,serverId: row.serverId ?? null,diff --git a/dash/apps/switchdash-desktop/src/main/core/pty/pty-env.ts b/dash/apps/switchdash-desktop/src/main/core/pty/pty-env.tsindex 3a88497f8..210c622b0 100644--- a/dash/apps/switchdash-desktop/src/main/core/pty/pty-env.ts+++ b/dash/apps/switchdash-desktop/src/main/core/pty/pty-env.ts@@ -2,6 +2,7 @@ import os from 'node:os';import type { ResolvedShellProfile } from '@main/core/terminal-shell/types';import { detectSshAuthSock } from '@main/utils/shellEnv';import { getWindowsEnvValue } from '@main/utils/windows-env';+import { buildAgentHookEnv } from '@shared/core/pty/hookEnv';export const AGENT_ENV_VARS = ['ALL_PROXY',@@ -136,31 +137,6 @@ function getWindowsEssentialEnv(resolvedPath: string): Record<string, string> {};}-export interface AgentHookEnv {- port: number;- ptyId: string;- token: string;-}--/**- * Environment that points an agent CLI's lifecycle hooks at a switchdash hook- * server (the local one for local sessions, the on-VM sidecar for remote ones)- * and stands the in-session Switch connector's own poll loop down so it does- * not race switchdash's poller on the bridge's destructive event queue.- *- * Shared by `buildAgentEnv` (local) and the SSH agent runtime (remote)- * so the hook wiring — including the no-double-delivery gate — lives in one- * place.- */-export function buildAgentHookEnv(hook: AgentHookEnv): Record<string, string> {- return {- SWITCHDASH_HOOK_PORT: String(hook.port),- SWITCHDASH_PTY_ID: hook.ptyId,- SWITCHDASH_HOOK_TOKEN: hook.token,- SWITCH_CHANNEL_DISABLE_POLL: '1',- };-}-export interface AgentEnvOptions {/*** Pass through AGENT_ENV_VARS from process.env.diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/backfillSessionAgentName.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/backfillSessionAgentName.tsdeleted file mode 100644index 3fe588d8f..000000000--- a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/backfillSessionAgentName.ts+++ /dev/null@@ -1,36 +0,0 @@-import { eq } from 'drizzle-orm';-import { db } from '@main/db/client';-import { sessions } from '@main/db/schema';--/**- * Backfill `config.agentName` on an agent's own pre-existing sessions to match- * its definitionName.- *- * `createSession` freezes a session's `agentName` from its agent's- * `definitionName` at creation time, and the sidebar joins a session to its- * agent by `agentName === definitionName`. Sessions created before the agent had- * a definitionName froze no `agentName`, so once the CHOO-1440 migration- * populates `definitionName` those sessions match no agent and vanish from the- * tree (they still exist and open via deeplink). This restores the pairing.- *- * Idempotent: only sessions with no `agentName`/`subagentName` are touched, so- * re-running is a no-op and sessions launched as a different definition (a former- * subagent) are left alone. Returns the number of sessions updated.- */-export async function backfillSessionAgentName(- agentId: string,- definitionName: string-): Promise<number> {- const rows = await db.select().from(sessions).where(eq(sessions.agentId, agentId));- let updated = 0;- for (const row of rows) {- const config = row.config ?? {};- if (config.agentName || config.subagentName) continue;- await db- .update(sessions)- .set({ config: { ...config, agentName: definitionName } })- .where(eq(sessions.id, row.id));- updated += 1;- }- return updated;-}diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/createSession.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/createSession.tsindex 1cfb0c239..412eef0a5 100644--- a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/createSession.ts+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/createSession.ts@@ -31,13 +31,9 @@ export async function createSession(const configObj: SessionConfig = {};if (params.autoApprove !== undefined) configObj.autoApprove = params.autoApprove;if (params.initialPrompt?.trim()) configObj.initialPrompt = params.initialPrompt.trim();- // A subagent is just an agent that launches as a provider definition. When the- // owning agent carries a definitionName, its sessions launch with- // `--agent <definitionName>` — derive it here so the runtime needs no DB- // lookup. An explicit param still wins (legacy "run this session as subagent- // X of parent" callers) (CHOO-1440).- const launchDefinition = params.agentName?.trim() || agent.definitionName?.trim();- if (launchDefinition) configObj.agentName = launchDefinition;+ // The session's launch identity is not stored — it is read live from the+ // owning agent's `name` (see mapSessionRowToSession). How that name spawns is+ // the provider's business (Claude Code → `--agent <name>`) (CHOO-1440).const config = Object.keys(configObj).length > 0 ? configObj : undefined;const [row] = await db@@ -63,7 +59,7 @@ export async function createSession(// as a Result instead of a raw UNIQUE-constraint throw.if (!row) return err({ type: 'already-exists' });- const session = mapSessionRowToSession(row, agent.providerId);+ const session = mapSessionRowToSession(row, agent.providerId, agent.name);try {const built = await provisionSessionRuntime(session, location);diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/getSession.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/getSession.tsindex 3b2318093..d925a8aaa 100644--- a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/getSession.ts+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/getSession.ts@@ -5,5 +5,5 @@ import { mapSessionRowToSession } from '../utils/utils';export async function getSession(sessionId: string): Promise<Session | null> {const loaded = await loadSessionWithAgent(sessionId);if (!loaded) return null;- return mapSessionRowToSession(loaded.row, loaded.providerId);+ return mapSessionRowToSession(loaded.row, loaded.providerId, loaded.name);}diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/getSessions.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/getSessions.tsindex 06cc7fdcd..3ec25f8c0 100644--- a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/getSessions.ts+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/getSessions.ts@@ -6,7 +6,7 @@ import { mapSessionRowToSession } from '../utils/utils';export async function getSessions(locationId?: string): Promise<Session[]> {const base = db- .select({ session: sessions, providerId: agents.providerId })+ .select({ session: sessions, providerId: agents.providerId, name: agents.name }).from(sessions).innerJoin(agents, eq(sessions.agentId, agents.id));@@ -14,5 +14,7 @@ export async function getSessions(locationId?: string): Promise<Session[]> {? await base.where(eq(agents.locationId, locationId)).orderBy(desc(sessions.updatedAt)): await base.orderBy(desc(sessions.updatedAt));- return rows.map(({ session, providerId }) => mapSessionRowToSession(session, providerId));+ return rows.map(({ session, providerId, name }) =>+ mapSessionRowToSession(session, providerId, name)+ );}diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/hydrateSession.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/hydrateSession.tsindex a3ba2a263..cb9bb4f0d 100644--- a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/hydrateSession.ts+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/hydrateSession.ts@@ -24,7 +24,7 @@ export async function hydrateSession(sessionId: string): Promise<void> {const isResuming = !isFirstSpawn;await agent.start(- mapSessionRowToSession(row, loaded.providerId),+ mapSessionRowToSession(row, loaded.providerId, loaded.name),undefined,isResuming,isFirstSpawn ? config.initialPrompt : undefineddiff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/renameSession.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/renameSession.tsindex a9ff8d0c8..88727b157 100644--- a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/renameSession.ts+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/renameSession.ts@@ -10,7 +10,7 @@ export async function renameSession(newTitle: string): Promise<Result<RenameSessionSuccess, RenameSessionError>> {const [existing] = await db- .select({ providerId: agents.providerId })+ .select({ providerId: agents.providerId, name: agents.name }).from(sessions).innerJoin(agents, eq(sessions.agentId, agents.id)).where(eq(sessions.id, sessionId))@@ -23,5 +23,5 @@ export async function renameSession(.where(eq(sessions.id, sessionId)).returning();- return ok({ session: mapSessionRowToSession(updatedRow, existing.providerId) });+ return ok({ session: mapSessionRowToSession(updatedRow, existing.providerId, existing.name) });}diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/restoreSession.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/restoreSession.tsindex a20b4cc99..b602294f6 100644--- a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/restoreSession.ts+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/restoreSession.ts@@ -17,11 +17,11 @@ export async function restoreSession(id: string): Promise<Session | undefined> {if (!updatedRow) return undefined;const [agent] = await db- .select({ providerId: agents.providerId })+ .select({ providerId: agents.providerId, name: agents.name }).from(agents).where(eq(agents.id, updatedRow.agentId)).limit(1);if (!agent) return undefined;- return mapSessionRowToSession(updatedRow, agent.providerId);+ return mapSessionRowToSession(updatedRow, agent.providerId, agent.name);}diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/session-builder.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/session-builder.tsindex 6aabc4a15..a283a567f 100644--- a/dash/apps/switchdash-desktop/src/main/core/sessions/session-builder.ts+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/session-builder.ts@@ -110,14 +110,12 @@ export async function buildSessionFromRuntime();// The remote preflight verifies the session's own creds file, keyed by the- // agent's NAME (`.switch/agents/<name>.json`). Resolve the name from the agent- // row's definitionName — the source of truth, so a session picks up the right- // name even if it was created (or restored) before the agent was migrated — and- // fall back to the session's own agentName. The agent-id path and the legacy- // shared `.claude/settings.local.json` are last-resort fallbacks for agents not- // yet migrated (CHOO-1440).+ // agent's NAME (`.switch/agents/<name>.json`). Resolve it from the agent row —+ // the source of truth — falling back to the session's denormalised agentName.+ // The agent-id path and the legacy shared `.claude/settings.local.json` are+ // last-resort fallbacks for agents not yet migrated (CHOO-1440).const agent = await getAgentById(session.agentId);- const slug = agent?.definitionName ?? session.agentName;+ const slug = agent?.name ?? session.agentName;const credsRelPaths = [...(slug ? [agentSettingsRelativePath(slug)] : []),agentSettingsRelativePath(session.agentId),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.tsindex 8f817c8ea..cf8037840 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@@ -7,21 +7,34 @@ export type SessionWithAgent = {row: SessionRow;locationId: string;providerId: AgentProviderId;+ /** 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;};/*** Loads a session row joined with its owning agent, exposing the agent's- * `locationId` and `providerId` (denormalised onto the session view).+ * `locationId`, `providerId`, and `name` (denormalised onto the session view).*/export async function loadSessionWithAgent(sessionId: string): Promise<SessionWithAgent | undefined> {const [joined] = await db- .select({ session: sessions, locationId: agents.locationId, providerId: agents.providerId })+ .select({+ session: sessions,+ locationId: agents.locationId,+ providerId: agents.providerId,+ name: agents.name,+ }).from(sessions).innerJoin(agents, eq(sessions.agentId, agents.id)).where(eq(sessions.id, sessionId)).limit(1);if (!joined) return undefined;- return { row: joined.session, locationId: joined.locationId, providerId: joined.providerId };+ return {+ row: joined.session,+ locationId: joined.locationId,+ providerId: joined.providerId,+ name: joined.name,+ };}diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/session-service.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/session-service.tsindex 6a294b4cf..6f79d9794 100644--- a/dash/apps/switchdash-desktop/src/main/core/sessions/session-service.ts+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/session-service.ts@@ -116,7 +116,7 @@ export class SessionService implements Hookable<SessionLifecycleHooks> {const agent = await getAgentById(row.agentId);if (!agent) throw new Error(`Agent not found: ${row.agentId}`);return {- session: mapSessionRowToSession(row, agent.providerId),+ session: mapSessionRowToSession(row, agent.providerId, agent.name),agentLocationId: agent.locationId,};}diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/utils/utils.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/utils/utils.tsindex 799e47f28..a7bfdd8be 100644--- a/dash/apps/switchdash-desktop/src/main/core/sessions/utils/utils.ts+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/utils/utils.ts@@ -4,10 +4,17 @@ import type { AgentStatus } from '@shared/core/providers/agentEvents';import type { Session, SessionLifecycleStatus } from '@shared/core/sessions/sessions';/**- * Maps a session row to a `Session`. `providerId` is denormalised from the- * owning agent and must be supplied by the caller (which has joined `agents`).+ * Maps a session row to a `Session`. `providerId` and `agentName` are+ * denormalised from the owning agent and must be supplied by the caller (which+ * has joined `agents`). `agentName` is the agent's live `name` — the value a+ * definitions-capable provider launches as (`--agent <name>`) — read from the+ * agent row rather than frozen into the session, so it follows a rename.*/-export function mapSessionRowToSession(row: SessionRow, providerId: AgentProviderId): Session {+export function mapSessionRowToSession(+ row: SessionRow,+ providerId: AgentProviderId,+ agentName: string+): Session {const config = row.config ?? {};return {id: row.id,@@ -26,7 +33,7 @@ export function mapSessionRowToSession(row: SessionRow, providerId: AgentProvidelastInteractedAt: row.lastInteractedAt ?? undefined,autoApprove: config.autoApprove,providerSessionId: config.providerSessionId,- agentName: config.agentName ?? config.subagentName,+ agentName,createdAt: row.createdAt,updatedAt: row.updatedAt,};diff --git a/dash/apps/switchdash-desktop/src/main/core/sidecar/controller.ts b/dash/apps/switchdash-desktop/src/main/core/sidecar/controller.tsnew file mode 100644index 000000000..fad8f317e--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/sidecar/controller.ts@@ -0,0 +1,124 @@+import { DEEPLINK_SCHEME } from '@main/app/deeplinks';+import {+ type AgentSidecarParams,+ ensureAgentSidecar,+ readAgentSidecarLog,+ readAgentSidecarStatus,+ restartAgentSidecar,+ stopAgentSidecar,+} from '@main/core/agent-runtime/impl/ensure-agent-sidecar';+import { getRemoteAgentLocation } from '@main/core/agents/agent-location';+import { connectRemoteAgent } from '@main/core/agents/connect-remote-agent';+import { getAgentById } from '@main/core/agents/getAgentById';+import { events } from '@main/lib/events';+import { log } from '@main/lib/logger';+import type { Agent } from '@shared/core/agents/agents';+import { type AgentSidecarStatus, sidecarStatusChannel } from '@shared/events/sidecarEvents';+import { createRPCController } from '@shared/lib/ipc/rpc';+import { SIDECAR_VERSION } from '../../../sidecar/sidecar-version';+import { verdictFor } from './verdict';++const LOG_TAIL_LINES = 100;++async function requireRemoteAgent(+ agentId: string+): Promise<{ agent: Agent; sshHost: string; repoDir: string; credsSlug: string }> {+ const agent = await getAgentById(agentId);+ if (!agent) throw new Error(`sidecar: unknown agent ${agentId}`);+ const location = await getRemoteAgentLocation(agent);+ if (!location) throw new Error(`sidecar: agent ${agentId} is not at a remote location`);+ return {+ agent,+ sshHost: location.sshHost,+ repoDir: location.dir,+ credsSlug: agent.name ?? agent.id,+ };+}++/** Build the shared sidecar params from a connected remote agent. */+async function paramsForAgent(agent: Agent): Promise<AgentSidecarParams> {+ const conn = await connectRemoteAgent(agent);+ return {+ providerId: agent.providerId,+ repoDir: conn.remoteRepoDir,+ deeplinkScheme: DEEPLINK_SCHEME,+ autoApprove: agent.autoApprove,+ credsSlug: agent.name ?? agent.id,+ agentName: agent.name ?? null,+ ctx: conn.ctx,+ connectionId: conn.connectionId,+ host: conn.host,+ };+}++/**+ * Read status for an agent, assemble the full UI shape, and broadcast it so any+ * open page updates live. Shared by the read path and by every mutation, which+ * re-read and re-emit once they finish.+ */+async function readAndBroadcast(agentId: string): Promise<AgentSidecarStatus> {+ const { agent, sshHost, repoDir, credsSlug } = await requireRemoteAgent(agentId);+ const { status, clientHash } = await readAgentSidecarStatus(await paramsForAgent(agent));+ const full: AgentSidecarStatus = {+ agentId,+ running: status.running,+ verdict: verdictFor(status, clientHash),+ clientHash,+ clientVersion: SIDECAR_VERSION,+ deployedHash: status.hash,+ deployedVersion: status.version,+ epoch: status.epoch,+ pid: status.pid,+ liveSessions: status.liveSessions,+ repoDir,+ sshHost,+ credsSlug,+ };+ events.emit(sidecarStatusChannel, full);+ return full;+}++export const sidecarController = createRPCController({+ /** Read-only status for one agent's sidecar. Never launches one. */+ getStatus: (agentId: string): Promise<AgentSidecarStatus> => readAndBroadcast(agentId),++ /**+ * Deploy the client's bundle if the running sidecar is a different, replaceable+ * build (idle). Honours the defer policy — a busy sidecar is left running — so+ * this is the "polite Update" action. Returns the refreshed status.+ */+ upgrade: async (agentId: string): Promise<AgentSidecarStatus> => {+ const { agent } = await requireRemoteAgent(agentId);+ await ensureAgentSidecar(await paramsForAgent(agent));+ return readAndBroadcast(agentId);+ },++ /**+ * Force a fresh sidecar process (stop + relaunch), even if the current one has+ * live sessions — they survive via the endpoint file. The "restart / force+ * upgrade now" action.+ */+ restart: async (agentId: string): Promise<AgentSidecarStatus> => {+ const { agent } = await requireRemoteAgent(agentId);+ await restartAgentSidecar(await paramsForAgent(agent));+ return readAndBroadcast(agentId);+ },++ /** Stop the sidecar. Sessions keep running but lose room injection until it is back. */+ stop: async (agentId: string): Promise<AgentSidecarStatus> => {+ const { agent } = await requireRemoteAgent(agentId);+ await stopAgentSidecar(await paramsForAgent(agent));+ return readAndBroadcast(agentId);+ },++ /** Tail of the sidecar log on the host, for debugging. */+ logTail: async (agentId: string): Promise<string> => {+ const { agent } = await requireRemoteAgent(agentId);+ try {+ return await readAgentSidecarLog(await paramsForAgent(agent), LOG_TAIL_LINES);+ } catch (error) {+ log.warn('sidecarController: failed to read log tail', { agentId, error: String(error) });+ return '';+ }+ },+});diff --git a/dash/apps/switchdash-desktop/src/main/core/sidecar/verdict.test.ts b/dash/apps/switchdash-desktop/src/main/core/sidecar/verdict.test.tsnew file mode 100644index 000000000..c49ed65b2--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/sidecar/verdict.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it } from 'vitest';+import type { SidecarRunStatus } from '@main/core/agent-runtime/impl/remote-sidecar-launcher';+import { verdictFor } from './verdict';++const CLIENT = 'client-hash';++const status = (over: Partial<SidecarRunStatus>): SidecarRunStatus => ({+ running: true,+ compatible: true,+ hash: CLIENT,+ version: '1.0',+ epoch: 1,+ pid: 100,+ liveSessions: 0,+ ...over,+});++describe('verdictFor', () => {+ it('not-running when nothing is up', () => {+ expect(verdictFor(status({ running: false }), CLIENT)).toBe('not-running');+ });++ it('up-to-date when the host runs this exact build', () => {+ expect(verdictFor(status({ hash: CLIENT }), CLIENT)).toBe('up-to-date');+ });++ it('upgrade-available when a different build is running and idle', () => {+ expect(verdictFor(status({ hash: 'other', liveSessions: 0 }), CLIENT)).toBe(+ 'upgrade-available'+ );+ });++ it('upgrade-pending when a different build is running but busy', () => {+ expect(verdictFor(status({ hash: 'other', liveSessions: 3 }), CLIENT)).toBe('upgrade-pending');+ });++ it('incompatible outranks any build comparison', () => {+ // Even the same hash is moot if we cannot speak its protocol — though in+ // practice an incompatible sidecar is a different build anyway.+ expect(verdictFor(status({ compatible: false, hash: 'other', liveSessions: 5 }), CLIENT)).toBe(+ 'incompatible'+ );+ });+});diff --git a/dash/apps/switchdash-desktop/src/main/core/sidecar/verdict.ts b/dash/apps/switchdash-desktop/src/main/core/sidecar/verdict.tsnew file mode 100644index 000000000..f8a8db385--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/sidecar/verdict.ts@@ -0,0 +1,16 @@+import type { SidecarRunStatus } from '@main/core/agent-runtime/impl/remote-sidecar-launcher';+import type { SidecarVerdict } from '@shared/events/sidecarEvents';++/**+ * Turn a raw host status + this client's build into the client-vs-host verdict.+ *+ * Compatibility (can I talk to it) is checked before the build comparison (is an+ * upgrade available), mirroring the launcher's deploy policy — a build that+ * differs is not a problem, only a protocol that does not fit is.+ */+export function verdictFor(status: SidecarRunStatus, clientHash: string): SidecarVerdict {+ if (!status.running) return 'not-running';+ if (!status.compatible) return 'incompatible';+ if (status.hash === clientHash) return 'up-to-date';+ return status.liveSessions > 0 ? 'upgrade-pending' : 'upgrade-available';+}diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/auto-session-watcher.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/auto-session-watcher.tsindex 370e83cdf..f1830fcea 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/auto-session-watcher.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/auto-session-watcher.ts@@ -202,7 +202,7 @@ class AutoSessionWatcher {// Read the agent's own identity from its provider-neutral per-agent file so// agents sharing a location watch as themselves; fall back to the location's// `.claude/settings.local.json` for un-migrated installs (CHOO-1440).- const slug = agent?.definitionName ?? localAgentId;+ const slug = agent?.name ?? localAgentId;const creds =(await readSwitchAgentCredentialsFromSettings(agentSettingsPath(rootPath, slug), log)) ??(await readSwitchAgentCredentials(rootPath, log));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.tsindex 39feb7847..74b062720 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@@ -1,13 +1,10 @@import * as os from 'node:os';import * as path from 'node:path';-import { eq } from 'drizzle-orm';import { DEEPLINK_SCHEME } from '@main/app/deeplinks';import { agentSettingsPath, subagentSettingsPath } from '@main/core/agents/switch-settings-paths';import { getLocationById } from '@main/core/locations/store';import { isHumanInputRecent } from '@main/core/pty/human-activity';import { loadSessionWithAgent } from '@main/core/sessions/session-join';-import { db } from '@main/db/client';-import { sessions } from '@main/db/schema';import { log } from '@main/lib/logger';import type { AgentStatus, NotificationType } from '@shared/core/providers/agentEvents';import { makeAgentPtySessionId } from '@shared/core/pty/ptySessionId';@@ -75,7 +72,13 @@ class SwitchNotificationPoller {roomName: string | null): Promise<void> {const loaded = await loadSessionWithAgent(ctx.sessionId);- const location = loaded ? await getLocationById(loaded.locationId) : undefined;+ if (!loaded) {+ log.warn('SwitchNotificationPoller: session not found; cannot read credentials', {+ sessionId: ctx.sessionId,+ });+ return;+ }+ const location = await getLocationById(loaded.locationId);if (!location) {log.warn('SwitchNotificationPoller: no location for session; cannot read credentials', {sessionId: ctx.sessionId,@@ -93,39 +96,24 @@ class SwitchNotificationPoller {}const rootPath = location.dir;- // A subagent session must poll as the subagent (its own credentials file),- // not the parent's `.claude/settings.local.json` — otherwise it receives the- // events addressed to the parent rather than to the subagent.- const [sessionRow] = await db- .select({ config: sessions.config, agentId: sessions.agentId })- .from(sessions)- .where(eq(sessions.id, ctx.sessionId))- .limit(1);- const agentName = sessionRow?.config?.agentName;- const agentId = sessionRow?.agentId;+ // A session polls as its OWN agent's identity — resolved from the joined+ // agent row, not from a name frozen into the session's config. An agent's+ // creds live in its provider-neutral `.switch/agents/<name>.json`, keyed by+ // the agent's name. Deriving the slug from the live agent row is what stops a+ // session from polling under the wrong identity when a stale tag disagrees+ // with the agent row.+ const slug = loaded.name;- // Credentials come from the agent's provider-neutral per-agent file — a- // subagent's `.switch/agents/<name>.json` or a plain agent's- // `.switch/agents/<agentId>.json` — so a session polls as its own identity- // even when agents share a location. Fall back to the legacy subagent path,- // then the location's `.claude/settings.local.json`, for un-migrated installs- // (CHOO-1440).- const creds = agentName- ? ((await readSwitchAgentCredentialsFromSettings(- agentSettingsPath(rootPath, agentName),- log- )) ??- (await readSwitchAgentCredentialsFromSettings(- subagentSettingsPath(rootPath, agentName),- log- )))- : ((agentId- ? await readSwitchAgentCredentialsFromSettings(agentSettingsPath(rootPath, agentId), log)- : null) ?? (await readSwitchAgentCredentials(rootPath, log)));+ // Fall back to the legacy subagent path, then the location's+ // `.claude/settings.local.json`, for un-migrated installs (CHOO-1440).+ const creds =+ (await readSwitchAgentCredentialsFromSettings(agentSettingsPath(rootPath, slug), log)) ??+ (await readSwitchAgentCredentialsFromSettings(subagentSettingsPath(rootPath, slug), log)) ??+ (await readSwitchAgentCredentials(rootPath, log));if (!creds) {log.warn('SwitchNotificationPoller: missing Switch credentials (SWITCH_API_TOKEN/ENDPOINT/AGENT_ID) — cannot poll room',- { sessionId: ctx.sessionId, dir: rootPath, roomId, agentName }+ { sessionId: ctx.sessionId, dir: rootPath, roomId, slug });return;}diff --git a/dash/apps/switchdash-desktop/src/main/db/schema.ts b/dash/apps/switchdash-desktop/src/main/db/schema.tsindex 1446124f6..b984c5b6e 100644--- a/dash/apps/switchdash-desktop/src/main/db/schema.ts+++ b/dash/apps/switchdash-desktop/src/main/db/schema.ts@@ -145,15 +145,12 @@ export const agents = sqliteTable(locationId: text('location_id').notNull().references(() => locations.id),+ // The agent's single identity. For a provider that launches as a named+ // definition (Claude Code → `--agent <name>`) this is that name; how the+ // name is turned into a launch is the provider's business, not a column.+ // There is no separate definition name (CHOO-1440).name: text('name').notNull(),providerId: text('provider_id').$type<AgentProviderId>().notNull(),- // The provider-level agent definition this row launches as, when it is one- // (e.g. a Claude Code subagent: the `.claude/agents/<name>.md` stem, passed- // to the CLI as `--agent <name>`). Null for a plain agent that launches the- // provider CLI with no definition. This single field replaces the former- // separate "subagent" concept — a subagent is just an agent with a- // definitionName sharing its location with other agents (CHOO-1440).- definitionName: text('definition_name'),switchAgentId: text('switch_agent_id'),apiEndpoint: text('api_endpoint'),serverId: text('server_id').references(() => switchServers.id, { onDelete: 'set null' }),diff --git a/dash/apps/switchdash-desktop/src/main/db/tests/migrations/0041-delete-leaked-tagged-sessions.test.ts b/dash/apps/switchdash-desktop/src/main/db/tests/migrations/0041-delete-leaked-tagged-sessions.test.tsnew file mode 100644index 000000000..e75983a8f--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/db/tests/migrations/0041-delete-leaked-tagged-sessions.test.ts@@ -0,0 +1,127 @@+/**+ * Migration 0041 — collapses agent identity onto `agents.name` and deletes+ * leaked / misidentified sessions (CHOO-1440 follow-up).+ *+ * Step 1 backfills `name` from the authoritative `definition_name`. Step 2+ * deletes sessions whose frozen `config.agentName` (legacy `subagentName`) tag+ * disagrees with the owning agent's (now-authoritative) `name`; healthy and+ * untagged sessions survive.+ *+ * This migration reads `definition_name`, which the very next migration drops —+ * so it cannot be replayed against the final schema that `openFixture` builds.+ * The test instead stands up a minimal isolated schema carrying just the columns+ * the migration touches, and applies the committed SQL 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/0041_delete_leaked_tagged_sessions.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);+ }+}++describe('migration 0041: collapse to agents.name + delete diverged sessions', () => {+ let db: Database.Database;++ beforeEach(() => {+ db = new Database(':memory:');+ db.exec(`+ CREATE TABLE agents (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ definition_name TEXT+ );+ CREATE TABLE sessions (+ id TEXT PRIMARY KEY,+ agent_id TEXT NOT NULL,+ title TEXT NOT NULL,+ config TEXT+ );+ `);+ });++ afterEach(() => {+ db.close();+ });++ function seedAgent(id: string, name: string, definitionName: string | null): void {+ db.prepare(`INSERT INTO agents (id, name, definition_name) VALUES (?, ?, ?)`).run(+ id,+ name,+ definitionName+ );+ }++ function seedSession(id: string, agentId: string, config: Record<string, unknown> | null): void {+ db.prepare(`INSERT INTO sessions (id, agent_id, title, config) VALUES (?, ?, ?, ?)`).run(+ id,+ agentId,+ id,+ config === null ? null : JSON.stringify(config)+ );+ }++ function agentName(id: string): string {+ return (db.prepare(`SELECT name FROM agents WHERE id = ?`).get(id) as { name: string }).name;+ }++ function sessionIds(): string[] {+ return (db.prepare(`SELECT id FROM sessions ORDER BY id`).all() as { id: string }[]).map(+ (r) => r.id+ );+ }++ it('backfills name from definition_name and keeps only matching/untagged sessions', () => {+ // 'main' already agrees; 'orchestrator' has a stale name that must be+ // rewritten to its authoritative definition_name.+ seedAgent('main', 'main', 'main');+ seedAgent('orchestrator', 'stale-name', 'room-orchestrator');++ // Healthy: tag matches the agent's authoritative (post-backfill) name.+ seedSession('healthy', 'main', { agentName: 'main', autoApprove: true });+ seedSession('healthy-legacy-key', 'orchestrator', { subagentName: 'room-orchestrator' });++ // Broken: owned by 'main' but tagged as another agent. Deleted.+ seedSession('mis-assigned', 'main', { agentName: 'room-orchestrator' });+ // Ghost: tagged as a name no agent carries. Deleted.+ seedSession('ghost', 'main', { agentName: 'vanished-agent' });+ // Untagged: nothing to reconcile. Kept.+ seedSession('untagged', 'main', { autoApprove: false });+ seedSession('untagged-null-config', 'main', null);++ applyMigration(db);++ expect(agentName('main')).toBe('main');+ expect(agentName('orchestrator')).toBe('room-orchestrator');+ expect(sessionIds()).toEqual([+ 'healthy',+ 'healthy-legacy-key',+ 'untagged',+ 'untagged-null-config',+ ]);+ });++ it('leaves name untouched when definition_name is null', () => {+ seedAgent('plain', 'plain-name', null);+ seedSession('s', 'plain', null);++ applyMigration(db);++ expect(agentName('plain')).toBe('plain-name');+ expect(sessionIds()).toEqual(['s']);+ });+});diff --git a/dash/apps/switchdash-desktop/src/main/rpc.ts b/dash/apps/switchdash-desktop/src/main/rpc.tsindex 32145f0ad..773a49bb3 100644--- a/dash/apps/switchdash-desktop/src/main/rpc.ts+++ b/dash/apps/switchdash-desktop/src/main/rpc.ts@@ -15,6 +15,7 @@ import { searchController } from './core/search/controller';import { sessionController } from './core/sessions/controller';import { appSettingsController } from './core/settings/controller';import { providerSettingsController } from './core/settings/provider-settings-controller';+import { sidecarController } from './core/sidecar/controller';import { switchRoomsController } from './core/switch-rooms/controller';import { switchServersController } from './core/switch-servers/controller';import { switchSetupController } from './core/switch-setup/controller';@@ -42,6 +43,7 @@ export const rpcRouter = createRPCRouter({localSwitchServer: localSwitchServerController,remoteSwitchServer: remoteSwitchServerController,remoteHosts: remoteHostsController,+ sidecar: sidecarController,fs: createRPCNamespace({watch: filesController,}),diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/main-panel/active-location.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/main-panel/active-location.tsxindex 7ce8cccbd..8fd5236d0 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/main-panel/active-location.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/main-panel/active-location.tsx@@ -1,6 +1,7 @@import { observer } from 'mobx-react-lite';import { SessionList } from '@renderer/features/locations/components/session-view/session-list';import { SettingsPanel } from '@renderer/features/locations/components/settings-view/settings-panel';+import { SidecarPanel } from '@renderer/features/locations/components/settings-view/sidecar-panel';import {asMounted,getLocationStore,@@ -53,13 +54,20 @@ export const ActiveLocation = observer(function ActiveLocation() {if (!store) return null;+ // The sidecar is a remote-only concern — a local agent runs no on-host process.+ const isRemote = store.data.sshHost !== null;+const items: Array<{ id: LocationView; label: string }> = [{ id: 'sessions', label: 'Sessions' },{ id: 'settings', label: 'Settings' },+ ...(isRemote ? [{ id: 'sidecar' as const, label: 'Sidecar' }] : []),];- // 'subagents' is a retired view; fall back to Sessions if a stale view sticks.- const activeView = store.view.activeView === 'settings' ? 'settings' : 'sessions';+ // Resolve the active view, falling back to Sessions for a retired ('subagents')+ // or now-unavailable ('sidecar' on a local location) stored view.+ const stored = store.view.activeView;+ const activeView: LocationView =+ stored === 'settings' || (stored === 'sidecar' && isRemote) ? stored : 'sessions';return (<div className="flex h-full min-h-0 w-full flex-1 flex-col overflow-hidden">@@ -74,6 +82,7 @@ export const ActiveLocation = observer(function ActiveLocation() {<div className="mx-auto flex h-full min-h-0 w-full max-w-4xl flex-col px-1 py-10">{activeView === 'sessions' && <SessionList />}{activeView === 'settings' && <SettingsPanel />}+ {activeView === 'sidecar' && <SidecarPanel />}</div></div></div>diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/agent-definition-settings-section.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/agent-definition-settings-section.tsxindex 151ee8154..27e13abbc 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/agent-definition-settings-section.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/agent-definition-settings-section.tsx@@ -35,7 +35,7 @@ export function AgentDefinitionSettingsSection({});const agent = (agents ?? []).find((a) => a.id === agentId);const providerId = agent?.providerId ?? null;- const editable = !!agent && agent.definitionName != null;+ const editable = !!agent;const { data: allFields } = useQuery({queryKey: ['agentDefinitionFields', providerId],diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/sidecar-settings-section.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/sidecar-settings-section.tsxnew file mode 100644index 000000000..2b6466f90--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/sidecar-settings-section.tsx@@ -0,0 +1,232 @@+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';+import { AlertTriangle, CheckCircle2, Loader2, Power, RefreshCw, XCircle } from 'lucide-react';+import { useEffect, useState } from 'react';+import { events, rpc } from '@renderer/lib/ipc';+import { Badge } from '@renderer/lib/ui/badge';+import { Button } from '@renderer/lib/ui/button';+import { Field, FieldDescription, FieldTitle } from '@renderer/lib/ui/field';+import { log } from '@renderer/utils/logger';+import type { AgentSidecarStatus, SidecarVerdict } from '@shared/events/sidecarEvents';+import { sidecarStatusChannel } from '@shared/events/sidecarEvents';++/**+ * Per-agent remote sidecar status + lifecycle controls.+ *+ * The sidecar is the on-VM process that keeps a remote agent connected to its+ * Switch rooms while switchdash is closed. It is deployed and upgraded silently+ * on connect; this section makes that state visible — which build the host runs+ * vs. which this client ships — and lets the operator update, restart, or stop it+ * by hand. Rendered only for remote agents (a local agent has no sidecar).+ */++const SHORT_HASH = 7;++const statusQueryKey = (agentId: string): string[] => ['sidecar-status', agentId];++function shortHash(hash: string | null): string {+ return hash ? hash.slice(0, SHORT_HASH) : '—';+}++const VERDICT_DISPLAY: Record<+ SidecarVerdict,+ {+ label: string;+ variant: 'default' | 'secondary' | 'destructive' | 'outline';+ icon: typeof CheckCircle2;+ }+> = {+ 'up-to-date': { label: 'Up to date', variant: 'secondary', icon: CheckCircle2 },+ 'upgrade-available': { label: 'Update available', variant: 'default', icon: RefreshCw },+ 'upgrade-pending': { label: 'Update pending', variant: 'outline', icon: AlertTriangle },+ incompatible: { label: 'Incompatible', variant: 'destructive', icon: AlertTriangle },+ 'not-running': { label: 'Not running', variant: 'outline', icon: XCircle },+};++export function SidecarSettingsSection({ agentId }: { agentId: string }) {+ const queryClient = useQueryClient();+ const queryKey = statusQueryKey(agentId);++ const { data, isLoading, isError, refetch } = useQuery({+ queryKey,+ queryFn: () => rpc.sidecar.getStatus(agentId),+ });++ // Live refresh: the controller broadcasts on every probe/upgrade/restart/stop,+ // so seed the cache from the event stream instead of polling.+ useEffect(() => {+ return events.on(sidecarStatusChannel, (status: AgentSidecarStatus) => {+ if (status.agentId === agentId) queryClient.setQueryData(statusQueryKey(agentId), status);+ });+ }, [agentId, queryClient]);++ const actionOptions = {+ onError: (error: unknown) => log.error('sidecar action failed', { agentId, error }),+ onSettled: () => void queryClient.invalidateQueries({ queryKey }),+ };+ const upgrade = useMutation({ mutationFn: () => rpc.sidecar.upgrade(agentId), ...actionOptions });+ const restart = useMutation({ mutationFn: () => rpc.sidecar.restart(agentId), ...actionOptions });+ const stop = useMutation({ mutationFn: () => rpc.sidecar.stop(agentId), ...actionOptions });+ const busy = upgrade.isPending || restart.isPending || stop.isPending;++ return (+ <Field>+ <div className="flex items-center justify-between gap-3">+ <FieldTitle>Remote sidecar</FieldTitle>+ {data && <VerdictBadge verdict={data.verdict} />}+ </div>+ <FieldDescription className="text-foreground-muted">+ The on-host process that keeps this agent connected to its Switch rooms while switchdash is+ closed. Updated automatically when switchdash connects; you can also manage it here.+ </FieldDescription>++ {isLoading && (+ <div className="flex items-center gap-2 text-sm text-foreground-muted">+ <Loader2 className="size-3.5 animate-spin" /> Checking sidecar…+ </div>+ )}++ {isError && (+ <div className="flex items-center justify-between gap-2 rounded-md border border-border px-3 py-2 text-sm">+ <span className="text-foreground-muted">+ Couldn't reach the host to check the sidecar.+ </span>+ <Button size="sm" variant="outline" onClick={() => void refetch()}>+ <RefreshCw className="size-3.5" /> Retry+ </Button>+ </div>+ )}++ {data && (+ <div className="flex flex-col gap-3">+ <VersionRows status={data} />++ <div className="flex flex-wrap items-center gap-2">+ <Button+ size="sm"+ variant="outline"+ disabled={busy || data.verdict === 'up-to-date' || data.verdict === 'incompatible'}+ onClick={() => upgrade.mutate()}+ >+ {upgrade.isPending ? (+ <Loader2 className="size-3.5 animate-spin" />+ ) : (+ <RefreshCw className="size-3.5" />+ )}+ Update+ </Button>+ <Button size="sm" variant="outline" disabled={busy} onClick={() => restart.mutate()}>+ {restart.isPending ? (+ <Loader2 className="size-3.5 animate-spin" />+ ) : (+ <RefreshCw className="size-3.5" />+ )}+ {data.verdict === 'incompatible' ? 'Replace' : 'Restart'}+ </Button>+ <Button+ size="sm"+ variant="outline"+ disabled={busy || !data.running}+ onClick={() => stop.mutate()}+ >+ {stop.isPending ? (+ <Loader2 className="size-3.5 animate-spin" />+ ) : (+ <Power className="size-3.5" />+ )}+ Stop+ </Button>+ </div>++ {data.verdict === 'upgrade-pending' && (+ <p className="text-xs text-foreground-muted">+ An update is ready but held back because {data.liveSessions} session+ {data.liveSessions === 1 ? '' : 's'} {data.liveSessions === 1 ? 'is' : 'are'} running.+ It applies next time the sidecar is idle — or use Restart to apply it now (running+ sessions reconnect automatically).+ </p>+ )}++ <SidecarLog agentId={agentId} />+ </div>+ )}+ </Field>+ );+}++function VerdictBadge({ verdict }: { verdict: SidecarVerdict }) {+ const { label, variant, icon: Icon } = VERDICT_DISPLAY[verdict];+ return (+ <Badge variant={variant}>+ <Icon className="size-3" /> {label}+ </Badge>+ );+}++function VersionRows({ status }: { status: AgentSidecarStatus }) {+ return (+ <dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-sm">+ <Row+ label="This client ships"+ value={`${status.clientVersion}+${shortHash(status.clientHash)}`}+ />+ <Row+ label="Host running"+ value={+ status.running+ ? `${status.deployedVersion ?? '?'}+${shortHash(status.deployedHash)}` ++ (status.epoch !== null ? ` · restart #${status.epoch}` : '') ++ (status.pid !== null ? ` · pid ${status.pid}` : '')+ : 'not running'+ }+ />+ <Row label="Live sessions" value={String(status.liveSessions)} />+ <Row label="Host" value={status.sshHost} />+ <Row label="Working dir" value={status.repoDir} mono />+ </dl>+ );+}++function Row({ label, value, mono }: { label: string; value: string; mono?: boolean }) {+ return (+ <>+ <dt className="text-foreground-muted">{label}</dt>+ <dd className={mono ? 'truncate font-mono text-xs' : 'truncate'}>{value}</dd>+ </>+ );+}++function SidecarLog({ agentId }: { agentId: string }) {+ const [open, setOpen] = useState(false);+ const { data, isFetching, refetch } = useQuery({+ queryKey: ['sidecar-log', agentId],+ queryFn: () => rpc.sidecar.logTail(agentId),+ enabled: open,+ });++ if (!open) {+ return (+ <Button size="xs" variant="ghost" className="self-start" onClick={() => setOpen(true)}>+ Show recent log+ </Button>+ );+ }++ return (+ <div className="flex flex-col gap-1">+ <div className="flex items-center justify-between">+ <span className="text-xs text-foreground-muted">Recent sidecar log</span>+ <Button size="xs" variant="ghost" disabled={isFetching} onClick={() => void refetch()}>+ {isFetching ? (+ <Loader2 className="size-3 animate-spin" />+ ) : (+ <RefreshCw className="size-3" />+ )}+ Refresh+ </Button>+ </div>+ <pre className="h-48 max-h-[80vh] min-h-24 resize-y overflow-auto rounded-md border border-border bg-background-2 p-2 text-xs whitespace-pre-wrap">+ {data ? data : 'No log output.'}+ </pre>+ </div>+ );+}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/settings-panel.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/settings-panel.tsxindex d4b055695..48690f463 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/settings-panel.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/settings-panel.tsx@@ -34,9 +34,7 @@ export const SettingsPanel = observer(function SettingsPanel() {);}- const agent = agentName- ? (agents ?? []).find((a) => a.definitionName === agentName)- : (agents ?? [])[0];+ const agent = agentName ? (agents ?? []).find((a) => a.name === agentName) : (agents ?? [])[0];const agentId = agent?.id;return (diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sidecar-panel.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sidecar-panel.tsxnew file mode 100644index 000000000..2ae196842--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sidecar-panel.tsx@@ -0,0 +1,44 @@+import { useQuery } from '@tanstack/react-query';+import { observer } from 'mobx-react-lite';+import { SidecarSettingsSection } from '@renderer/features/locations/components/settings-view/sections/sidecar-settings-section';+import { rpc } from '@renderer/lib/ipc';+import { useParams } from '@renderer/lib/layout/navigation-provider';+import { Spinner } from '@renderer/lib/ui/spinner';++/**+ * The "Sidecar" tab for a remote location: the on-host process that keeps this+ * agent connected to Switch while switchdash is closed. Scoped to the same agent+ * the Settings tab resolves (by definition name, else the first). Only shown for+ * remote locations — `ActiveLocation` gates the tab — so this just resolves the+ * agent and hands off to the section.+ */+export const SidecarPanel = observer(function SidecarPanel() {+ const {+ params: { locationId, agentName },+ } = useParams('location');++ const { data: agents, isLoading } = useQuery({+ queryKey: ['location-agents', locationId],+ queryFn: () => rpc.agents.getAgents(locationId),+ });++ if (isLoading) {+ return (+ <div className="flex items-center justify-center py-10">+ <Spinner />+ </div>+ );+ }++ const agent = agentName ? (agents ?? []).find((a) => a.name === agentName) : (agents ?? [])[0];++ if (!agent) {+ return <p className="py-10 text-sm text-foreground-muted">No agent found for this location.</p>;+ }++ return (+ <div className="flex flex-col gap-6">+ <SidecarSettingsSection agentId={agent.id} />+ </div>+ );+});diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/location-manager.test.ts b/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/location-manager.test.tsindex cac4b4d0b..42c398958 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/location-manager.test.ts+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/location-manager.test.ts@@ -67,7 +67,6 @@ function agent(overrides: Partial<Agent> = {}): Agent {locationId: 'location-id',name: 'Agent',providerId: 'claude',- definitionName: null,switchAgentId: 'sw-1',apiEndpoint: 'https://switch.example.com',serverId: 'server-1',diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/location-view.ts b/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/location-view.tsindex 53aa38b59..972a6d2d3 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/location-view.ts+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/location-view.ts@@ -2,7 +2,7 @@ import { makeAutoObservable } from 'mobx';import type { Snapshottable } from '@renderer/lib/stores/snapshottable';import type { LocationViewSnapshot } from '@shared/view-state';-export type LocationView = 'sessions' | 'subagents' | 'settings';+export type LocationView = 'sessions' | 'subagents' | 'settings' | 'sidecar';export class LocationViewStore implements Snapshottable<LocationViewSnapshot> {activeView: LocationView = 'sessions';diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/create-session-modal/create-session-modal.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sessions/create-session-modal/create-session-modal.tsxindex 0f20a7ae7..dd33c8180 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/create-session-modal/create-session-modal.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/create-session-modal/create-session-modal.tsx@@ -37,7 +37,6 @@ import {import { Textarea } from '@renderer/lib/ui/textarea';import { log } from '@renderer/utils/logger';import { cn } from '@renderer/utils/utils';-import { representativeAgent } from '@shared/core/agents/agents';import type { RemoteAgentRoom } from '@shared/core/switch-servers/switch-servers';import { buildConnectPrompt } from './build-connect-prompt';@@ -97,14 +96,12 @@ export const CreateSessionModal = observer(function CreateSessionModal({enabled: !!selectedLocationId,});const locationAgents = agentsQuery.data ?? [];- const agent = representativeAgent(locationAgents) ?? null;+ const agent = locationAgents[0] ?? null;- // When launching as a subagent, the session joins rooms under the subagent's- // own Switch identity — its own agent row (a definitionName agent) — so the- // room picker uses the subagent's id/server, not the parent agent's (CHOO-1440).- const subagent = agentName- ? (locationAgents.find((a) => a.definitionName === agentName) ?? null)- : null;+ // When a specific agent is named, the session joins rooms under that agent's+ // own Switch identity — its own agent row — so the room picker uses that+ // agent's id/server, matched by name (CHOO-1440).+ const subagent = agentName ? (locationAgents.find((a) => a.name === agentName) ?? null) : null;const serverId = agentName ? (subagent?.serverId ?? null) : (agent?.serverId ?? null);const switchAgentId = agentName@@ -147,10 +144,19 @@ export const CreateSessionModal = observer(function CreateSessionModal({const initialPrompt = buildConnectPrompt(room?.roomName ?? null, chosenRole, prompt);void (async () => {- const resolvedAgent =- agent ?? representativeAgent(await rpc.agents.getAgents(selectedLocationId));+ const freshAgents = await rpc.agents.getAgents(selectedLocationId);+ // A named session must be OWNED by that agent's own row — identity flows+ // from `session.agent_id → agents.name`, so the session is+ // invisible/misidentified if it points at a different agent. Resolve the+ // row by name here; error out rather than silently fall back (CHOO-1440).+ const resolvedAgent = agentName+ ? (subagent ?? freshAgents.find((a) => a.name === agentName) ?? null)+ : (agent ?? freshAgents[0]);if (!resolvedAgent) {- log.error('spawn session failed: location has no agents', selectedLocationId);+ log.error('spawn session failed: no agent for location/subagent', {+ locationId: selectedLocationId,+ agentName,+ });return;}// createSession registers the session synchronously (before its firstdiff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/agent-item.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/agent-item.tsxindex b6cef47d2..fee67e138 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/agent-item.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/agent-item.tsx@@ -67,7 +67,7 @@ export const SidebarAgentItem = observer(function SidebarAgentItem({const confirmDeleteAgent = useConfirmDeleteAgent();const { toastPromise } = useToast();- const agentName = agent.definitionName ?? undefined;+ const agentName = agent.name;const location = getLocationStore(agent.locationId);// The row is labelled by the agent's registered Switch name; fall back to thediff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsxindex 76d35ff31..f22aa87a3 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx@@ -19,11 +19,6 @@ import {} from './sidebar-room-grouping';import { agentRoomGroupKey, roomViewGroupKey, UNASSIGNED_ROOM_KEY } from './sidebar-store';-/** The provider definition a session was launched as, if any. */-function sessionDefinitionName(session: SessionStore): string | undefined {- return 'agentName' in session.data ? session.data.agentName : undefined;-}-/** An agent paired with its (mounted) location, for the flat sidebar list. */type AgentEntry = { agent: Agent; location: LocationStore };@@ -44,14 +39,18 @@ function scopedAgents(): AgentEntry[] {);}-/** An agent's visible sessions: its location's sessions launched as its definition. */+/**+ * An agent's visible sessions: the location's sessions it owns. Sessions are+ * paired to their agent by `agent_id` — the authoritative link — not by matching+ * a name frozen into the session's config against the agent's definition. A+ * session whose owning agent no longer matches by name is still shown under its+ * agent instead of silently vanishing (CHOO-1440).+ */function agentSessions(entry: AgentEntry): SessionStore[] {const all = sidebarStore.visibleSessionsForLocation(entry.location.id);- const def = entry.agent.definitionName;- return all.filter((session) => {- const name = sessionDefinitionName(session);- return def == null ? !name : name === def;- });+ return all.filter(+ (session) => 'agentId' in session.data && session.data.agentId === entry.agent.id+ );}export const SidebarGroupedList = observer(function SidebarGroupedList() {diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-store.ts b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-store.tsindex d362fae5f..e8dc31d34 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-store.ts+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-store.ts@@ -11,7 +11,6 @@ import {import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';import type { Snapshottable } from '@renderer/lib/stores/snapshottable';import type { AgentConnectionKind } from '@shared/core/agents/agent-connection';-import { representativeAgent } from '@shared/core/agents/agents';import {AGENT_PROVIDER_IDS,isValidProviderId,@@ -210,7 +209,7 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {/** The representative agent of a location (the agent shown on its sidebar row):* the first real (non-definition) agent, not a former subagent's row. */private parentAgent(locationId: string) {- return representativeAgent(agentsStore.byLocation.get(locationId) ?? []);+ return (agentsStore.byLocation.get(locationId) ?? [])[0];}/** Where a location runs — `remote` when it has an SSH host, else `local`. */diff --git a/dash/apps/switchdash-desktop/src/shared/core/agents/agents.ts b/dash/apps/switchdash-desktop/src/shared/core/agents/agents.tsindex bae321a39..63d980a2c 100644--- a/dash/apps/switchdash-desktop/src/shared/core/agents/agents.ts+++ b/dash/apps/switchdash-desktop/src/shared/core/agents/agents.ts@@ -12,12 +12,11 @@ import type { AgentProviderId } from '@shared/core/providers/agent-provider-regiexport type Agent = {id: string;locationId: string;+ /** The agent's single identity. For a provider that launches as a named+ * definition (Claude Code → `--agent <name>`) this is that name; turning the+ * name into a launch is the provider's business (CHOO-1440). */name: string;providerId: AgentProviderId;- /** The provider-level definition this agent launches as (e.g. a Claude Code- * subagent — the `.claude/agents/<name>.md` stem, passed as `--agent <name>`),- * or null for a plain agent with no definition. */- definitionName: string | null;switchAgentId: string | null;apiEndpoint: string | null;serverId: string | null;@@ -30,31 +29,11 @@ export type Agent = {updatedAt: string;};-/** True for an agent that launches as a provider definition (a former subagent). */-export function isDefinitionAgent(agent: Pick<Agent, 'definitionName'>): boolean {- return agent.definitionName != null;-}--/**- * The agent that represents a location in single-agent UI surfaces (the sidebar- * location row, a location's settings target): the first non-definition ("real")- * agent, falling back to the first agent. Keeps a former subagent's agent row- * from being mistaken for the location's primary agent (CHOO-1440).- */-export function representativeAgent<T extends Pick<Agent, 'definitionName'>>(- agents: readonly T[]-): T | undefined {- return agents.find((a) => a.definitionName == null) ?? agents[0];-}-export type CreateAgentParams = {id: string;locationId: string;name: string;providerId: AgentProviderId;- /** The provider-level definition to launch as (`--agent <name>`), or null for- * a plain agent. */- definitionName?: string | null;switchAgentId: string | null;apiEndpoint: string | null;/** The Switch server this agent belongs to. Every agent must have one — it isdiff --git a/dash/apps/switchdash-desktop/src/shared/core/pty/hookEnv.ts b/dash/apps/switchdash-desktop/src/shared/core/pty/hookEnv.tsnew file mode 100644index 000000000..3810d091b--- /dev/null+++ b/dash/apps/switchdash-desktop/src/shared/core/pty/hookEnv.ts@@ -0,0 +1,35 @@+export interface AgentHookEnv {+ port: number;+ ptyId: string;+ token: string;+ /**+ * Absolute path to the sidecar's endpoint file, when the session is served by+ * one. The generated hook command prefers the port/token in this file over the+ * baked env, so a pane keeps reaching its sidecar after that sidecar restarts+ * on a fresh port with a fresh token. Omitted for local sessions, whose hook+ * server dies with the app anyway.+ */+ endpointFile?: string;+}++/**+ * Environment that points an agent CLI's lifecycle hooks at a switchdash hook+ * server (the local one for local sessions, the on-VM sidecar for remote ones)+ * and stands the in-session Switch connector's own poll loop down so it does+ * not race switchdash's poller on the bridge's destructive event queue.+ *+ * Lives here rather than beside the PTY env allowlist so the remote sidecar —+ * which must bundle free of Electron and the database — shares this wiring+ * instead of re-inlining it. Every consumer of the hook protocol goes through+ * this one function: `buildAgentEnv` (local), the SSH agent runtime (remote,+ * UI-started), and the sidecar's own spawner (remote, auto-started).+ */+export function buildAgentHookEnv(hook: AgentHookEnv): Record<string, string> {+ return {+ SWITCHDASH_HOOK_PORT: String(hook.port),+ SWITCHDASH_PTY_ID: hook.ptyId,+ SWITCHDASH_HOOK_TOKEN: hook.token,+ SWITCH_CHANNEL_DISABLE_POLL: '1',+ ...(hook.endpointFile ? { SWITCHDASH_HOOK_ENDPOINT_FILE: hook.endpointFile } : {}),+ };+}diff --git a/dash/apps/switchdash-desktop/src/shared/core/sessions/session-config.ts b/dash/apps/switchdash-desktop/src/shared/core/sessions/session-config.tsindex 0919a1a45..90859b0a5 100644--- a/dash/apps/switchdash-desktop/src/shared/core/sessions/session-config.ts+++ b/dash/apps/switchdash-desktop/src/shared/core/sessions/session-config.ts@@ -13,19 +13,6 @@ const sessionConfigV0Schema = z.object({providerSessionId: z.string().optional(),/** Initial prompt to deliver on the first spawn; cleared from config after the session starts. */initialPrompt: z.string().optional(),- /**- * When set, this session runs as the repository-defined agent of this name: the- * provider launches its CLI to run as that agent (Claude Code → `--agent <name>`)- * with the agent's own Switch credentials, so it joins rooms under that identity.- * The value is the agent's definition name (its `.switch/agents/<name>.json`- * credentials key). switchdash has no "subagent" concept — how the provider runs- * a named agent is the provider's business (CHOO-1440).- */- agentName: z.string().optional(),- /** Legacy key for {@link agentName}, kept so sessions persisted before the- * rename still resolve their identity after an upgrade; coalesced into- * `agentName` when read (CHOO-1440). */- subagentName: z.string().optional(),});export const sessionConfig = defineVersionedSchema().unversioned(sessionConfigV0Schema).build();diff --git a/dash/apps/switchdash-desktop/src/shared/events/sidecarEvents.ts b/dash/apps/switchdash-desktop/src/shared/events/sidecarEvents.tsnew file mode 100644index 000000000..77cea3d93--- /dev/null+++ b/dash/apps/switchdash-desktop/src/shared/events/sidecarEvents.ts@@ -0,0 +1,46 @@+import { defineEvent } from '@shared/lib/ipc/events';++/**+ * The client-vs-host relationship for one agent's remote sidecar. Derived from+ * comparing what this client ships against what the host reports running.+ *+ * - `not-running` — no sidecar is up on the host.+ * - `up-to-date` — the host runs this client's exact build.+ * - `upgrade-available` — a different build is running and can be replaced now+ * (the sidecar is idle).+ * - `upgrade-pending` — a different build is running but has live sessions, so+ * the upgrade is deferred until it is idle rather than interrupting work.+ * - `incompatible` — the host runs a protocol this client cannot speak; it must+ * be replaced before this client can use it.+ */+export type SidecarVerdict =+ | 'not-running'+ | 'up-to-date'+ | 'upgrade-available'+ | 'upgrade-pending'+ | 'incompatible';++/** Full per-agent sidecar status for the UI. */+export interface AgentSidecarStatus {+ agentId: string;+ running: boolean;+ verdict: SidecarVerdict;+ /** What this client ships. `version` is the human-readable `x.y`; `hash` is the+ * exact build fingerprint (what actually decides "is an upgrade available"). */+ clientHash: string;+ clientVersion: string;+ /** What the host reports running (null when nothing is up). */+ deployedHash: string | null;+ deployedVersion: string | null;+ epoch: number | null;+ pid: number | null;+ liveSessions: number;+ /** Where it lives on the host. */+ repoDir: string;+ sshHost: string;+ credsSlug: string;+}++/** Pushed after any sidecar status change (probe, upgrade, restart, stop) so the+ * per-agent page updates live instead of polling. */+export const sidecarStatusChannel = defineEvent<AgentSidecarStatus>('remote-sidecar:status');diff --git a/dash/apps/switchdash-desktop/src/shared/lib/versioned-schema/versioned-schema.ts b/dash/apps/switchdash-desktop/src/shared/lib/versioned-schema/versioned-schema.tsindex a28c7d468..42916bc46 100644--- a/dash/apps/switchdash-desktop/src/shared/lib/versioned-schema/versioned-schema.ts+++ b/dash/apps/switchdash-desktop/src/shared/lib/versioned-schema/versioned-schema.ts@@ -136,7 +136,7 @@ export class VersionedSchema<TLatest> {// In dev: validate the stored data against its declared schema to catch drift.// In production: trust the data was valid when written, skip validation for performance.let current: unknown = data;- if (import.meta.env.DEV) {+ if (import.meta.env?.DEV) {const parsed = entry.schema.safeParse(data);if (!parsed.success) {return {@@ -178,7 +178,7 @@ export class VersionedSchema<TLatest> {return { status: 'needs-context', version: resolvedVersion, raw: data };}- if (import.meta.env.DEV) {+ if (import.meta.env?.DEV) {const check = nextEntry.schema.safeParse(upgraded);if (!check.success) {return {diff --git a/dash/apps/switchdash-desktop/src/sidecar/atomic-file.ts b/dash/apps/switchdash-desktop/src/sidecar/atomic-file.tsnew file mode 100644index 000000000..9c69cbf88--- /dev/null+++ b/dash/apps/switchdash-desktop/src/sidecar/atomic-file.ts@@ -0,0 +1,16 @@+import { rename, writeFile } from 'node:fs/promises';++/**+ * Write a file so concurrent readers only ever observe the old bytes or the new+ * ones, never a torn mix. `rename(2)` is atomic within a filesystem, and the+ * temp file is created alongside the target to stay on the same one.+ *+ * The sidecar's endpoint and state files are read by other processes (hooks+ * firing at arbitrary times, other clients polling) while it rewrites them, so+ * a plain truncate-and-write would hand out empty or half-written content.+ */+export async function atomicWriteFile(absPath: string, content: string): Promise<void> {+ const tmp = `${absPath}.${process.pid}.tmp`;+ await writeFile(tmp, content, 'utf8');+ await rename(tmp, absPath);+}diff --git a/dash/apps/switchdash-desktop/src/sidecar/index.ts b/dash/apps/switchdash-desktop/src/sidecar/index.tsindex 6d469b4dd..053955be6 100644--- a/dash/apps/switchdash-desktop/src/sidecar/index.ts+++ b/dash/apps/switchdash-desktop/src/sidecar/index.ts@@ -1,6 +1,8 @@import { execFile } from 'node:child_process';-import { readFile } from 'node:fs/promises';+import { createHash } from 'node:crypto';+import { mkdir, readFile } from 'node:fs/promises';import path from 'node:path';+import { fileURLToPath } from 'node:url';import { promisify } from 'node:util';import { HookEventLog, HookServer } from '@main/core/agent-hooks/hook-server';import { agentSettingsPath } from '@main/core/agents/switch-settings-paths';@@ -10,16 +12,21 @@ import {} from '@main/core/switch-rooms/switch-credentials';import { createTmuxRun } from '@main/core/switch-rooms/tmux-injection-sink';import { type AgentLaunchSpec } from './agent-launch-spec';-import { NotificationWatcher } from './notification-watcher';+import { atomicWriteFile } from './atomic-file';+import { NotificationWatcher, type WatcherLogger } from './notification-watcher';import { InProcessSessionSpawner } from './session-spawner';import { createSidecarLogger, requireEnv } from './sidecar-logger';import {LEGACY_LAUNCH_SPEC_REL_PATH,LEGACY_WATCH_ENABLED_REL_PATH,+ sidecarEndpointRelPath,sidecarLaunchSpecRelPath,+ sidecarReadyRelPath,sidecarWatchEnabledRelPath,} from './sidecar-paths';import { defaultRoomConnectionFactory, SidecarRuntime } from './sidecar-runtime';+import { SidecarStateStore } from './sidecar-state';+import { SIDECAR_VERSION } from './sidecar-version';import { exactTmuxTarget, parseAgentTmuxSessionName } from './vm-tmux';/**@@ -51,6 +58,26 @@ const PANE_POLL_INTERVAL_MS = 2000;const execFileAsync = promisify(execFile);+/**+ * sha256 of the bundle file this process was actually loaded from.+ *+ * Deriving it here rather than trusting the launcher's env closes the window+ * where a concurrent deploy replaces the bundle between the launcher hashing it+ * and node reading it — after which the sidecar would advertise one build while+ * running another, and every client would happily reattach to it forever.+ */+async function hashOwnBundle(log: WatcherLogger): Promise<string | null> {+ try {+ const self = fileURLToPath(import.meta.url);+ return createHash('sha256')+ .update(await readFile(self))+ .digest('hex');+ } catch (error) {+ log.warn('sidecar: could not hash own bundle', { error: String(error) });+ return null;+ }+}+async function readLaunchSpec(repoDir: string, specRelPath: string): Promise<AgentLaunchSpec> {const specPath = path.join(repoDir, specRelPath);let raw: string;@@ -126,6 +153,16 @@ async function main(): Promise<void> {}};+ // Durable session registry. Restored entries whose pane is gone are dropped+ // here, so what survives is what is actually still running on the host.+ const stateSlug = credsSlug ?? 'default';+ const store = await SidecarStateStore.open({+ repoDir,+ slug: stateSlug,+ isPaneAlive: hasSession,+ log,+ });+const runtime = new SidecarRuntime({creds,deeplinkScheme,@@ -133,8 +170,23 @@ async function main(): Promise<void> {isPaneLive,log,createConnection: defaultRoomConnectionFactory,+ registry: store,});+ // Bring each restored session's room connection back up. The agent is still+ // sitting in its pane and still a member of the room server-side; only our+ // poll + injection loop died with the previous process, and an idle agent+ // would never post the hook that would otherwise rebuild it.+ for (const entry of store.entries()) {+ if (!entry.roomId) continue;+ liveTargets.add(entry.tmuxTarget); // seed, so injection is not deferred pre-poll+ runtime.restoreSession({+ sessionId: entry.sessionId,+ roomId: entry.roomId,+ providerId: entry.providerId,+ });+ }+// Every raw hook the agents post is buffered so switchdash can replay it// through its own hook path (room/status/session) while the UI is attached;// the sidecar still handles it VM-locally for injection regardless.@@ -144,7 +196,7 @@ async function main(): Promise<void> {let spawner: InProcessSessionSpawner | null = null;let watcher: NotificationWatcher | null = null;- const eventLog = new HookEventLog();+ const eventLog = new HookEventLog(undefined, store.epoch);const server = new HookServer(log);await server.start(async (raw) => {@@ -166,9 +218,12 @@ async function main(): Promise<void> {// Every live agent pane THIS sidecar owns, room or not — so bare sessions// are discoverable. Scope by hasSeen: tmux names carry no repo/agent, so// the VM-wide enumeration must be filtered to this sidecar's sessions.+ // That ownership is durable, so a pane restored across a restart is+ // reported immediately rather than only once its agent next speaks —+ // otherwise clients read the gap as "deleted" and prune a live session.for (const sessionId of await listAgentSessionIds()) {if (runtime.hasSeen(sessionId) && !byId.has(sessionId)) {- byId.set(sessionId, null);+ byId.set(sessionId, store.roomIdFor(sessionId));}}// Room-attending / watcher-spawned sessions overwrite with their room id.@@ -203,10 +258,19 @@ async function main(): Promise<void> {});+ // Publish the live endpoint before anything can be spawned against it. Panes+ // resolve the port/token from this file at hook time rather than from the env+ // they were launched with, so sessions started by a previous incarnation of+ // this sidecar keep reaching us across a restart, upgrade, or token rotation.+ const endpointFile = path.join(repoDir, sidecarEndpointRelPath(credsSlug ?? 'default'));+ await mkdir(path.dirname(endpointFile), { recursive: true });+ await atomicWriteFile(endpointFile, `${server.getPort()}\n${server.getToken()}\n`);+spawner = new InProcessSessionSpawner({spec: launchSpec,hookPort: server.getPort(),hookToken: server.getToken(),+ endpointFile,runtime,switchEnv: {SWITCH_API_ENDPOINT: creds.apiEndpoint,@@ -284,24 +348,35 @@ async function main(): Promise<void> {void refresh();const paneTimer = setInterval(() => void refresh(), PANE_POLL_INTERVAL_MS);- // Echo the bundle hash switchdash launched us with so it can tell, on reattach,- // whether this running process is the current bundle or a stale one to replace.- const bundleHash = process.env.SWITCHDASH_SIDECAR_BUNDLE_HASH?.trim() || undefined;- process.stdout.write(- `${JSON.stringify({- event: 'ready',- port: server.getPort(),- token: server.getToken(),- hash: bundleHash,- })}\n`- );+ // Hash our OWN bytes rather than echoing the hash we were launched with: the+ // launcher can skip an upload it believes is redundant and be wrong, and a+ // sidecar that advertises a build it is not running is undetectable.+ const bundleHash = await hashOwnBundle(log);+ const readyLine = `${JSON.stringify({+ event: 'ready',+ port: server.getPort(),+ token: server.getToken(),+ hash: bundleHash,+ version: SIDECAR_VERSION,+ epoch: store.epoch,+ pid: process.pid,+ })}\n`;+ // Write the ready file ourselves, atomically, instead of letting the shell+ // truncate it on redirect. It is the only record of the running sidecar's+ // endpoint, so a reader arriving mid-startup must see the previous complete+ // line or the new one — never an empty file, which reads as "no sidecar" and+ // sends that client off to kill and relaunch a healthy process.+ await atomicWriteFile(path.join(repoDir, sidecarReadyRelPath(stateSlug)), readyLine);+ process.stdout.write(readyLine);const shutdown = (): void => {clearInterval(paneTimer);watcher?.stop();runtime.stop();server.stop();- process.exit(0);+ // Flush any debounced state change before exiting, so a clean restart (the+ // upgrade path) resumes from the sessions we actually had.+ void store.close().finally(() => process.exit(0));};process.on('SIGTERM', shutdown);process.on('SIGINT', shutdown);diff --git a/dash/apps/switchdash-desktop/src/sidecar/session-spawner.ts b/dash/apps/switchdash-desktop/src/sidecar/session-spawner.tsindex 32a9a519e..8a08dd1bc 100644--- a/dash/apps/switchdash-desktop/src/sidecar/session-spawner.ts+++ b/dash/apps/switchdash-desktop/src/sidecar/session-spawner.ts@@ -2,6 +2,7 @@ import { execFile } from 'node:child_process';import { randomUUID } from 'node:crypto';import { promisify } from 'node:util';import { quoteShellArg } from '@main/utils/shellEscape';+import { buildAgentHookEnv } from '@shared/core/pty/hookEnv';import { makePtyId } from '@shared/core/pty/ptyId';import { type AgentLaunchSpec, materializeAgentCommand } from './agent-launch-spec';import type { SessionSpawner, WatcherLogger } from './notification-watcher';@@ -19,6 +20,10 @@ export interface InProcessSessionSpawnerDeps {/** The local sidecar hook server the spawned session's hooks post back to. */hookPort: number;hookToken: string;+ /** Absolute path to the endpoint file carrying the CURRENT port/token. Hooks+ * prefer it over the baked env, so the pane follows this sidecar across a+ * restart instead of posting to the port it happened to hold at launch. */+ endpointFile: string;/** The multi-session runtime — a room it already serves needs no new session. */runtime: RoomLivenessSource;/** The agent's Switch identity as `SWITCH_*` env, injected into every@@ -123,17 +128,19 @@ export class InProcessSessionSpawner implements SessionSpawner {}async launch(roomId: string): Promise<void> {- const { hookPort, hookToken, log } = this.deps;+ const { hookPort, hookToken, endpointFile, log } = this.deps;const spec = this.spec;const sessionId = randomUUID();const tmuxTarget = makeAgentTmuxSessionName(sessionId);const hookEnv = {...this.deps.switchEnv,- SWITCHDASH_HOOK_PORT: String(hookPort),- SWITCHDASH_PTY_ID: makePtyId(spec.providerId, sessionId),- SWITCHDASH_HOOK_TOKEN: hookToken,- SWITCH_CHANNEL_DISABLE_POLL: '1',+ ...buildAgentHookEnv({+ port: hookPort,+ ptyId: makePtyId(spec.providerId, sessionId),+ token: hookToken,+ endpointFile,+ }),};const command = materializeAgentCommand(spec, {sessionId,diff --git a/dash/apps/switchdash-desktop/src/sidecar/sidecar-paths.ts b/dash/apps/switchdash-desktop/src/sidecar/sidecar-paths.tsindex 5e2f2b3e0..cd40d1326 100644--- a/dash/apps/switchdash-desktop/src/sidecar/sidecar-paths.ts+++ b/dash/apps/switchdash-desktop/src/sidecar/sidecar-paths.ts@@ -12,9 +12,16 @@export const SIDECAR_DIR = '.switchdash';-/** Shared sidecar bundle + its hash (identical for every agent in the dir). */+/**+ * Shared sidecar bundle (identical for every agent in the dir).+ *+ * There is deliberately no companion hash file: keeping one alongside the+ * bundle meant two writes that could tear or fall out of step, and a stale hash+ * silently defeats the comparison it exists to serve. The bundle is hashed from+ * its own bytes instead — on the host when deciding whether to upload, and by+ * the sidecar itself when reporting what it is running.+ */export const SIDECAR_BUNDLE_REL_PATH = `${SIDECAR_DIR}/sidecar.mjs`;-export const SIDECAR_BUNDLE_HASH_REL_PATH = `${SIDECAR_DIR}/sidecar.mjs.sha256`;/** Per-agent state directory, keyed by the creds slug (definition name / id). */export function sidecarAgentDir(slug: string): string {@@ -33,6 +40,27 @@ export function sidecarReadyRelPath(slug: string): string {return `${sidecarAgentDir(slug)}/sidecar.ready`;}+/**+ * Current hook endpoint (port on line 1, token on line 2), rewritten by the+ * sidecar every time it binds. Sessions are launched with the *path* to this+ * file rather than the port/token themselves, so a restarted sidecar — which+ * always gets a fresh ephemeral port and token — is still reachable from panes+ * that were spawned against the previous process.+ */+export function sidecarEndpointRelPath(slug: string): string {+ return `${sidecarAgentDir(slug)}/endpoint`;+}++/** Durable sidecar state (session registry + event epoch), survives restarts. */+export function sidecarStateRelPath(slug: string): string {+ return `${sidecarAgentDir(slug)}/state.json`;+}++/** Atomically-created deploy lock directory (mkdir is atomic on POSIX). */+export function sidecarDeployLockRelPath(slug: string): string {+ return `${sidecarAgentDir(slug)}/deploy.lock`;+}+export function sidecarLogRelPath(slug: string): string {return `${sidecarAgentDir(slug)}/sidecar.log`;}diff --git a/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.test.ts b/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.test.tsindex 554bbaf60..5c97b76dc 100644--- a/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.test.ts+++ b/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.test.ts@@ -5,8 +5,10 @@ import { makePtyId } from '@shared/core/pty/ptyId';import {type ManagedConnection,type RoomConnectionFactory,+ type SessionRegistry,SidecarRuntime,} from './sidecar-runtime';+import type { SidecarSessionEntry } from './sidecar-state';// Use the generic parser so raw 'start'/'stop' map to status deterministically,// independent of any provider's custom hook parser.@@ -34,6 +36,20 @@ function statusHook(type: string, ptyId: string): RawHookRequest {return { ptyId, type, body: JSON.stringify({}) } as RawHookRequest;}+/** In-memory stand-in for the durable state store. */+function fakeRegistry(): SessionRegistry & { entries: () => SidecarSessionEntry[] } {+ const sessions = new Map<string, SidecarSessionEntry>();+ return {+ has: (id) => sessions.has(id),+ record: (entry) => {+ const prev = sessions.get(entry.sessionId);+ sessions.set(entry.sessionId, { ...entry, roomId: entry.roomId ?? prev?.roomId ?? null });+ },+ forget: (id) => void sessions.delete(id),+ entries: () => [...sessions.values()],+ };+}+function makeRuntime() {const created: Array<{ deps: RoomConnectionDeps; conn: ManagedConnection }> = [];const factory: RoomConnectionFactory = (deps) => {@@ -41,6 +57,7 @@ function makeRuntime() {created.push({ deps, conn });return conn;};+ const registry = fakeRegistry();const runtime = new SidecarRuntime({creds: { agentId: 'agent-1', apiEndpoint: 'https://switch.test', token: 'tok' },locationId: 'proj-1',@@ -49,8 +66,9 @@ function makeRuntime() {isPaneLive: () => true,log: silentLog,createConnection: factory,+ registry,});- return { runtime, created };+ return { runtime, created, registry };}const PTY_A = makePtyId('codex', 'session-a');@@ -153,6 +171,7 @@ describe('SidecarRuntime (multi-session)', () => {isPaneLive: () => paneLive,log: silentLog,createConnection: factory,+ registry: fakeRegistry(),});await runtime.handleHook(switchRoomHook('room-1', PTY_A));expect(runtime.connectedSessions()).toHaveLength(1);diff --git a/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.ts b/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.tsindex bcc8f3581..08542383a 100644--- a/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.ts+++ b/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.ts@@ -39,6 +39,22 @@ export interface SidecarRuntimeDeps {isPaneLive: (tmuxTarget: string) => boolean;log: RoomConnectionLogger;createConnection: RoomConnectionFactory;+ /** Durable registry of the sessions this sidecar owns. Backed by the state+ * file so ownership survives a restart, rather than being rebuilt only as+ * each session happens to post its next hook. */+ registry: SessionRegistry;+}++/** The slice of the durable state store the runtime needs. */+export interface SessionRegistry {+ has(sessionId: string): boolean;+ record(entry: {+ sessionId: string;+ roomId: string | null;+ providerId: string;+ tmuxTarget: string;+ }): void;+ forget(sessionId: string): void;}interface SessionConnection {@@ -62,9 +78,6 @@ interface SessionConnection {export class SidecarRuntime {/** sessionId → its live room connection. */private readonly sessions = new Map<string, SessionConnection>();- /** Every session id that has posted a hook to this sidecar — i.e. the- * sessions it owns, used to scope the VM-wide tmux enumeration in `/sessions`. */- private readonly seen = new Set<string>();private readonly resolveContext: ContextResolver;/** Notified when a session connects to a room, so the notification watcher can* hand its per-room in-flight guard off to the live-room check (mirrors the@@ -96,7 +109,14 @@ export class SidecarRuntime {// panes — tmux session names carry no repo/agent, so without this a sidecar// would report other agents' sessions on the same host.const pid = parsePtyId(raw.ptyId);- if (pid) this.seen.add(pid.sessionId);+ if (pid) {+ this.deps.registry.record({+ sessionId: pid.sessionId,+ roomId: null,+ providerId: pid.providerId,+ tmuxTarget: makeAgentTmuxSessionName(pid.sessionId),+ });+ }let parsed: ParsedHookEvent;try {@@ -173,11 +193,25 @@ export class SidecarRuntime {log: this.deps.log,});this.sessions.set(sessionId, { connection, roomId, tmuxTarget });+ this.deps.registry.record({ sessionId, roomId, providerId, tmuxTarget });this.deps.log.debug('SidecarRuntime: room connected', { sessionId, roomId, roomName });connection.start();this.roomConnectedListener?.(roomId);}+ /**+ * Re-establish a room connection for a session restored from durable state.+ *+ * Without this a restarted sidecar would sit idle for every session it just+ * restored, resuming poll and injection only when that agent next posted a+ * hook — which an agent waiting on a room message never does. The room+ * membership itself is server-side and outlived the restart; only our+ * connection to it did not.+ */+ restoreSession(entry: { sessionId: string; roomId: string; providerId: string }): void {+ this.connectRoom(entry.sessionId, entry.providerId, entry.roomId, null);+ }+/** The room a session is currently attending, or null if it has none. */roomIdForSession(sessionId: string): string | null {return this.sessions.get(sessionId)?.roomId ?? null;@@ -193,6 +227,7 @@ export class SidecarRuntime {if (!session) return;session.connection.stop();this.sessions.delete(sessionId);+ this.deps.registry.forget(sessionId);this.deps.log.debug('SidecarRuntime: session stopped', { sessionId });}@@ -216,10 +251,12 @@ export class SidecarRuntime {return out;}- /** Whether a session has ever posted a hook to this sidecar (i.e. it is- * one of this agent's own sessions, not another agent's pane on the host). */+ /** Whether this sidecar owns the session — i.e. it is one of this agent's own+ * sessions rather than another agent's pane on the same host. Backed by the+ * durable registry, so it is true from boot for a restored session instead of+ * only once that session next posts a hook. */hasSeen(sessionId: string): boolean {- return this.seen.has(sessionId);+ return this.deps.registry.has(sessionId);}/** True when a live session is attending the room and its pane is up (watcher gate). */diff --git a/dash/apps/switchdash-desktop/src/sidecar/sidecar-state.test.ts b/dash/apps/switchdash-desktop/src/sidecar/sidecar-state.test.tsnew file mode 100644index 000000000..1b8c2b18b--- /dev/null+++ b/dash/apps/switchdash-desktop/src/sidecar/sidecar-state.test.ts@@ -0,0 +1,157 @@+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { sidecarAgentDir, sidecarStateRelPath } from './sidecar-paths';+import {+ loadSidecarState,+ type SidecarSessionEntry,+ SidecarStateStore,+ SidecarStateTooNewError,+} from './sidecar-state';++const SLUG = 'claude-code.repo.me';+const silentLog = { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() };++let repoDir: string;++beforeEach(async () => {+ repoDir = await mkdtemp(path.join(tmpdir(), 'sidecar-state-'));+ await mkdir(path.join(repoDir, sidecarAgentDir(SLUG)), { recursive: true });+});++afterEach(async () => {+ await rm(repoDir, { recursive: true, force: true });+});++const statePath = (): string => path.join(repoDir, sidecarStateRelPath(SLUG));++const writeState = (raw: string): Promise<void> => writeFile(statePath(), raw);++const entry = (over: Partial<SidecarSessionEntry> = {}): SidecarSessionEntry => ({+ sessionId: 'session-a',+ roomId: 'room-1',+ providerId: 'claude',+ tmuxTarget: 'switchdash-abc',+ ...over,+});++describe('loadSidecarState', () => {+ it('returns empty state on first run', async () => {+ const state = await loadSidecarState(repoDir, SLUG, silentLog);+ expect(state).toEqual({ version: '1', epoch: 0, sessions: [] });+ });++ it('reads back a persisted state file', async () => {+ await writeState(JSON.stringify({ version: '1', epoch: 4, sessions: [entry()] }));++ const state = await loadSidecarState(repoDir, SLUG, silentLog);++ expect(state.epoch).toBe(4);+ expect(state.sessions).toEqual([entry()]);+ });++ it('treats a corrupt file as empty rather than failing to start', async () => {+ await writeState('{ not json');++ const state = await loadSidecarState(repoDir, SLUG, silentLog);++ expect(state.sessions).toEqual([]);+ expect(silentLog.warn).toHaveBeenCalled();+ });++ it('refuses to start on state written by a NEWER sidecar', async () => {+ // Starting empty here would report zero sessions to every client, which+ // prunes rows for sessions that are alive — worse than not starting.+ await writeState(JSON.stringify({ version: '99', epoch: 1, sessions: [entry()] }));++ await expect(loadSidecarState(repoDir, SLUG, silentLog)).rejects.toBeInstanceOf(+ SidecarStateTooNewError+ );+ });+});++describe('SidecarStateStore', () => {+ const open = (isPaneAlive: (t: string) => Promise<boolean> = async () => true) =>+ SidecarStateStore.open({ repoDir, slug: SLUG, isPaneAlive, log: silentLog });++ it('restores sessions whose pane is still alive', async () => {+ await writeState(JSON.stringify({ version: '1', epoch: 1, sessions: [entry()] }));++ const store = await open();++ expect(store.entries()).toEqual([entry()]);+ expect(store.has('session-a')).toBe(true);+ expect(store.roomIdFor('session-a')).toBe('room-1');+ await store.close();+ });++ it('drops restored sessions whose pane is gone, so no ghost row is served', async () => {+ await writeState(+ JSON.stringify({+ version: '1',+ epoch: 1,+ sessions: [entry(), entry({ sessionId: 'session-dead', tmuxTarget: 'switchdash-dead' })],+ })+ );++ const store = await open(async (target) => target !== 'switchdash-dead');++ expect(store.entries().map((s) => s.sessionId)).toEqual(['session-a']);+ await store.close();+ });++ it('bumps the epoch on every open so a restarted stream is distinguishable', async () => {+ await writeState(JSON.stringify({ version: '1', epoch: 7, sessions: [] }));++ const store = await open();++ expect(store.epoch).toBe(8);+ await store.close();+ });++ it('persists recorded sessions across a restart', async () => {+ const first = await open();+ first.record(entry());+ await first.close();++ const second = await open();++ expect(second.entries()).toEqual([entry()]);+ await second.close();+ });++ it('keeps a known room when a later bare hook reports none', async () => {+ const store = await open();+ store.record(entry());+ store.record(entry({ roomId: null }));++ expect(store.roomIdFor('session-a')).toBe('room-1');+ await store.close();+ });++ it('forgets a deleted session so it is not restored', async () => {+ const first = await open();+ first.record(entry());+ first.forget('session-a');+ await first.close();++ const second = await open();++ expect(second.entries()).toEqual([]);+ await second.close();+ });++ it('writes atomically, leaving no partial file behind', async () => {+ const store = await open();+ store.record(entry());+ await store.close();++ const written = JSON.parse(await readFile(statePath(), 'utf8')) as { version: string };+ expect(written.version).toBe('1');+ // The temp file the atomic write renames from must not survive.+ const stray = path.join(repoDir, sidecarAgentDir(SLUG));+ const { readdir } = await import('node:fs/promises');+ expect((await readdir(stray)).filter((f) => f.includes('.tmp'))).toEqual([]);+ });+});diff --git a/dash/apps/switchdash-desktop/src/sidecar/sidecar-state.ts b/dash/apps/switchdash-desktop/src/sidecar/sidecar-state.tsnew file mode 100644index 000000000..f29463beb--- /dev/null+++ b/dash/apps/switchdash-desktop/src/sidecar/sidecar-state.ts@@ -0,0 +1,253 @@+import { readFile } from 'node:fs/promises';+import path from 'node:path';+import z from 'zod';+import { defineVersionedSchema } from '@shared/lib/versioned-schema/versioned-schema';+import { atomicWriteFile } from './atomic-file';+import type { WatcherLogger } from './notification-watcher';+import { sidecarStateRelPath } from './sidecar-paths';++/**+ * The sidecar's durable state.+ *+ * Everything the sidecar knew used to live in process memory, so a restart made+ * it forget which panes on the host were its own. That mattered more than it+ * sounds: `/sessions` only reports a pane the sidecar has "seen", and it only+ * sees one when that session posts a hook — which an idle agent never does. So+ * a restarted sidecar reported no sessions at all, and every client, unable to+ * tell "gone" from "not yet re-seen", deleted its rows for sessions whose panes+ * were alive and healthy.+ *+ * Persisting the registry closes that window: the sidecar knows its sessions+ * from the moment it boots, before any agent says anything.+ */++const sessionEntry = z.object({+ sessionId: z.string(),+ /** The Switch room this session attends, or null for a bare session. */+ roomId: z.string().nullable(),+ /** Needed to rebuild the session's prompt injector and control adapter when+ * its room connection is restored after a restart. */+ providerId: z.string(),+ tmuxTarget: z.string(),+});++const stateV1 = z.object({+ version: z.literal('1'),+ /**+ * Incremented on every start. Clients tag their `/events` cursor with it so a+ * restarted sidecar — whose sequence numbers begin again at zero — is not+ * mistaken for the same stream continuing.+ */+ epoch: z.number().int().nonnegative(),+ sessions: z.array(sessionEntry),+});++export const sidecarStateSchema = defineVersionedSchema().initial('1', stateV1).build();++export type SidecarSessionEntry = z.infer<typeof sessionEntry>;+export type SidecarState = z.infer<typeof stateV1>;++const EMPTY_STATE: SidecarState = { version: '1', epoch: 0, sessions: [] };++/** Raised when the state on disk was written by a NEWER sidecar than this one. */+export class SidecarStateTooNewError extends Error {+ constructor(readonly foundVersion: string) {+ super(+ `sidecar: state file was written by a newer sidecar (schema version ${foundVersion}); ` ++ 'refusing to start rather than discard its sessions — deploy the matching sidecar version'+ );+ this.name = 'SidecarStateTooNewError';+ }+}++/**+ * Load durable state, upgrading older schema versions forward.+ *+ * A missing file is a first run, and a corrupt one is logged and treated as+ * empty — in both cases the sidecar can rebuild by observation. A *newer*+ * version is different in kind: the state belongs to a sidecar that understands+ * more than this one, and quietly starting empty would delete its sessions from+ * every client. That one throws.+ */+export async function loadSidecarState(+ repoDir: string,+ slug: string,+ log: WatcherLogger+): Promise<SidecarState> {+ const file = path.join(repoDir, sidecarStateRelPath(slug));+ let raw: string;+ try {+ raw = await readFile(file, 'utf8');+ } catch {+ return { ...EMPTY_STATE };+ }++ // `parseJson` collapses every failure to null, which loses the one+ // distinction that matters here: unreadable (rebuild by observation) versus+ // written-by-a-newer-sidecar (stop). Parse and dispatch on the status.+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch {+ log.warn('sidecar: state file is not valid JSON — starting with empty state', { file });+ return { ...EMPTY_STATE };+ }++ const result = sidecarStateSchema.safeParse(parsed);+ switch (result.status) {+ case 'ok':+ return result.data;+ case 'future-version':+ throw new SidecarStateTooNewError(result.version);+ default:+ log.warn('sidecar: state file unreadable — starting with empty state', {+ file,+ status: result.status,+ });+ return { ...EMPTY_STATE };+ }+}++/**+ * Persist state atomically. Callers mutate through `SidecarStateStore`, which+ * coalesces bursts — a session connecting touches this several times in a row.+ */+async function writeSidecarState(+ repoDir: string,+ slug: string,+ state: SidecarState+): Promise<void> {+ const file = path.join(repoDir, sidecarStateRelPath(slug));+ await atomicWriteFile(file, sidecarStateSchema.serialize(state));+}++const FLUSH_DEBOUNCE_MS = 250;++/**+ * In-memory view of the durable state, flushed on a short debounce.+ *+ * Reads are synchronous because the hot paths (`/sessions`, hook handling) run+ * on every event and must not wait on the disk.+ */+export class SidecarStateStore {+ private readonly sessions = new Map<string, SidecarSessionEntry>();+ private flushTimer: ReturnType<typeof setTimeout> | null = null;+ private flushing: Promise<void> = Promise.resolve();+ private stopped = false;++ private constructor(+ private readonly repoDir: string,+ private readonly slug: string,+ readonly epoch: number,+ private readonly log: WatcherLogger+ ) {}++ /**+ * Load state, drop entries whose pane no longer exists, and bump the epoch.+ *+ * The reconcile against tmux is the point: replaying the file verbatim would+ * resurrect sessions that died while the sidecar was down, and a ghost row is+ * how a client ends up re-attaching into a blank pane.+ */+ static async open(opts: {+ repoDir: string;+ slug: string;+ isPaneAlive: (tmuxTarget: string) => Promise<boolean>;+ log: WatcherLogger;+ }): Promise<SidecarStateStore> {+ const { repoDir, slug, isPaneAlive, log } = opts;+ const loaded = await loadSidecarState(repoDir, slug, log);+ const store = new SidecarStateStore(repoDir, slug, loaded.epoch + 1, log);++ const alive = await Promise.all(+ loaded.sessions.map(async (s) => ((await isPaneAlive(s.tmuxTarget)) ? s : null))+ );+ for (const entry of alive) if (entry) store.sessions.set(entry.sessionId, entry);++ const dropped = loaded.sessions.length - store.sessions.size;+ if (dropped > 0) {+ log.info('sidecar: dropped restored sessions whose pane is gone', { dropped });+ }+ log.info('sidecar: restored durable state', {+ epoch: store.epoch,+ sessions: store.sessions.size,+ });+ store.scheduleFlush();+ return store;+ }++ /** Every session this sidecar owns, whether or not it has posted a hook yet. */+ knownSessionIds(): string[] {+ return [...this.sessions.keys()];+ }++ has(sessionId: string): boolean {+ return this.sessions.has(sessionId);+ }++ entries(): SidecarSessionEntry[] {+ return [...this.sessions.values()];+ }++ roomIdFor(sessionId: string): string | null {+ return this.sessions.get(sessionId)?.roomId ?? null;+ }++ /**+ * Record (or update) a session. A null `roomId` means "no room information",+ * not "left its room" — a bare hook from a session that is already attending+ * one must not erase that, so the known room is kept.+ */+ record(entry: SidecarSessionEntry): void {+ const prev = this.sessions.get(entry.sessionId);+ const merged: SidecarSessionEntry = { ...entry, roomId: entry.roomId ?? prev?.roomId ?? null };+ if (+ prev &&+ prev.roomId === merged.roomId &&+ prev.providerId === merged.providerId &&+ prev.tmuxTarget === merged.tmuxTarget+ ) {+ return;+ }+ this.sessions.set(entry.sessionId, merged);+ this.scheduleFlush();+ }++ forget(sessionId: string): void {+ if (this.sessions.delete(sessionId)) this.scheduleFlush();+ }++ private scheduleFlush(): void {+ if (this.stopped || this.flushTimer) return;+ this.flushTimer = setTimeout(() => {+ this.flushTimer = null;+ this.flushing = this.flush();+ }, FLUSH_DEBOUNCE_MS);+ }++ private async flush(): Promise<void> {+ const state: SidecarState = {+ version: '1',+ epoch: this.epoch,+ sessions: this.entries(),+ };+ try {+ await writeSidecarState(this.repoDir, this.slug, state);+ } catch (error) {+ // Losing a write degrades restart fidelity but must not take the sidecar+ // down while it is serving live sessions.+ this.log.warn('sidecar: failed to persist state', { error: String(error) });+ }+ }++ /** Flush any pending change and stop scheduling new ones. */+ async close(): Promise<void> {+ if (this.flushTimer) {+ clearTimeout(this.flushTimer);+ this.flushTimer = null;+ this.flushing = this.flush();+ }+ this.stopped = true;+ await this.flushing;+ }+}diff --git a/dash/apps/switchdash-desktop/src/sidecar/sidecar-version.ts b/dash/apps/switchdash-desktop/src/sidecar/sidecar-version.tsnew file mode 100644index 000000000..4480957ac--- /dev/null+++ b/dash/apps/switchdash-desktop/src/sidecar/sidecar-version.ts@@ -0,0 +1,40 @@+/**+ * The sidecar's human-readable version, `x.y`.+ *+ * - `x` (major) — the wire contract between client and sidecar. Bump it on a+ * BREAKING change (the ready line, an endpoint's request/response, or the+ * on-disk layout the two sides share). Compatibility — "can this client talk+ * to that running sidecar" — is judged on the major alone.+ * - `y` (minor) — a release/patch counter, purely for humans to read. It drives+ * NO machine decision. Whether a running sidecar is the exact build this+ * client ships — and therefore whether an upgrade is available — is decided by+ * the content hash carried alongside, not by `y`.+ *+ * Keeping "is it the same build" on the hash rather than on `y` is deliberate: a+ * forgotten `y` bump then can never make a changed build look up-to-date, and+ * dev builds (which nobody bumps between iterations) still redeploy correctly.+ * The full identity a user sees is `x.y+<shorthash>` — semver build metadata —+ * so they read `1.0` while the machine compares the hash.+ *+ * Bump policy: `x` on a wire break (and only then), `y` on every release that+ * changes the sidecar.+ */+export const SIDECAR_VERSION = '1.0';++/**+ * Oldest major this client can still speak to. Raise it only when support for an+ * older sidecar is genuinely dropped — every sidecar below it is replaced on+ * sight, including one with live sessions. A sidecar predating versioning+ * reports no version and is treated as major 0.+ */+export const MIN_SUPPORTED_SIDECAR_MAJOR = 0;++/** The major of an `x.y` version string; 0 for a missing/unparseable one. */+export function sidecarMajor(version: string | null): number {+ if (!version) return 0;+ const major = Number.parseInt(version.split('.')[0] ?? '', 10);+ return Number.isFinite(major) ? major : 0;+}++/** This client's own major, for compatibility comparisons. */+export const SIDECAR_CLIENT_MAJOR = sidecarMajor(SIDECAR_VERSION);diff --git a/dash/packages/core/src/agents/plugins/helpers/hooks.test.ts b/dash/packages/core/src/agents/plugins/helpers/hooks.test.tsnew file mode 100644index 000000000..852f964ca--- /dev/null+++ b/dash/packages/core/src/agents/plugins/helpers/hooks.test.ts@@ -0,0 +1,118 @@+import { execFile } from 'node:child_process';+import { mkdtemp, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { promisify } from 'node:util';+import { describe, expect, it } from 'vitest';+import { filterUserHooks, makeStdinHookCommand, SWITCHDASH_MARKER } from './hooks';++const execFileAsync = promisify(execFile);++/**+ * Run a generated POSIX hook command under a real `sh` with `curl` stubbed out,+ * and report the URL and token it would have posted to. The endpoint resolution+ * is shell code, so asserting on the string alone would not catch a quoting or+ * `sed` mistake — only executing it does.+ */+async function resolveEndpoint(+ env: Record<string, string>+): Promise<{ url: string; token: string }> {+ const dir = await mkdtemp(path.join(tmpdir(), 'hook-cmd-'));+ try {+ // A `curl` that records its own argv instead of making a request.+ const stub = path.join(dir, 'curl');+ const out = path.join(dir, 'argv');+ await writeFile(stub, `#!/bin/sh\nprintf '%s\\n' "$@" > ${JSON.stringify(out)}\n`, {+ mode: 0o755,+ });++ const command = makeStdinHookCommand('notification', { platform: 'linux' });+ await execFileAsync('sh', ['-c', command], {+ env: { ...env, PATH: `${dir}:${process.env.PATH ?? ''}` },+ });++ const { stdout } = await execFileAsync('cat', [out]);+ const argv = stdout.split('\n');+ const url = argv.find((a) => a.startsWith('http://')) ?? '';+ const tokenIdx = argv.findIndex((a) => a.startsWith('X-Switchdash-Token:'));+ return { url, token: argv[tokenIdx]?.replace('X-Switchdash-Token: ', '') ?? '' };+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+}++describe('makeStdinHookCommand endpoint resolution', () => {+ it('uses the env port and token when no endpoint file is configured', async () => {+ const { url, token } = await resolveEndpoint({+ SWITCHDASH_HOOK_PORT: '5001',+ SWITCHDASH_HOOK_TOKEN: 'env-token',+ SWITCHDASH_PTY_ID: 'claude:s1',+ });++ expect(url).toBe('http://127.0.0.1:5001/hook');+ expect(token).toBe('env-token');+ });++ it('prefers the endpoint file, so a pane follows a restarted sidecar', async () => {+ const dir = await mkdtemp(path.join(tmpdir(), 'hook-ep-'));+ const endpointFile = path.join(dir, 'endpoint');+ // What the sidecar rewrites after rebinding on a fresh port + token.+ await writeFile(endpointFile, '6002\nfresh-token\n');++ try {+ const { url, token } = await resolveEndpoint({+ // Stale values baked into the pane at spawn time.+ SWITCHDASH_HOOK_PORT: '5001',+ SWITCHDASH_HOOK_TOKEN: 'stale-token',+ SWITCHDASH_PTY_ID: 'claude:s1',+ SWITCHDASH_HOOK_ENDPOINT_FILE: endpointFile,+ });++ expect(url).toBe('http://127.0.0.1:6002/hook');+ expect(token).toBe('fresh-token');+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+ });++ it('falls back to the env when the endpoint file is missing or unreadable', async () => {+ const { url, token } = await resolveEndpoint({+ SWITCHDASH_HOOK_PORT: '5001',+ SWITCHDASH_HOOK_TOKEN: 'env-token',+ SWITCHDASH_PTY_ID: 'claude:s1',+ SWITCHDASH_HOOK_ENDPOINT_FILE: '/nonexistent/endpoint',+ });++ expect(url).toBe('http://127.0.0.1:5001/hook');+ expect(token).toBe('env-token');+ });++ it('falls back to the env when the endpoint file is empty (mid-write)', async () => {+ const dir = await mkdtemp(path.join(tmpdir(), 'hook-ep-'));+ const endpointFile = path.join(dir, 'endpoint');+ await writeFile(endpointFile, '');++ try {+ const { url, token } = await resolveEndpoint({+ SWITCHDASH_HOOK_PORT: '5001',+ SWITCHDASH_HOOK_TOKEN: 'env-token',+ SWITCHDASH_PTY_ID: 'claude:s1',+ SWITCHDASH_HOOK_ENDPOINT_FILE: endpointFile,+ });++ expect(url).toBe('http://127.0.0.1:5001/hook');+ expect(token).toBe('env-token');+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+ });++ it('stays recognisable to filterUserHooks so managed entries are replaced, not duplicated', () => {+ const command = makeStdinHookCommand('notification', { platform: 'linux' });++ expect(command).toContain(SWITCHDASH_MARKER);+ expect(filterUserHooks([{ command }, { command: 'user-own-hook' }])).toEqual([+ { command: 'user-own-hook' },+ ]);+ });+});diff --git a/dash/packages/core/src/agents/plugins/helpers/hooks.ts b/dash/packages/core/src/agents/plugins/helpers/hooks.tsindex e84be345e..8d2b8f9ae 100644--- a/dash/packages/core/src/agents/plugins/helpers/hooks.ts+++ b/dash/packages/core/src/agents/plugins/helpers/hooks.ts@@ -20,17 +20,41 @@ function quotePowerShellString(value: string): string {type HookPostPayload = 'stdin' | { json: Record<string, string> };+/**+ * Resolve the hook endpoint at fire time, preferring the endpoint file when the+ * launching runtime pointed us at one.+ *+ * A pane's environment is fixed at spawn, so a session launched against the+ * remote sidecar would keep posting to the port and token that sidecar happened+ * to hold at the time — both of which change every time it restarts. Baking the+ * *path* to the endpoint file instead lets those sessions follow the sidecar+ * across restarts, upgrades, and token rotation.+ *+ * The file is parsed line-by-line rather than sourced: it lives in the agent's+ * repo dir, and `.`-ing it would make anything that can write there able to run+ * arbitrary code in every hook. Falls back to the environment, which is how+ * local sessions (and any pane spawned before this existed) keep working.+ */+const POSIX_ENDPOINT_PREAMBLE =+ '_sd_p="$SWITCHDASH_HOOK_PORT"; _sd_t="$SWITCHDASH_HOOK_TOKEN"; ' ++ 'if [ -n "$SWITCHDASH_HOOK_ENDPOINT_FILE" ] && [ -r "$SWITCHDASH_HOOK_ENDPOINT_FILE" ]; then ' ++ '_sd_f=$(sed -n 1p "$SWITCHDASH_HOOK_ENDPOINT_FILE"); ' ++ '_sd_g=$(sed -n 2p "$SWITCHDASH_HOOK_ENDPOINT_FILE"); ' ++ '[ -n "$_sd_f" ] && _sd_p="$_sd_f"; [ -n "$_sd_g" ] && _sd_t="$_sd_g"; ' ++ 'fi; ';+function makePosixHookPostCommand(eventType: string, payload: HookPostPayload): string {const payloadPart =payload === 'stdin' ? '-d @- ' : `--data-binary '${JSON.stringify(payload.json)}' `;return (+ POSIX_ENDPOINT_PREAMBLE +'curl -sf -X POST ' +'-H "Content-Type: application/json" ' +- '-H "X-Switchdash-Token: $SWITCHDASH_HOOK_TOKEN" ' ++ '-H "X-Switchdash-Token: $_sd_t" ' +'-H "X-Switchdash-Pty-Id: $SWITCHDASH_PTY_ID" ' +`-H "X-Switchdash-Event-Type: ${eventType}" ` +payloadPart +- '"http://127.0.0.1:$SWITCHDASH_HOOK_PORT/hook" || true'+ '"http://127.0.0.1:$_sd_p/hook" || true');}