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): remove workspace/project abstraction — first-class Location (CHOO-1426) (#23)
Louis Amaudruz60bc2095fdfd
diff --git a/dash/AGENTS.md b/dash/AGENTS.mdindex 530e91b73..a5952d706 100644--- a/dash/AGENTS.md+++ b/dash/AGENTS.md@@ -225,12 +225,12 @@ views, modals, command providers, project state, terminals, and session workflowShared IPC primitives, provider metadata, events, MCP types, skills types, anddomain types live under `src/shared/`.-Major main-process domains live under `src/main/core/`: agent hooks, agents, app,-agent runtime, dependencies, execution context, fs, projects, prompt library, PTY,-resource monitor, runtime, search, secrets, sessions, settings, switch agents,-terminal shell, terminals, updates, view state, and workspaces. Stateful-main-process concerns use singleton services; expected failures should use the-`Result<T, E>` pattern from `src/main/lib/result.ts`.+agent runtime, dependencies, execution context, fs, locations (an agent's working+dir on a host — formerly the project/workspace split), prompt library, PTY,+resource monitor, search, secrets, sessions, settings, switch agents, terminal+shell, terminals, updates, and view state. Stateful main-process concerns use+singleton services; expected failures should use the `Result<T, E>` pattern from+`src/main/lib/result.ts`.## Testing Strategy@@ -296,17 +296,16 @@ pnpm run lint- Keep renderer-main calls on typed RPC and typed events. The preload bridge in`src/preload/index.ts` should stay small; add direct `window.electronAPI` surfaceonly when a browser/Electron primitive cannot fit the RPC/event path.-- Access session and project MobX stores through selectors and session view hooks:+- Access session and location MobX stores through selectors and session view hooks:`getSessionStore`, `asProvisioned`, `sessionViewKind`, `getSessionManagerStore`,- `getProjectStore`, `asMounted`, `useSessionViewKind`, `useWorkspace`,- `useWorkspaceId`, `useDevServers`, `useWorkspaceViewModel`, and- `useSessionAgent`.+ `getLocationStore`, `asMounted`, `useSessionViewKind`, `useSessionRuntime`,+ `useSessionLocationId`, `useSessionViewModel`, and `useSessionAgent`.- Never use `asProvisioned(...)!` or `asMounted(...)!`; use explicit null checks.- State guards must check `kind !== 'ready'` rather than enumerating non-ready states.-- Access session managers through `getSessionManagerStore(projectId)`, not `project.sessionManager`.-- Access mounted projects through `asMounted(getProjectStore(id))`, not inline guards.+- Access session managers through `getSessionManagerStore(locationId)`, not `location.sessionManager`.+- Access mounted locations through `asMounted(getLocationStore(id))`, not inline guards.- Session selectors live in `src/renderer/features/sessions/stores/session-selectors.ts`.-- Project selectors live in `src/renderer/features/projects/stores/project-selectors.ts`.+- Location selectors live in `src/renderer/features/locations/stores/location-selectors.ts`.- For provider changes, update shared provider metadata, PTY env passthrough if needed,hook/plugin integrations, renderer assumptions, and tests for non-standard behavior.- For MCP changes, keep canonical data in shared types and adapt provider formats at edges.@@ -329,10 +328,10 @@ pnpm run test- View definitions and navigation guards are centralized in `src/renderer/app/view-registry.ts`.- MCP types live under `src/shared/core/mcp/`.- Skills types and validation live under `src/shared/core/skills/`.-- Per-project runtime settings can be supplied through `.switchdash.json`:+- Per-location runtime settings can be supplied through `.switchdash.json`:`preservePatterns`, `scripts.setup`, `scripts.run`, `scripts.teardown`, and`shellSetup`.-- Project settings such as `tmux` and `workspaceProvider` are DB-backed, not+- Location settings such as `tmux` and `locationProvider` are DB-backed, not`.switchdash.json`.- Optional environment variables:`SWITCHDASH_DB_FILE`, `SWITCHDASH_DISABLE_NATIVE_DB`,diff --git a/dash/apps/switchdash-desktop/drizzle/0031_mean_king_cobra.sql b/dash/apps/switchdash-desktop/drizzle/0031_mean_king_cobra.sqlnew file mode 100644index 000000000..3c0979f5d--- /dev/null+++ b/dash/apps/switchdash-desktop/drizzle/0031_mean_king_cobra.sql@@ -0,0 +1,28 @@+CREATE TABLE `location_settings` (+ `location_id` text PRIMARY KEY NOT NULL,+ `base_settings_json` text DEFAULT '{}' NOT NULL,+ `shareable_settings_json` text DEFAULT '{}' NOT NULL,+ `legacy_config_migrated_at` text,+ `created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,+ `updated_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,+ FOREIGN KEY (`location_id`) REFERENCES `locations`(`id`) ON UPDATE no action ON DELETE cascade+);+--> statement-breakpoint+CREATE TABLE `locations` (+ `id` text PRIMARY KEY NOT NULL,+ `name` text NOT NULL,+ `ssh_host` text DEFAULT '' NOT NULL,+ `dir` text NOT NULL,+ `created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,+ `updated_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL+);+--> statement-breakpoint+ALTER TABLE `agents` ADD `location_id` text REFERENCES locations(id);--> statement-breakpoint+CREATE UNIQUE INDEX `idx_locations_host_dir` ON `locations` (`ssh_host`,`dir`);--> statement-breakpoint+/*+ SQLite does not support "Creating foreign key on existing column" out of the box, we do not generate automatic migration for that, so it has to be done manually+ Please refer to: https://www.techonthenet.com/sqlite/tables/alter_table.php+ https://www.sqlite.org/lang_altertable.html++ Due to that we don't generate migration automatically and it has to be done manually+*/\ No newline at end of filediff --git a/dash/apps/switchdash-desktop/drizzle/0032_backfill_locations.sql b/dash/apps/switchdash-desktop/drizzle/0032_backfill_locations.sqlnew file mode 100644index 000000000..fe20fea73--- /dev/null+++ b/dash/apps/switchdash-desktop/drizzle/0032_backfill_locations.sql@@ -0,0 +1,53 @@+/*+ Backfill locations from projects + agents (CHOO-1426). Each project row maps+ to one location, reusing the project id: a local project contributes+ (ssh_host = '', dir = path); a remote project (path IS NULL) takes host + dir+ from its remote agent's remote_config_json. ON CONFLICT dedupes the edge case+ of two projects resolving to the same (host, dir); agents are then re-pointed+ by computed (host, dir) so agents of a deduped project land on the surviving+ location. project_settings rows follow their project into location_settings.+*/+INSERT INTO `locations` (`id`, `name`, `ssh_host`, `dir`, `created_at`, `updated_at`)+SELECT+ `p`.`id`,+ `p`.`name`,+ COALESCE(+ (SELECT json_extract(`a`.`remote_config_json`, '$.sshHost')+ FROM `agents` `a`+ WHERE `a`.`project_id` = `p`.`id` AND `a`.`connection` = 'remote'+ LIMIT 1),+ ''+ ),+ COALESCE(+ (SELECT json_extract(`a`.`remote_config_json`, '$.remoteRepoDir')+ FROM `agents` `a`+ WHERE `a`.`project_id` = `p`.`id` AND `a`.`connection` = 'remote'+ LIMIT 1),+ `p`.`path`,+ ''+ ),+ `p`.`created_at`,+ `p`.`updated_at`+FROM `projects` `p`+WHERE true+ON CONFLICT (`ssh_host`, `dir`) DO NOTHING;--> statement-breakpoint+UPDATE `agents` SET `location_id` = (+ SELECT `l`.`id` FROM `locations` `l`+ WHERE `l`.`ssh_host` = CASE+ WHEN `agents`.`connection` = 'remote'+ THEN COALESCE(json_extract(`agents`.`remote_config_json`, '$.sshHost'), '')+ ELSE ''+ END+ AND `l`.`dir` = CASE+ WHEN `agents`.`connection` = 'remote'+ THEN COALESCE(json_extract(`agents`.`remote_config_json`, '$.remoteRepoDir'), '')+ ELSE COALESCE((SELECT `p`.`path` FROM `projects` `p` WHERE `p`.`id` = `agents`.`project_id`), '')+ END+);--> statement-breakpoint+UPDATE `agents` SET `location_id` = `project_id` WHERE `location_id` IS NULL;--> statement-breakpoint+INSERT INTO `location_settings` (`location_id`, `base_settings_json`, `shareable_settings_json`, `legacy_config_migrated_at`, `created_at`, `updated_at`)+SELECT `ps`.`project_id`, `ps`.`base_project_settings_json`, `ps`.`shareable_project_settings_json`, `ps`.`legacy_config_migrated_at`, `ps`.`created_at`, `ps`.`updated_at`+FROM `project_settings` `ps`+WHERE `ps`.`project_id` IN (SELECT `id` FROM `locations`)+ON CONFLICT (`location_id`) DO NOTHING;+diff --git a/dash/apps/switchdash-desktop/drizzle/0033_majestic_slapstick.sql b/dash/apps/switchdash-desktop/drizzle/0033_majestic_slapstick.sqlnew file mode 100644index 000000000..b17268e82--- /dev/null+++ b/dash/apps/switchdash-desktop/drizzle/0033_majestic_slapstick.sql@@ -0,0 +1,26 @@+DROP TABLE `project_settings`;--> statement-breakpoint+DROP TABLE `projects`;--> statement-breakpoint+/*+ SQLite does not support "Dropping foreign key" out of the box, we do not generate automatic migration for that, so it has to be done manually+ Please refer to: https://www.techonthenet.com/sqlite/tables/alter_table.php+ https://www.sqlite.org/lang_altertable.html++ Due to that we don't generate migration automatically and it has to be done manually+*/--> statement-breakpoint+DROP INDEX IF EXISTS `idx_agents_project_id`;--> statement-breakpoint+/*+ SQLite does not support "Set not null to column" out of the box, we do not generate automatic migration for that, so it has to be done manually+ Please refer to: https://www.techonthenet.com/sqlite/tables/alter_table.php+ https://www.sqlite.org/lang_altertable.html+ https://stackoverflow.com/questions/2083543/modify-a-columns-type-in-sqlite3++ Due to that we don't generate migration automatically and it has to be done manually+*/--> statement-breakpoint+CREATE INDEX `idx_agents_location_id` ON `agents` (`location_id`);--> statement-breakpoint+/*+ The generated `ALTER TABLE agents DROP COLUMN project_id/connection/+ remote_config_json` statements cannot run — SQLite refuses to drop a column+ named in a foreign-key clause. The 0034 custom migration recreates `agents`+ without those columns (and enforces NOT NULL on location_id) instead.+*/+SELECT 1;\ No newline at end of filediff --git a/dash/apps/switchdash-desktop/drizzle/0034_enforce_agents_location_not_null.sql b/dash/apps/switchdash-desktop/drizzle/0034_enforce_agents_location_not_null.sqlnew file mode 100644index 000000000..7b9f0bd0d--- /dev/null+++ b/dash/apps/switchdash-desktop/drizzle/0034_enforce_agents_location_not_null.sql@@ -0,0 +1,27 @@+/*+ Enforce NOT NULL on agents.location_id via the SQLite table-recreation dance+ (drizzle-kit cannot generate "set not null"; the 0033 snapshot already+ records the column as NOT NULL, this brings the actual DDL in line). Runs+ with foreign_keys=OFF inside the migration transaction, so dropping and+ renaming does not disturb the sessions FK, which tracks the table name.+*/+CREATE TABLE `__new_agents` (+ `id` text PRIMARY KEY NOT NULL,+ `location_id` text NOT NULL,+ `name` text NOT NULL,+ `provider_id` text NOT NULL,+ `switch_agent_id` text,+ `api_endpoint` text,+ `server_id` text,+ `status` text,+ `created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,+ `updated_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,+ FOREIGN KEY (`location_id`) REFERENCES `locations`(`id`) ON UPDATE no action ON DELETE no action,+ FOREIGN KEY (`server_id`) REFERENCES `switch_servers`(`id`) ON UPDATE no action ON DELETE set null+);--> statement-breakpoint+INSERT INTO `__new_agents` (`id`, `location_id`, `name`, `provider_id`, `switch_agent_id`, `api_endpoint`, `server_id`, `status`, `created_at`, `updated_at`)+SELECT `id`, `location_id`, `name`, `provider_id`, `switch_agent_id`, `api_endpoint`, `server_id`, `status`, `created_at`, `updated_at` FROM `agents`;--> statement-breakpoint+DROP TABLE `agents`;--> statement-breakpoint+ALTER TABLE `__new_agents` RENAME TO `agents`;--> statement-breakpoint+CREATE INDEX `idx_agents_location_id` ON `agents` (`location_id`);--> statement-breakpoint+CREATE INDEX `idx_agents_server_id` ON `agents` (`server_id`);diff --git a/dash/apps/switchdash-desktop/drizzle/0035_rename_app_settings_keys.sql b/dash/apps/switchdash-desktop/drizzle/0035_rename_app_settings_keys.sqlnew file mode 100644index 000000000..083173b87--- /dev/null+++ b/dash/apps/switchdash-desktop/drizzle/0035_rename_app_settings_keys.sql@@ -0,0 +1,9 @@+/*+ CHOO-1426: the app-settings sections that held default location settings were+ renamed `project` -> `location` and `localProject` -> `localLocation`. Carry an+ upgrader's persisted rows across so their defaults are not silently reset. Only+ rename when the new key isn't already present (fresh installs have neither).+*/+UPDATE OR IGNORE app_settings SET key = 'location' WHERE key = 'project';--> statement-breakpoint+UPDATE OR IGNORE app_settings SET key = 'localLocation' WHERE key = 'localProject';--> statement-breakpoint+DELETE FROM app_settings WHERE key IN ('project', 'localProject');diff --git a/dash/apps/switchdash-desktop/drizzle/0036_rename_workspace_provider_setting.sql b/dash/apps/switchdash-desktop/drizzle/0036_rename_workspace_provider_setting.sqlnew file mode 100644index 000000000..0e8feb282--- /dev/null+++ b/dash/apps/switchdash-desktop/drizzle/0036_rename_workspace_provider_setting.sql@@ -0,0 +1,16 @@+/*+ CHOO-1426: the base location setting `workspaceProvider` was renamed to+ `locationProvider`. It lives inside the `base_settings_json` blob (not a+ column), so rewrite persisted blobs: move the nested object to the new key and+ drop the old one. Only touch rows that actually carry the old key.+*/+UPDATE location_settings+SET base_settings_json = json_remove(+ json_set(+ base_settings_json,+ '$.locationProvider',+ json(json_extract(base_settings_json, '$.workspaceProvider'))+ ),+ '$.workspaceProvider'+)+WHERE json_type(base_settings_json, '$.workspaceProvider') IS NOT NULL;diff --git a/dash/apps/switchdash-desktop/drizzle/meta/0031_snapshot.json b/dash/apps/switchdash-desktop/drizzle/meta/0031_snapshot.jsonnew file mode 100644index 000000000..e3b63f855--- /dev/null+++ b/dash/apps/switchdash-desktop/drizzle/meta/0031_snapshot.json@@ -0,0 +1,818 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "cf426291-f28c-48f0-82b9-c298aa60427e",+ "prevId": "0d318c47-ff94-4887-a8a3-5792027da23b",+ "tables": {+ "agents": {+ "name": "agents",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "location_id": {+ "name": "location_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "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+ },+ "connection": {+ "name": "connection",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'local'"+ },+ "remote_config_json": {+ "name": "remote_config_json",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "idx_agents_project_id": {+ "name": "idx_agents_project_id",+ "columns": ["project_id"],+ "isUnique": false+ },+ "idx_agents_server_id": {+ "name": "idx_agents_server_id",+ "columns": ["server_id"],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "agents_project_id_projects_id_fk": {+ "name": "agents_project_id_projects_id_fk",+ "tableFrom": "agents",+ "tableTo": "projects",+ "columnsFrom": ["project_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "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": {}+ },+ "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": {}+ },+ "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": {}+ },+ "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": {}+ },+ "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": {}+ },+ "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": {}+ },+ "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": {}+ },+ "project_settings": {+ "name": "project_settings",+ "columns": {+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "base_project_settings_json": {+ "name": "base_project_settings_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "shareable_project_settings_json": {+ "name": "shareable_project_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": {+ "project_settings_project_id_projects_id_fk": {+ "name": "project_settings_project_id_projects_id_fk",+ "tableFrom": "project_settings",+ "tableTo": "projects",+ "columnsFrom": ["project_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {}+ },+ "projects": {+ "name": "projects",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "path": {+ "name": "path",+ "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_projects_path": {+ "name": "idx_projects_path",+ "columns": ["path"],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {}+ },+ "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": {}+ },+ "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": {}+ },+ "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+ },+ "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": {}+ }+ },+ "enums": {},+ "_meta": {+ "schemas": {},+ "tables": {},+ "columns": {}+ },+ "internal": {+ "indexes": {}+ }+}diff --git a/dash/apps/switchdash-desktop/drizzle/meta/0032_snapshot.json b/dash/apps/switchdash-desktop/drizzle/meta/0032_snapshot.jsonnew file mode 100644index 000000000..b38bcb7a5--- /dev/null+++ b/dash/apps/switchdash-desktop/drizzle/meta/0032_snapshot.json@@ -0,0 +1,818 @@+{+ "id": "94276309-8a15-4163-a0f6-c1aad71eed99",+ "prevId": "cf426291-f28c-48f0-82b9-c298aa60427e",+ "version": "6",+ "dialect": "sqlite",+ "tables": {+ "agents": {+ "name": "agents",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "location_id": {+ "name": "location_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "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+ },+ "connection": {+ "name": "connection",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'local'"+ },+ "remote_config_json": {+ "name": "remote_config_json",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "idx_agents_project_id": {+ "name": "idx_agents_project_id",+ "columns": ["project_id"],+ "isUnique": false+ },+ "idx_agents_server_id": {+ "name": "idx_agents_server_id",+ "columns": ["server_id"],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "agents_project_id_projects_id_fk": {+ "name": "agents_project_id_projects_id_fk",+ "tableFrom": "agents",+ "columnsFrom": ["project_id"],+ "tableTo": "projects",+ "columnsTo": ["id"],+ "onUpdate": "no action",+ "onDelete": "cascade"+ },+ "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": {}+ },+ "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": {}+ },+ "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": {}+ },+ "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": {}+ },+ "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": {}+ },+ "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": {}+ },+ "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": {}+ },+ "project_settings": {+ "name": "project_settings",+ "columns": {+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "base_project_settings_json": {+ "name": "base_project_settings_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "shareable_project_settings_json": {+ "name": "shareable_project_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": {+ "project_settings_project_id_projects_id_fk": {+ "name": "project_settings_project_id_projects_id_fk",+ "tableFrom": "project_settings",+ "columnsFrom": ["project_id"],+ "tableTo": "projects",+ "columnsTo": ["id"],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {}+ },+ "projects": {+ "name": "projects",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "path": {+ "name": "path",+ "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_projects_path": {+ "name": "idx_projects_path",+ "columns": ["path"],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {}+ },+ "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": {}+ },+ "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": {}+ },+ "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+ },+ "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": {}+ }+ },+ "enums": {},+ "_meta": {+ "columns": {},+ "schemas": {},+ "tables": {}+ },+ "internal": {+ "indexes": {}+ }+}diff --git a/dash/apps/switchdash-desktop/drizzle/meta/0033_snapshot.json b/dash/apps/switchdash-desktop/drizzle/meta/0033_snapshot.jsonnew file mode 100644index 000000000..9e6dc73d3--- /dev/null+++ b/dash/apps/switchdash-desktop/drizzle/meta/0033_snapshot.json@@ -0,0 +1,670 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "088044a5-00c8-4529-b122-ab85d96d95ca",+ "prevId": "94276309-8a15-4163-a0f6-c1aad71eed99",+ "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+ },+ "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": {}+ },+ "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": {}+ },+ "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": {}+ },+ "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": {}+ },+ "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": {}+ },+ "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": {}+ },+ "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": {}+ },+ "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": {}+ },+ "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": {}+ },+ "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+ },+ "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": {}+ }+ },+ "enums": {},+ "_meta": {+ "schemas": {},+ "tables": {},+ "columns": {}+ },+ "internal": {+ "indexes": {}+ }+}diff --git a/dash/apps/switchdash-desktop/drizzle/meta/0034_snapshot.json b/dash/apps/switchdash-desktop/drizzle/meta/0034_snapshot.jsonnew file mode 100644index 000000000..82ce248d8--- /dev/null+++ b/dash/apps/switchdash-desktop/drizzle/meta/0034_snapshot.json@@ -0,0 +1,670 @@+{+ "id": "9bbce846-811f-40cf-b133-cb0945590ea4",+ "prevId": "088044a5-00c8-4529-b122-ab85d96d95ca",+ "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+ },+ "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+ },+ "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": {}+ },+ "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": {}+ },+ "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": {}+ },+ "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": {}+ },+ "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": {}+ },+ "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": {}+ },+ "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": {}+ },+ "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": {}+ },+ "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": {}+ },+ "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+ },+ "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": {}+ }+ },+ "enums": {},+ "_meta": {+ "columns": {},+ "schemas": {},+ "tables": {}+ },+ "internal": {+ "indexes": {}+ }+}diff --git a/dash/apps/switchdash-desktop/drizzle/meta/0035_snapshot.json b/dash/apps/switchdash-desktop/drizzle/meta/0035_snapshot.jsonnew file mode 100644index 000000000..8819e882f--- /dev/null+++ b/dash/apps/switchdash-desktop/drizzle/meta/0035_snapshot.json@@ -0,0 +1,670 @@+{+ "id": "d3061c73-4590-4b72-9602-6463c3f2b1bb",+ "prevId": "9bbce846-811f-40cf-b133-cb0945590ea4",+ "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+ },+ "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+ },+ "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": {}+ },+ "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": {}+ },+ "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": {}+ },+ "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": {}+ },+ "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": {}+ },+ "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": {}+ },+ "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": {}+ },+ "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": {}+ },+ "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": {}+ },+ "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+ },+ "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": {}+ }+ },+ "enums": {},+ "_meta": {+ "columns": {},+ "schemas": {},+ "tables": {}+ },+ "internal": {+ "indexes": {}+ }+}diff --git a/dash/apps/switchdash-desktop/drizzle/meta/0036_snapshot.json b/dash/apps/switchdash-desktop/drizzle/meta/0036_snapshot.jsonnew file mode 100644index 000000000..92120a32f--- /dev/null+++ b/dash/apps/switchdash-desktop/drizzle/meta/0036_snapshot.json@@ -0,0 +1,670 @@+{+ "id": "57e3dc0d-71bf-4223-8960-3f284d9ef932",+ "prevId": "d3061c73-4590-4b72-9602-6463c3f2b1bb",+ "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+ },+ "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+ },+ "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": {}+ },+ "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": {}+ },+ "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": {}+ },+ "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": {}+ },+ "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": {}+ },+ "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": {}+ },+ "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": {}+ },+ "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": {}+ },+ "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": {}+ },+ "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+ },+ "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": {}+ }+ },+ "enums": {},+ "_meta": {+ "columns": {},+ "schemas": {},+ "tables": {}+ },+ "internal": {+ "indexes": {}+ }+}diff --git a/dash/apps/switchdash-desktop/drizzle/meta/_journal.json b/dash/apps/switchdash-desktop/drizzle/meta/_journal.jsonindex 5062fcfbb..fe13b0ab2 100644--- a/dash/apps/switchdash-desktop/drizzle/meta/_journal.json+++ b/dash/apps/switchdash-desktop/drizzle/meta/_journal.json@@ -218,6 +218,48 @@"when": 1782906745219,"tag": "0030_optimal_major_mapleleaf","breakpoints": true+ },+ {+ "idx": 31,+ "version": "6",+ "when": 1784397875070,+ "tag": "0031_mean_king_cobra",+ "breakpoints": true+ },+ {+ "idx": 32,+ "version": "6",+ "when": 1784397891249,+ "tag": "0032_backfill_locations",+ "breakpoints": true+ },+ {+ "idx": 33,+ "version": "6",+ "when": 1784397998899,+ "tag": "0033_majestic_slapstick",+ "breakpoints": true+ },+ {+ "idx": 34,+ "version": "6",+ "when": 1784398050835,+ "tag": "0034_enforce_agents_location_not_null",+ "breakpoints": true+ },+ {+ "idx": 35,+ "version": "6",+ "when": 1784403927964,+ "tag": "0035_rename_app_settings_keys",+ "breakpoints": true+ },+ {+ "idx": 36,+ "version": "6",+ "when": 1784451483886,+ "tag": "0036_rename_workspace_provider_setting",+ "breakpoints": true}]}diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/agent-hook-service.ts b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/agent-hook-service.tsindex 46dc1deb8..0d9edee30 100644--- a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/agent-hook-service.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/agent-hook-service.ts@@ -39,7 +39,7 @@ function determineSoundEvent(}async function handleSessionEvent(- ctx: { sessionId: string; projectId: string; providerId: string },+ ctx: { sessionId: string; providerId: string },providerSessionId: string): Promise<void> {if (!isValidProviderSessionId(ctx.providerId, providerSessionId)) return;@@ -54,7 +54,6 @@ async function handleSessionEvent(events.emit(sessionChangedChannel, {sessionId: ctx.sessionId,- projectId: ctx.projectId,changes: { providerSessionId },});}@@ -130,7 +129,7 @@ class AgentHookService implements IInitializable, IDisposable, Hookable<AgentHooasync initialize(): Promise<void> {await this.server.start(async (raw) => this.handleRawHook(raw, { startLocalPoller: true }));- sessionHooks.on('session:input-submitted', ({ projectId, sessionId, providerId }) => {+ sessionHooks.on('session:input-submitted', ({ sessionId, providerId }) => {// Only synthesise a 'start' event when the plugin does not supply its own// start hook (e.g. UserPromptSubmit). Providers with start-capable hooks// get 'working' from the real hook event instead.@@ -145,7 +144,6 @@ class AgentHookService implements IInitializable, IDisposable, Hookable<AgentHootype: 'start',source: 'input',providerId,- projectId,sessionId,timestamp: Date.now(),payload: {},@@ -157,7 +155,6 @@ class AgentHookService implements IInitializable, IDisposable, Hookable<AgentHoovoid touchSession(sessionId, now).then(() => {events.emit(sessionChangedChannel, {sessionId,- projectId,changes: { lastInteractedAt: now },});});@@ -194,7 +191,6 @@ class AgentHookService implements IInitializable, IDisposable, Hookable<AgentHooevents.emit(sessionAgentStatusChangedChannel, {sessionId: event.sessionId,- projectId: event.projectId,status,seen: seen === 1,soundEvent: determineSoundEvent(event, status),@@ -223,7 +219,6 @@ class AgentHookService implements IInitializable, IDisposable, Hookable<AgentHooevents.emit(sessionAgentStatusChangedChannel, {sessionId,- projectId: loaded.projectId,status: 'idle',seen: true,soundEvent: undefined,diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/claude-trust-service.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/claude-trust-service.test.tsindex 45bfbdb6a..4521d178b 100644--- a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/claude-trust-service.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/claude-trust-service.test.ts@@ -111,9 +111,9 @@ describe('ClaudeTrustService', () => {expect(renameTo).toBe('/home/local-user/.claude.json');const written = JSON.parse(String(content));- expect(written.projects[path.resolve(relPath)]).toEqual({+ expect(written.locations[path.resolve(relPath)]).toEqual({hasTrustDialogAccepted: true,- hasCompletedProjectOnboarding: true,+ hasCompletedLocationOnboarding: true,});});@@ -158,10 +158,10 @@ describe('ClaudeTrustService', () => {const trustedPath = '/already/trusted';mockReadFile.mockResolvedValue(JSON.stringify({- projects: {+ locations: {[trustedPath]: {hasTrustDialogAccepted: true,- hasCompletedProjectOnboarding: true,+ hasCompletedLocationOnboarding: true,},},})@@ -237,13 +237,13 @@ describe('ClaudeTrustService', () => {expect(mockWriteFile).toHaveBeenCalledTimes(2);const secondWriteContent = JSON.parse(String(mockWriteFile.mock.calls[1][1]));- expect(secondWriteContent.projects[path.resolve('/worktree/a')]).toEqual({+ expect(secondWriteContent.locations[path.resolve('/worktree/a')]).toEqual({hasTrustDialogAccepted: true,- hasCompletedProjectOnboarding: true,+ hasCompletedLocationOnboarding: true,});- expect(secondWriteContent.projects[path.resolve('/worktree/b')]).toEqual({+ expect(secondWriteContent.locations[path.resolve('/worktree/b')]).toEqual({hasTrustDialogAccepted: true,- hasCompletedProjectOnboarding: true,+ hasCompletedLocationOnboarding: true,});});});diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/claude-trust-service.ts b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/claude-trust-service.tsindex 9f9e44b4f..7c3aac742 100644--- a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/claude-trust-service.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/claude-trust-service.ts@@ -65,7 +65,7 @@ export class ClaudeTrustService {return {configName: CLAUDE_CONFIG_NAME,parseWarningName: 'Claude',- withTrustedPath: withClaudeTrustedProject,+ withTrustedPath: withClaudeTrustedLocation,};}@@ -129,26 +129,26 @@ function parseConfig(raw: string | null, warningName: string): Record<string, un}}-function withClaudeTrustedProject(+function withClaudeTrustedLocation(config: Record<string, unknown>,worktreePath: string): Record<string, unknown> | null {- const projects = isPlainObject(config.projects) ? config.projects : {};- const existing = isPlainObject(projects[worktreePath]) ? projects[worktreePath] : {};+ const locations = isPlainObject(config.locations) ? config.locations : {};+ const existing = isPlainObject(locations[worktreePath]) ? locations[worktreePath] : {};const alreadyTrusted =existing['hasTrustDialogAccepted'] === true &&- existing['hasCompletedProjectOnboarding'] === true;+ existing['hasCompletedLocationOnboarding'] === true;if (alreadyTrusted) return null;return {...config,- projects: {- ...projects,+ locations: {+ ...locations,[worktreePath]: {...existing,hasTrustDialogAccepted: true,- hasCompletedProjectOnboarding: true,+ hasCompletedLocationOnboarding: true,},},};diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/cursor-trust-service.ts b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/cursor-trust-service.tsindex 1e829b8a9..ca136b842 100644--- a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/cursor-trust-service.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/cursor-trust-service.ts@@ -33,7 +33,7 @@ export class CursorTrustService {const workspacePath = path.resolve(cwd);const dataDir = path.join(homedir, CURSOR_DATA_DIR_NAME);const markerPath = path.join(- cursorProjectDir(workspacePath, dataDir, path),+ cursorLocationDir(workspacePath, dataDir, path),CURSOR_TRUST_MARKER_NAME);@@ -84,7 +84,7 @@ function createTrustMarker(workspacePath: string): Record<string, string> {};}-function cursorProjectDir(+function cursorLocationDir(workspacePath: string,dataDir: string,pathImpl: Pick<typeof path, 'join'>diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/db-context-resolver.ts b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/db-context-resolver.tsindex a23a9ff7c..98c831a68 100644--- a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/db-context-resolver.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/db-context-resolver.ts@@ -4,8 +4,8 @@ import type { ContextResolver } from './event-enricher';/*** The local main process's hook context resolver: derives the session context- * for a `ptyId` by parsing it and loading the session (for its project id)- * from the database.+ * for a `ptyId` by parsing it and confirming the session exists in the+ * database.*/export const dbContextResolver: ContextResolver = async (ptyId) => {const parsed = parsePtyId(ptyId);@@ -16,7 +16,6 @@ export const dbContextResolver: ContextResolver = async (ptyId) => {return {sessionId: parsed.sessionId,- projectId: loaded.projectId,providerId: parsed.providerId,ptyId,};diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/derive-agent-status.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/derive-agent-status.test.tsindex be48031e0..256eca967 100644--- a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/derive-agent-status.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/derive-agent-status.test.ts@@ -6,7 +6,7 @@ function event(partial: Partial<AgentEvent> & Pick<AgentEvent, 'type'>): AgentEvreturn {source: 'hook',providerId: 'claude-code',- projectId: 'p',+ locationId: 'p',sessionId: 's',timestamp: 1,payload: {},diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/workspace-trust-service.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/dir-trust-service.test.tssimilarity index 81%rename from dash/apps/switchdash-desktop/src/main/core/agent-hooks/workspace-trust-service.test.tsrename to dash/apps/switchdash-desktop/src/main/core/agent-hooks/dir-trust-service.test.tsindex f937d13ac..0409b00f2 100644--- a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/workspace-trust-service.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/dir-trust-service.test.ts@@ -4,7 +4,7 @@ vi.mock('@main/core/settings/settings-service', () => ({appSettingsService: { get: vi.fn() },}));-import { WorkspaceTrustService } from './workspace-trust-service';+import { DirTrustService } from './dir-trust-service';function makeProvider() {return {@@ -12,11 +12,11 @@ function makeProvider() {};}-describe('WorkspaceTrustService', () => {+describe('DirTrustService', () => {it('delegates local workspace trust to each provider', async () => {const first = makeProvider();const second = makeProvider();- const service = new WorkspaceTrustService([first, second]);+ const service = new DirTrustService([first, second]);const args = {providerId: 'cursor' as const,cwd: '/tmp/worktree',diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/dir-trust-service.ts b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/dir-trust-service.tsnew file mode 100644index 000000000..8d6f16ced--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/dir-trust-service.ts@@ -0,0 +1,26 @@+import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';+import { claudeTrustService } from './claude-trust-service';+import { cursorTrustService } from './cursor-trust-service';++type DirTrustLocalArgs = {+ providerId: AgentProviderId;+ cwd?: string;+ homedir: string;+ force?: boolean;+};++type DirTrustProvider = {+ maybeAutoTrustLocal(args: DirTrustLocalArgs): Promise<void>;+};++export class DirTrustService {+ constructor(private readonly providers: readonly DirTrustProvider[]) {}++ async maybeAutoTrustLocal(args: DirTrustLocalArgs): Promise<void> {+ for (const provider of this.providers) {+ await provider.maybeAutoTrustLocal(args);+ }+ }+}++export const dirTrustService = new DirTrustService([claudeTrustService, cursorTrustService]);diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/event-enricher.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/event-enricher.test.tsindex 51d88f78f..6e9c7a27a 100644--- a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/event-enricher.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/event-enricher.test.ts@@ -4,7 +4,6 @@ import type { RawHookRequest } from './hook-server';const ctx: AgentHookContext = {sessionId: 'session-1',- projectId: 'proj-1',providerId: 'claude-code',ptyId: 'claude-code::session-1',};diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/event-enricher.ts b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/event-enricher.tsindex b6d1b80dd..20df99d5b 100644--- a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/event-enricher.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/event-enricher.ts@@ -6,7 +6,6 @@ import type { RawHookRequest } from './hook-server';export type AgentHookContext = {sessionId: string;- projectId: string;providerId: string;ptyId: string;};@@ -73,7 +72,6 @@ function canonicalToAgentEvent(source: 'hook',ptyId: ctx.ptyId,providerId: ctx.providerId,- projectId: ctx.projectId,sessionId: ctx.sessionId,timestamp: Date.now(),payload: {diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/hook-config-service.ts b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/hook-config-service.tsindex 0a384f390..db8f1ac0d 100644--- a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/hook-config-service.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/hook-config-service.ts@@ -50,8 +50,8 @@ export async function ensureHooksInstalled({sessionPath: string;}): Promise<boolean> {try {- const localProjectSettings = await appSettingsService.get('localProject');- const writeGitIgnoreEntries = localProjectSettings.writeAgentConfigToGitIgnore ?? true;+ const localLocationSettings = await appSettingsService.get('localLocation');+ const writeGitIgnoreEntries = localLocationSettings.writeAgentConfigToGitIgnore ?? true;const plugin = getPlugin(providerId);const hooksDescriptor = plugin.capabilities.hooks;diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/notification.ts b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/notification.tsindex c29bcf9f7..61eba399d 100644--- a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/notification.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/notification.ts@@ -1,6 +1,7 @@import { eq } from 'drizzle-orm';import { app, BrowserWindow, Notification } from 'electron';import { getMainWindow } from '@main/app/window';+import { loadSessionWithAgent } from '@main/core/sessions/session-join';import { appSettingsService } from '@main/core/settings/settings-service';import { db } from '@main/db/client';import { sessions } from '@main/db/schema';@@ -75,9 +76,12 @@ export async function maybeShowNotification(event: AgentEvent, appFocused: boolereleaseNotification();if (event.sessionId) {- events.emit(notificationFocusSessionChannel, {- projectId: event.projectId,- sessionId: event.sessionId,+ void loadSessionWithAgent(event.sessionId).then((loaded) => {+ if (!loaded) return;+ events.emit(notificationFocusSessionChannel, {+ agentId: loaded.row.agentId,+ sessionId: event.sessionId,+ });});}});diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/workspace-trust-service.ts b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/workspace-trust-service.tsdeleted file mode 100644index 6824fdb51..000000000--- a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/workspace-trust-service.ts+++ /dev/null@@ -1,29 +0,0 @@-import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';-import { claudeTrustService } from './claude-trust-service';-import { cursorTrustService } from './cursor-trust-service';--type WorkspaceTrustLocalArgs = {- providerId: AgentProviderId;- cwd?: string;- homedir: string;- force?: boolean;-};--type WorkspaceTrustProvider = {- maybeAutoTrustLocal(args: WorkspaceTrustLocalArgs): Promise<void>;-};--export class WorkspaceTrustService {- constructor(private readonly providers: readonly WorkspaceTrustProvider[]) {}-- async maybeAutoTrustLocal(args: WorkspaceTrustLocalArgs): Promise<void> {- for (const provider of this.providers) {- await provider.maybeAutoTrustLocal(args);- }- }-}--export const workspaceTrustService = new WorkspaceTrustService([- claudeTrustService,- cursorTrustService,-]);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 1e6ef485f..9ad935dac 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@@ -18,7 +18,6 @@ import { resolveSidecarBundlePath } from './resolve-sidecar-bundle';*/export async function ensureAgentSidecar(params: {providerId: string;- projectId: string;/** Absolute remote repo dir; the agent's Switch creds + bundle live under it. */repoDir: string;deeplinkScheme: string;@@ -26,7 +25,7 @@ export async function ensureAgentSidecar(params: {connectionId: string;host: SidecarHost;}): Promise<SidecarEndpoint> {- const { providerId, projectId, repoDir, deeplinkScheme, ctx, connectionId, host } = params;+ const { providerId, repoDir, deeplinkScheme, ctx, connectionId, host } = params;const launchSpec = await generateAgentLaunchSpec({providerId,remoteRepoDir: repoDir,@@ -38,7 +37,7 @@ export async function ensureAgentSidecar(params: {host,bundlePath: resolveSidecarBundlePath(),sidecarTmuxName: agentSidecarTmuxName(repoDir),- config: { projectId, repoDir, deeplinkScheme, launchSpec },+ config: { repoDir, deeplinkScheme, launchSpec },log,});return launcher.deployAndLaunch();@@ -53,14 +52,13 @@ export async function ensureAgentSidecar(params: {*/export async function probeAgentSidecar(params: {providerId: string;- projectId: string;repoDir: string;deeplinkScheme: string;ctx: IExecutionContext;connectionId: string;host: SidecarHost;}): Promise<SidecarEndpoint | null> {- const { providerId, projectId, repoDir, deeplinkScheme, ctx, connectionId, host } = params;+ const { providerId, repoDir, deeplinkScheme, ctx, connectionId, host } = params;const launchSpec = await generateAgentLaunchSpec({providerId,remoteRepoDir: repoDir,@@ -72,7 +70,7 @@ export async function probeAgentSidecar(params: {host,bundlePath: resolveSidecarBundlePath(),sidecarTmuxName: agentSidecarTmuxName(repoDir),- config: { projectId, repoDir, deeplinkScheme, launchSpec },+ config: { repoDir, deeplinkScheme, launchSpec },log,});return launcher.probeExisting();diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.test.tsindex 9f78f5246..15e479f69 100644--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.test.ts@@ -33,8 +33,8 @@ vi.mock('@main/core/agent-hooks/agent-hook-service', () => ({},}));-vi.mock('@main/core/agent-hooks/workspace-trust-service', () => ({- workspaceTrustService: {+vi.mock('@main/core/agent-hooks/dir-trust-service', () => ({+ dirTrustService: {maybeAutoTrustLocal: vi.fn(),},}));@@ -141,7 +141,7 @@ vi.mock('@main/core/settings/settings-service', () => ({fontSize: 13,}: {- defaultProjectsDirectory: '',+ defaultLocationsDirectory: '',defaultWorktreeDirectory: '',writeAgentConfigToGitIgnore: true,}@@ -177,7 +177,7 @@ function localProvider({ctx?: ConstructorParameters<typeof LocalAgentRuntime>[0]['ctx'];} = {}) {return new LocalAgentRuntime({- projectId: 'project-1',+ locationId: 'location-1',sessionId: 'session-1',sessionPath: '/tmp/session-1',tmux,@@ -217,9 +217,9 @@ function fakePty(exitHandlers: Array<(info: PtyExitInfo) => void>): Pty {function mockSettings(): void {vi.mocked(appSettingsService.get).mockImplementation(async (key) => {- if (key === 'localProject') {+ if (key === 'localLocation') {return {- defaultProjectsDirectory: '',+ defaultLocationsDirectory: '',defaultWorktreeDirectory: '',writeAgentConfigToGitIgnore: true,} as never;@@ -242,7 +242,7 @@ describe('local agent runtime respawn state', () => {vi.mocked(events.emit).mockClear();vi.mocked(agentHookService.getPort).mockReturnValue(0);vi.mocked(agentHookService.getToken).mockReturnValue('token');- ptySessionRegistry.unregister('project-1:session-1');+ ptySessionRegistry.unregister('location-1:session-1');});it('passes global editor variables to local agent sessions', async () => {@@ -422,7 +422,7 @@ describe('local agent runtime respawn state', () => {spawnLocalPty.mockReturnValue(fakePty(exitHandlers));const provider = localProvider();const item = session();- const sessionId = makeAgentPtySessionId('project-1', item.id);+ const sessionId = makeAgentPtySessionId('location-1', item.id);await provider.start(item);vi.mocked(events.emit).mockClear();@@ -442,7 +442,7 @@ describe('local agent runtime respawn state', () => {});const provider = localProvider();const item = session();- const sessionId = makeAgentPtySessionId('project-1', item.id);+ const sessionId = makeAgentPtySessionId('location-1', item.id);await provider.start(item, { cols: 100, rows: 40 }, true);ptySessionRegistry.resize(sessionId, 68, 42);diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.tsindex e5e937eab..a2d576c20 100644--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.ts@@ -1,7 +1,7 @@import { homedir } from 'node:os';import { agentHookService } from '@main/core/agent-hooks/agent-hook-service';+import { dirTrustService } from '@main/core/agent-hooks/dir-trust-service';import { ensureHooksInstalled } from '@main/core/agent-hooks/hook-config-service';-import { workspaceTrustService } from '@main/core/agent-hooks/workspace-trust-service';import { AgentRuntimeSupervisor } from '@main/core/agent-runtime/agent-runtime-supervisor';import { resolveAgentSessionCommandArgs } from '@main/core/agent-runtime/resolve-agent-session-command';import type { AgentRuntimeProvider } from '@main/core/agent-runtime/types';@@ -44,7 +44,7 @@ export class LocalAgentRuntime implements AgentRuntimeProvider {private pty: Pty | null = null;private known = false;private supervisor = new AgentRuntimeSupervisor();- private readonly projectId: string;+ private readonly locationId: string;private readonly sessionPath: string;private readonly sessionId: string;private readonly tmux: boolean;@@ -53,7 +53,7 @@ export class LocalAgentRuntime implements AgentRuntimeProvider {private readonly ctx: IExecutionContext;private readonly sessionEnvVars: Record<string, string>;constructor({- projectId,+ locationId,sessionPath,sessionId,tmux = false,@@ -62,7 +62,7 @@ export class LocalAgentRuntime implements AgentRuntimeProvider {ctx,sessionEnvVars = {},}: {- projectId: string;+ locationId: string;sessionPath: string;sessionId: string;tmux?: boolean;@@ -71,7 +71,7 @@ export class LocalAgentRuntime implements AgentRuntimeProvider {ctx: IExecutionContext;sessionEnvVars?: Record<string, string>;}) {- this.projectId = projectId;+ this.locationId = locationId;this.sessionPath = sessionPath;this.sessionId = sessionId;this.tmux = tmux;@@ -83,7 +83,7 @@ export class LocalAgentRuntime implements AgentRuntimeProvider {/** The registry key of this session's agent PTY (session id == session id). */private get ptySessionId(): string {- return makeAgentPtySessionId(this.projectId, this.sessionId);+ return makeAgentPtySessionId(this.locationId, this.sessionId);}async start(@@ -116,7 +116,7 @@ export class LocalAgentRuntime implements AgentRuntimeProvider {if (!spawnToken) return;try {- await workspaceTrustService.maybeAutoTrustLocal({+ await dirTrustService.maybeAutoTrustLocal({providerId: session.providerId,cwd: this.sessionPath,homedir: homedir(),@@ -271,7 +271,6 @@ export class LocalAgentRuntime implements AgentRuntimeProvider {void switchRoomService.restorePoller({sessionId: this.sessionId,- projectId: this.projectId,providerId: session.providerId,ptyId,})diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-plugin-fs.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-plugin-fs.tsindex bd7e828e1..719b9e84f 100644--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-plugin-fs.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-plugin-fs.ts@@ -9,7 +9,7 @@ import {/*** Adapt a remote SSH `FileSystemProvider` to the `PluginFs` shape that plugin* hook/config writers expect, so the same `writeHooks` logic that runs against- * the local workspace can install an agent's hooks on its VM over SFTP.+ * a local location can install an agent's hooks on its VM over SFTP.** The provider is rooted at the agent's remote repo dir, so paths are relative* to it (e.g. `.claude/settings.local.json`). Remote hosts are POSIX, so parentdiff --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 1ff45ebcc..7730d68b4 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@@ -20,7 +20,6 @@ const SPEC: AgentLaunchSpec = {};const CONFIG: SidecarLaunchConfig = {- projectId: 'proj-1',repoDir: '/home/dev/repo',deeplinkScheme: 'switchdash',launchSpec: SPEC,@@ -155,7 +154,7 @@ describe('RemoteSidecarLauncher', () => {]);const inner = launch!.args[6];expect(inner).toContain("SWITCHDASH_SIDECAR_REPO_DIR='/home/dev/repo'");- expect(inner).toContain("SWITCHDASH_SIDECAR_PROJECT_ID='proj-1'");+ expect(inner).not.toContain('SWITCHDASH_SIDECAR_LOCATION_ID');expect(inner).not.toContain('SWITCHDASH_SIDECAR_TMUX_TARGET');expect(inner).toContain('.switchdash/sidecar.mjs');});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 ea70a6254..77253d58d 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@@ -30,7 +30,6 @@ const READY_POLL_INTERVAL_MS = 250;const READY_MAX_ATTEMPTS = 80; // ~20sexport interface SidecarLaunchConfig {- projectId: string;/** Absolute remote repo dir; the bundle, spec, ready file, and log live under .switchdash/. */repoDir: string;deeplinkScheme: string;@@ -62,7 +61,6 @@ export interface SidecarLauncherLogger {function sidecarEnv(config: SidecarLaunchConfig): Record<string, string> {return {- SWITCHDASH_SIDECAR_PROJECT_ID: config.projectId,SWITCHDASH_SIDECAR_REPO_DIR: config.repoDir,SWITCHDASH_SIDECAR_DEEPLINK_SCHEME: config.deeplinkScheme,};diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.tsindex c16cd2096..ae7af288c 100644--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts@@ -139,7 +139,7 @@ function sshProvider({ctx?: ConstructorParameters<typeof SshAgentRuntime>[0]['ctx'];} = {}) {return new SshAgentRuntime({- projectId: 'project-1',+ locationId: 'location-1',sessionId: 'session-1',sessionPath: '/repo',tmux,@@ -199,14 +199,14 @@ describe('SshAgentRuntime', () => {httpPostJsonOverChannel.mockClear();vi.mocked(events.emit).mockClear();connectionListeners.length = 0;- ptySessionRegistry.unregister('project-1:session-1');+ ptySessionRegistry.unregister('location-1:session-1');});it('spawns the agent over SSH and registers a remote pty', async () => {const exitHandlers: Array<Array<(info: PtyExitInfo) => void>> = [];mockSpawn(exitHandlers);const item = session();- const sessionId = makeAgentPtySessionId('project-1', item.id);+ const sessionId = makeAgentPtySessionId('location-1', item.id);await sshProvider().start(item);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 97649970c..fd1004ba1 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@@ -56,7 +56,7 @@ export class SshAgentRuntime implements AgentRuntimeProvider {private sidecarEndpoint: { port: number; token: string } | null = null;private supervisor = new AgentRuntimeSupervisor();private readonly handleConnectionEvent: (evt: SshConnectionManagerEvent) => void;- private readonly projectId: string;+ private readonly locationId: string;private readonly sessionPath: string;private readonly sessionId: string;private readonly sessionEnvVars: Record<string, string>;@@ -68,7 +68,7 @@ export class SshAgentRuntime implements AgentRuntimeProvider {private readonly connectionId: string;constructor({- projectId,+ locationId,sessionPath,sessionId,sessionEnvVars = {},@@ -79,7 +79,7 @@ export class SshAgentRuntime implements AgentRuntimeProvider {proxy,connectionId,}: {- projectId: string;+ locationId: string;sessionPath: string;sessionId: string;sessionEnvVars?: Record<string, string>;@@ -90,7 +90,7 @@ export class SshAgentRuntime implements AgentRuntimeProvider {proxy: SshClientProxy;connectionId: string;}) {- this.projectId = projectId;+ this.locationId = locationId;this.sessionPath = sessionPath;this.sessionId = sessionId;this.sessionEnvVars = sessionEnvVars;@@ -115,7 +115,7 @@ export class SshAgentRuntime implements AgentRuntimeProvider {/** The registry key of this session's agent PTY. */private get ptySessionId(): string {- return makeAgentPtySessionId(this.projectId, this.sessionId);+ return makeAgentPtySessionId(this.locationId, this.sessionId);}/**@@ -199,7 +199,6 @@ export class SshAgentRuntime implements AgentRuntimeProvider {// this session's hooks at its shared hook server. Reattaches if already up.const endpoint = await ensureAgentSidecar({providerId: session.providerId,- projectId: this.projectId,repoDir: this.sessionPath,deeplinkScheme: DEEPLINK_SCHEME,ctx: this.ctx,@@ -589,7 +588,7 @@ export class SshAgentRuntime implements AgentRuntimeProvider {);}sessionHooks._emit('session:remote-terminated', {- projectId: this.projectId,+ locationId: this.locationId,sessionId: this.sessionId,terminatedSessionId,});diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/agent-events.ts b/dash/apps/switchdash-desktop/src/main/core/agents/agent-events.tsnew file mode 100644index 000000000..aec60f174--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agents/agent-events.ts@@ -0,0 +1,24 @@+import { HookCore, type Hookable } from '@main/lib/hookable';+import { log } from '@main/lib/logger';+import type { Agent } from '@shared/core/agents/agents';++export type AgentCrudHooks = {+ 'agent:created': (agent: Agent) => void | Promise<void>;+ 'agent:deleted': (agentId: string) => void | Promise<void>;+};++class AgentEvents implements Hookable<AgentCrudHooks> {+ private readonly _core = new HookCore<AgentCrudHooks>((name, e) =>+ log.error(`AgentEvents: ${String(name)} hook error`, e)+ );++ on<K extends keyof AgentCrudHooks>(name: K, handler: AgentCrudHooks[K]) {+ return this._core.on(name, handler);+ }++ _emit<K extends keyof AgentCrudHooks>(name: K, ...args: Parameters<AgentCrudHooks[K]>): void {+ this._core.callHookBackground(name, ...args);+ }+}++export const agentEvents = new AgentEvents();diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/agent-location.ts b/dash/apps/switchdash-desktop/src/main/core/agents/agent-location.tsnew file mode 100644index 000000000..b7606ca0f--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agents/agent-location.ts@@ -0,0 +1,21 @@+import { getLocationById } from '@main/core/locations/store';+import type { Agent } from '@shared/core/agents/agents';+import type { Location } from '@shared/core/locations/locations';++/** Resolve an agent's location, failing loud when the row is missing. */+export async function getAgentLocation(agent: Pick<Agent, 'id' | 'locationId'>): Promise<Location> {+ const location = await getLocationById(agent.locationId);+ if (!location) {+ throw new Error(`Location ${agent.locationId} not found for agent ${agent.id}`);+ }+ return location;+}++/** The agent's location when it is remote (on an SSH host), else null. */+export async function getRemoteAgentLocation(+ agent: Pick<Agent, 'id' | 'locationId'>+): Promise<(Location & { sshHost: string }) | null> {+ const location = await getAgentLocation(agent);+ if (location.sshHost === null) return null;+ return { ...location, sshHost: location.sshHost };+}diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/connect-remote-agent.ts b/dash/apps/switchdash-desktop/src/main/core/agents/connect-remote-agent.tsindex ff8660097..2e4d675d3 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/connect-remote-agent.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/connect-remote-agent.ts@@ -2,10 +2,11 @@ import type { SidecarHost } from '@main/core/agent-runtime/impl/remote-sidecar-limport { SshExecutionContext } from '@main/core/execution-context/ssh-execution-context';import type { IExecutionContext } from '@main/core/execution-context/types';import { SshFileSystem } from '@main/core/fs/impl/ssh-fs';+import { sshConnectionIdForHost } from '@main/core/locations/location-transport';import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';import type { SshClientProxy } from '@main/core/ssh/lifecycle/ssh-client-proxy';-import { agentSshConnectionId } from '@main/core/workspaces/resolve-agent-workspace';import type { Agent } from '@shared/core/agents/agents';+import { getRemoteAgentLocation } from './agent-location';function createSidecarHost(ctx: IExecutionContext,@@ -28,7 +29,7 @@ function createSidecarHost(};}-/** Resolve the SSH execution context + a host seam + proxy for a remote agent, or throw if not remote. */+/** Resolve the SSH execution context + a host seam + proxy for an agent at a remote location, or throw. */export async function connectRemoteAgent(agent: Agent): Promise<{ctx: IExecutionContext;connectionId: string;@@ -36,18 +37,18 @@ export async function connectRemoteAgent(agent: Agent): Promise<{host: SidecarHost;proxy: SshClientProxy;}> {- if (agent.connection !== 'remote' || !agent.remoteConfig) {- throw new Error(`agent ${agent.id} is not configured to run remotely`);+ const location = await getRemoteAgentLocation(agent);+ if (!location) {+ throw new Error(`agent ${agent.id} is not at a remote location`);}- const { sshHost, remoteRepoDir } = agent.remoteConfig;- const connectionId = agentSshConnectionId(sshHost);- const proxy = await ensureSshConnected(connectionId, sshHost);- const ctx = new SshExecutionContext(proxy, { root: remoteRepoDir });+ const connectionId = sshConnectionIdForHost(location.sshHost);+ const proxy = await ensureSshConnected(connectionId, location.sshHost);+ const ctx = new SshExecutionContext(proxy, { root: location.dir });return {ctx,connectionId,- remoteRepoDir,- host: createSidecarHost(ctx, proxy, remoteRepoDir),+ remoteRepoDir: location.dir,+ host: createSidecarHost(ctx, proxy, location.dir),proxy,};}diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/controller.ts b/dash/apps/switchdash-desktop/src/main/core/agents/controller.tsindex 059e71d43..84cd6af5c 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/controller.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/controller.ts@@ -1,7 +1,5 @@-import { eq } from 'drizzle-orm';-import { db } from '@main/db/client';-import { projects } from '@main/db/schema';import type { CreateAgentParams, RenameAgentParams } from '@shared/core/agents/agents';+import type { OnboardAgentParams } from '@shared/core/agents/onboarding';import type { AgentVerifyResult } from '@shared/core/switch-servers/switch-servers';import { createRPCController } from '@shared/lib/ipc/rpc';import { assignAgentServer } from './assignAgentServer';@@ -9,20 +7,19 @@ import { createAgent } from './createAgent';import { deleteAgent } from './deleteAgent';import { getAgentById } from './getAgentById';import { getAgents } from './getAgents';-import { ensureRemoteWatcher, startRemoteDiscovery } from './remote-watcher';+import { onboardAgent } from './onboard-agent';import { renameAgent } from './renameAgent';import {getAgentAutoSession,setAgentAutoSession,type AgentAutoSessionParams,} from './setAgentAutoSession';-import { setAgentConnection, type SetAgentConnectionParams } from './setAgentConnection';-import { setupRemoteAgent } from './setup-remote-agent';import { updateAgent, type UpdateAgentParams } from './updateAgent';export const agentsController = createRPCController({createAgent: (params: CreateAgentParams) => createAgent(params),- getAgents: (projectId?: string) => getAgents(projectId),+ onboardAgent: (params: OnboardAgentParams) => onboardAgent(params),+ getAgents: (locationId?: string) => getAgents(locationId),getAgentById: (agentId: string) => getAgentById(agentId),renameAgent: (params: RenameAgentParams) => renameAgent(params),deleteAgent: (agentId: string) => deleteAgent(agentId),@@ -33,40 +30,4 @@ export const agentsController = createRPCController({setAgentAutoSession(params),getAgentAutoSession: (params: { agentId: string }): Promise<boolean> =>getAgentAutoSession(params),- setAgentConnection: (params: SetAgentConnectionParams) => setAgentConnection(params),-- /**- * Copy a remote agent's Switch credentials onto its host (CHOO-1059, option A).- * Run after configuring an agent remote and before its first remote session.- * Resolves the agent's local project dir (where its minted creds live) and- * ships them to the remote working dir over SFTP.- */- setupRemoteAgent: async (params: { agentId: string }): Promise<void> => {- const agent = await getAgentById(params.agentId);- if (!agent) throw new Error(`No agent with id ${params.agentId}`);- if (agent.connection !== 'remote' || !agent.remoteConfig) {- throw new Error(`Agent ${params.agentId} is not configured to run remotely`);- }- const [project] = await db- .select({ path: projects.path })- .from(projects)- .where(eq(projects.id, agent.projectId))- .limit(1);- if (!project) {- throw new Error(`No project ${agent.projectId} for agent ${params.agentId}`);- }- if (project.path === null) {- throw new Error(- `Agent ${params.agentId} has no local directory; its Switch credentials already live on the remote host, so there is nothing to copy.`- );- }- await setupRemoteAgent({ remoteConfig: agent.remoteConfig, localDir: project.path });- // Bring up (or reattach to) the on-VM notification-watcher daemon so the- // agent auto-starts sessions while switchdash is closed. No-op unless- // auto_session is enabled for the agent.- await ensureRemoteWatcher(params.agentId);- // Discover sessions this agent already has running elsewhere (another client- // or the VM watcher), regardless of auto_session.- await startRemoteDiscovery(params.agentId);- },});diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/createAgent.ts b/dash/apps/switchdash-desktop/src/main/core/agents/createAgent.tsindex dc8e8715a..12653b8f1 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/createAgent.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/createAgent.ts@@ -9,7 +9,7 @@ export async function createAgent(params: CreateAgentParams): Promise<Agent> {.insert(agents).values({id: params.id,- projectId: params.projectId,+ locationId: params.locationId,name: params.name,providerId: params.providerId,switchAgentId: params.switchAgentId,diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/deleteAgent.ts b/dash/apps/switchdash-desktop/src/main/core/agents/deleteAgent.tsindex 721805d98..bc11cb538 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/deleteAgent.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/deleteAgent.ts@@ -5,24 +5,47 @@ import {setAutoSessionSubagent,} from '@main/core/switch-rooms/auto-session-store';import { autoSessionWatcher } from '@main/core/switch-rooms/auto-session-watcher';+import { viewStateService } from '@main/core/view-state/view-state-service';import { db } from '@main/db/client';-import { agents } from '@main/db/schema';+import { agents, sessions } from '@main/db/schema';import { log } from '@main/lib/logger';+import { sessionRuntimeManager } from '../sessions/session-runtime-manager';+import { agentEvents } from './agent-events';+import { getAgentLocation } from './agent-location';import { getAgentById } from './getAgentById';import { stopRemoteWatcher } from './remote-watcher';/**- * Delete an agent and tear down its auto_session state first. The watcher caches- * the agent's Switch credentials in memory, so without an explicit stop it keeps- * posting watch heartbeats and polling the notification stream for an agent that- * no longer exists. Stop the watcher(s) and clear the local mirror before removing- * the row so a deleted agent goes quiet immediately and does not linger in the- * mirror across a restart.+ * Delete an agent — the one real delete entry point (the sidebar's Remove+ * Agent routes here). Tears down everything a bare row delete would leak:+ *+ * 1. The agent's running sessions (runtime + view-state), which previously+ * only the location-delete path handled.+ * 2. Its auto_session watcher (or, for a remote agent, the on-VM sidecar's+ * watch flag + reconciler) and the local auto_session mirror. The watcher+ * caches the agent's Switch credentials in memory, so without an explicit+ * stop it keeps heartbeating and polling notifications for an agent that+ * no longer exists.+ *+ * The agent's location row is intentionally kept — locations are reusable+ * and other agents may still live there.*/export async function deleteAgent(agentId: string): Promise<void> {const agent = await getAgentById(agentId);+ const location = agent ? await getAgentLocation(agent).catch(() => null) : null;- if (agent?.connection === 'remote') {+ const sessionRows = await db+ .select({ id: sessions.id })+ .from(sessions)+ .where(eq(sessions.agentId, agentId));+ await Promise.allSettled(+ sessionRows.flatMap((row) => [+ sessionRuntimeManager.teardownSession(row.id),+ viewStateService.del(`session:${row.id}`),+ ])+ );++ if (location && location.sshHost !== null) {await stopRemoteWatcher(agentId).catch((error) => {log.warn('deleteAgent: failed to stop remote watcher', { agentId, error: String(error) });});@@ -38,4 +61,5 @@ export async function deleteAgent(agentId: string): Promise<void> {await setAutoSessionAgent(agentId, false);await db.delete(agents).where(eq(agents.id, agentId));+ agentEvents._emit('agent:deleted', agentId);}diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/detect-remote.ts b/dash/apps/switchdash-desktop/src/main/core/agents/detect-remote.tsindex a6e708d62..10713e4cf 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/detect-remote.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/detect-remote.ts@@ -1,7 +1,7 @@import { SshFileSystem } from '@main/core/fs/impl/ssh-fs';import { FileSystemError, FileSystemErrorCodes } from '@main/core/fs/types';+import { sshConnectionIdForHost } from '@main/core/locations/location-transport';import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';-import { agentSshConnectionId } from '@main/core/workspaces/resolve-agent-workspace';import { log } from '@main/lib/logger';import type { SwitchAgentConfig } from '@shared/switch-agents';import { parseSwitchAgentSettings } from './detect';@@ -27,7 +27,7 @@ export async function detectSwitchAgentRemote(sshHost: string,remoteRepoDir: string): Promise<SwitchAgentConfig | null> {- const proxy = await ensureSshConnected(agentSshConnectionId(sshHost), sshHost);+ const proxy = await ensureSshConnected(sshConnectionIdForHost(sshHost), sshHost);const fs = new SshFileSystem(proxy, remoteRepoDir);let raw: string;diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/getAgents.ts b/dash/apps/switchdash-desktop/src/main/core/agents/getAgents.tsindex 9dd774e5c..62c410014 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/getAgents.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/getAgents.ts@@ -4,12 +4,12 @@ import { agents } from '@main/db/schema';import type { Agent } from '@shared/core/agents/agents';import { mapAgentRowToAgent } from './utils';-export async function getAgents(projectId?: string): Promise<Agent[]> {- const rows = projectId+export async function getAgents(locationId?: string): Promise<Agent[]> {+ const rows = locationId? await db.select().from(agents)- .where(eq(agents.projectId, projectId))+ .where(eq(agents.locationId, locationId)).orderBy(desc(agents.updatedAt)): await db.select().from(agents).orderBy(desc(agents.updatedAt));return rows.map(mapAgentRowToAgent);diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/onboard-agent.ts b/dash/apps/switchdash-desktop/src/main/core/agents/onboard-agent.tsnew file mode 100644index 000000000..4fa2349df--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agents/onboard-agent.ts@@ -0,0 +1,121 @@+import { randomUUID } from 'node:crypto';+import { err, ok } from '@switchdash/shared';+import { locationManager } from '@main/core/locations/location-manager';+import { checkIsValidDirectory } from '@main/core/locations/path-utils';+import { ensureLocation } from '@main/core/locations/store';+import { agentExistsOnServer, GatewayError } from '@main/core/switch-servers/gateway-client';+import { getServer } from '@main/core/switch-servers/servers-store';+import { log } from '@main/lib/logger';+import type {+ OnboardAgentError,+ OnboardAgentParams,+ OnboardAgentResult,+} from '@shared/core/agents/onboarding';+import { basenameFromAnyPath } from '@shared/path-name';+import { agentEvents } from './agent-events';+import { createAgent } from './createAgent';+import { detectSwitchAgent } from './detect';+import { detectSwitchAgentRemote } from './detect-remote';+import { reconcileAgentAutoSessionFromGateway } from './setAgentAutoSession';++/**+ * Gate agent creation on the chosen server actually owning the detected agent+ * (and on being signed in). Every agent in the app is bound to a usable server+ * it provably exists on. `dir` is used only for error reporting.+ */+async function verifyAgentOnServer(+ serverId: string,+ agentId: string,+ dir: string+): Promise<OnboardAgentError | null> {+ const server = await getServer(serverId);+ if (!server) {+ throw new Error(`No Switch server with id ${serverId}`);+ }+ try {+ const exists = await agentExistsOnServer(server, agentId);+ if (!exists) {+ return {+ type: 'switch-agent-not-on-server',+ dir,+ serverId: server.id,+ serverName: server.name,+ agentId,+ };+ }+ return null;+ } catch (cause) {+ if (cause instanceof GatewayError && cause.kind === 'unauthorized') {+ return {+ type: 'switch-server-unauthenticated',+ dir,+ serverId: server.id,+ serverName: server.name,+ };+ }+ throw cause;+ }+}++/**+ * Onboard an agent: resolve the Switch identity already configured in the+ * working dir (locally or over SSH), verify it on the chosen server, and+ * create the agent at its location — creating the location row first if this+ * is the first agent there. Identity minting (for a brand-new agent) happens+ * before this call via `switchServers.provisionAgent` / `provisionRemoteAgent`.+ */+export async function onboardAgent(params: OnboardAgentParams): Promise<OnboardAgentResult> {+ const sshHost = params.sshHost ?? null;++ let switchAgent;+ if (sshHost === null) {+ if (!checkIsValidDirectory(params.dir)) {+ return err({ type: 'invalid-directory', dir: params.dir, message: 'Invalid directory' });+ }+ // Onboarding a directory == onboarding a Switch agent. Reject directories+ // that are not configured as one (no `.claude/settings.local.json` block).+ switchAgent = await detectSwitchAgent(params.dir);+ } else {+ switchAgent = await detectSwitchAgentRemote(sshHost, params.dir);+ }+ if (!switchAgent) {+ return err({+ type: 'invalid-directory',+ dir: params.dir,+ message:+ sshHost === null+ ? 'This directory is not configured as a Switch agent. Configure the agent first (run the switch-connector configure skill) before adding it.'+ : `The remote directory ${params.dir} on ${sshHost} is not configured as a Switch agent.`,+ });+ }++ const serverError = await verifyAgentOnServer(params.serverId, switchAgent.agentId, params.dir);+ if (serverError) return err(serverError);++ const location = await ensureLocation({ sshHost, dir: params.dir, name: params.name });++ const agent = await createAgent({+ id: params.id ?? randomUUID(),+ locationId: location.id,+ name: basenameFromAnyPath(params.dir) || params.providerId,+ providerId: params.providerId,+ switchAgentId: switchAgent.agentId,+ apiEndpoint: switchAgent.apiEndpoint,+ serverId: params.serverId,+ });++ // Seed the local auto_session mirror + start the watcher from the gateway+ // profile so an agent registered with auto_session on starts watching now,+ // without the operator toggling it off→on (CHOO-1185). Best-effort: a gateway+ // hiccup must not fail onboarding — the settings panel reconciles later.+ await reconcileAgentAutoSessionFromGateway(agent.id).catch((error) => {+ log.warn('onboardAgent: failed to reconcile auto_session for new agent', {+ agentId: agent.id,+ error: String(error),+ });+ });++ await locationManager.openLocation(location);+ agentEvents._emit('agent:created', agent);+ return ok(agent);+}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 58737f9c3..26575fc84 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@@ -5,7 +5,7 @@ const REMOTE_AGENT = {connection: 'remote',remoteConfig: { sshHost: 'vm', remoteRepoDir: '/home/dev/repo' },providerId: 'claude',- projectId: 'proj-1',+ locationId: 'proj-1',switchAgentId: 'switch-1',};@@ -14,7 +14,7 @@ const createSession = vi.fn(async (_p: unknown) => ({success: true,data: { session: { id: 'x' } },}));-const provisionWorkspace = vi.fn(async (_id: string) => ({ success: true }));+const provisionSession = vi.fn(async (_id: string) => ({ success: true }));const probeAgentSidecar = vi.fn(async () => ({ port: 4321, token: 'tok' }) as { port: number; token: string } | null);@@ -23,6 +23,16 @@ let knownRows: Array<{ id: string; agentId?: string }> = [];const deleteWhere = vi.fn(async (_arg?: unknown) => ({ changes: 1 }));vi.mock('./getAgentById', () => ({ getAgentById: () => getAgentById() }));+vi.mock('./agent-location', () => ({+ getRemoteAgentLocation: async () => ({+ id: 'loc-1',+ name: 'loc',+ sshHost: 'vm',+ dir: '/home/dev/repo',+ createdAt: '',+ updatedAt: '',+ }),+}));vi.mock('./connect-remote-agent', () => ({connectRemoteAgent: async () => ({proxy: { forwardOut: async () => ({ destroy: vi.fn() }) },@@ -41,7 +51,7 @@ vi.mock('@main/core/agent-runtime/impl/sidecar-http', () => ({vi.mock('@main/core/sessions/session-service', () => ({sessionService: {createSession: (p: unknown) => createSession(p as never),- provisionWorkspace: (id: string) => provisionWorkspace(id as never),+ provisionSession: (id: string) => provisionSession(id as never),},}));vi.mock('@main/app/deeplinks', () => ({ DEEPLINK_SCHEME: 'switchdash' }));@@ -95,7 +105,7 @@ describe('RemoteSessionReconciler', () => {expect(createSession).toHaveBeenCalledWith(expect.objectContaining({ id: 'session-new', agentId: 'agent-1', autoApprove: true }));- expect(provisionWorkspace).toHaveBeenCalledWith('session-new');+ expect(provisionSession).toHaveBeenCalledWith('session-new');});it('skips a VM session that already has a switchdash row', async () => {@@ -149,7 +159,7 @@ describe('RemoteSessionReconciler', () => {emitSpy.mockRestore();});- it('notifies the renderer (session:deleted) with the resolved projectId when a row is removed', async () => {+ it('notifies the renderer (session:deleted) when a row is removed', async () => {// The removal originates in the main process, so the renderer needs an IPC// event to drop the sidebar row (a user-initiated delete removes it itself).knownRows = [{ id: 'session-term', agentId: 'agent-1' }];@@ -157,7 +167,6 @@ describe('RemoteSessionReconciler', () => {expect(eventsEmit).toHaveBeenCalledWith(sessionDeletedChannel, {sessionId: 'session-term',- projectId: 'proj-1',});});@@ -251,7 +260,7 @@ describe('RemoteSessionReconciler', () => {await reconcile('agent-1');expect(createSession).toHaveBeenCalledTimes(1);- expect(provisionWorkspace).not.toHaveBeenCalled();+ expect(provisionSession).not.toHaveBeenCalled();});it('stops a duplicate reconciler whose agent shares an already-claimed sidecar', async () => {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 7c1c401c1..0b243f7fe 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@@ -3,16 +3,17 @@ import { DEEPLINK_SCHEME } from '@main/app/deeplinks';import { probeAgentSidecar } from '@main/core/agent-runtime/impl/ensure-agent-sidecar';import type { SidecarEndpoint } from '@main/core/agent-runtime/impl/remote-sidecar-launcher';import { httpGetJsonOverChannel } from '@main/core/agent-runtime/impl/sidecar-http';+import { sshConnectionIdForHost } from '@main/core/locations/location-transport';import { sessionHooks } from '@main/core/sessions/session-hooks';import { sessionService } from '@main/core/sessions/session-service';import { sshConnectionManager } from '@main/core/ssh/lifecycle/production-ssh-connection-manager';-import { agentSshConnectionId } from '@main/core/workspaces/resolve-agent-workspace';import { db } from '@main/db/client';import { sessions } from '@main/db/schema';import { events } from '@main/lib/events';import { log } from '@main/lib/logger';import type { Agent } from '@shared/core/agents/agents';import { sessionDeletedChannel } from '@shared/core/sessions/sessionEvents';+import { getRemoteAgentLocation } from './agent-location';import { connectRemoteAgent } from './connect-remote-agent';import { getAgentById } from './getAgentById';@@ -109,13 +110,7 @@ class RemoteSessionReconciler {for (const ids of this.adopted.values()) ids.delete(sessionId);this.missingStreak.delete(sessionId);let deleted: { changes: number };- let agentId: string | undefined;try {- const [row] = await db- .select({ agentId: sessions.agentId })- .from(sessions)- .where(eq(sessions.id, sessionId));- agentId = row?.agentId;deleted = await db.delete(sessions).where(eq(sessions.id, sessionId));} catch (error) {log.warn('RemoteSessionReconciler: failed to delete session row', {@@ -132,21 +127,11 @@ class RemoteSessionReconciler {// Tell the renderer to drop the row too. Unlike a user-initiated delete// (the renderer removes it itself), this removal originates in the main// process, so without an IPC event every attached window shows a ghost row- // until restart. Resolve the project the deleted session belonged to so the- // per-project session manager can route it.- const projectId = agentId ? (await getAgentById(agentId))?.projectId : undefined;- if (projectId) {- log.info('RemoteSessionReconciler: notifying UI to remove session (remote-driven delete)', {- sessionId,- projectId,- });- events.emit(sessionDeletedChannel, { sessionId: sessionId, projectId });- } else {- log.warn(- 'RemoteSessionReconciler: could not resolve projectId for removed session — sidebar row may linger until restart',- { sessionId, agentId }- );- }+ // until restart; stores that own the session drop it by id.+ log.info('RemoteSessionReconciler: notifying UI to remove session (remote-driven delete)', {+ sessionId,+ });+ events.emit(sessionDeletedChannel, { sessionId });return true;}@@ -230,20 +215,21 @@ class RemoteSessionReconciler {private async reconcileOnce(agentId: string): Promise<void> {const agent = await getAgentById(agentId);- if (!agent || agent.connection !== 'remote' || !agent.remoteConfig) {+ const location = agent ? await getRemoteAgentLocation(agent) : null;+ if (!agent || !location) {this.stop(agentId);this.endpoints.delete(agentId);return;}- if (!this.claimSidecar(agentId, agent)) return;+ if (!this.claimSidecar(agentId, location)) return;// The manager is mid-backoff rebuilding the transport: let it finish// rather than racing it with connect attempts every tick. Disconnected and// suspended states DO proceed — connectRemoteAgent's connect() is what// revives them.const connectionState = sshConnectionManager.getConnectionState(- agentSshConnectionId(agent.remoteConfig.sshHost)+ sshConnectionIdForHost(location.sshHost));if (connectionState === 'reconnecting') return;@@ -281,9 +267,8 @@ class RemoteSessionReconciler {* the same sidecar, so shared-dir agents cannot double-poll one snapshot and* race each other's adoptions.*/- private claimSidecar(agentId: string, agent: Agent): boolean {- const remote = agent.remoteConfig!;- const key = `${remote.sshHost}::${remote.remoteRepoDir}`;+ private claimSidecar(agentId: string, location: { id: string }): boolean {+ const key = location.id;const holder = this.sidecarKeys.get(key);if (holder !== undefined && holder !== agentId && this.timers.has(holder)) {log.info('RemoteSessionReconciler: sidecar already reconciled by another agent — stopping', {@@ -354,7 +339,6 @@ class RemoteSessionReconciler {// to be started. When none is running there is nothing to discover.const endpoint = await probeAgentSidecar({providerId: agent.providerId,- projectId: agent.projectId,repoDir: conn.remoteRepoDir,deeplinkScheme: DEEPLINK_SCHEME,ctx: conn.ctx,@@ -420,9 +404,9 @@ class RemoteSessionReconciler {}// createSession provisions the runtime inline but emits only session:created,// not session:provisioned — without the latter an open renderer leaves the- // session stuck "Setting up workspace…". provisionWorkspace is idempotent and+ // session stuck "Setting up session…". provisionSession is idempotent and// emits the provisioned event the renderer needs.- await sessionService.provisionWorkspace(sessionId).catch((error) => {+ await sessionService.provisionSession(sessionId).catch((error) => {log.warn('RemoteSessionReconciler: post-adopt provision-reconcile failed', {agentId: agent.id,sessionId,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 12016f1a7..ee9fcc34c 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@@ -3,6 +3,7 @@ import { ensureAgentSidecar } from '@main/core/agent-runtime/impl/ensure-agent-simport { writeWatchEnabled } from '@main/core/agent-runtime/impl/remote-sidecar-launcher';import { listAutoSessionAgentIds } from '@main/core/switch-rooms/auto-session-store';import { log } from '@main/lib/logger';+import { getRemoteAgentLocation } from './agent-location';import { connectRemoteAgent } from './connect-remote-agent';import { getAgentById } from './getAgentById';import { getAgents } from './getAgents';@@ -37,8 +38,10 @@ export async function initializeRemoteWatchers(): Promise<void> {const remote: string[] = [];for (const agentId of ids) {const agent = await getAgentById(agentId);- if (agent?.connection !== 'remote' || !agent.remoteConfig) continue;- const key = `${agent.remoteConfig.sshHost}::${agent.remoteConfig.remoteRepoDir}`;+ if (!agent) continue;+ const location = await getRemoteAgentLocation(agent);+ if (!location) continue;+ const key = location.id;if (seen.has(key)) {log.info('initializeRemoteWatchers: skipping agent sharing a sidecar dir at boot', {agentId,@@ -75,7 +78,8 @@ export async function initializeRemoteWatchers(): Promise<void> {export async function initializeRemoteDiscovery(): Promise<void> {const agents = await getAgents();for (const agent of agents) {- if (agent.connection === 'remote' && agent.remoteConfig && agent.switchAgentId) {+ if (!agent.switchAgentId) continue;+ if (await getRemoteAgentLocation(agent)) {remoteSessionReconciler.start(agent.id);}}@@ -84,7 +88,7 @@ export async function initializeRemoteDiscovery(): Promise<void> {/** Start discovery for one remote agent (e.g. just added). Idempotent; no-op for non-remote. */export async function startRemoteDiscovery(agentId: string): Promise<void> {const agent = await getAgentById(agentId);- if (agent?.connection === 'remote' && agent.remoteConfig && agent.switchAgentId) {+ if (agent?.switchAgentId && (await getRemoteAgentLocation(agent))) {remoteSessionReconciler.start(agentId);}}@@ -92,7 +96,7 @@ export async function startRemoteDiscovery(agentId: string): Promise<void> {export async function ensureRemoteWatcher(agentId: string): Promise<void> {const agent = await getAgentById(agentId);if (!agent) throw new Error(`No agent with id ${agentId}`);- if (agent.connection !== 'remote' || !agent.remoteConfig) return;+ if (!(await getRemoteAgentLocation(agent))) return;if (!agent.switchAgentId) {log.warn('ensureRemoteWatcher: agent has no Switch id; cannot watch', { agentId });return;@@ -107,7 +111,6 @@ export async function ensureRemoteWatcher(agentId: string): Promise<void> {const { ctx, connectionId, remoteRepoDir, host } = await connectRemoteAgent(agent);await ensureAgentSidecar({providerId: agent.providerId,- projectId: agent.projectId,repoDir: remoteRepoDir,deeplinkScheme: DEEPLINK_SCHEME,ctx,@@ -133,7 +136,7 @@ export async function ensureRemoteWatcher(agentId: string): Promise<void> {*/export async function stopRemoteWatcher(agentId: string): Promise<void> {const agent = await getAgentById(agentId);- if (!agent || agent.connection !== 'remote' || !agent.remoteConfig) return;+ if (!agent || !(await getRemoteAgentLocation(agent))) return;remoteSessionReconciler.stop(agentId);const { host } = await connectRemoteAgent(agent);await writeWatchEnabled(host, false);diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/resolve-servers.db.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/resolve-servers.db.test.tsindex 56fe37b15..1bf6f9f3f 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/resolve-servers.db.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/resolve-servers.db.test.ts@@ -2,7 +2,7 @@ import { openFixture } from '@tooling/utils/db';import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { AppDb } from '@main/db/client';-import { agents, projects, switchServers } from '@main/db/schema';+import { agents, locations, switchServers } from '@main/db/schema';import { resolveAgentServers } from './resolve-servers';const mocks = vi.hoisted(() => ({@@ -48,8 +48,8 @@ describe('resolveAgentServers', () => {fixture.sqlite.pragma('foreign_keys = OFF');await fixture.db- .insert(projects)- .values({ id: 'project-1', name: 'Project', path: '/repo/project-1' });+ .insert(locations)+ .values({ id: 'location-1', name: 'Location', sshHost: '', dir: '/repo/location-1' });await fixture.db.insert(switchServers).values([{id: 'pilot',@@ -76,7 +76,7 @@ describe('resolveAgentServers', () => {// Explicitly linked to a registered server -> kept (not re-derived).{id: 'agent-pilot',- projectId: 'project-1',+ locationId: 'location-1',name: 'pilot',providerId: 'claude',apiEndpoint: 'https://pilot.example.com/agent-bridge',@@ -85,7 +85,7 @@ describe('resolveAgentServers', () => {// Linked to a server that is no longer registered -> unlinked.{id: 'agent-dangling',- projectId: 'project-1',+ locationId: 'location-1',name: 'dangling',providerId: 'claude',apiEndpoint: 'https://gone.example.com',@@ -94,7 +94,7 @@ describe('resolveAgentServers', () => {// Never assigned -> stays null.{id: 'agent-none',- projectId: 'project-1',+ locationId: 'location-1',name: 'none',providerId: 'claude',apiEndpoint: null,@@ -114,7 +114,7 @@ describe('resolveAgentServers', () => {// behavior would auto-link; the new behavior must leave it unassigned.await fixture.db.insert(agents).values({id: 'agent-origin-match',- projectId: 'project-1',+ locationId: 'location-1',name: 'origin-match',providerId: 'claude',apiEndpoint: 'http://localhost:8080',diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/setAgentAutoSession.ts b/dash/apps/switchdash-desktop/src/main/core/agents/setAgentAutoSession.tsindex f4c40a886..5fa984e52 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/setAgentAutoSession.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/setAgentAutoSession.ts@@ -11,6 +11,7 @@ import {import { getServer } from '@main/core/switch-servers/servers-store';import { log } from '@main/lib/logger';import type { Agent } from '@shared/core/agents/agents';+import { getRemoteAgentLocation } from './agent-location';import { getAgentById } from './getAgentById';import { ensureRemoteWatcher, stopRemoteWatcher } from './remote-watcher';@@ -26,7 +27,7 @@ export type AgentAutoSessionParams = { agentId: string; enabled: boolean };*/async function applyLocalAutoSessionState(agent: Agent, enabled: boolean): Promise<void> {await setAutoSessionAgent(agent.id, enabled);- if (agent.connection === 'remote') {+ if ((await getRemoteAgentLocation(agent)) !== null) {if (enabled) await ensureRemoteWatcher(agent.id);else await stopRemoteWatcher(agent.id);} else {diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/setAgentConnection.ts b/dash/apps/switchdash-desktop/src/main/core/agents/setAgentConnection.tsdeleted file mode 100644index faae7c2f0..000000000--- a/dash/apps/switchdash-desktop/src/main/core/agents/setAgentConnection.ts+++ /dev/null@@ -1,39 +0,0 @@-import { eq, sql } from 'drizzle-orm';-import { db } from '@main/db/client';-import { agents } from '@main/db/schema';-import { agentRemoteConfig, type AgentRemoteConfig } from '@shared/core/agents/agent-connection';-import type { Agent } from '@shared/core/agents/agents';-import { mapAgentRowToAgent } from './utils';--/**- * Set an agent to run locally or on a remote SSH host. Local clears any stored- * remote config; remote requires a validated `{ sshHost, remoteRepoDir }`. This- * only records the connection intent — remote setup/preflight (claude + plugin- * install, writing the remote Switch creds, gateway reachability) runs- * separately before a remote session is provisioned.- */-export type SetAgentConnectionParams =- | { agentId: string; connection: 'local' }- | { agentId: string; connection: 'remote'; remoteConfig: AgentRemoteConfig };--export async function setAgentConnection(params: SetAgentConnectionParams): Promise<Agent> {- if (params.connection === 'remote') {- const parsed = agentRemoteConfig.schema.safeParse(params.remoteConfig);- if (!parsed.success) {- throw new Error(`Invalid remote agent config: ${parsed.error.message}`);- }- }-- const [row] = await db- .update(agents)- .set({- connection: params.connection,- remoteConfigJson: params.connection === 'remote' ? params.remoteConfig : null,- updatedAt: sql`CURRENT_TIMESTAMP`,- })- .where(eq(agents.id, params.agentId))- .returning();-- if (!row) throw new Error(`No agent with id ${params.agentId}`);- return mapAgentRowToAgent(row);-}diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/setup-remote-agent.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/setup-remote-agent.test.tsdeleted file mode 100644index 7b93c9c7a..000000000--- a/dash/apps/switchdash-desktop/src/main/core/agents/setup-remote-agent.test.ts+++ /dev/null@@ -1,56 +0,0 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';--const readSwitchAgentCredentials = vi.hoisted(() => vi.fn());-const ensureSshConnected = vi.hoisted(() => vi.fn(async () => ({ isConnected: true })));-const writeRemoteSwitchSettings = vi.hoisted(() => vi.fn(async () => {}));-const SshFileSystemCtor = vi.hoisted(() => vi.fn());--vi.mock('@main/core/switch-rooms/switch-credentials', () => ({ readSwitchAgentCredentials }));-vi.mock('@main/core/ssh/connect/connect-agent-ssh', () => ({ ensureSshConnected }));-vi.mock('./write-remote-switch-settings', () => ({ writeRemoteSwitchSettings }));-vi.mock('@main/core/fs/impl/ssh-fs', () => ({- SshFileSystem: vi.fn(function (this: { close: () => void }, proxy: unknown, root: unknown) {- SshFileSystemCtor(proxy, root);- this.close = vi.fn();- }),-}));-vi.mock('@main/lib/logger', () => ({ log: { warn: vi.fn() } }));--const { setupRemoteAgent } = await import('./setup-remote-agent');--const REMOTE = { sshHost: 'box', remoteRepoDir: '/home/dev/r' };--describe('setupRemoteAgent', () => {- beforeEach(() => {- vi.clearAllMocks();- });-- it('reads local creds and writes them to the remote working dir', async () => {- readSwitchAgentCredentials.mockResolvedValueOnce({- agentId: 'a-1',- apiEndpoint: 'https://switch.example.com',- token: 'tok',- });-- await setupRemoteAgent({ remoteConfig: REMOTE, localDir: '/local/proj' });-- expect(readSwitchAgentCredentials).toHaveBeenCalledWith('/local/proj', expect.anything());- expect(ensureSshConnected).toHaveBeenCalledWith('agent-ssh:box', 'box');- expect(SshFileSystemCtor).toHaveBeenCalledWith(expect.anything(), '/home/dev/r');- // token → apiToken mapping for the writer.- expect(writeRemoteSwitchSettings).toHaveBeenCalledWith(expect.anything(), {- apiEndpoint: 'https://switch.example.com',- apiToken: 'tok',- agentId: 'a-1',- });- });-- it('fails loud when the agent has no local creds to copy', async () => {- readSwitchAgentCredentials.mockResolvedValueOnce(null);-- await expect(- setupRemoteAgent({ remoteConfig: REMOTE, localDir: '/local/proj' })- ).rejects.toThrow(/no Switch credentials/);- expect(writeRemoteSwitchSettings).not.toHaveBeenCalled();- });-});diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/setup-remote-agent.ts b/dash/apps/switchdash-desktop/src/main/core/agents/setup-remote-agent.tsdeleted file mode 100644index 08ea0775c..000000000--- a/dash/apps/switchdash-desktop/src/main/core/agents/setup-remote-agent.ts+++ /dev/null@@ -1,45 +0,0 @@-import { SshFileSystem } from '@main/core/fs/impl/ssh-fs';-import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';-import { readSwitchAgentCredentials } from '@main/core/switch-rooms/switch-credentials';-import { agentSshConnectionId } from '@main/core/workspaces/resolve-agent-workspace';-import { log } from '@main/lib/logger';-import type { AgentRemoteConfig } from '@shared/core/agents/agent-connection';-import { writeRemoteSwitchSettings } from './write-remote-switch-settings';--/**- * Set up a remote agent's host (CHOO-1059, option A): copy the agent's Switch- * credentials to the VM the moment it is configured remote.- *- * switchdash does not persist the agent's API token — it is minted at- * onboarding and written only to the local `.claude/settings.local.json`. So we- * read it back from there and write it into the remote working dir over SFTP,- * where the sidecar reads it. Fails loud if the agent has no local creds yet- * (it must be onboarded locally first) — there is no token to ship otherwise.- */-export async function setupRemoteAgent(params: {- remoteConfig: AgentRemoteConfig;- /** The agent's local working dir (its project dir) holding the minted creds. */- localDir: string;-}): Promise<void> {- const creds = await readSwitchAgentCredentials(params.localDir, log);- if (!creds) {- throw new Error(- `cannot set up remote agent: no Switch credentials at ${params.localDir}/.claude/settings.local.json — onboard the agent locally first so its token exists to copy.`- );- }-- const proxy = await ensureSshConnected(- agentSshConnectionId(params.remoteConfig.sshHost),- params.remoteConfig.sshHost- );- const fs = new SshFileSystem(proxy, params.remoteConfig.remoteRepoDir);- try {- await writeRemoteSwitchSettings(fs, {- apiEndpoint: creds.apiEndpoint,- apiToken: creds.token,- agentId: creds.agentId,- });- } finally {- fs.close();- }-}diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/switch-settings-paths.ts b/dash/apps/switchdash-desktop/src/main/core/agents/switch-settings-paths.tsindex 5832ae018..f25086d02 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/switch-settings-paths.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/switch-settings-paths.ts@@ -10,7 +10,7 @@ import path from 'node:path';/*** Relative path, from an agent's working directory, to the Claude Code settings* file that the switch-connector `configure` skill writes the `SWITCH_*` env- * block into for a per-project agent.+ * block into for a per-location agent.*/export const SWITCH_SETTINGS_RELATIVE_PATH = path.join('.claude', 'settings.local.json');diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/utils.ts b/dash/apps/switchdash-desktop/src/main/core/agents/utils.tsindex 260b0addb..ee1fafd3d 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/utils.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/utils.ts@@ -4,15 +4,13 @@ import type { Agent } from '@shared/core/agents/agents';export function mapAgentRowToAgent(row: AgentRow): Agent {return {id: row.id,- projectId: row.projectId,+ locationId: row.locationId,name: row.name,providerId: row.providerId,switchAgentId: row.switchAgentId ?? null,apiEndpoint: row.apiEndpoint ?? null,serverId: row.serverId ?? null,status: row.status ?? null,- connection: row.connection,- remoteConfig: row.remoteConfigJson ?? null,createdAt: row.createdAt,updatedAt: row.updatedAt,};diff --git a/dash/apps/switchdash-desktop/src/main/core/dependencies/remote-dependency-manager.ts b/dash/apps/switchdash-desktop/src/main/core/dependencies/remote-dependency-manager.tsindex be7c9379b..bdabc0d72 100644--- a/dash/apps/switchdash-desktop/src/main/core/dependencies/remote-dependency-manager.ts+++ b/dash/apps/switchdash-desktop/src/main/core/dependencies/remote-dependency-manager.ts@@ -1,8 +1,8 @@import type { Platform } from '@switchdash/core/deps';import { HostDependencyManager } from '@switchdash/core/deps/runtime';import { SshExecutionContext } from '@main/core/execution-context/ssh-execution-context';+import { sshConnectionIdForHost } from '@main/core/locations/location-transport';import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';-import { agentSshConnectionId } from '@main/core/workspaces/resolve-agent-workspace';import { log } from '@main/lib/logger';import { agentUpdateService } from './agent-update-service';import { CORE_DEPENDENCIES } from './core-dependencies';@@ -37,7 +37,7 @@ async function detectRemotePlatform(ctx: SshExecutionContext): Promise<Platform>const managerCache = new Map<string, Promise<HostDependencyManager>>();async function buildRemoteDependencyManager(sshHost: string): Promise<HostDependencyManager> {- const connectionId = agentSshConnectionId(sshHost);+ const connectionId = sshConnectionIdForHost(sshHost);const proxy = await ensureSshConnected(connectionId, sshHost);const ctx = new SshExecutionContext(proxy);const platform = await detectRemotePlatform(ctx);diff --git a/dash/apps/switchdash-desktop/src/main/core/execution-context/ssh-execution-context.test.ts b/dash/apps/switchdash-desktop/src/main/core/execution-context/ssh-execution-context.test.tsindex 53715e528..003440f65 100644--- a/dash/apps/switchdash-desktop/src/main/core/execution-context/ssh-execution-context.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/execution-context/ssh-execution-context.test.ts@@ -33,10 +33,10 @@ function makeProxy(describe('buildSshCommand', () => {it('uses the shared remote shell command builder for fallback SSH exec commands', () => {- const command = buildSshCommand('/workspace/project', 'which', ['claude']);+ const command = buildSshCommand('/workspace/location', 'which', ['claude']);expect(command).toBe(- "'/bin/sh' -c 'cd '\\''/workspace/project'\\'' && which '\\''claude'\\'''"+ "'/bin/sh' -c 'cd '\\''/workspace/location'\\'' && which '\\''claude'\\'''");});@@ -48,24 +48,24 @@ describe('buildSshCommand', () => {},};- const command = buildSshCommand('/workspace/project', 'which', ['claude'], profile);+ const command = buildSshCommand('/workspace/location', 'which', ['claude'], profile);expect(command).toBe(- "'/bin/zsh' -lc 'export PATH='\\''/Users/jona/.local/bin:/opt/homebrew/bin:/usr/bin'\\''; cd '\\''/workspace/project'\\'' && which '\\''claude'\\'''"+ "'/bin/zsh' -lc 'export PATH='\\''/Users/jona/.local/bin:/opt/homebrew/bin:/usr/bin'\\''; cd '\\''/workspace/location'\\'' && which '\\''claude'\\'''");});it('disables interactive Git credential prompts for SSH exec commands', () => {- const command = buildSshCommand('/workspace/project', 'git', ['fetch', 'origin']);+ const command = buildSshCommand('/workspace/location', 'git', ['fetch', 'origin']);expect(command).toBe(- "'/bin/sh' -c 'cd '\\''/workspace/project'\\'' && GIT_ASKPASS='\\'''\\'' GIT_TERMINAL_PROMPT='\\''0'\\'' GCM_INTERACTIVE='\\''never'\\'' SSH_ASKPASS='\\'''\\'' git '\\''fetch'\\'' '\\''origin'\\'''"+ "'/bin/sh' -c 'cd '\\''/workspace/location'\\'' && GIT_ASKPASS='\\'''\\'' GIT_TERMINAL_PROMPT='\\''0'\\'' GCM_INTERACTIVE='\\''never'\\'' SSH_ASKPASS='\\'''\\'' git '\\''fetch'\\'' '\\''origin'\\'''");});it('prepends the stdout marker after the cd when a marker is given', () => {const command = buildSshCommand(- '/workspace/project',+ '/workspace/location','which',['claude'],undefined,diff --git a/dash/apps/switchdash-desktop/src/main/core/fs/controller.ts b/dash/apps/switchdash-desktop/src/main/core/fs/controller.tsindex 3086d84da..a0e0fd24d 100644--- a/dash/apps/switchdash-desktop/src/main/core/fs/controller.ts+++ b/dash/apps/switchdash-desktop/src/main/core/fs/controller.ts@@ -1,302 +1,22 @@-import { promises as fs } from 'node:fs';-import path from 'node:path';import { err, ok } from '@switchdash/shared';import { fsEvents } from '@main/core/fs/fs-events';+import { resolveLocationRuntime } from '@main/core/locations/utils';import { events } from '@main/lib/events';import { fsWatchEventChannel } from '@shared/core/fs/fsEvents';-import { planEventChannel } from '@shared/events/appEvents';import { createRPCController } from '@shared/lib/ipc/rpc';-import { resolveWorkspace } from '../projects/utils';-import {- FileSystemErrorCodes,- type FileWatcher,- type ListOptions,- type SearchOptions,-} from './types';+import { type FileWatcher } from './types';-// One watcher per (projectId, workspaceId) pair, shared across all consumers via labels.+// One watcher per location, shared across all consumers via labels.// Local: single recursive @parcel/watcher subscription — update() is a no-op.// SSH: poll-based — update() receives the union of all labels' paths to poll.const watcherRegistry = new Map<string, FileWatcher>();-// Per-label path groups, keyed by `${projectId}::${workspaceId}` → label → paths.+// Per-label path groups, keyed by location id → label → paths.// Paths are forwarded to update() for SSH compatibility; local ignores them.const watcherLabeledPaths = new Map<string, Map<string, string[]>>();-function normalizeRelativePath(filePath: string, options?: { allowEmpty?: boolean }): string {- if (!filePath && options?.allowEmpty) return '';- const normalized = path.posix.normalize(filePath.replaceAll('\\', '/'));- if (- !filePath ||- path.isAbsolute(filePath) ||- path.posix.isAbsolute(normalized) ||- path.win32.isAbsolute(filePath) ||- normalized === '..' ||- normalized.startsWith('../') ||- normalized.includes('/../')- ) {- throw new Error('Invalid file path');- }- return normalized === '.' ? '' : normalized;-}--function joinWorkspacePath(rootPath: string, filePath: string): string {- if (!filePath) return rootPath;- const separator =- rootPath.includes('\\') && !rootPath.includes('/') ? path.win32.sep : path.posix.sep;- return rootPath.endsWith('/') || rootPath.endsWith('\\')- ? `${rootPath}${filePath}`- : `${rootPath}${separator}${filePath}`;-}-export const filesController = createRPCController({- listFiles: async (- projectId: string,- workspaceId: string,- dirPath: string,- options?: ListOptions- ) => {- const env = resolveWorkspace(projectId, workspaceId);- if (!env)- return err({ type: 'not_found' as const, entity: 'filesystem' as const, detail: undefined });-- try {- const result = await env.fs.list(dirPath, options);- return ok(result);- } catch (e) {- return err({ type: 'fs_error' as const, message: String(e) });- }- },-- readFile: async (projectId: string, workspaceId: string, filePath: string, maxBytes?: number) => {- const env = resolveWorkspace(projectId, workspaceId);- if (!env)- return err({ type: 'not_found' as const, entity: 'filesystem' as const, detail: undefined });-- try {- const result = await env.fs.read(filePath, maxBytes);- return ok(result);- } catch (e) {- return err({ type: 'fs_error' as const, message: String(e) });- }- },-- writeFile: async (projectId: string, workspaceId: string, filePath: string, content: string) => {- const env = resolveWorkspace(projectId, workspaceId);- if (!env)- return err({ type: 'not_found' as const, entity: 'filesystem' as const, detail: undefined });-- try {- const result = await env.fs.write(filePath, content);- return ok(result);- } catch (e) {- if (- e instanceof Error &&- (e as unknown as { code?: string }).code === FileSystemErrorCodes.PERMISSION_DENIED- ) {- events.emit(planEventChannel, {- type: 'write_blocked' as const,- root: projectId,- relPath: filePath,- message: e.message,- });- }- return err({ type: 'fs_error' as const, message: String(e) });- }- },-- removeFile: async (projectId: string, workspaceId: string, filePath: string) => {- const env = resolveWorkspace(projectId, workspaceId);- if (!env)- return err({ type: 'not_found' as const, entity: 'filesystem' as const, detail: undefined });-- if (!env.fs.remove) {- return err({- type: 'fs_error' as const,- message: 'remove not supported by this filesystem',- });- }-- try {- const result = await env.fs.remove(filePath);- return ok(result);- } catch (e) {- if (- e instanceof Error &&- (e as unknown as { code?: string }).code === FileSystemErrorCodes.PERMISSION_DENIED- ) {- events.emit(planEventChannel, {- type: 'remove_blocked' as const,- root: projectId,- relPath: filePath,- message: e.message,- });- }- return err({ type: 'fs_error' as const, message: String(e) });- }- },-- readImage: async (projectId: string, workspaceId: string, filePath: string) => {- const env = resolveWorkspace(projectId, workspaceId);- if (!env)- return err({ type: 'not_found' as const, entity: 'filesystem' as const, detail: undefined });-- if (!env.fs.readImage) {- return err({- type: 'fs_error' as const,- message: 'readImage not supported by this filesystem',- });- }-- try {- const result = await env.fs.readImage(filePath);- return ok(result);- } catch (e) {- return err({ type: 'fs_error' as const, message: String(e) });- }- },-- searchFiles: async (- projectId: string,- workspaceId: string,- query: string,- options?: SearchOptions- ) => {- const env = resolveWorkspace(projectId, workspaceId);- if (!env)- return err({ type: 'not_found' as const, entity: 'filesystem' as const, detail: undefined });-- try {- const result = await env.fs.search(query, options);- return ok(result);- } catch (e) {- return err({ type: 'fs_error' as const, message: String(e) });- }- },-- statFile: async (projectId: string, workspaceId: string, filePath: string) => {- const env = resolveWorkspace(projectId, workspaceId);- if (!env)- return err({ type: 'not_found' as const, entity: 'filesystem' as const, detail: undefined });-- try {- const entry = await env.fs.stat(filePath);- return ok({ entry });- } catch (e) {- return err({ type: 'fs_error' as const, message: String(e) });- }- },-- fileExists: async (projectId: string, workspaceId: string, filePath: string) => {- const env = resolveWorkspace(projectId, workspaceId);- if (!env)- return err({ type: 'not_found' as const, entity: 'filesystem' as const, detail: undefined });-- try {- const exists = await env.fs.exists(filePath);- return ok({ exists });- } catch (e) {- return err({ type: 'fs_error' as const, message: String(e) });- }- },-- getAbsolutePath: async (projectId: string, workspaceId: string, filePath: string) => {- const env = resolveWorkspace(projectId, workspaceId);- if (!env)- return err({ type: 'not_found' as const, entity: 'filesystem' as const, detail: undefined });-- try {- return ok({ path: joinWorkspacePath(env.path, normalizeRelativePath(filePath)) });- } catch (e) {- return err({ type: 'fs_error' as const, message: String(e) });- }- },-- copyLocalFiles: async (- projectId: string,- workspaceId: string,- srcPaths: string[],- destDirPath: string,- options?: { overwrite?: boolean }- ) => {- const env = resolveWorkspace(projectId, workspaceId);- if (!env)- return err({ type: 'not_found' as const, entity: 'filesystem' as const, detail: undefined });-- if (!env.fs.copyLocalFile) {- return err({- type: 'fs_error' as const,- message: 'copyLocalFile not supported by this filesystem',- });- }-- try {- const destDir = normalizeRelativePath(destDirPath, { allowEmpty: true });- await env.fs.mkdir(destDir || '.', { recursive: true });-- const plannedCopies = await Promise.all(- srcPaths.map(async (srcPath) => {- if (!path.isAbsolute(srcPath)) throw new Error('Source path must be absolute');- const fileName = path.basename(srcPath);- if (!fileName) throw new Error('Source path must include a file name');- const srcStat = await fs.stat(srcPath);- if (srcStat.isDirectory()) throw new Error(`Cannot import directories: ${srcPath}`);- const destRelPath = destDir ? path.posix.join(destDir, fileName) : fileName;- return { srcPath, destRelPath };- })- );-- const seenDestPaths = new Set<string>();- const conflicts: string[] = [];- for (const { destRelPath } of plannedCopies) {- if (seenDestPaths.has(destRelPath))- throw new Error(`Duplicate destination: ${destRelPath}`);- seenDestPaths.add(destRelPath);- if (!options?.overwrite && (await env.fs.exists(destRelPath))) conflicts.push(destRelPath);- }- if (conflicts.length > 0) throw new Error(`Files already exist:\n${conflicts.join('\n')}`);-- for (const { srcPath, destRelPath } of plannedCopies) {- await env.fs.copyLocalFile(srcPath, destRelPath);- }-- return ok({ copied: srcPaths.length });- } catch (e) {- return err({ type: 'fs_error' as const, message: String(e) });- }- },-- saveAttachment: async (- projectId: string,- workspaceId: string,- srcPath: string,- subdir?: string- ) => {- const env = resolveWorkspace(projectId, workspaceId);- if (!env)- return err({ type: 'not_found' as const, entity: 'filesystem' as const, detail: undefined });-- if (!env.fs.saveAttachment) {- return err({- type: 'fs_error' as const,- message: 'saveAttachment not supported by this filesystem',- });- }-- try {- const result = await env.fs.saveAttachment(srcPath, subdir);- return ok(result);- } catch (e) {- return err({ type: 'fs_error' as const, message: String(e) });- }- },-- watchSetPaths: async (- projectId: string,- workspaceId: string,- paths: string[],- label = 'default'- ) => {- const env = resolveWorkspace(projectId, workspaceId);+ watchSetPaths: async (locationId: string, paths: string[], label = 'default') => {+ const env = resolveLocationRuntime(locationId);if (!env) {return err({ type: 'not_found' as const, entity: 'filesystem' as const, detail: undefined });}@@ -305,39 +25,37 @@ export const filesController = createRPCController({return ok({ supported: false as const });}- const key = `${projectId}::${workspaceId}`;- const groups = watcherLabeledPaths.get(key) ?? new Map<string, string[]>();+ const groups = watcherLabeledPaths.get(locationId) ?? new Map<string, string[]>();groups.set(label, paths);- watcherLabeledPaths.set(key, groups);+ watcherLabeledPaths.set(locationId, groups);const union = [...new Set([...groups.values()].flat())];- const existing = watcherRegistry.get(key);+ const existing = watcherRegistry.get(locationId);if (existing) {existing.update(union);} else {const watcher = env.fs.watch((evts) => {- const event = { projectId, workspaceId, events: evts };+ const event = { locationId, events: evts };events.emit(fsWatchEventChannel, event);fsEvents.emitWatchEvent(event);});watcher.update(union);- watcherRegistry.set(key, watcher);+ watcherRegistry.set(locationId, watcher);}return ok({ supported: true as const });},- watchStop: async (projectId: string, workspaceId: string, label = 'default') => {- const key = `${projectId}::${workspaceId}`;- const groups = watcherLabeledPaths.get(key);+ watchStop: async (locationId: string, label = 'default') => {+ const groups = watcherLabeledPaths.get(locationId);groups?.delete(label);if (!groups?.size) {- watcherLabeledPaths.delete(key);- watcherRegistry.get(key)?.close();- watcherRegistry.delete(key);+ watcherLabeledPaths.delete(locationId);+ watcherRegistry.get(locationId)?.close();+ watcherRegistry.delete(locationId);} else {const union = [...new Set([...groups.values()].flat())];- watcherRegistry.get(key)?.update(union);+ watcherRegistry.get(locationId)?.update(union);}return ok({});},diff --git a/dash/apps/switchdash-desktop/src/main/core/fs/fs-events.ts b/dash/apps/switchdash-desktop/src/main/core/fs/fs-events.tsindex d3ad86a75..33768010d 100644--- a/dash/apps/switchdash-desktop/src/main/core/fs/fs-events.ts+++ b/dash/apps/switchdash-desktop/src/main/core/fs/fs-events.ts@@ -3,11 +3,7 @@ import { log } from '@main/lib/logger';import type { FileWatchEvent } from '@shared/core/fs/fs';export type FsHooks = {- 'watch:event': (event: {- projectId: string;- workspaceId: string;- events: FileWatchEvent[];- }) => void | Promise<void>;+ 'watch:event': (event: { locationId: string; events: FileWatchEvent[] }) => void | Promise<void>;};class FsEvents implements Hookable<FsHooks> {@@ -19,11 +15,7 @@ class FsEvents implements Hookable<FsHooks> {return this._core.on(name, handler);}- emitWatchEvent(event: {- projectId: string;- workspaceId: string;- events: FileWatchEvent[];- }): void {+ emitWatchEvent(event: { locationId: string; events: FileWatchEvent[] }): void {this._core.callHookBackground('watch:event', event);}}diff --git a/dash/apps/switchdash-desktop/src/main/core/fs/impl/local-fs.test.ts b/dash/apps/switchdash-desktop/src/main/core/fs/impl/local-fs.test.tsindex 1f6709bf4..38991a0a5 100644--- a/dash/apps/switchdash-desktop/src/main/core/fs/impl/local-fs.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/fs/impl/local-fs.test.ts@@ -19,13 +19,13 @@ describe('LocalFileSystem', () => {});describe('constructor', () => {- it('should throw error when project path is empty', () => {+ it('should throw error when location path is empty', () => {expect(() => new LocalFileSystem('')).toThrow(FileSystemError);- expect(() => new LocalFileSystem('')).toThrow('Project path is required');+ expect(() => new LocalFileSystem('')).toThrow('Location path is required');});- it('should resolve project path', () => {- const relativePath = 'relative/project';+ it('should resolve location path', () => {+ const relativePath = 'relative/location';const service = new LocalFileSystem(relativePath);expect(service).toBeDefined();});diff --git a/dash/apps/switchdash-desktop/src/main/core/fs/impl/local-fs.ts b/dash/apps/switchdash-desktop/src/main/core/fs/impl/local-fs.tsindex 39786c416..881a38e8c 100644--- a/dash/apps/switchdash-desktop/src/main/core/fs/impl/local-fs.ts+++ b/dash/apps/switchdash-desktop/src/main/core/fs/impl/local-fs.ts@@ -143,11 +143,11 @@ const IMAGE_MIME_TYPES: Record<string, string> = {export class LocalFileSystem implements FileSystemProvider {private listAbort: AbortController | null = null;- constructor(private projectPath: string) {- if (!projectPath) {- throw new FileSystemError('Project path is required', FileSystemErrorCodes.INVALID_PATH);+ constructor(private rootPath: string) {+ if (!rootPath) {+ throw new FileSystemError('Location path is required', FileSystemErrorCodes.INVALID_PATH);}- this.projectPath = resolve(projectPath);+ this.rootPath = resolve(rootPath);}/**@@ -162,20 +162,18 @@ export class LocalFileSystem implements FileSystemProvider {}/**- * Resolve and validate a relative path, ensuring it doesn't escape the project root+ * Resolve and validate a relative path, ensuring it doesn't escape the location root*/private resolvePath(relPath: string): string {- // Normalize the path and resolve it against project root+ // Normalize the path and resolve it against location rootconst normalizedRelPath = relPath.replace(/\\/g, '/').replace(/^\//, '');- const fullPath = resolve(join(this.projectPath, normalizedRelPath));+ const fullPath = resolve(join(this.rootPath, normalizedRelPath));- // Security: ensure path is within projectPath (handle trailing separator edge cases)- const projectPathWithSep = this.projectPath.endsWith(sep)- ? this.projectPath- : this.projectPath + sep;+ // Security: ensure path is within rootPath (handle trailing separator edge cases)+ const locationPathWithSep = this.rootPath.endsWith(sep) ? this.rootPath : this.rootPath + sep;const fullPathWithSep = fullPath.endsWith(sep) ? fullPath : fullPath + sep;- if (!fullPathWithSep.startsWith(projectPathWithSep) && fullPath !== this.projectPath) {+ if (!fullPathWithSep.startsWith(locationPathWithSep) && fullPath !== this.rootPath) {throw new FileSystemError(`Path traversal detected: ${relPath}`,FileSystemErrorCodes.PATH_ESCAPE,@@ -190,7 +188,7 @@ export class LocalFileSystem implements FileSystemProvider {* Get relative path from absolute path*/private relPath(fullPath: string): string {- return relative(this.projectPath, fullPath).replace(/\\/g, '/');+ return relative(this.rootPath, fullPath).replace(/\\/g, '/');}/**@@ -436,7 +434,7 @@ export class LocalFileSystem implements FileSystemProvider {let gitIgnore: ReturnType<typeof ignore> | undefined;try {- const gitIgnorePath = join(this.projectPath, '.gitignore');+ const gitIgnorePath = join(this.rootPath, '.gitignore');const content = await fs.readFile(gitIgnorePath, 'utf-8');gitIgnore = ignore().add(content);} catch {@@ -543,7 +541,7 @@ export class LocalFileSystem implements FileSystemProvider {}};- await searchDir(this.projectPath);+ await searchDir(this.rootPath);return {matches,@@ -629,7 +627,7 @@ export class LocalFileSystem implements FileSystemProvider {return { success: false, error: 'Unsupported attachment type' };}- const destDir = join(this.projectPath, '.switchdash', subdir ?? 'attachments');+ const destDir = join(this.rootPath, '.switchdash', subdir ?? 'attachments');await fs.mkdir(destDir, { recursive: true });const baseName = basename(srcPath);@@ -652,7 +650,7 @@ export class LocalFileSystem implements FileSystemProvider {}await fs.copyFile(srcPath, destAbs);- const relPath = relative(this.projectPath, destAbs);+ const relPath = relative(this.rootPath, destAbs);return { success: true, absPath: destAbs, relPath, fileName: destName };} catch (err: unknown) {return { success: false, error: err instanceof Error ? err.message : String(err) };@@ -723,7 +721,7 @@ export class LocalFileSystem implements FileSystemProvider {}async glob(pattern: string, options?: { cwd?: string; dot?: boolean }): Promise<string[]> {- const cwd = options?.cwd ? this.resolvePath(options.cwd) : this.projectPath;+ const cwd = options?.cwd ? this.resolvePath(options.cwd) : this.rootPath;return glob(pattern, { cwd, dot: options?.dot ?? false, absolute: false });}@@ -759,16 +757,16 @@ export class LocalFileSystem implements FileSystemProvider {flushTimer = setTimeout(flush, stabilityMs);};- const toRel = (absPath: string) => relative(this.projectPath, absPath).replace(/\\/g, '/');+ const toRel = (absPath: string) => relative(this.rootPath, absPath).replace(/\\/g, '/');void parcelWatcher.subscribe(- this.projectPath,+ this.rootPath,(err, events) => {if (err) return;for (const e of events) {const rel = toRel(e.path);- // Skip paths outside the project root (shouldn't happen, but guard anyway).+ // Skip paths outside the location root (shouldn't happen, but guard anyway).if (rel.startsWith('..')) continue;let entryType: 'file' | 'directory' = 'file';@@ -793,7 +791,7 @@ export class LocalFileSystem implements FileSystemProvider {}}).catch(() => {- // Subscription failed (e.g. project path removed before watch started).+ // Subscription failed (e.g. location path removed before watch started).});return {diff --git a/dash/apps/switchdash-desktop/src/main/core/fs/impl/ssh-fs.test.ts b/dash/apps/switchdash-desktop/src/main/core/fs/impl/ssh-fs.test.tsindex 4f542677d..8432308e7 100644--- a/dash/apps/switchdash-desktop/src/main/core/fs/impl/ssh-fs.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/fs/impl/ssh-fs.test.ts@@ -124,7 +124,7 @@ describe('SshFileSystem.remove', () => {expect(proxy.exec).not.toHaveBeenCalled();});- it('removes directories recursively inside the workspace', async () => {+ it('removes directories recursively inside the location', async () => {const { fs, execCommands } = makeRemoveFs();await expect(fs.remove('subdir', { recursive: true })).resolves.toEqual({ success: true });diff --git a/dash/apps/switchdash-desktop/src/main/core/fs/types.ts b/dash/apps/switchdash-desktop/src/main/core/fs/types.tsindex 8de4277be..bf211bce8 100644--- a/dash/apps/switchdash-desktop/src/main/core/fs/types.ts+++ b/dash/apps/switchdash-desktop/src/main/core/fs/types.ts@@ -18,7 +18,7 @@ export interface FileWatcher {* File entry metadata returned by filesystem operations*/export interface FileEntry {- /** Relative path from the project root */+ /** Relative path from the location root */path: string;/** Entry type - file or directory */type: 'file' | 'dir';@@ -143,7 +143,7 @@ export interface SearchMatch {export interface FileSystemProvider {/*** List directory contents- * @param path - Directory path relative to project root+ * @param path - Directory path relative to location root* @param options - Listing options* @returns Promise resolving to file list result*/@@ -151,7 +151,7 @@ export interface FileSystemProvider {/*** Read file contents- * @param path - File path relative to project root+ * @param path - File path relative to location root* @param maxBytes - Maximum bytes to read (default: 200KB)* @returns Promise resolving to read result*/@@ -159,7 +159,7 @@ export interface FileSystemProvider {/*** Write file contents- * @param path - File path relative to project root+ * @param path - File path relative to location root* @param content - Content to write* @returns Promise resolving to write result*/@@ -167,14 +167,14 @@ export interface FileSystemProvider {/*** Check if a path exists- * @param path - Path to check relative to project root+ * @param path - Path to check relative to location root* @returns Promise resolving to true if exists*/exists(path: string): Promise<boolean>;/*** Get file/directory metadata- * @param path - Path to stat relative to project root+ * @param path - Path to stat relative to location root* @returns Promise resolving to file entry or null if not found*/stat(path: string): Promise<FileEntry | null>;@@ -189,7 +189,7 @@ export interface FileSystemProvider {/*** Remove a file or directory.- * @param path - Path relative to project root+ * @param path - Path relative to location root* @param options - Pass `{ recursive: true }` to remove directories and all contents* @returns Promise resolving to success status*/@@ -200,7 +200,7 @@ export interface FileSystemProvider {/*** Resolve a path to its absolute, canonical form (resolving symlinks).- * @param path - Path relative to project root+ * @param path - Path relative to location root* @returns Promise resolving to the absolute path*/realPath(path: string): Promise<string>;@@ -214,7 +214,7 @@ export interface FileSystemProvider {glob(pattern: string, options?: { cwd?: string; dot?: boolean }): Promise<string[]>;/**- * Copy a file from src to dest (both paths relative to project root).+ * Copy a file from src to dest (both paths relative to location root).* Does not create parent directories — caller must ensure they exist.* @param src - Source path* @param dest - Destination path@@ -223,7 +223,7 @@ export interface FileSystemProvider {/*** Read image file as base64 data URL- * @param path - Image file path relative to project root+ * @param path - Image file path relative to location root* @returns Promise resolving to image data*/readImage?(path: string): Promise<{@@ -235,7 +235,7 @@ export interface FileSystemProvider {}>;/**- * Copy a local file into the project's .switchdash attachments directory.+ * Copy a local file into the location's .switchdash attachments directory.* Only supported on local filesystems (srcPath is an absolute local path).* @param srcPath - Absolute local path of the source file* @param subdir - Subdirectory inside .switchdash/ (defaults to "attachments")diff --git a/dash/apps/switchdash-desktop/src/main/core/locations/controller.ts b/dash/apps/switchdash-desktop/src/main/core/locations/controller.tsnew file mode 100644index 000000000..4f0323b82--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/locations/controller.ts@@ -0,0 +1,23 @@+import { createRPCController } from '@shared/lib/ipc/rpc';+import { inspectLocationPath } from './operations/inspect-location-path';+import { openLocation } from './operations/open-location';+import { countLocationsUsingGithubAccount } from './settings/count-locations-using-github-account';+import { locationSettingsService } from './settings/location-settings-service';+import { getLocations } from './store';++export const locationsController = createRPCController({+ getLocations,+ inspectLocationPath,+ openLocation,+ getLocationSettingsPage: (locationId: string) =>+ locationSettingsService.getLocationSettingsPage(locationId),+ updateLocationSettings: (locationId, settings) =>+ locationSettingsService.updateLocationSettings(locationId, settings),+ patchLocationSettings: (locationId, patch) =>+ locationSettingsService.patchLocationSettings(locationId, patch),+ shareLocationSettingsToConfig: (locationId, request) =>+ locationSettingsService.shareLocationSettingsToConfig(locationId, request),+ migrateLocationConfig: (locationId, request) =>+ locationSettingsService.migrateLocationConfig(locationId, request),+ countLocationsUsingGithubAccount,+});diff --git a/dash/apps/switchdash-desktop/src/main/core/locations/create-location-provider.ts b/dash/apps/switchdash-desktop/src/main/core/locations/create-location-provider.tsnew file mode 100644index 000000000..044e84810--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/locations/create-location-provider.ts@@ -0,0 +1,28 @@+import { LocalExecutionContext } from '@main/core/execution-context/local-execution-context';+import { SshExecutionContext } from '@main/core/execution-context/ssh-execution-context';+import { LocalFileSystem } from '@main/core/fs/impl/local-fs';+import { SshFileSystem } from '@main/core/fs/impl/ssh-fs';+import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';+import type { Location } from '@shared/core/locations/locations';+import { LocationProvider } from './location-provider';+import { locationTransport } from './location-transport';+import { LocalLocationSettingsProvider } from './settings/providers/local-location-settings-provider';+import { RemoteLocationSettingsProvider } from './settings/providers/remote-location-settings-provider';++export async function createProvider(location: Location): Promise<LocationProvider> {+ const transport = locationTransport(location);+ if (transport.kind === 'ssh') {+ const proxy = await ensureSshConnected(transport.connectionId, transport.host);+ const ctx = new SshExecutionContext(proxy, { root: location.dir });+ const remoteFs = new SshFileSystem(proxy, location.dir);+ const settings = new RemoteLocationSettingsProvider(location.id, location.dir, remoteFs);+ await settings.ensure();+ return new LocationProvider(location, transport, { ctx, fs: remoteFs, settings });+ }++ const localFs = new LocalFileSystem(location.dir);+ const ctx = new LocalExecutionContext({ root: location.dir });+ const settings = new LocalLocationSettingsProvider(location.id, location.dir);+ await settings.ensure();+ return new LocationProvider(location, transport, { ctx, fs: localFs, settings });+}diff --git a/dash/apps/switchdash-desktop/src/main/core/workspaces/workspace-lifecycle-service.test.ts b/dash/apps/switchdash-desktop/src/main/core/locations/lifecycle-service.test.tssimilarity index 91%rename from dash/apps/switchdash-desktop/src/main/core/workspaces/workspace-lifecycle-service.test.tsrename to dash/apps/switchdash-desktop/src/main/core/locations/lifecycle-service.test.tsindex cd974fc0e..e8cf850e9 100644--- a/dash/apps/switchdash-desktop/src/main/core/workspaces/workspace-lifecycle-service.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/locations/lifecycle-service.test.ts@@ -3,7 +3,7 @@ import { ptySessionRegistry } from '@main/core/pty/pty-session-registry';import { createLifecycleScriptTerminalId } from '@shared/core/terminals/terminals';import type { Pty, PtyExitInfo } from '../pty/pty';import type { LifecycleScriptSpawnRequest, TerminalProvider } from '../terminals/terminal-provider';-import { LifecycleScriptService } from './workspace-lifecycle-service';+import { LifecycleScriptService } from './lifecycle-service';vi.mock('@main/lib/events', () => ({events: {@@ -64,7 +64,7 @@ function makeTerminalProvider(): {spawned.push(pty);requests.push(request);ptySessionRegistry.register(- `${terminal.projectId}:${terminal.sessionId}:${terminal.id}`,+ `${terminal.locationId}:${terminal.sessionId}:${terminal.id}`,pty,{preserveBufferOnExit: true,@@ -77,12 +77,11 @@ function makeTerminalProvider(): {return { provider, spawned, requests };}-describe('WorkspaceLifecycleService', () => {+describe('LifecycleScriptService', () => {it('respawns an interactive lifecycle shell after an exit-backed script finishes', async () => {const { provider, spawned, requests } = makeTerminalProvider();const service = new LifecycleScriptService({- projectId: 'project-1',- workspaceId: 'branch:feature',+ locationId: 'location-1',terminals: provider,});@@ -102,8 +101,7 @@ describe('WorkspaceLifecycleService', () => {it('does not prepare a second lifecycle shell when one is already active', async () => {const { provider, spawned, requests } = makeTerminalProvider();const service = new LifecycleScriptService({- projectId: 'project-prepare',- workspaceId: 'branch:feature',+ locationId: 'location-prepare',terminals: provider,});@@ -117,8 +115,7 @@ describe('WorkspaceLifecycleService', () => {it('keeps the same lifecycle PTY when the script text changes', async () => {const { provider, spawned, requests } = makeTerminalProvider();const service = new LifecycleScriptService({- projectId: 'project-2',- workspaceId: 'branch:feature',+ locationId: 'location-2',terminals: provider,});@@ -134,8 +131,7 @@ describe('WorkspaceLifecycleService', () => {it('respawns with the latest shell setup after repeated exit-backed runs', async () => {const { provider, spawned, requests } = makeTerminalProvider();const service = new LifecycleScriptService({- projectId: 'project-3',- workspaceId: 'branch:feature',+ locationId: 'location-3',terminals: provider,});@@ -158,8 +154,7 @@ describe('WorkspaceLifecycleService', () => {it('resolves waitForExit when an exit-backed script exits successfully', async () => {const { provider, spawned } = makeTerminalProvider();const service = new LifecycleScriptService({- projectId: 'project-4',- workspaceId: 'branch:feature',+ locationId: 'location-4',terminals: provider,});@@ -184,8 +179,7 @@ describe('WorkspaceLifecycleService', () => {it('does not attach another awaited execution to a PTY that is already running', async () => {const { provider, spawned } = makeTerminalProvider();const service = new LifecycleScriptService({- projectId: 'project-concurrent',- workspaceId: 'branch:feature',+ locationId: 'location-concurrent',terminals: provider,});@@ -211,8 +205,7 @@ describe('WorkspaceLifecycleService', () => {it('can restore an interactive lifecycle shell after an awaited script exits', async () => {const { provider, spawned } = makeTerminalProvider();const service = new LifecycleScriptService({- projectId: 'project-6',- workspaceId: 'branch:feature',+ locationId: 'location-6',terminals: provider,});@@ -236,8 +229,7 @@ describe('WorkspaceLifecycleService', () => {it('can restore an interactive lifecycle shell after an awaited script is stopped', async () => {const { provider, spawned } = makeTerminalProvider();const service = new LifecycleScriptService({- projectId: 'project-7',- workspaceId: 'branch:feature',+ locationId: 'location-7',terminals: provider,});@@ -261,8 +253,7 @@ describe('WorkspaceLifecycleService', () => {it('returns the output tail when an exit-backed script fails', async () => {const { provider, spawned } = makeTerminalProvider();const service = new LifecycleScriptService({- projectId: 'project-5',- workspaceId: 'branch:feature',+ locationId: 'location-5',terminals: provider,});diff --git a/dash/apps/switchdash-desktop/src/main/core/workspaces/workspace-lifecycle-service.ts b/dash/apps/switchdash-desktop/src/main/core/locations/lifecycle-service.tssimilarity index 92%rename from dash/apps/switchdash-desktop/src/main/core/workspaces/workspace-lifecycle-service.tsrename to dash/apps/switchdash-desktop/src/main/core/locations/lifecycle-service.tsindex ae4a34841..7f94eb662 100644--- a/dash/apps/switchdash-desktop/src/main/core/workspaces/workspace-lifecycle-service.ts+++ b/dash/apps/switchdash-desktop/src/main/core/locations/lifecycle-service.ts@@ -44,25 +44,15 @@ function appendOutputTail(current: string, chunk: string): string {}export class LifecycleScriptService implements IDisposable {- private readonly projectId: string;- private readonly workspaceId: string;+ private readonly locationId: string;private readonly terminals: TerminalProvider;private readonly sessionsWithRespawnHandler = new Set<string>();private readonly sessionsWaitingForExit = new Set<string>();private readonly latestRespawnRequest = new Map<string, LifecycleRespawnRequest>();private disposed = false;- constructor({- projectId,- workspaceId,- terminals,- }: {- projectId: string;- workspaceId: string;- terminals: TerminalProvider;- }) {- this.projectId = projectId;- this.workspaceId = workspaceId;+ constructor({ locationId, terminals }: { locationId: string; terminals: TerminalProvider }) {+ this.locationId = locationId;this.terminals = terminals;}@@ -101,7 +91,7 @@ export class LifecycleScriptService implements IDisposable {sessionId: string;} {const terminalId = createLifecycleScriptTerminalId(script.type);- const sessionId = makePtySessionId(this.projectId, this.workspaceId, terminalId);+ const sessionId = makePtySessionId(this.locationId, this.locationId, terminalId);return { terminalId, sessionId };}@@ -116,8 +106,8 @@ export class LifecycleScriptService implements IDisposable {await this.terminals.spawnLifecycleScript({terminal: {id: terminalId,- projectId: this.projectId,- sessionId: this.workspaceId,+ locationId: this.locationId,+ sessionId: this.locationId,shellId: 'system',name: script.type,},@@ -154,7 +144,7 @@ export class LifecycleScriptService implements IDisposable {const pty = ptySessionRegistry.get(sessionId);if (!pty) {throw new Error(- `Lifecycle script session unavailable for ${script.type} in workspace ${this.workspaceId}`+ `Lifecycle script session unavailable for ${script.type} in location ${this.locationId}`);}diff --git a/dash/apps/switchdash-desktop/src/main/core/locations/location-events.ts b/dash/apps/switchdash-desktop/src/main/core/locations/location-events.tsnew file mode 100644index 000000000..6d09f98c9--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/locations/location-events.ts@@ -0,0 +1,27 @@+import { HookCore, type Hookable } from '@main/lib/hookable';+import { log } from '@main/lib/logger';+import type { Location } from '@shared/core/locations/locations';++export type LocationCrudHooks = {+ 'location:created': (location: Location) => void | Promise<void>;+ 'location:deleted': (locationId: string) => void | Promise<void>;+};++class LocationEvents implements Hookable<LocationCrudHooks> {+ private readonly _core = new HookCore<LocationCrudHooks>((name, e) =>+ log.error(`LocationEvents: ${String(name)} hook error`, e)+ );++ on<K extends keyof LocationCrudHooks>(name: K, handler: LocationCrudHooks[K]) {+ return this._core.on(name, handler);+ }++ _emit<K extends keyof LocationCrudHooks>(+ name: K,+ ...args: Parameters<LocationCrudHooks[K]>+ ): void {+ this._core.callHookBackground(name, ...args);+ }+}++export const locationEvents = new LocationEvents();diff --git a/dash/apps/switchdash-desktop/src/main/core/locations/location-manager.ts b/dash/apps/switchdash-desktop/src/main/core/locations/location-manager.tsnew file mode 100644index 000000000..d0114487d--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/locations/location-manager.ts@@ -0,0 +1,97 @@+import { err, ok, type Result } from '@switchdash/shared';+import type { IDisposable } from '@switchdash/shared';+import { HookCore, type Hookable } from '@main/lib/hookable';+import { LifecycleMap } from '@main/lib/lifecycle-map';+import { log } from '@main/lib/logger';+import type { Location } from '@shared/core/locations/locations';+import { createProvider } from './create-location-provider';+import type { LocationProvider } from './location-provider';+import { TimeoutSignal, withTimeout } from './utils';++const OPEN_PROVIDER_TIMEOUT_MS = 20_000;+const TEARDOWN_PROVIDER_TIMEOUT_MS = 60_000;++type LocationManagerHooks = {+ locationOpened: (locationId: string, provider: LocationProvider) => void | Promise<void>;+ locationClosed: (locationId: string) => void | Promise<void>;+};++type ProviderLifecycleError =+ | { type: 'timeout'; message: string; timeout: number }+ | { type: 'error'; message: string };++function toLifecycleError(e: unknown): ProviderLifecycleError {+ if (e instanceof TimeoutSignal) return { type: 'timeout', message: e.message, timeout: e.ms };+ return { type: 'error', message: e instanceof Error ? e.message : String(e) };+}++class LocationManager implements Hookable<LocationManagerHooks>, IDisposable {+ private readonly _hooks = new HookCore<LocationManagerHooks>((name, e) =>+ log.error(`LocationManager: ${String(name)} hook error`, e)+ );+ private readonly _lifecycle = new LifecycleMap<+ LocationProvider,+ ProviderLifecycleError,+ ProviderLifecycleError+ >({+ postProvision: (id, provider) => this._hooks.callHookBackground('locationOpened', id, provider),+ postTeardown: (id) => this._hooks.callHookBackground('locationClosed', id),+ });++ on<K extends keyof LocationManagerHooks>(name: K, handler: LocationManagerHooks[K]) {+ return this._hooks.on(name, handler);+ }++ async openLocation(+ location: Location+ ): Promise<Result<LocationProvider, ProviderLifecycleError>> {+ return this._lifecycle.provision(location.id, async () => {+ try {+ const provider = await withTimeout(createProvider(location), OPEN_PROVIDER_TIMEOUT_MS);+ return ok(provider);+ } catch (e) {+ const initError = toLifecycleError(e);+ log.error('LocationManager: error during location initialization', {+ locationId: location.id,+ ...initError,+ });+ return err(initError);+ }+ });+ }++ async closeLocation(locationId: string): Promise<Result<void, ProviderLifecycleError>> {+ return (+ this._lifecycle.teardown(locationId, async (provider) => {+ try {+ await withTimeout(provider.dispose(), TEARDOWN_PROVIDER_TIMEOUT_MS);+ return ok();+ } catch (e) {+ const error = toLifecycleError(e);+ log.error('LocationManager: error during location teardown', { locationId, ...error });+ return err(error);+ }+ }) ?? ok()+ );+ }++ getLocation(locationId: string): LocationProvider | undefined {+ return this._lifecycle.get(locationId);+ }++ async dispose(): Promise<void> {+ const ids = Array.from(this._lifecycle.keys());+ await Promise.allSettled(ids.map((id) => this.closeLocation(id)));+ for (const id of ids) {+ const status = this._lifecycle.teardownStatus(id);+ if (status.status === 'error') {+ log.error('LocationManager: location teardown error recorded after dispose', {+ locationId: id,+ message: status.error.message,+ });+ }+ }+ }+}++export const locationManager = new LocationManager();diff --git a/dash/apps/switchdash-desktop/src/main/core/locations/location-provider.ts b/dash/apps/switchdash-desktop/src/main/core/locations/location-provider.tsnew file mode 100644index 000000000..d7b3d3208--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/locations/location-provider.ts@@ -0,0 +1,70 @@+import type { IDisposable } from '@switchdash/shared';+import type { IExecutionContext } from '@main/core/execution-context/types';+import type { FileSystemProvider } from '@main/core/fs/types';+import type { Location } from '@shared/core/locations/locations';+import type { AgentRuntimeProvider } from '../agent-runtime/types';+import { sessionRuntimeManager } from '../sessions/session-runtime-manager';+import { locationRuntimeRegistry } from './location-runtime-registry';+import type { LocationTransport } from './location-transport';+import type { LocationSettingsProvider } from './settings/provider';++export type ProvisionResult = {+ agent: AgentRuntimeProvider;+ persistData: {+ locationId: string;+ };+};++/**+ * The open handle on a location: its execution context, filesystem and+ * settings, built local or SSH according to the location's transport. One+ * provider per open location, managed by the location manager.+ */+export class LocationProvider implements IDisposable {+ readonly location: Location;+ readonly transport: LocationTransport;+ readonly settings: LocationSettingsProvider;+ readonly fs: FileSystemProvider;++ private readonly _ctx: IExecutionContext;++ constructor(+ location: Location,+ transport: LocationTransport,+ deps: {+ ctx: IExecutionContext;+ fs: FileSystemProvider;+ settings: LocationSettingsProvider;+ }+ ) {+ this.location = location;+ this.transport = transport;+ this._ctx = deps.ctx;+ this.settings = deps.settings;+ this.fs = deps.fs;+ }++ get locationId(): string {+ return this.location.id;+ }++ /** The working directory on the location's host. */+ get dir(): string {+ return this.location.dir;+ }++ get ctx(): IExecutionContext {+ return this._ctx;+ }++ async dispose(): Promise<void> {+ const settings = await this.settings.get();+ // Detach (don't terminate) when work should outlive the app: tmux sessions,+ // and remote locations whose on-VM sidecar must keep listening to Switch+ // while switchdash is closed (CHOO-1059). Terminate only cleans up the+ // local pane.+ const mode = settings.tmux || this.transport.kind === 'ssh' ? 'detach' : 'terminate';+ await sessionRuntimeManager.teardownAllForLocation(this.location.id, mode);+ await locationRuntimeRegistry.releaseAll(this.location.id, mode);+ }+}diff --git a/dash/apps/switchdash-desktop/src/main/core/workspaces/workspace-factory.test.ts b/dash/apps/switchdash-desktop/src/main/core/locations/location-runtime-factory.test.tssimilarity index 86%rename from dash/apps/switchdash-desktop/src/main/core/workspaces/workspace-factory.test.tsrename to dash/apps/switchdash-desktop/src/main/core/locations/location-runtime-factory.test.tsindex b3d7098d1..e063fd57f 100644--- a/dash/apps/switchdash-desktop/src/main/core/workspaces/workspace-factory.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/locations/location-runtime-factory.test.ts@@ -1,5 +1,5 @@import { describe, expect, it, vi } from 'vitest';-import { buildAgentRuntime } from './workspace-factory';+import { buildAgentRuntime } from './location-runtime-factory';const connect = vi.hoisted(() => vi.fn(async () => ({ isConnected: true })));const register = vi.hoisted(() => vi.fn());@@ -23,24 +23,24 @@ vi.mock('@main/core/agent-runtime/impl/ssh-agent-runtime', () => ({}),}));-const SSH_TYPE = {+const SSH_TRANSPORT = {kind: 'ssh' as const,host: 'box',- remoteRepoDir: '/home/dev/r',+ dir: '/home/dev/r',connectionId: 'agent-ssh:box',};const OPTS = {- projectId: 'proj-1',+ locationId: 'loc-1',sessionId: 'session-1',sessionPath: '/home/dev/r',- tmuxEnabled: false, // project setting is off; remote must still force tmux on+ tmuxEnabled: false, // location setting is off; remote must still force tmux onsessionEnvVars: {},};describe('buildAgentRuntime (ssh)', () => {it('connects to the agent host and builds the SSH runtime with tmux forced on', async () => {- await buildAgentRuntime(SSH_TYPE, OPTS);+ await buildAgentRuntime(SSH_TRANSPORT, OPTS);expect(register).toHaveBeenCalledWith('agent-ssh:box', expect.any(Function));expect(connect).toHaveBeenCalledWith('agent-ssh:box');diff --git a/dash/apps/switchdash-desktop/src/main/core/workspaces/workspace-factory.ts b/dash/apps/switchdash-desktop/src/main/core/locations/location-runtime-factory.tssimilarity index 60%rename from dash/apps/switchdash-desktop/src/main/core/workspaces/workspace-factory.tsrename to dash/apps/switchdash-desktop/src/main/core/locations/location-runtime-factory.tsindex b7a1b56f4..ca2cb1343 100644--- a/dash/apps/switchdash-desktop/src/main/core/workspaces/workspace-factory.ts+++ b/dash/apps/switchdash-desktop/src/main/core/locations/location-runtime-factory.ts@@ -7,7 +7,10 @@ import type { IExecutionContext } from '@main/core/execution-context/types';import { LocalFileSystem } from '@main/core/fs/impl/local-fs';import { SshFileSystem } from '@main/core/fs/impl/ssh-fs';import type { FileSystemProvider } from '@main/core/fs/types';-import { workspaceFileIndexService } from '@main/core/search/workspace-file-index-service';+import { LifecycleScriptService } from '@main/core/locations/lifecycle-service';+import type { LocationRuntime } from '@main/core/locations/location-runtime';+import { type LocationRuntimeFactoryResult } from '@main/core/locations/location-runtime-registry';+import { locationFileIndexService } from '@main/core/search/location-file-index-service';import { preflightRemoteSession } from '@main/core/sessions/remote-session-preflight';import { appSettingsService } from '@main/core/settings/settings-service';import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';@@ -17,86 +20,78 @@ import type { ResolvedShellProfile } from '@main/core/terminal-shell/types';import { LocalTerminalProvider } from '@main/core/terminals/impl/local-terminal-provider';import { SshTerminalProvider } from '@main/core/terminals/impl/ssh-terminal-provider';import { runLifecycleScriptWithPolicy } from '@main/core/terminals/lifecycle-script-coordinator';-import type { Workspace } from '@main/core/workspaces/workspace';-import { LifecycleScriptService } from '@main/core/workspaces/workspace-lifecycle-service';-import { type WorkspaceFactoryResult } from '@main/core/workspaces/workspace-registry';import { log } from '@main/lib/logger';import type { Session } from '@shared/core/sessions/sessions';-import { getEffectiveSessionSettings } from '../projects/settings/effective-session-settings';-import type { ProjectSettingsProvider } from '../projects/settings/provider';+import { getEffectiveSessionSettings } from '../locations/settings/effective-session-settings';+import type { LocationSettingsProvider } from '../locations/settings/provider';import { TEARDOWN_SCRIPT_WAIT_MS } from '../sessions/provision-session-error';-import { getSessionEnvVars } from './workspace-env';+import type { LocationTransport } from './location-transport';+import { getSessionEnvVars } from './session-env';-export type WorkspaceType =- | { kind: 'local' }- | { kind: 'ssh'; host: string; remoteRepoDir: string; connectionId: string };+type SshTransport = Extract<LocationTransport, { kind: 'ssh' }>;-type SshWorkspaceType = Extract<WorkspaceType, { kind: 'ssh' }>;--function connectSshWorkspace(type: SshWorkspaceType): Promise<SshClientProxy> {- return ensureSshConnected(type.connectionId, type.host);+function connectSshTransport(transport: SshTransport): Promise<SshClientProxy> {+ return ensureSshConnected(transport.connectionId, transport.host);}-type WorkspaceFactoryContext = {+type LocationRuntimeFactoryContext = {session: Pick<Session, 'id' | 'title'>;workDir: string;- projectId: string;- projectPath: string;- settings: ProjectSettingsProvider;+ settings: LocationSettingsProvider;logPrefix: string;extraHooks?: {- onCreate?: (ws: Workspace) => Promise<void>;- onDestroy?: (ws: Workspace) => Promise<void>;- onDetach?: (ws: Workspace) => Promise<void>;+ onCreate?: (runtime: LocationRuntime) => Promise<void>;+ onDestroy?: (runtime: LocationRuntime) => Promise<void>;+ onDetach?: (runtime: LocationRuntime) => Promise<void>;};};/**- * Returns a factory function suitable for passing to `WorkspaceRegistry.acquire`.+ * Returns a factory function suitable for passing to `LocationRuntimeRegistry.acquire`.* Handles all transport-specific construction (local vs SSH) and wires lifecycle* script hooks. Provider-specific hooks are passed via `extraHooks`.*/-export function createWorkspaceFactory(- workspaceId: string,- _type: WorkspaceType,- context: WorkspaceFactoryContext-): () => Promise<WorkspaceFactoryResult> {+export function createLocationRuntimeFactory(+ locationId: string,+ transport: LocationTransport,+ context: LocationRuntimeFactoryContext+): () => Promise<LocationRuntimeFactoryResult> {return async () => {const workDir = context.workDir;// Transport: local runs on this machine; ssh runs on the agent's host. The// SSH connection is established here (and reused by the session providers).let ctx: IExecutionContext;- let workspaceFs: FileSystemProvider;- if (_type.kind === 'ssh') {- const proxy = await connectSshWorkspace(_type);- ctx = new SshExecutionContext(proxy, { root: _type.remoteRepoDir });- workspaceFs = new SshFileSystem(proxy, _type.remoteRepoDir);+ let runtimeFs: FileSystemProvider;+ if (transport.kind === 'ssh') {+ const proxy = await connectSshTransport(transport);+ ctx = new SshExecutionContext(proxy, { root: transport.dir });+ runtimeFs = new SshFileSystem(proxy, transport.dir);} else {ctx = new LocalExecutionContext();- workspaceFs = new LocalFileSystem(workDir);+ runtimeFs = new LocalFileSystem(workDir);}// Settings (shared)- const projectSettings = await context.settings.get();+ const locationSettings = await context.settings.get();const bootstrapSessionEnvVars = getSessionEnvVars({sessionId: context.session.id,sessionName: context.session.title,sessionPath: workDir,- projectPath: context.projectPath,+ rootPath: workDir,portSeed: workDir,});// Remote sessions require tmux — it is the persistence substrate the sidecar// injects into and reattaches to across UI disconnects.- const tmuxEnabled = _type.kind === 'ssh' ? true : (projectSettings.tmux ?? false);+ const tmuxEnabled = transport.kind === 'ssh' ? true : (locationSettings.tmux ?? false);const sessionLevelSettings = await getEffectiveSessionSettings({- projectSettings: context.settings,- sessionFs: workspaceFs,+ locationSettings: context.settings,+ sessionFs: runtimeFs,});- const shellSetup = sessionLevelSettings.shellSetup ?? projectSettings.shellSetup;+ const shellSetup = sessionLevelSettings.shellSetup ?? locationSettings.shellSetup;const scripts = sessionLevelSettings.scripts;- // Workspace terminal provider (used only by lifecycle scripts)+ // Location terminal provider (used only by lifecycle scripts)const terminalOpts = {sessionPath: workDir,tmux: tmuxEnabled,@@ -104,25 +99,24 @@ export function createWorkspaceFactory(ctx,sessionEnvVars: bootstrapSessionEnvVars,};- const workspaceTerminals =- _type.kind === 'ssh'+ const runtimeTerminals =+ transport.kind === 'ssh'? new SshTerminalProvider({...terminalOpts,- scopeId: workspaceId,- proxy: await connectSshWorkspace(_type),+ scopeId: locationId,+ proxy: await connectSshTransport(transport),}): new LocalTerminalProvider(terminalOpts);const lifecycleService = new LifecycleScriptService({- projectId: context.projectId,- workspaceId,- terminals: workspaceTerminals,+ locationId,+ terminals: runtimeTerminals,});- const workspace: Workspace = {- id: workspaceId,+ const runtime: LocationRuntime = {+ id: locationId,path: workDir,- fs: workspaceFs,+ fs: runtimeFs,settings: context.settings,lifecycleService,};@@ -130,17 +124,16 @@ export function createWorkspaceFactory(const { logPrefix } = context;return {- workspace,+ runtime,- onCreateSideEffect: (ws) => {- void workspaceFileIndexService.onWorkspaceCreated(workspaceId, ws);+ onCreateSideEffect: (rt) => {+ void locationFileIndexService.onRuntimeCreated(locationId, rt);void (async () => {- if (scripts?.setup && (projectSettings.autoRunSetupScriptOnSessionCreation ?? true)) {+ if (scripts?.setup && (locationSettings.autoRunSetupScriptOnSessionCreation ?? true)) {const setupResult = await runLifecycleScriptWithPolicy({- workspace: ws,- projectId: context.projectId,+ runtime: rt,sessionId: context.session.id,- workspaceId,+ locationId,type: 'setup',script: scripts.setup,shellSetup,@@ -156,12 +149,11 @@ export function createWorkspaceFactory(if (setupResult.kind !== 'succeeded') return;}- if (scripts?.run && (projectSettings.autoRunRunScriptOnSessionCreation ?? false)) {+ if (scripts?.run && (locationSettings.autoRunRunScriptOnSessionCreation ?? false)) {await runLifecycleScriptWithPolicy({- workspace: ws,- projectId: context.projectId,+ runtime: rt,sessionId: context.session.id,- workspaceId,+ locationId,type: 'run',script: scripts.run,shellSetup,@@ -180,27 +172,26 @@ export function createWorkspaceFactory(onCreate: context.extraHooks?.onCreate,- onDestroy: async (ws) => {- workspaceFileIndexService.onWorkspaceDestroyed(workspaceId);+ onDestroy: async (rt) => {+ locationFileIndexService.onRuntimeDestroyed(locationId);const latestSessionSettings = await getEffectiveSessionSettings({- projectSettings: context.settings,- sessionFs: ws.fs,+ locationSettings: context.settings,+ sessionFs: rt.fs,});- const latestProjectSettings = await context.settings.get();+ const latestLocationSettings = await context.settings.get();const latestShellSetup =- latestSessionSettings.shellSetup ?? latestProjectSettings.shellSetup;+ latestSessionSettings.shellSetup ?? latestLocationSettings.shellSetup;const teardownScript = latestSessionSettings.scripts?.teardown;if (teardownScript) {await runLifecycleScriptWithPolicy({- workspace: ws,- projectId: context.projectId,+ runtime: rt,sessionId: context.session.id,- workspaceId,+ locationId,type: 'teardown',script: teardownScript,shellSetup: latestShellSetup,- origin: 'workspace-destroy',+ origin: 'location-destroy',policy: {timeoutMs: TEARDOWN_SCRIPT_WAIT_MS,logFailure: true,@@ -210,18 +201,18 @@ export function createWorkspaceFactory(logPrefix,});}- await context.extraHooks?.onDestroy?.(ws);+ await context.extraHooks?.onDestroy?.(rt);},- onDetach: async (ws) => {- await context.extraHooks?.onDetach?.(ws);+ onDetach: async (rt) => {+ await context.extraHooks?.onDetach?.(rt);},};};}type AgentRuntimeOpts = {- projectId: string;+ locationId: string;sessionId: string;sessionPath: string;tmuxEnabled: boolean;@@ -243,24 +234,24 @@ async function resolveLocalAgentShellProfile(sessionId: string): Promise<Resolve}/**- * Creates the session's agent runtime for the given transport type. The exec- * function is derived internally from the WorkspaceType.+ * Creates the session's agent runtime for the given transport. The exec+ * function is derived internally from the LocationTransport.*/export async function buildAgentRuntime(- _type: WorkspaceType,+ transport: LocationTransport,opts: AgentRuntimeOpts): Promise<AgentRuntimeProvider> {- if (_type.kind === 'ssh') {- const proxy = await connectSshWorkspace(_type);- const ctx = new SshExecutionContext(proxy, { root: _type.remoteRepoDir });- const fs = new SshFileSystem(proxy, _type.remoteRepoDir);+ if (transport.kind === 'ssh') {+ const proxy = await connectSshTransport(transport);+ const ctx = new SshExecutionContext(proxy, { root: transport.dir });+ const fs = new SshFileSystem(proxy, transport.dir);// Gate remote session start: fail loud now (missing tools / absent creds /// no egress to Switch) rather than spawning an agent that never connects.- await preflightRemoteSession({ ctx, fs, log, host: _type.host, workDir: _type.remoteRepoDir });+ await preflightRemoteSession({ ctx, fs, log, host: transport.host, workDir: transport.dir });// Remote sessions always run under tmux — it persists the agent's PTY and// is the pane the sidecar injects into and reattaches to.return new SshAgentRuntime({- projectId: opts.projectId,+ locationId: opts.locationId,sessionPath: opts.sessionPath,sessionId: opts.sessionId,tmux: true,@@ -268,7 +259,7 @@ export async function buildAgentRuntime(ctx,fs,proxy,- connectionId: _type.connectionId,+ connectionId: transport.connectionId,sessionEnvVars: opts.sessionEnvVars,});}@@ -276,7 +267,7 @@ export async function buildAgentRuntime(const ctx = new LocalExecutionContext();const agentShellProfile = await resolveLocalAgentShellProfile(opts.sessionId);return new LocalAgentRuntime({- projectId: opts.projectId,+ locationId: opts.locationId,sessionPath: opts.sessionPath,sessionId: opts.sessionId,tmux: opts.tmuxEnabled,@@ -288,33 +279,33 @@ export async function buildAgentRuntime(}/**- * Resolves the session-level environment variables and settings from an already-acquired workspace.- * Used by providers after `workspaceRegistry.acquire` to avoid duplicating settings reads.+ * Resolves the session-level environment variables and settings from an+ * already-acquired location runtime. Used by providers after+ * `locationRuntimeRegistry.acquire` to avoid duplicating settings reads.*/export async function resolveSessionEnv(session: Pick<Session, 'id' | 'title'>,- workspace: Pick<Workspace, 'path' | 'fs'>,- projectPath: string,- settings: ProjectSettingsProvider+ runtime: Pick<LocationRuntime, 'path' | 'fs'>,+ settings: LocationSettingsProvider): Promise<{sessionEnvVars: Record<string, string>;tmuxEnabled: boolean;shellSetup?: string;}> {- const projectSettings = await settings.get();+ const locationSettings = await settings.get();const sessionLevelSettings = await getEffectiveSessionSettings({- projectSettings: settings,- sessionFs: workspace.fs,+ locationSettings: settings,+ sessionFs: runtime.fs,});return {sessionEnvVars: getSessionEnvVars({sessionId: session.id,sessionName: session.title,- sessionPath: workspace.path,- projectPath,- portSeed: workspace.path,+ sessionPath: runtime.path,+ rootPath: runtime.path,+ portSeed: runtime.path,}),- tmuxEnabled: projectSettings.tmux ?? false,- shellSetup: sessionLevelSettings.shellSetup ?? projectSettings.shellSetup,+ tmuxEnabled: locationSettings.tmux ?? false,+ shellSetup: sessionLevelSettings.shellSetup ?? locationSettings.shellSetup,};}diff --git a/dash/apps/switchdash-desktop/src/main/core/locations/location-runtime-registry.test.ts b/dash/apps/switchdash-desktop/src/main/core/locations/location-runtime-registry.test.tsnew file mode 100644index 000000000..fe8ec1d3f--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/locations/location-runtime-registry.test.ts@@ -0,0 +1,274 @@+import { describe, expect, it, vi } from 'vitest';+import type { LocationRuntime } from './location-runtime';+import { LocationRuntimeRegistry } from './location-runtime-registry';++function makeRuntime(id: string): {+ runtime: LocationRuntime;+ dispose: ReturnType<typeof vi.fn>;+} {+ const dispose = vi.fn(async () => {});++ return {+ runtime: {+ id,+ path: `/tmp/${id}`,+ fs: {} as LocationRuntime['fs'],+ settings: {} as LocationRuntime['settings'],+ lifecycleService: {+ dispose,+ } as unknown as LocationRuntime['lifecycleService'],+ },+ dispose,+ };+}++describe('LocationRuntimeRegistry', () => {+ it('creates once and increments ref count on repeated acquire', async () => {+ const registry = new LocationRuntimeRegistry();+ const { runtime } = makeRuntime('loc-a');+ const factory = vi.fn(async () => ({ runtime }));++ const first = await registry.acquire('loc-a', factory);+ const second = await registry.acquire('loc-a', factory);++ expect(first).toBe(runtime);+ expect(second).toBe(runtime);+ expect(factory).toHaveBeenCalledTimes(1);+ expect(registry.get('loc-a')).toBe(runtime);+ expect(registry.refCount('loc-a')).toBe(2);+ });++ it('coalesces concurrent acquires for the same key', async () => {+ const registry = new LocationRuntimeRegistry();+ const { runtime } = makeRuntime('loc-a');+ let resolveFactory: ((value: { runtime: LocationRuntime }) => void) | undefined;+ const factory = vi.fn(+ () =>+ new Promise<{ runtime: LocationRuntime }>((resolve) => {+ resolveFactory = resolve;+ })+ );++ const first = registry.acquire('loc-a', factory);+ const second = registry.acquire('loc-a', factory);++ expect(factory).toHaveBeenCalledTimes(1);+ resolveFactory?.({ runtime });++ await expect(first).resolves.toBe(runtime);+ await expect(second).resolves.toBe(runtime);+ expect(registry.refCount('loc-a')).toBe(2);+ });++ it('disposes runtime resources when ref count reaches zero', async () => {+ const registry = new LocationRuntimeRegistry();+ const { runtime, dispose } = makeRuntime('loc-a');+ const factory = vi.fn(async () => ({ runtime }));++ await registry.acquire('loc-a', factory);+ await registry.acquire('loc-a', factory);++ await registry.release('loc-a');+ expect(dispose).not.toHaveBeenCalled();+ expect(registry.refCount('loc-a')).toBe(1);++ await registry.release('loc-a');+ expect(dispose).toHaveBeenCalledTimes(1);+ expect(registry.get('loc-a')).toBeUndefined();+ expect(registry.refCount('loc-a')).toBe(0);+ });++ it('disposeAll disposes each runtime once and clears the registry', async () => {+ const registry = new LocationRuntimeRegistry();+ const first = makeRuntime('loc-a');+ const second = makeRuntime('loc-b');++ await registry.acquire('loc-a', async () => ({ runtime: first.runtime }));+ await registry.acquire('loc-a', async () => ({ runtime: first.runtime }));+ await registry.acquire('loc-b', async () => ({ runtime: second.runtime }));++ await registry.disposeAll();++ expect(first.dispose).toHaveBeenCalledTimes(1);+ expect(second.dispose).toHaveBeenCalledTimes(1);+ expect(registry.refCount('loc-a')).toBe(0);+ expect(registry.refCount('loc-b')).toBe(0);+ });++ it('ignores release for unknown keys', async () => {+ const registry = new LocationRuntimeRegistry();+ await expect(registry.release('missing')).resolves.toBeUndefined();+ });++ it('calls onCreateSideEffect once on first acquire and not on re-acquire', async () => {+ const registry = new LocationRuntimeRegistry();+ const { runtime } = makeRuntime('loc-a');+ const onCreateSideEffect = vi.fn();+ const factory = vi.fn(async () => ({ runtime, onCreateSideEffect }));++ await registry.acquire('loc-a', factory);+ expect(onCreateSideEffect).toHaveBeenCalledTimes(1);+ expect(onCreateSideEffect).toHaveBeenCalledWith(runtime);++ await registry.acquire('loc-a', factory);+ expect(onCreateSideEffect).toHaveBeenCalledTimes(1);+ });++ it('awaits onCreate before acquire resolves', async () => {+ const registry = new LocationRuntimeRegistry();+ const { runtime } = makeRuntime('loc-a');+ const order: string[] = [];++ const onCreate = vi.fn(async () => {+ order.push('onCreate');+ });+ const factory = vi.fn(async () => ({ runtime, onCreate }));++ const acquired = registry.acquire('loc-a', factory).then((rt) => {+ order.push('acquired');+ return rt;+ });++ await acquired;++ expect(order).toEqual(['onCreate', 'acquired']);+ expect(onCreate).toHaveBeenCalledWith(runtime);+ });++ it('does not call onCreate on re-acquire', async () => {+ const registry = new LocationRuntimeRegistry();+ const { runtime } = makeRuntime('loc-a');+ const onCreate = vi.fn(async () => {});+ const factory = vi.fn(async () => ({ runtime, onCreate }));++ await registry.acquire('loc-a', factory);+ await registry.acquire('loc-a', factory);++ expect(onCreate).toHaveBeenCalledTimes(1);+ });++ it('calls onDestroy once at final release, not on earlier releases', async () => {+ const registry = new LocationRuntimeRegistry();+ const { runtime } = makeRuntime('loc-a');+ const onDestroy = vi.fn(async () => {});+ const factory = vi.fn(async () => ({ runtime, onDestroy }));++ await registry.acquire('loc-a', factory);+ await registry.acquire('loc-a', factory);++ await registry.release('loc-a');+ expect(onDestroy).not.toHaveBeenCalled();++ await registry.release('loc-a');+ expect(onDestroy).toHaveBeenCalledTimes(1);+ expect(onDestroy).toHaveBeenCalledWith(runtime);+ });++ it('calls onDestroy before lifecycleService.dispose', async () => {+ const registry = new LocationRuntimeRegistry();+ const { runtime, dispose } = makeRuntime('loc-a');+ const order: string[] = [];++ dispose.mockImplementation(() => {+ order.push('lifecycleDispose');+ return undefined;+ });++ const onDestroy = vi.fn(() => {+ order.push('onDestroy');+ return Promise.resolve();+ });+ const factory = vi.fn(async () => ({ runtime, onDestroy }));++ await registry.acquire('loc-a', factory);+ await registry.release('loc-a');++ expect(order).toEqual(['onDestroy', 'lifecycleDispose']);+ });++ it('calls onDestroy for each entry in disposeAll', async () => {+ const registry = new LocationRuntimeRegistry();+ const first = makeRuntime('loc-a');+ const second = makeRuntime('loc-b');+ const onDestroyFirst = vi.fn(async () => {});+ const onDestroySecond = vi.fn(async () => {});++ await registry.acquire('loc-a', async () => ({+ runtime: first.runtime,+ onDestroy: onDestroyFirst,+ }));+ await registry.acquire('loc-b', async () => ({+ runtime: second.runtime,+ onDestroy: onDestroySecond,+ }));++ await registry.disposeAll();++ expect(onDestroyFirst).toHaveBeenCalledTimes(1);+ expect(onDestroyFirst).toHaveBeenCalledWith(first.runtime);+ expect(onDestroySecond).toHaveBeenCalledTimes(1);+ expect(onDestroySecond).toHaveBeenCalledWith(second.runtime);+ });++ it('calls onDetach (not onDestroy) when releasing with detach mode', async () => {+ const registry = new LocationRuntimeRegistry();+ const { runtime } = makeRuntime('loc-a');+ const onDestroy = vi.fn(async () => {});+ const onDetach = vi.fn(async () => {});+ const factory = vi.fn(async () => ({ runtime, onDestroy, onDetach }));++ await registry.acquire('loc-a', factory);+ await registry.release('loc-a', 'detach');++ expect(onDetach).toHaveBeenCalledTimes(1);+ expect(onDetach).toHaveBeenCalledWith(runtime);+ expect(onDestroy).not.toHaveBeenCalled();+ });++ it('calls onDestroy (not onDetach) when releasing with terminate mode', async () => {+ const registry = new LocationRuntimeRegistry();+ const { runtime } = makeRuntime('loc-a');+ const onDestroy = vi.fn(async () => {});+ const onDetach = vi.fn(async () => {});+ const factory = vi.fn(async () => ({ runtime, onDestroy, onDetach }));++ await registry.acquire('loc-a', factory);+ await registry.release('loc-a', 'terminate');++ expect(onDestroy).toHaveBeenCalledTimes(1);+ expect(onDestroy).toHaveBeenCalledWith(runtime);+ expect(onDetach).not.toHaveBeenCalled();+ });++ it('does not call onDetach when ref count has not reached zero', async () => {+ const registry = new LocationRuntimeRegistry();+ const { runtime } = makeRuntime('loc-a');+ const onDetach = vi.fn(async () => {});+ const factory = vi.fn(async () => ({ runtime, onDetach }));++ await registry.acquire('loc-a', factory);+ await registry.acquire('loc-a', factory);++ await registry.release('loc-a', 'detach');+ expect(onDetach).not.toHaveBeenCalled();++ await registry.release('loc-a', 'detach');+ expect(onDetach).toHaveBeenCalledTimes(1);+ });++ it('releaseAll forces teardown regardless of ref count', async () => {+ const registry = new LocationRuntimeRegistry();+ const { runtime } = makeRuntime('loc-a');+ const onDestroy = vi.fn(async () => {});+ const onDetach = vi.fn(async () => {});++ await registry.acquire('loc-a', async () => ({ runtime, onDestroy, onDetach }));+ await registry.acquire('loc-a', async () => ({ runtime, onDestroy, onDetach }));++ await registry.releaseAll('loc-a', 'detach');++ expect(onDetach).toHaveBeenCalledTimes(1);+ expect(onDestroy).not.toHaveBeenCalled();+ expect(registry.refCount('loc-a')).toBe(0);+ });+});diff --git a/dash/apps/switchdash-desktop/src/main/core/locations/location-runtime-registry.ts b/dash/apps/switchdash-desktop/src/main/core/locations/location-runtime-registry.tsnew file mode 100644index 000000000..5b96fcfab--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/locations/location-runtime-registry.ts@@ -0,0 +1,136 @@+import type { LocationRuntime } from './location-runtime';++export type TeardownMode = 'detach' | 'terminate';++type LocationRuntimeHooks = {+ onCreate?: (runtime: LocationRuntime) => Promise<void>;+ onCreateSideEffect?: (runtime: LocationRuntime) => void;+ onDestroy?: (runtime: LocationRuntime) => Promise<void>;+ onDetach?: (runtime: LocationRuntime) => Promise<void>;+};++export type LocationRuntimeFactoryResult = { runtime: LocationRuntime } & LocationRuntimeHooks;++type RuntimeEntry = {+ runtime: LocationRuntime;+ refCount: number;+ onDestroy?: (runtime: LocationRuntime) => Promise<void>;+ onDetach?: (runtime: LocationRuntime) => Promise<void>;+};++/**+ * Ref-counted registry of live location runtimes, keyed by location id. Every+ * session at a location shares one runtime; the last release tears it down+ * (running teardown scripts on `terminate`, skipping them on `detach`).+ */+export class LocationRuntimeRegistry {+ private entries = new Map<string, RuntimeEntry>();+ private acquiring = new Map<string, Promise<LocationRuntime>>();++ async acquire(+ locationId: string,+ factory: () => Promise<LocationRuntimeFactoryResult>+ ): Promise<LocationRuntime> {+ const existing = this.entries.get(locationId);+ if (existing) {+ existing.refCount += 1;+ return existing.runtime;+ }++ const inFlight = this.acquiring.get(locationId);+ if (inFlight) {+ const runtime = await inFlight;+ const current = this.entries.get(locationId);+ if (current) current.refCount += 1;+ return runtime;+ }++ const pending = factory()+ .then(async (result) => {+ this.entries.set(locationId, {+ runtime: result.runtime,+ refCount: 1,+ onDestroy: result.onDestroy,+ onDetach: result.onDetach,+ });+ result.onCreateSideEffect?.(result.runtime);+ await result.onCreate?.(result.runtime);+ return result.runtime;+ })+ .finally(() => {+ this.acquiring.delete(locationId);+ });++ this.acquiring.set(locationId, pending);+ return pending;+ }++ async release(locationId: string, mode: TeardownMode = 'terminate'): Promise<void> {+ const entry = this.entries.get(locationId);+ if (!entry) {+ const inFlight = this.acquiring.get(locationId);+ if (inFlight) {+ await inFlight;+ await this.release(locationId, mode);+ }+ return;+ }++ if (entry.refCount > 1) {+ entry.refCount -= 1;+ return;+ }++ this.entries.delete(locationId);+ if (mode === 'terminate') {+ await entry.onDestroy?.(entry.runtime);+ }+ await entry.runtime.dispose?.();+ await entry.runtime.lifecycleService.dispose();+ if (mode === 'detach') {+ await entry.onDetach?.(entry.runtime);+ }+ }++ /** Release the runtime regardless of how many sessions still hold it. */+ async releaseAll(locationId: string, mode: TeardownMode = 'terminate'): Promise<void> {+ const entry = this.entries.get(locationId);+ if (!entry) {+ const inFlight = this.acquiring.get(locationId);+ if (inFlight) {+ await inFlight;+ return this.releaseAll(locationId, mode);+ }+ return;+ }+ entry.refCount = 1;+ await this.release(locationId, mode);+ }++ get(locationId: string): LocationRuntime | undefined {+ return this.entries.get(locationId)?.runtime;+ }++ refCount(locationId: string): number {+ return this.entries.get(locationId)?.refCount ?? 0;+ }++ async disposeAll(mode: TeardownMode = 'terminate'): Promise<void> {+ const entries = Array.from(this.entries.values());+ this.entries.clear();+ await Promise.all(+ entries.map(async (entry) => {+ if (mode === 'terminate') {+ await entry.onDestroy?.(entry.runtime);+ }+ await entry.runtime.dispose?.();+ await entry.runtime.lifecycleService.dispose();+ if (mode === 'detach') {+ await entry.onDetach?.(entry.runtime);+ }+ })+ );+ }+}++export const locationRuntimeRegistry = new LocationRuntimeRegistry();diff --git a/dash/apps/switchdash-desktop/src/main/core/locations/location-runtime-settings-controller.ts b/dash/apps/switchdash-desktop/src/main/core/locations/location-runtime-settings-controller.tsnew file mode 100644index 000000000..0db6d3851--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/locations/location-runtime-settings-controller.ts@@ -0,0 +1,20 @@+import { locationRuntimeRegistry } from '@main/core/locations/location-runtime-registry';+import { getEffectiveSessionSettings } from '@main/core/locations/settings/effective-session-settings';+import type { LocationSettings } from '@shared/core/location-settings/location-settings';+import { createRPCController } from '@shared/lib/ipc/rpc';++async function getSettings(locationId: string): Promise<LocationSettings> {+ const runtime = locationRuntimeRegistry.get(locationId);+ if (!runtime) {+ throw new Error(`No live runtime for location ${locationId}`);+ }++ return getEffectiveSessionSettings({+ locationSettings: runtime.settings,+ sessionFs: runtime.fs,+ });+}++export const locationRuntimeSettingsController = createRPCController({+ getSettings,+});diff --git a/dash/apps/switchdash-desktop/src/main/core/locations/location-runtime.ts b/dash/apps/switchdash-desktop/src/main/core/locations/location-runtime.tsnew file mode 100644index 000000000..b0d638e33--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/locations/location-runtime.ts@@ -0,0 +1,18 @@+import type { FileSystemProvider } from '@main/core/fs/types';+import type { LocationSettingsProvider } from '@main/core/locations/settings/provider';+import type { LifecycleScriptService } from './lifecycle-service';++/**+ * The live execution environment for a location: its filesystem, settings and+ * lifecycle scripts, shared by every session running there. Acquired/released+ * per session through the location runtime registry (ref-counted, one runtime+ * per location id).+ */+export interface LocationRuntime {+ readonly id: string;+ readonly path: string;+ readonly fs: FileSystemProvider;+ readonly settings: LocationSettingsProvider;+ readonly lifecycleService: LifecycleScriptService;+ dispose?(): void | Promise<void>;+}diff --git a/dash/apps/switchdash-desktop/src/main/core/locations/location-transport.ts b/dash/apps/switchdash-desktop/src/main/core/locations/location-transport.tsnew file mode 100644index 000000000..892a3998c--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/locations/location-transport.ts@@ -0,0 +1,29 @@+import type { Location } from '@shared/core/locations/locations';++/**+ * How a location's execution reaches its working directory: on this machine,+ * or over a pooled SSH connection to the location's host. Derived from the+ * location row — the runtime registry, runtime factory, and session providers+ * all key off this.+ */+export type LocationTransport =+ | { kind: 'local' }+ | { kind: 'ssh'; host: string; dir: string; connectionId: string };++export function locationTransport(location: Pick<Location, 'sshHost' | 'dir'>): LocationTransport {+ if (location.sshHost === null) return { kind: 'local' };+ return {+ kind: 'ssh',+ host: location.sshHost,+ dir: location.dir,+ connectionId: sshConnectionIdForHost(location.sshHost),+ };+}++/**+ * The pooled SSH connection id for a host. One connection per host, shared by+ * every remote session, sidecar deploy, and fs operation on that host.+ */+export function sshConnectionIdForHost(sshHost: string): string {+ return `agent-ssh:${sshHost}`;+}diff --git a/dash/apps/switchdash-desktop/src/main/core/locations/operations/inspect-location-path.ts b/dash/apps/switchdash-desktop/src/main/core/locations/operations/inspect-location-path.tsnew file mode 100644index 000000000..d8cae1132--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/locations/operations/inspect-location-path.ts@@ -0,0 +1,22 @@+import { detectSwitchAgent } from '@main/core/agents/detect';+import type {+ InspectLocationPathParams,+ LocationPathInspection,+} from '@shared/core/locations/locations';+import { checkIsValidDirectory } from '../path-utils';+import { getLocationByHostDir } from '../store';++export async function inspectLocationPath(+ params: InspectLocationPathParams+): Promise<LocationPathInspection> {+ const [existingLocation, switchAgent] = await Promise.all([+ getLocationByHostDir(null, params.path),+ detectSwitchAgent(params.path),+ ]);++ return {+ isDirectory: checkIsValidDirectory(params.path),+ existingLocation,+ switchAgent,+ };+}diff --git a/dash/apps/switchdash-desktop/src/main/core/locations/operations/open-location.ts b/dash/apps/switchdash-desktop/src/main/core/locations/operations/open-location.tsnew file mode 100644index 000000000..bc7c143cd--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/locations/operations/open-location.ts@@ -0,0 +1,21 @@+import { err, ok, type Result } from '@switchdash/shared';+import { locationManager } from '@main/core/locations/location-manager';+import type { OpenLocationError } from '@shared/core/locations/locations';+import { checkIsValidDirectory } from '../path-utils';+import { getLocationById } from '../store';++export async function openLocation(locationId: string): Promise<Result<void, OpenLocationError>> {+ const location = await getLocationById(locationId);+ if (!location) return err({ type: 'error', message: `Location not found: ${locationId}` });+ // Remote locations have no local path — their working dir lives on the host,+ // so there is nothing to validate here; provisioning handles the remote.+ if (location.sshHost === null && !checkIsValidDirectory(location.dir)) {+ return err({ type: 'path-not-found', path: location.dir });+ }+ const result = await locationManager.openLocation(location);+ if (!result.success) {+ return err({ type: 'error', message: result.error.message });+ }++ return ok();+}diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/path-utils.ts b/dash/apps/switchdash-desktop/src/main/core/locations/path-utils.tssimilarity index 100%rename from dash/apps/switchdash-desktop/src/main/core/projects/path-utils.tsrename to dash/apps/switchdash-desktop/src/main/core/locations/path-utils.tsdiff --git a/dash/apps/switchdash-desktop/src/main/core/workspaces/workspace-env.ts b/dash/apps/switchdash-desktop/src/main/core/locations/session-env.tssimilarity index 93%rename from dash/apps/switchdash-desktop/src/main/core/workspaces/workspace-env.tsrename to dash/apps/switchdash-desktop/src/main/core/locations/session-env.tsindex b3aca0bab..f89b98eb6 100644--- a/dash/apps/switchdash-desktop/src/main/core/workspaces/workspace-env.ts+++ b/dash/apps/switchdash-desktop/src/main/core/locations/session-env.ts@@ -2,7 +2,7 @@ export interface SessionEnvContext {sessionId: string;sessionName: string;sessionPath: string;- projectPath: string;+ rootPath: string;portSeed?: string;}@@ -13,7 +13,7 @@ export function getSessionEnvVars(ctx: SessionEnvContext): Record<string, stringSWITCHDASH_SESSION_ID: ctx.sessionId,SWITCHDASH_SESSION_NAME: sessionName,SWITCHDASH_SESSION_PATH: ctx.sessionPath,- SWITCHDASH_ROOT_PATH: ctx.projectPath,+ SWITCHDASH_ROOT_PATH: ctx.rootPath,SWITCHDASH_PORT: String(getBasePort(portSeed)),};}diff --git a/dash/apps/switchdash-desktop/src/main/core/locations/settings/count-locations-using-github-account.db.test.ts b/dash/apps/switchdash-desktop/src/main/core/locations/settings/count-locations-using-github-account.db.test.tsnew file mode 100644index 000000000..2c28ed957--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/locations/settings/count-locations-using-github-account.db.test.ts@@ -0,0 +1,99 @@+import { openFixture } from '@tooling/utils/db';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { AppDb } from '@main/db/client';+import { locations, locationSettings } from '@main/db/schema';+import { countLocationsUsingGithubAccount } from './count-locations-using-github-account';++const mocks = vi.hoisted(() => ({+ db: undefined as AppDb | undefined,+}));++vi.mock('@main/db/client', () => ({+ get db() {+ if (!mocks.db) throw new Error('Test database not initialized');+ return mocks.db;+ },+}));++const TARGET_ACCOUNT_ID = 'github.com:42';+const OTHER_ACCOUNT_ID = 'github.com:99';++function baseSettingsJson(githubAccountId?: string | null): string {+ const settings: Record<string, unknown> = {+ defaultBranch: 'main',+ baseRemote: 'origin',+ };+ if (githubAccountId !== undefined) {+ settings.githubAccountId = githubAccountId;+ }+ return JSON.stringify(settings);+}++describe('countLocationsUsingGithubAccount', () => {+ let fixture: Awaited<ReturnType<typeof openFixture>>;++ beforeEach(async () => {+ fixture = await openFixture('empty');+ mocks.db = fixture.db;+ });++ afterEach(() => {+ fixture.close();+ mocks.db = undefined;+ });++ it('counts only persisted locations pinned to the target account', async () => {+ await fixture.db.insert(locations).values([+ { id: 'loc-match-1', name: 'Match 1', sshHost: '', dir: '/repo/match-1' },+ { id: 'loc-match-2', name: 'Match 2', sshHost: '', dir: '/repo/match-2' },+ { id: 'loc-null', name: 'Null', sshHost: '', dir: '/repo/null' },+ { id: 'loc-other', name: 'Other', sshHost: '', dir: '/repo/other' },+ { id: 'loc-unconfigured', name: 'Unconfigured', sshHost: '', dir: '/repo/unconfigured' },+ ]);+ await fixture.db.insert(locationSettings).values([+ {+ locationId: 'loc-match-1',+ baseSettingsJson: baseSettingsJson(TARGET_ACCOUNT_ID),+ },+ {+ locationId: 'loc-match-2',+ baseSettingsJson: baseSettingsJson(` ${TARGET_ACCOUNT_ID} `),+ },+ {+ locationId: 'loc-null',+ baseSettingsJson: baseSettingsJson(null),+ },+ {+ locationId: 'loc-other',+ baseSettingsJson: baseSettingsJson(OTHER_ACCOUNT_ID),+ },+ {+ locationId: 'loc-unconfigured',+ baseSettingsJson: baseSettingsJson(),+ },+ ]);++ await expect(countLocationsUsingGithubAccount(TARGET_ACCOUNT_ID)).resolves.toBe(2);+ await expect(countLocationsUsingGithubAccount(OTHER_ACCOUNT_ID)).resolves.toBe(1);+ await expect(countLocationsUsingGithubAccount('github.com:missing')).resolves.toBe(0);+ });++ it('skips malformed base settings JSON', async () => {+ await fixture.db.insert(locations).values([+ { id: 'loc-malformed', name: 'Malformed', sshHost: '', dir: '/repo/malformed' },+ { id: 'loc-valid', name: 'Valid', sshHost: '', dir: '/repo/valid' },+ ]);+ await fixture.db.insert(locationSettings).values([+ {+ locationId: 'loc-malformed',+ baseSettingsJson: '{not-json',+ },+ {+ locationId: 'loc-valid',+ baseSettingsJson: baseSettingsJson(TARGET_ACCOUNT_ID),+ },+ ]);++ await expect(countLocationsUsingGithubAccount(TARGET_ACCOUNT_ID)).resolves.toBe(1);+ });+});diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/settings/count-projects-using-github-account.ts b/dash/apps/switchdash-desktop/src/main/core/locations/settings/count-locations-using-github-account.tssimilarity index 58%rename from dash/apps/switchdash-desktop/src/main/core/projects/settings/count-projects-using-github-account.tsrename to dash/apps/switchdash-desktop/src/main/core/locations/settings/count-locations-using-github-account.tsindex d398f7f16..bb30e820c 100644--- a/dash/apps/switchdash-desktop/src/main/core/projects/settings/count-projects-using-github-account.ts+++ b/dash/apps/switchdash-desktop/src/main/core/locations/settings/count-locations-using-github-account.ts@@ -1,6 +1,6 @@import { db } from '@main/db/client';-import { projectSettings as projectSettingsTable } from '@main/db/schema';-import { parseJsonObject } from './project-settings-json';+import { locationSettings as locationSettingsTable } from '@main/db/schema';+import { parseJsonObject } from './location-settings-json';function readPinnedGithubAccountId(raw: string): string | undefined {try {@@ -14,18 +14,18 @@ function readPinnedGithubAccountId(raw: string): string | undefined {}}-export async function countProjectsUsingGithubAccount(accountId: string): Promise<number> {+export async function countLocationsUsingGithubAccount(accountId: string): Promise<number> {const targetAccountId = accountId.trim();if (!targetAccountId) return 0;const rows = db- .select({ baseProjectSettingsJson: projectSettingsTable.baseProjectSettingsJson })- .from(projectSettingsTable)+ .select({ baseSettingsJson: locationSettingsTable.baseSettingsJson })+ .from(locationSettingsTable).all();let count = 0;for (const row of rows) {- if (readPinnedGithubAccountId(row.baseProjectSettingsJson) === targetAccountId) {+ if (readPinnedGithubAccountId(row.baseSettingsJson) === targetAccountId) {count += 1;}}diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/settings/effective-session-settings.test.ts b/dash/apps/switchdash-desktop/src/main/core/locations/settings/effective-session-settings.test.tssimilarity index 75%rename from dash/apps/switchdash-desktop/src/main/core/projects/settings/effective-session-settings.test.tsrename to dash/apps/switchdash-desktop/src/main/core/locations/settings/effective-session-settings.test.tsindex 6ea497bcb..a975d24b9 100644--- a/dash/apps/switchdash-desktop/src/main/core/projects/settings/effective-session-settings.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/locations/settings/effective-session-settings.test.ts@@ -1,12 +1,12 @@import { describe, expect, it, vi } from 'vitest';import type { FileSystemProvider } from '@main/core/fs/types';import { getEffectiveSessionSettings } from './effective-session-settings';-import type { ProjectSettingsProvider } from './provider';+import type { LocationSettingsProvider } from './provider';-function makeProjectSettings(settings: Awaited<ReturnType<ProjectSettingsProvider['get']>>) {+function makeLocationSettings(settings: Awaited<ReturnType<LocationSettingsProvider['get']>>) {return {get: vi.fn().mockResolvedValue(settings),- } as unknown as ProjectSettingsProvider;+ } as unknown as LocationSettingsProvider;}function makeSessionFs(config: unknown | null): FileSystemProvider {@@ -21,9 +21,9 @@ function makeSessionFs(config: unknown | null): FileSystemProvider {}describe('getEffectiveSessionSettings', () => {- it('merges shareable project settings by leaf with project settings winning', async () => {+ it('merges shareable location settings by leaf with location settings winning', async () => {const settings = await getEffectiveSessionSettings({- projectSettings: makeProjectSettings({+ locationSettings: makeLocationSettings({preservePatterns: ['.env.local'],scripts: { run: 'pnpm dev' },}),@@ -48,9 +48,9 @@ describe('getEffectiveSessionSettings', () => {expect(settings).not.toHaveProperty('baseRemote');});- it('falls back to defaults plus project settings when the session config is invalid', async () => {+ it('falls back to defaults plus location settings when the session config is invalid', async () => {const settings = await getEffectiveSessionSettings({- projectSettings: makeProjectSettings({ shellSetup: 'nvm use' }),+ locationSettings: makeLocationSettings({ shellSetup: 'nvm use' }),sessionFs: {exists: vi.fn().mockResolvedValue(true),read: vi.fn().mockResolvedValue({ content: '{', truncated: false, totalSize: 1 }),@@ -62,9 +62,9 @@ describe('getEffectiveSessionSettings', () => {expect(settings.shellSetup).toBe('nvm use');});- it('falls back to defaults when project settings are invalid', async () => {+ it('falls back to defaults when location settings are invalid', async () => {const settings = await getEffectiveSessionSettings({- projectSettings: makeProjectSettings({+ locationSettings: makeLocationSettings({preservePatterns: 'not-an-array',} as never),sessionFs: makeSessionFs(null),diff --git a/dash/apps/switchdash-desktop/src/main/core/locations/settings/effective-session-settings.ts b/dash/apps/switchdash-desktop/src/main/core/locations/settings/effective-session-settings.tsnew file mode 100644index 000000000..6fe03cd73--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/locations/settings/effective-session-settings.ts@@ -0,0 +1,32 @@+import type { FileSystemProvider } from '@main/core/fs/types';+import { log } from '@main/lib/logger';+import {+ defaultShareableLocationSettings,+ shareableLocationSettingsSchema,+ type LocationSettings,+} from '@shared/core/location-settings/location-settings';+import { mergeShareableLocationSettings } from '@shared/core/location-settings/location-settings-fields';+import type { LocationSettingsProvider } from './provider';++export async function getEffectiveSessionSettings(args: {+ locationSettings: LocationSettingsProvider;+ sessionFs: FileSystemProvider;+}): Promise<LocationSettings> {+ const { locationSettings, sessionFs } = args;+ const parsedSettings = shareableLocationSettingsSchema.safeParse(await locationSettings.get());+ const localShareableSettings = parsedSettings.success ? parsedSettings.data : {};+ const defaults = defaultShareableLocationSettings();+ const exists = await sessionFs.exists('.switchdash.json');+ if (!exists) {+ return mergeShareableLocationSettings(defaults, localShareableSettings);+ }++ try {+ const { content } = await sessionFs.read('.switchdash.json');+ const locationFileSettings = shareableLocationSettingsSchema.parse(JSON.parse(content));+ return mergeShareableLocationSettings(defaults, locationFileSettings, localShareableSettings);+ } catch (err) {+ log.warn('Failed to parse session .switchdash.json, falling back to location settings', err);+ return mergeShareableLocationSettings(defaults, localShareableSettings);+ }+}diff --git a/dash/apps/switchdash-desktop/src/main/core/locations/settings/legacy-location-settings-migration.ts b/dash/apps/switchdash-desktop/src/main/core/locations/settings/legacy-location-settings-migration.tsnew file mode 100644index 000000000..231a5aa7e--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/locations/settings/legacy-location-settings-migration.ts@@ -0,0 +1,120 @@+import type { Result } from '@switchdash/shared';+import type { FileSystemProvider } from '@main/core/fs/types';+import { log } from '@main/lib/logger';+import {+ baseLocationSettingsSchema,+ legacyBaseLocationSettingsSchema,+ legacyLocationConfigSchema,+ shareableLocationSettingsSchema,+ type BaseLocationSettings,+ type ShareableLocationSettings,+} from '@shared/core/location-settings/location-settings';+import { mergeShareableLocationSettings } from '@shared/core/location-settings/location-settings-fields';+import type { UpdateLocationSettingsError } from '@shared/core/locations/locations';+import {+ hasLegacyShareableConfigMigrated,+ serializeShareableLocationSettings,+} from './legacy-shareable-migration-marker';+import { compactUndefined, parseJsonObject, readJson } from './location-settings-json';+import type { LocationSettingsStorage, StoredLocationSettings } from './location-settings-storage';++export type LegacyLocationSettingsMigrationArgs = {+ locationId: string;+ row: StoredLocationSettings | undefined;+ configReader: Pick<FileSystemProvider, 'exists' | 'read'> | undefined;+ storage: LocationSettingsStorage;+ git?: LocationSettingsGitInspector;+ normalizeStoredWorktreeDirectory: (+ worktreeDirectory: string+ ) => Promise<Result<string, UpdateLocationSettingsError>>;+};++export type LocationSettingsGitInspector = {+ isFileCleanlyTracked(filePath: string): Promise<boolean>;+};++async function readLegacyLocationConfig(+ configReader: Pick<FileSystemProvider, 'exists' | 'read'> | undefined+): Promise<BaseLocationSettings | undefined> {+ if (!configReader) return undefined;+ try {+ if (!(await configReader.exists('.switchdash.json'))) return undefined;+ const { content } = await configReader.read('.switchdash.json');+ const parsed = legacyLocationConfigSchema.safeParse(parseJsonObject(content));+ if (!parsed.success) {+ log.warn('Failed to parse legacy .switchdash.json for migration', parsed.error);+ return undefined;+ }+ return parsed.data;+ } catch (error) {+ log.warn('Failed to read legacy .switchdash.json for migration', error);+ return undefined;+ }+}++export async function migrateLegacyLocationSettingsIfNeeded({+ locationId,+ row,+ configReader,+ storage,+ git,+ normalizeStoredWorktreeDirectory,+}: LegacyLocationSettingsMigrationArgs): Promise<void> {+ if (!row) return;++ const baseAlreadyMigrated = Boolean(row.legacyConfigMigratedAt);+ const shareableAlreadyMigrated = hasLegacyShareableConfigMigrated(row.shareableSettingsJson);+ if (baseAlreadyMigrated && shareableAlreadyMigrated) return;++ const current = readJson(+ row.baseSettingsJson,+ legacyBaseLocationSettingsSchema,+ 'base location settings'+ );+ const currentShareable = readJson(+ row.shareableSettingsJson,+ shareableLocationSettingsSchema,+ 'shareable location settings'+ );+ const legacy = await readLegacyLocationConfig(configReader);+ const next: BaseLocationSettings = baseLocationSettingsSchema.parse(current);+ let nextShareable: ShareableLocationSettings | undefined;++ if (legacy && !baseAlreadyMigrated) {+ if (legacy.worktreeDirectory !== undefined) {+ const normalized = await normalizeStoredWorktreeDirectory(legacy.worktreeDirectory);+ if (normalized.success) next.worktreeDirectory = normalized.data;+ }+ if (legacy.tmux !== undefined) next.tmux = legacy.tmux;+ if (legacy.locationProvider !== undefined) {+ next.locationProvider = legacy.locationProvider;+ }+ }++ if (legacy && !shareableAlreadyMigrated) {+ if ((await git?.isFileCleanlyTracked('.switchdash.json')) === false) {+ const legacyShareable = shareableLocationSettingsSchema.parse(legacy);+ nextShareable = mergeShareableLocationSettings(currentShareable, legacyShareable);+ }+ }++ const update: Partial<StoredLocationSettings> = {+ ...(nextShareable+ ? {+ shareableSettingsJson: serializeShareableLocationSettings(nextShareable, {+ previousRaw: row.shareableSettingsJson,+ markLegacyShareableConfigMigrated: true,+ }),+ }+ : {}),+ };++ if (!baseAlreadyMigrated) {+ update.baseSettingsJson = JSON.stringify(compactUndefined(next));+ update.legacyConfigMigratedAt = new Date().toISOString();+ }++ if (Object.keys(update).length > 0) {+ await storage.update(locationId, update);+ }+}diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/settings/legacy-shareable-migration-marker.ts b/dash/apps/switchdash-desktop/src/main/core/locations/settings/legacy-shareable-migration-marker.tssimilarity index 81%rename from dash/apps/switchdash-desktop/src/main/core/projects/settings/legacy-shareable-migration-marker.tsrename to dash/apps/switchdash-desktop/src/main/core/locations/settings/legacy-shareable-migration-marker.tsindex 2784cb278..1ec309cac 100644--- a/dash/apps/switchdash-desktop/src/main/core/projects/settings/legacy-shareable-migration-marker.ts+++ b/dash/apps/switchdash-desktop/src/main/core/locations/settings/legacy-shareable-migration-marker.ts@@ -1,5 +1,5 @@-import type { ShareableProjectSettings } from '@shared/core/project-settings/project-settings';-import { compactUndefined, parseJsonObject } from './project-settings-json';+import type { ShareableLocationSettings } from '@shared/core/location-settings/location-settings';+import { compactUndefined, parseJsonObject } from './location-settings-json';const LEGACY_SHAREABLE_CONFIG_MIGRATED_AT = '__legacyShareableConfigMigratedAt';@@ -18,8 +18,8 @@ export function hasLegacyShareableConfigMigrated(raw: string): boolean {return readLegacyShareableConfigMigratedAt(raw) !== undefined;}-export function serializeShareableProjectSettings(- settings: ShareableProjectSettings,+export function serializeShareableLocationSettings(+ settings: ShareableLocationSettings,options: {previousRaw?: string;markLegacyShareableConfigMigrated?: boolean;diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/settings/project-settings-json.ts b/dash/apps/switchdash-desktop/src/main/core/locations/settings/location-settings-json.tssimilarity index 100%rename from dash/apps/switchdash-desktop/src/main/core/projects/settings/project-settings-json.tsrename to dash/apps/switchdash-desktop/src/main/core/locations/settings/location-settings-json.tsdiff --git a/dash/apps/switchdash-desktop/src/main/core/locations/settings/location-settings-service.ts b/dash/apps/switchdash-desktop/src/main/core/locations/settings/location-settings-service.tsnew file mode 100644index 000000000..85be92bb6--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/locations/settings/location-settings-service.ts@@ -0,0 +1,170 @@+import { err, ok, type Result } from '@switchdash/shared';+import type { IInitializable } from '@switchdash/shared';+import { events } from '@main/lib/events';+import { HookCore, type Hookable } from '@main/lib/hookable';+import { log } from '@main/lib/logger';+import {+ type MigrateLocationConfigRequest,+ type MigrateLocationConfigResult,+ type LocationSettingsPatch,+ type LocationSettings,+ type LocationSettingsPage,+ type WriteLocationConfigRequest,+} from '@shared/core/location-settings/location-settings';+import { hasConfiguredShareableLocationSettings } from '@shared/core/location-settings/location-settings-fields';+import { locationSettingsChangedChannel } from '@shared/core/locations/locationEvents';+import type { UpdateLocationSettingsError } from '@shared/core/locations/locations';+import { locationManager } from '../location-manager';+import type { LocationProvider } from '../location-provider';+import {+ inspectLocationConfigMigrations,+ migrateLocationConfigFromProvider,+} from './sharing/config-migration';+import { computeLocationSettingsOverrideState } from './sharing/location-settings-override-state';+import {+ getLocationSettingsWriteTargets,+ resolveAllLocationSettingsTargets,+} from './sharing/location-settings-target-resolver';+import { shareLocationSettingsToConfig as writeSharedLocationSettingsToConfig } from './sharing/share-location-settings-to-config';++export type LocationSettingsHooks = {+ 'location-settings:changed': (event: {+ locationId: string;+ settings: LocationSettings;+ }) => void | Promise<void>;+};++export class LocationSettingsService implements Hookable<LocationSettingsHooks>, IInitializable {+ private readonly _hooks = new HookCore<LocationSettingsHooks>((name, e) =>+ log.error(`LocationSettingsService: ${String(name)} hook error`, e)+ );+ private _disposeRendererBridge: (() => void) | null = null;++ on<K extends keyof LocationSettingsHooks>(name: K, handler: LocationSettingsHooks[K]) {+ return this._hooks.on(name, handler);+ }++ initialize(): void {+ this._disposeRendererBridge?.();+ this._disposeRendererBridge = this.on('location-settings:changed', ({ locationId }) => {+ events.emit(locationSettingsChangedChannel, { locationId });+ });+ }++ async getLocationSettingsPage(+ locationId: string+ ): Promise<Result<LocationSettingsPage, UpdateLocationSettingsError>> {+ const location = this.requireLocation(locationId);+ if (!location.success) return location;+ return ok(await this.getLocationSettingsPageForLocation(location.data));+ }++ async updateLocationSettings(+ locationId: string,+ settings: LocationSettings+ ): Promise<Result<LocationSettings, UpdateLocationSettingsError>> {+ const location = this.requireLocation(locationId);+ if (!location.success) return location;++ const result = await location.data.settings.update(settings);+ if (!result.success) return result;++ const updatedSettings = await location.data.settings.get();+ this.emitSettingsChanged(locationId, updatedSettings);+ return ok(updatedSettings);+ }++ async patchLocationSettings(+ locationId: string,+ patch: LocationSettingsPatch+ ): Promise<Result<LocationSettings, UpdateLocationSettingsError>> {+ const location = this.requireLocation(locationId);+ if (!location.success) return location;++ const result = await location.data.settings.patch(patch);+ if (!result.success) return result;++ const updatedSettings = await location.data.settings.get();+ this.emitSettingsChanged(locationId, updatedSettings);+ return ok(updatedSettings);+ }++ async shareLocationSettingsToConfig(+ locationId: string,+ request: WriteLocationConfigRequest+ ): Promise<Result<LocationSettingsPage, UpdateLocationSettingsError>> {+ const location = this.requireLocation(locationId);+ if (!location.success) return location;++ const resolvedTargets = await resolveAllLocationSettingsTargets(location.data);+ const result = await writeSharedLocationSettingsToConfig(+ location.data,+ request,+ resolvedTargets+ );+ if (!result.success) return result;++ const page = await this.getLocationSettingsPageForLocation(location.data);+ this.emitSettingsChanged(locationId, page.settings);+ return ok(page);+ }++ async migrateLocationConfig(+ locationId: string,+ request: MigrateLocationConfigRequest+ ): Promise<Result<MigrateLocationConfigResult, UpdateLocationSettingsError>> {+ const location = this.requireLocation(locationId);+ if (!location.success) return location;++ const settings = await location.data.settings.get();+ if (hasConfiguredShareableLocationSettings(settings)) {+ return err({+ type: 'write-config-failed',+ message: 'Shareable location settings are already configured.',+ });+ }++ const result = await migrateLocationConfigFromProvider(location.data, request);+ if (!result.success) return result;++ const page = await this.getLocationSettingsPageForLocation(location.data);+ this.emitSettingsChanged(locationId, page.settings);+ return ok({ page, migration: result.data });+ }++ private requireLocation(+ locationId: string+ ): Result<LocationProvider, UpdateLocationSettingsError> {+ const location = locationManager.getLocation(locationId);+ return location ? ok(location) : err({ type: 'location-not-found' });+ }++ private async getLocationSettingsPageForLocation(+ location: LocationProvider+ ): Promise<LocationSettingsPage> {+ const settings = await location.settings.get();+ const defaults = {+ worktreeDirectory: await location.settings.getDefaultWorktreeDirectory(),+ };+ const resolvedTargets = await resolveAllLocationSettingsTargets(location);+ const writeTargets = getLocationSettingsWriteTargets(resolvedTargets);+ const overrideState = await computeLocationSettingsOverrideState(resolvedTargets);+ const configMigrations = hasConfiguredShareableLocationSettings(settings)+ ? []+ : await inspectLocationConfigMigrations(location.fs);+ return {+ settings,+ defaults,+ writeTargets,+ overrideState,+ configMigrations,+ shouldPromptConfigMigration: configMigrations.length > 0,+ };+ }++ private emitSettingsChanged(locationId: string, settings: LocationSettings): void {+ this._hooks.callHookBackground('location-settings:changed', { locationId, settings });+ }+}++export const locationSettingsService = new LocationSettingsService();diff --git a/dash/apps/switchdash-desktop/src/main/core/locations/settings/location-settings-storage.ts b/dash/apps/switchdash-desktop/src/main/core/locations/settings/location-settings-storage.tsnew file mode 100644index 000000000..88fc80d88--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/locations/settings/location-settings-storage.ts@@ -0,0 +1,54 @@+import { eq, sql } from 'drizzle-orm';+import { db } from '@main/db/client';+import { locationSettings as locationSettingsTable } from '@main/db/schema';++export type StoredLocationSettings = {+ baseSettingsJson: string;+ shareableSettingsJson: string;+ legacyConfigMigratedAt: string | null;+};++export interface LocationSettingsStorage {+ get(locationId: string): Promise<StoredLocationSettings | undefined>;+ insertIfMissing(locationId: string, settings: StoredLocationSettings): Promise<void>;+ update(locationId: string, settings: Partial<StoredLocationSettings>): Promise<void>;+}++export class LocationSettingsRepository implements LocationSettingsStorage {+ async get(locationId: string): Promise<StoredLocationSettings | undefined> {+ const row = db+ .select()+ .from(locationSettingsTable)+ .where(eq(locationSettingsTable.locationId, locationId))+ .get();+ if (!row) return undefined;+ return {+ baseSettingsJson: row.baseSettingsJson,+ shareableSettingsJson: row.shareableSettingsJson,+ legacyConfigMigratedAt: row.legacyConfigMigratedAt,+ };+ }++ async insertIfMissing(locationId: string, settings: StoredLocationSettings): Promise<void> {+ await db+ .insert(locationSettingsTable)+ .values({+ locationId,+ baseSettingsJson: settings.baseSettingsJson,+ shareableSettingsJson: settings.shareableSettingsJson,+ legacyConfigMigratedAt: settings.legacyConfigMigratedAt,+ updatedAt: sql`CURRENT_TIMESTAMP`,+ })+ .onConflictDoNothing();+ }++ async update(locationId: string, settings: Partial<StoredLocationSettings>): Promise<void> {+ await db+ .update(locationSettingsTable)+ .set({+ ...settings,+ updatedAt: sql`CURRENT_TIMESTAMP`,+ })+ .where(eq(locationSettingsTable.locationId, locationId));+ }+}diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/settings/project-settings.test.ts b/dash/apps/switchdash-desktop/src/main/core/locations/settings/location-settings.test.tssimilarity index 58%rename from dash/apps/switchdash-desktop/src/main/core/projects/settings/project-settings.test.tsrename to dash/apps/switchdash-desktop/src/main/core/locations/settings/location-settings.test.tsindex 312b1cd28..828bb7266 100644--- a/dash/apps/switchdash-desktop/src/main/core/projects/settings/project-settings.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/locations/settings/location-settings.test.ts@@ -3,12 +3,12 @@ import fs from 'node:fs';import os from 'node:os';import path from 'node:path';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { DEFAULT_PRESERVE_PATTERNS } from '@shared/core/project-settings/project-settings';-import type { ProjectSettingsStorage } from './project-settings-storage';-import { LocalProjectSettingsProvider } from './providers/local-project-settings-provider';+import { DEFAULT_PRESERVE_PATTERNS } from '@shared/core/location-settings/location-settings';+import type { LocationSettingsStorage } from './location-settings-storage';+import { LocalLocationSettingsProvider } from './providers/local-location-settings-provider';const storageMockState = vi.hoisted(() => ({- storage: undefined as ProjectSettingsStorage | undefined,+ storage: undefined as LocationSettingsStorage | undefined,}));function makeTrackingGit(isFileCleanlyTracked: boolean) {@@ -20,7 +20,7 @@ function makeTrackingGit(isFileCleanlyTracked: boolean) {vi.mock('@main/core/settings/settings-service', () => ({appSettingsService: {get: vi.fn().mockImplementation((key: string) => {- if (key === 'project') return Promise.resolve({ tmuxByDefault: false });+ if (key === 'location') return Promise.resolve({ tmuxByDefault: false });return Promise.resolve({defaultWorktreeDirectory: '/tmp/switchdash/worktrees',});@@ -32,10 +32,10 @@ vi.mock('@main/db/client', () => ({db: {},}));-vi.mock('./project-settings-storage', () => ({- ProjectSettingsRepository: vi.fn(function ProjectSettingsRepository() {+vi.mock('./location-settings-storage', () => ({+ LocationSettingsRepository: vi.fn(function LocationSettingsRepository() {if (!storageMockState.storage) {- throw new Error('ProjectSettingsRepository test storage was not configured');+ throw new Error('LocationSettingsRepository test storage was not configured');}return storageMockState.storage;}),@@ -47,29 +47,29 @@ vi.mock('electron', () => ({},}));-describe('ProjectSettingsProvider worktreeDirectory validation', () => {+describe('LocationSettingsProvider worktreeDirectory validation', () => {const tempDirs: string[] = [];- const createStorage = (): ProjectSettingsStorage => {+ const createStorage = (): LocationSettingsStorage => {const rows = new Map<string,{- baseProjectSettingsJson: string;- shareableProjectSettingsJson: string;+ baseSettingsJson: string;+ shareableSettingsJson: string;legacyConfigMigratedAt: string | null;}>();return {- get: async (projectId) => rows.get(projectId),- insertIfMissing: async (projectId, settings) => {- if (!rows.has(projectId)) rows.set(projectId, settings);+ get: async (locationId) => rows.get(locationId),+ insertIfMissing: async (locationId, settings) => {+ if (!rows.has(locationId)) rows.set(locationId, settings);},- update: async (projectId, settings) => {- rows.set(projectId, { ...rows.get(projectId)!, ...settings });+ update: async (locationId, settings) => {+ rows.set(locationId, { ...rows.get(locationId)!, ...settings });},};};- const projectId = () => `project-${randomUUID()}`;+ const locationId = () => `location-${randomUUID()}`;beforeEach(() => {storageMockState.storage = createStorage();@@ -83,10 +83,10 @@ describe('ProjectSettingsProvider worktreeDirectory validation', () => {});it('seeds default preserve patterns when the repo has no shared config', async () => {- const projectPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-settings-local-'));- tempDirs.push(projectPath);+ const rootPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-settings-local-'));+ tempDirs.push(rootPath);- const provider = new LocalProjectSettingsProvider(projectId(), projectPath);+ const provider = new LocalLocationSettingsProvider(locationId(), rootPath);await expect(provider.get()).resolves.toMatchObject({preservePatterns: [...DEFAULT_PRESERVE_PATTERNS],@@ -94,14 +94,14 @@ describe('ProjectSettingsProvider worktreeDirectory validation', () => {});it('seeds default preserve patterns when shared config omits preservePatterns', async () => {- const projectPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-settings-local-'));- tempDirs.push(projectPath);+ const rootPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-settings-local-'));+ tempDirs.push(rootPath);fs.writeFileSync(- path.join(projectPath, '.switchdash.json'),+ path.join(rootPath, '.switchdash.json'),JSON.stringify({ shellSetup: 'nvm use' }));- const provider = new LocalProjectSettingsProvider(projectId(), projectPath);+ const provider = new LocalLocationSettingsProvider(locationId(), rootPath);await expect(provider.get()).resolves.toMatchObject({preservePatterns: [...DEFAULT_PRESERVE_PATTERNS],@@ -109,23 +109,23 @@ describe('ProjectSettingsProvider worktreeDirectory validation', () => {});it('does not seed default preserve patterns when shared config defines preservePatterns', async () => {- const projectPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-settings-local-'));- tempDirs.push(projectPath);+ const rootPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-settings-local-'));+ tempDirs.push(rootPath);fs.writeFileSync(- path.join(projectPath, '.switchdash.json'),+ path.join(rootPath, '.switchdash.json'),JSON.stringify({ preservePatterns: ['.env.shared'] }));- const provider = new LocalProjectSettingsProvider(projectId(), projectPath);+ const provider = new LocalLocationSettingsProvider(locationId(), rootPath);await expect(provider.get()).resolves.not.toHaveProperty('preservePatterns');});it('migrates shareable settings from a local-only root config', async () => {- const projectPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-settings-local-'));- tempDirs.push(projectPath);+ const rootPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-settings-local-'));+ tempDirs.push(rootPath);fs.writeFileSync(- path.join(projectPath, '.switchdash.json'),+ path.join(rootPath, '.switchdash.json'),JSON.stringify({preservePatterns: ['.env.local'],shellSetup: 'nvm use',@@ -137,7 +137,7 @@ describe('ProjectSettingsProvider worktreeDirectory validation', () => {}));- const provider = new LocalProjectSettingsProvider(projectId(), projectPath, {+ const provider = new LocalLocationSettingsProvider(locationId(), rootPath, {git: makeTrackingGit(false),});@@ -153,10 +153,10 @@ describe('ProjectSettingsProvider worktreeDirectory validation', () => {});it('migrates local-only shareable settings for rows already base-migrated', async () => {- const projectPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-settings-local-'));- tempDirs.push(projectPath);+ const rootPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-settings-local-'));+ tempDirs.push(rootPath);fs.writeFileSync(- path.join(projectPath, '.switchdash.json'),+ path.join(rootPath, '.switchdash.json'),JSON.stringify({shellSetup: 'nvm use',scripts: {@@ -166,19 +166,19 @@ describe('ProjectSettingsProvider worktreeDirectory validation', () => {}));const row = {- baseProjectSettingsJson: JSON.stringify({ defaultBranch: 'main' }),- shareableProjectSettingsJson: '{}',+ baseSettingsJson: JSON.stringify({ defaultBranch: 'main' }),+ shareableSettingsJson: '{}',legacyConfigMigratedAt: new Date().toISOString(),};- const settingsStorage: ProjectSettingsStorage = {+ const settingsStorage: LocationSettingsStorage = {get: async () => row,insertIfMissing: vi.fn(),- update: async (_projectId, settings) => {+ update: async (_locationId, settings) => {Object.assign(row, settings);},};storageMockState.storage = settingsStorage;- const provider = new LocalProjectSettingsProvider(projectId(), projectPath, {+ const provider = new LocalLocationSettingsProvider(locationId(), rootPath, {git: makeTrackingGit(false),});@@ -197,10 +197,10 @@ describe('ProjectSettingsProvider worktreeDirectory validation', () => {});it('keeps cleanly tracked shareable settings file-backed', async () => {- const projectPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-settings-local-'));- tempDirs.push(projectPath);+ const rootPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-settings-local-'));+ tempDirs.push(rootPath);fs.writeFileSync(- path.join(projectPath, '.switchdash.json'),+ path.join(rootPath, '.switchdash.json'),JSON.stringify({shellSetup: 'nvm use',scripts: {@@ -210,7 +210,7 @@ describe('ProjectSettingsProvider worktreeDirectory validation', () => {}));- const provider = new LocalProjectSettingsProvider(projectId(), projectPath, {+ const provider = new LocalLocationSettingsProvider(locationId(), rootPath, {git: makeTrackingGit(true),});@@ -221,11 +221,11 @@ describe('ProjectSettingsProvider worktreeDirectory validation', () => {await expect(provider.get()).resolves.not.toHaveProperty('scripts');});- it('does not seed computed worktreeDirectory into project settings', async () => {- const projectPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-settings-local-'));- tempDirs.push(projectPath);+ it('does not seed computed worktreeDirectory into location settings', async () => {+ const rootPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-settings-local-'));+ tempDirs.push(rootPath);- const provider = new LocalProjectSettingsProvider(projectId(), projectPath);+ const provider = new LocalLocationSettingsProvider(locationId(), rootPath);await expect(provider.get()).resolves.not.toHaveProperty('worktreeDirectory');await expect(provider.getDefaultWorktreeDirectory()).resolves.toBe('/tmp/switchdash/worktrees');@@ -233,10 +233,10 @@ describe('ProjectSettingsProvider worktreeDirectory validation', () => {});it('keeps computed worktreeDirectory default separate from configured overrides', async () => {- const projectPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-settings-local-'));- tempDirs.push(projectPath);- const provider = new LocalProjectSettingsProvider(projectId(), projectPath);- const expectedOverridePath = path.resolve(projectPath, 'worktrees');+ const rootPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-settings-local-'));+ tempDirs.push(rootPath);+ const provider = new LocalLocationSettingsProvider(locationId(), rootPath);+ const expectedOverridePath = path.resolve(rootPath, 'worktrees');const result = await provider.update({preservePatterns: [],worktreeDirectory: expectedOverridePath,@@ -249,10 +249,10 @@ describe('ProjectSettingsProvider worktreeDirectory validation', () => {await expect(provider.getWorktreeDirectory()).resolves.toBe(expectedOverride);});- it('stores the selected GitHub account as base project settings', async () => {- const projectPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-settings-local-'));- tempDirs.push(projectPath);- const provider = new LocalProjectSettingsProvider(projectId(), projectPath);+ it('stores the selected GitHub account as base location settings', async () => {+ const rootPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-settings-local-'));+ tempDirs.push(rootPath);+ const provider = new LocalLocationSettingsProvider(locationId(), rootPath);const result = await provider.update({preservePatterns: [],@@ -263,10 +263,10 @@ describe('ProjectSettingsProvider worktreeDirectory validation', () => {await expect(provider.get()).resolves.toMatchObject({ githubAccountId: 'github.com:42' });});- it('stores null GitHub account selection as an explicit project override', async () => {- const projectPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-settings-local-'));- tempDirs.push(projectPath);- const provider = new LocalProjectSettingsProvider(projectId(), projectPath);+ it('stores null GitHub account selection as an explicit location override', async () => {+ const rootPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-settings-local-'));+ tempDirs.push(rootPath);+ const provider = new LocalLocationSettingsProvider(locationId(), rootPath);const result = await provider.update({preservePatterns: [],@@ -278,31 +278,31 @@ describe('ProjectSettingsProvider worktreeDirectory validation', () => {});it('patches the selected GitHub account without replacing other base settings', async () => {- const projectPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-settings-local-'));- tempDirs.push(projectPath);+ const rootPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-settings-local-'));+ tempDirs.push(rootPath);const row = {- baseProjectSettingsJson: JSON.stringify({+ baseSettingsJson: JSON.stringify({tmux: true,}),- shareableProjectSettingsJson: JSON.stringify({+ shareableSettingsJson: JSON.stringify({preservePatterns: ['.env.local'],}),legacyConfigMigratedAt: new Date().toISOString(),};- const settingsStorage: ProjectSettingsStorage = {+ const settingsStorage: LocationSettingsStorage = {get: async () => row,insertIfMissing: vi.fn(),- update: async (_projectId, settings) => {+ update: async (_locationId, settings) => {Object.assign(row, settings);},};storageMockState.storage = settingsStorage;- const provider = new LocalProjectSettingsProvider(projectId(), projectPath);+ const provider = new LocalLocationSettingsProvider(locationId(), rootPath);const result = await provider.patch({ githubAccountId: 'github.com:42' });expect(result.success).toBe(true);- expect(JSON.parse(row.baseProjectSettingsJson)).toEqual({+ expect(JSON.parse(row.baseSettingsJson)).toEqual({githubAccountId: 'github.com:42',tmux: true,});@@ -314,25 +314,25 @@ describe('ProjectSettingsProvider worktreeDirectory validation', () => {});it('retries legacy config migration after a failed attempt', async () => {- const projectPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-settings-local-'));- tempDirs.push(projectPath);+ const rootPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-settings-local-'));+ tempDirs.push(rootPath);const row = {- baseProjectSettingsJson: '{}',- shareableProjectSettingsJson: '{}',+ baseSettingsJson: '{}',+ shareableSettingsJson: '{}',legacyConfigMigratedAt: null,};let updateAttempts = 0;- const settingsStorage: ProjectSettingsStorage = {+ const settingsStorage: LocationSettingsStorage = {get: async () => row,insertIfMissing: vi.fn(),- update: async (_projectId, settings) => {+ update: async (_locationId, settings) => {updateAttempts += 1;if (updateAttempts === 1) throw new Error('db write failed');Object.assign(row, settings);},};storageMockState.storage = settingsStorage;- const provider = new LocalProjectSettingsProvider(projectId(), projectPath);+ const provider = new LocalLocationSettingsProvider(locationId(), rootPath);await expect(provider.ensure()).rejects.toThrow('db write failed');await expect(provider.ensure()).resolves.toBeUndefined();@@ -342,13 +342,13 @@ describe('ProjectSettingsProvider worktreeDirectory validation', () => {});it('clears shareable fields without validating base settings', async () => {- const projectPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-settings-local-'));- tempDirs.push(projectPath);+ const rootPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-settings-local-'));+ tempDirs.push(rootPath);const row = {- baseProjectSettingsJson: JSON.stringify({- worktreeDirectory: path.join(projectPath, 'not-yet-created'),+ baseSettingsJson: JSON.stringify({+ worktreeDirectory: path.join(rootPath, 'not-yet-created'),}),- shareableProjectSettingsJson: JSON.stringify({+ shareableSettingsJson: JSON.stringify({preservePatterns: ['.env'],scripts: {setup: 'pnpm install',@@ -357,22 +357,22 @@ describe('ProjectSettingsProvider worktreeDirectory validation', () => {}),legacyConfigMigratedAt: new Date().toISOString(),};- const settingsStorage: ProjectSettingsStorage = {+ const settingsStorage: LocationSettingsStorage = {get: async () => row,insertIfMissing: vi.fn(),- update: async (_projectId, settings) => {+ update: async (_locationId, settings) => {Object.assign(row, settings);},};storageMockState.storage = settingsStorage;- const provider = new LocalProjectSettingsProvider(projectId(), projectPath);+ const provider = new LocalLocationSettingsProvider(locationId(), rootPath);const result = await provider.patch({clearShareableFields: ['preservePatterns', 'scripts.run'],});expect(result.success).toBe(true);- expect(JSON.parse(row.shareableProjectSettingsJson)).toEqual({+ expect(JSON.parse(row.shareableSettingsJson)).toEqual({scripts: {setup: 'pnpm install',},@@ -380,11 +380,11 @@ describe('ProjectSettingsProvider worktreeDirectory validation', () => {});it('normalizes and canonicalizes local absolute worktreeDirectory on update', async () => {- const projectPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-settings-local-'));- tempDirs.push(projectPath);+ const rootPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-settings-local-'));+ tempDirs.push(rootPath);- const provider = new LocalProjectSettingsProvider(projectId(), projectPath);- const expectedPath = path.resolve(projectPath, 'worktrees');+ const provider = new LocalLocationSettingsProvider(locationId(), rootPath);+ const expectedPath = path.resolve(rootPath, 'worktrees');const result = await provider.update({ preservePatterns: [], worktreeDirectory: expectedPath });expect(result.success).toBe(true);@@ -396,10 +396,10 @@ describe('ProjectSettingsProvider worktreeDirectory validation', () => {});it('rejects local relative worktreeDirectory values', async () => {- const projectPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-settings-local-'));- tempDirs.push(projectPath);+ const rootPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-settings-local-'));+ tempDirs.push(rootPath);- const provider = new LocalProjectSettingsProvider(projectId(), projectPath);+ const provider = new LocalLocationSettingsProvider(locationId(), rootPath);const result = await provider.update({ preservePatterns: [], worktreeDirectory: 'worktrees' });expect(result).toEqual({@@ -408,11 +408,11 @@ describe('ProjectSettingsProvider worktreeDirectory validation', () => {});});- it('rejects foreign absolute worktreeDirectory values for local projects', async () => {- const projectPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-settings-local-'));- tempDirs.push(projectPath);+ it('rejects foreign absolute worktreeDirectory values for local locations', async () => {+ const rootPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-settings-local-'));+ tempDirs.push(rootPath);- const provider = new LocalProjectSettingsProvider(projectId(), projectPath);+ const provider = new LocalLocationSettingsProvider(locationId(), rootPath);const foreignPath = process.platform === 'win32' ? '/tmp/worktrees' : 'C:\\worktrees';const result = await provider.update({ preservePatterns: [], worktreeDirectory: foreignPath });@@ -423,14 +423,14 @@ describe('ProjectSettingsProvider worktreeDirectory validation', () => {});it('surfaces local worktreeDirectory validation errors', async () => {- const projectPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-settings-local-'));- tempDirs.push(projectPath);- fs.writeFileSync(path.join(projectPath, 'not-a-directory'), 'file');+ const rootPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-settings-local-'));+ tempDirs.push(rootPath);+ fs.writeFileSync(path.join(rootPath, 'not-a-directory'), 'file');- const provider = new LocalProjectSettingsProvider(projectId(), projectPath);+ const provider = new LocalLocationSettingsProvider(locationId(), rootPath);const result = await provider.update({preservePatterns: [],- worktreeDirectory: path.join(projectPath, 'not-a-directory', 'worktrees'),+ worktreeDirectory: path.join(rootPath, 'not-a-directory', 'worktrees'),});expect(result).toEqual({success: false,@@ -439,10 +439,10 @@ describe('ProjectSettingsProvider worktreeDirectory validation', () => {});it('clears blank local worktreeDirectory values', async () => {- const projectPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-settings-local-'));- tempDirs.push(projectPath);+ const rootPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-settings-local-'));+ tempDirs.push(rootPath);- const provider = new LocalProjectSettingsProvider(projectId(), projectPath);+ const provider = new LocalLocationSettingsProvider(locationId(), rootPath);const result = await provider.update({ preservePatterns: [], worktreeDirectory: ' ' });expect(result.success).toBe(true);diff --git a/dash/apps/switchdash-desktop/src/main/core/locations/settings/provider.ts b/dash/apps/switchdash-desktop/src/main/core/locations/settings/provider.tsnew file mode 100644index 000000000..4b2f68359--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/locations/settings/provider.ts@@ -0,0 +1,16 @@+import type { Result } from '@switchdash/shared';+import type {+ LocationSettings,+ LocationSettingsPatch,+} from '@shared/core/location-settings/location-settings';+import type { UpdateLocationSettingsError } from '@shared/core/locations/locations';+export type { LocationSettingsPatch };++export interface LocationSettingsProvider {+ getDefaultWorktreeDirectory(): Promise<string>;+ getWorktreeDirectory(): Promise<string>;+ get(): Promise<LocationSettings>;+ update(settings: LocationSettings): Promise<Result<void, UpdateLocationSettingsError>>;+ patch(patch: LocationSettingsPatch): Promise<Result<void, UpdateLocationSettingsError>>;+ ensure(): Promise<void>;+}diff --git a/dash/apps/switchdash-desktop/src/main/core/locations/settings/providers/db-location-settings-provider.ts b/dash/apps/switchdash-desktop/src/main/core/locations/settings/providers/db-location-settings-provider.tsnew file mode 100644index 000000000..a34ddd87f--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/locations/settings/providers/db-location-settings-provider.ts@@ -0,0 +1,252 @@+import { err, ok, type Result } from '@switchdash/shared';+import type { FileSystemProvider } from '@main/core/fs/types';+import { appSettingsService } from '@main/core/settings/settings-service';+import { log } from '@main/lib/logger';+import {+ baseLocationSettingsSchema,+ DEFAULT_PRESERVE_PATTERNS,+ legacyBaseLocationSettingsSchema,+ locationSettingsSchema,+ shareableLocationSettingsSchema,+ type BaseLocationSettings,+ type LocationSettings,+ type ShareableLocationSettings,+} from '@shared/core/location-settings/location-settings';+import { SHAREABLE_FIELD_ACCESSORS } from '@shared/core/location-settings/location-settings-fields';+import type { UpdateLocationSettingsError } from '@shared/core/locations/locations';+import {+ migrateLegacyLocationSettingsIfNeeded,+ type LocationSettingsGitInspector,+} from '../legacy-location-settings-migration';+import { serializeShareableLocationSettings } from '../legacy-shareable-migration-marker';+import { compactUndefined, parseJsonObject, readJson } from '../location-settings-json';+import { LocationSettingsRepository } from '../location-settings-storage';+import type { LocationSettingsPatch, LocationSettingsProvider } from '../provider';+import { CONFIG_FILE } from '../sharing/switchdash-config-file';++export type DbLocationSettingsProviderOptions = {+ git?: LocationSettingsGitInspector;+};++export abstract class DbLocationSettingsProvider implements LocationSettingsProvider {+ private legacyMigrationPromise: Promise<void> | undefined;+ private readonly storage = new LocationSettingsRepository();++ protected constructor(+ private readonly locationId: string,+ protected readonly rootPath: string,+ private readonly configReader: Pick<FileSystemProvider, 'exists' | 'read'> | undefined,+ private readonly options: DbLocationSettingsProviderOptions = {}+ ) {}++ protected abstract defaultWorktreeDirectory(): Promise<string>;++ protected abstract validateWorktreeDirectory(+ worktreeDirectory: string | undefined+ ): Promise<Result<string | undefined, UpdateLocationSettingsError>>;++ protected abstract normalizeStoredWorktreeDirectory(+ worktreeDirectory: string+ ): Promise<Result<string, UpdateLocationSettingsError>>;++ protected async initialBaseLocationSettings(): Promise<BaseLocationSettings> {+ const locationDefaults = await appSettingsService.get('location');+ return {+ tmux: locationDefaults.tmuxByDefault,+ };+ }++ private async hasSharedPreservePatterns(): Promise<boolean> {+ if (!this.configReader) return false;+ try {+ if (!(await this.configReader.exists(CONFIG_FILE))) return false;+ const { content } = await this.configReader.read(CONFIG_FILE);+ const parsed = shareableLocationSettingsSchema.safeParse(parseJsonObject(content));+ if (!parsed.success) {+ log.warn('Failed to inspect shared location settings during initialization', parsed.error);+ return false;+ }+ return parsed.data.preservePatterns !== undefined;+ } catch (error) {+ log.warn('Failed to inspect shared location settings during initialization', error);+ return false;+ }+ }++ private async ensureRow(): Promise<void> {+ if (await this.storage.get(this.locationId)) return;++ const baseSettings = await this.initialBaseLocationSettings();+ const shareableSettings = (await this.hasSharedPreservePatterns())+ ? {}+ : { preservePatterns: [...DEFAULT_PRESERVE_PATTERNS] };+ await this.storage.insertIfMissing(this.locationId, {+ baseSettingsJson: JSON.stringify(compactUndefined(baseSettings)),+ shareableSettingsJson: serializeShareableLocationSettings(shareableSettings),+ legacyConfigMigratedAt: null,+ });+ }++ private async readSettingsRow(): Promise<{+ base: BaseLocationSettings;+ shareable: ShareableLocationSettings;+ legacyConfigMigratedAt: string | null;+ }> {+ await this.ensureRow();+ await this.migrateLegacyConfigIfNeeded();+ const row = await this.storage.get(this.locationId);+ if (!row) {+ return {+ base: await this.initialBaseLocationSettings(),+ shareable: {},+ legacyConfigMigratedAt: null,+ };+ }+ const baseSettings = readJson(+ row.baseSettingsJson,+ legacyBaseLocationSettingsSchema,+ 'base location settings'+ );++ return {+ base: baseLocationSettingsSchema.parse(baseSettings),+ shareable: readJson(+ row.shareableSettingsJson,+ shareableLocationSettingsSchema,+ 'shareable location settings'+ ),+ legacyConfigMigratedAt: row.legacyConfigMigratedAt,+ };+ }++ private async migrateLegacyConfigIfNeeded(git = this.options.git): Promise<void> {+ if (this.legacyMigrationPromise) {+ await this.legacyMigrationPromise;+ return;+ }++ this.legacyMigrationPromise = (async () => {+ const row = await this.storage.get(this.locationId);+ await migrateLegacyLocationSettingsIfNeeded({+ locationId: this.locationId,+ row,+ configReader: this.configReader,+ storage: this.storage,+ git,+ normalizeStoredWorktreeDirectory: (worktreeDirectory) =>+ this.normalizeStoredWorktreeDirectory(worktreeDirectory),+ });+ })();++ try {+ await this.legacyMigrationPromise;+ } catch (error) {+ this.legacyMigrationPromise = undefined;+ throw error;+ }+ }++ async ensure(options: DbLocationSettingsProviderOptions = {}): Promise<void> {+ await this.ensureRow();+ await this.migrateLegacyConfigIfNeeded(options.git);+ }++ async get(): Promise<LocationSettings> {+ const { base, shareable } = await this.readSettingsRow();+ return locationSettingsSchema.parse({ ...base, ...shareable });+ }++ async update(settings: LocationSettings): Promise<Result<void, UpdateLocationSettingsError>> {+ const parsed = locationSettingsSchema.safeParse(settings);+ if (!parsed.success) {+ return err({ type: 'invalid-settings' });+ }++ const nextSettings = parsed.data;+ const worktreeDirectoryResult = await this.validateWorktreeDirectory(+ nextSettings.worktreeDirectory+ );+ if (!worktreeDirectoryResult.success) {+ return worktreeDirectoryResult;+ }+ nextSettings.worktreeDirectory = worktreeDirectoryResult.data;++ const base = baseLocationSettingsSchema.parse(nextSettings);+ const shareable = shareableLocationSettingsSchema.parse(nextSettings);++ try {+ await this.ensure();+ const row = await this.storage.get(this.locationId);+ await this.storage.update(this.locationId, {+ baseSettingsJson: JSON.stringify(compactUndefined(base)),+ shareableSettingsJson: serializeShareableLocationSettings(shareable, {+ previousRaw: row?.shareableSettingsJson,+ }),+ });+ return ok();+ } catch (error) {+ log.warn('Failed to update location settings', error);+ return err({ type: 'error' });+ }+ }++ async patch(patch: LocationSettingsPatch): Promise<Result<void, UpdateLocationSettingsError>> {+ try {+ await this.ensure();+ const row = await this.storage.get(this.locationId);+ const base = row+ ? readJson(row.baseSettingsJson, legacyBaseLocationSettingsSchema, 'base location settings')+ : await this.initialBaseLocationSettings();+ const shareable = row+ ? readJson(+ row.shareableSettingsJson,+ shareableLocationSettingsSchema,+ 'shareable location settings'+ )+ : {};++ for (const field of patch.clearShareableFields ?? []) {+ SHAREABLE_FIELD_ACCESSORS[field].clear(shareable);+ }++ const nextBase = baseLocationSettingsSchema.parse({+ ...base,+ ...(Object.hasOwn(patch, 'githubAccountId')+ ? { githubAccountId: patch.githubAccountId }+ : {}),+ });++ await this.storage.update(this.locationId, {+ baseSettingsJson: JSON.stringify(compactUndefined(nextBase)),+ shareableSettingsJson: serializeShareableLocationSettings(shareable, {+ previousRaw: row?.shareableSettingsJson,+ }),+ });+ return ok();+ } catch (error) {+ log.warn('Failed to clear shareable location settings', error);+ return err({ type: 'error' });+ }+ }++ async getDefaultWorktreeDirectory(): Promise<string> {+ return this.defaultWorktreeDirectory();+ }++ async getWorktreeDirectory(): Promise<string> {+ const settings = await this.get();+ const defaultWorktreeDirectory = await this.getDefaultWorktreeDirectory();+ if (settings.worktreeDirectory) {+ const normalized = await this.normalizeStoredWorktreeDirectory(settings.worktreeDirectory);+ if (normalized.success) {+ return normalized.data;+ }+ log.warn('LocationSettingsProvider: invalid worktreeDirectory, falling back to default', {+ worktreeDirectory: settings.worktreeDirectory,+ defaultWorktreeDirectory,+ error: normalized.error.type,+ });+ }+ return defaultWorktreeDirectory;+ }+}diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/settings/providers/local-project-settings-provider.ts b/dash/apps/switchdash-desktop/src/main/core/locations/settings/providers/local-location-settings-provider.tssimilarity index 64%rename from dash/apps/switchdash-desktop/src/main/core/projects/settings/providers/local-project-settings-provider.tsrename to dash/apps/switchdash-desktop/src/main/core/locations/settings/providers/local-location-settings-provider.tsindex b7553981b..b60710b6a 100644--- a/dash/apps/switchdash-desktop/src/main/core/projects/settings/providers/local-project-settings-provider.ts+++ b/dash/apps/switchdash-desktop/src/main/core/locations/settings/providers/local-location-settings-provider.ts@@ -3,35 +3,35 @@ import os from 'node:os';import path from 'node:path';import type { Result } from '@switchdash/shared';import { appSettingsService } from '@main/core/settings/settings-service';-import type { UpdateProjectSettingsError } from '@shared/projects';+import type { UpdateLocationSettingsError } from '@shared/core/locations/locations';import {normalizeWorktreeDirectory,resolveAndValidateWorktreeDirectory,} from '../worktree-directory';import {- DbProjectSettingsProvider,- type DbProjectSettingsProviderOptions,-} from './db-project-settings-provider';+ DbLocationSettingsProvider,+ type DbLocationSettingsProviderOptions,+} from './db-location-settings-provider';async function getLocalDefaultWorktreeDirectory(): Promise<string> {- return (await appSettingsService.get('localProject')).defaultWorktreeDirectory;+ return (await appSettingsService.get('localLocation')).defaultWorktreeDirectory;}const localPathPlatform = process.platform === 'win32' ? 'win32' : 'posix';-export class LocalProjectSettingsProvider extends DbProjectSettingsProvider {+export class LocalLocationSettingsProvider extends DbLocationSettingsProvider {constructor(- projectId: string,- projectPath: string,- options: DbProjectSettingsProviderOptions = {}+ locationId: string,+ rootPath: string,+ options: DbLocationSettingsProviderOptions = {}) {super(- projectId,- projectPath,+ locationId,+ rootPath,{- exists: async (filePath) => fs.existsSync(path.join(projectPath, filePath)),+ exists: async (filePath) => fs.existsSync(path.join(rootPath, filePath)),read: async (filePath) => {- const content = await fs.promises.readFile(path.join(projectPath, filePath), 'utf8');+ const content = await fs.promises.readFile(path.join(rootPath, filePath), 'utf8');return { content, truncated: false, totalSize: Buffer.byteLength(content) };},},@@ -45,7 +45,7 @@ export class LocalProjectSettingsProvider extends DbProjectSettingsProvider {protected validateWorktreeDirectory(worktreeDirectory: string | undefined- ): Promise<Result<string | undefined, UpdateProjectSettingsError>> {+ ): Promise<Result<string | undefined, UpdateLocationSettingsError>> {return resolveAndValidateWorktreeDirectory(worktreeDirectory, {pathApi: path,pathPlatform: localPathPlatform,@@ -61,7 +61,7 @@ export class LocalProjectSettingsProvider extends DbProjectSettingsProvider {protected normalizeStoredWorktreeDirectory(worktreeDirectory: string- ): Promise<Result<string, UpdateProjectSettingsError>> {+ ): Promise<Result<string, UpdateLocationSettingsError>> {return normalizeWorktreeDirectory(worktreeDirectory, {pathApi: path,pathPlatform: localPathPlatform,diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/settings/providers/remote-project-settings-provider.ts b/dash/apps/switchdash-desktop/src/main/core/locations/settings/providers/remote-location-settings-provider.tssimilarity index 57%rename from dash/apps/switchdash-desktop/src/main/core/projects/settings/providers/remote-project-settings-provider.tsrename to dash/apps/switchdash-desktop/src/main/core/locations/settings/providers/remote-location-settings-provider.tsindex 1ff0f5a4f..0612efab5 100644--- a/dash/apps/switchdash-desktop/src/main/core/projects/settings/providers/remote-project-settings-provider.ts+++ b/dash/apps/switchdash-desktop/src/main/core/locations/settings/providers/remote-location-settings-provider.ts@@ -1,41 +1,41 @@import { posix as pathPosix } from 'node:path';import { ok, type Result } from '@switchdash/shared';import type { FileSystemProvider } from '@main/core/fs/types';-import type { UpdateProjectSettingsError } from '@shared/projects';+import type { UpdateLocationSettingsError } from '@shared/core/locations/locations';import {- DbProjectSettingsProvider,- type DbProjectSettingsProviderOptions,-} from './db-project-settings-provider';+ DbLocationSettingsProvider,+ type DbLocationSettingsProviderOptions,+} from './db-location-settings-provider';/**- * DB-backed project settings for a remote (SSH) agent. Its working directory+ * DB-backed location settings for a remote (SSH) agent. Its working directory* lives on the host, so there is no local path to read/validate; the config* reader is backed by the SSH filesystem. switchdash runs every session in the* remote working dir (no worktrees), so worktree-directory handling is a no-op.*/-export class RemoteProjectSettingsProvider extends DbProjectSettingsProvider {+export class RemoteLocationSettingsProvider extends DbLocationSettingsProvider {constructor(- projectId: string,+ locationId: string,remoteRepoDir: string,fs: Pick<FileSystemProvider, 'exists' | 'read'>,- options: DbProjectSettingsProviderOptions = {}+ options: DbLocationSettingsProviderOptions = {}) {- super(projectId, remoteRepoDir, fs, options);+ super(locationId, remoteRepoDir, fs, options);}protected defaultWorktreeDirectory(): Promise<string> {- return Promise.resolve(this.projectPath);+ return Promise.resolve(this.rootPath);}protected validateWorktreeDirectory(worktreeDirectory: string | undefined- ): Promise<Result<string | undefined, UpdateProjectSettingsError>> {+ ): Promise<Result<string | undefined, UpdateLocationSettingsError>> {return Promise.resolve(ok(worktreeDirectory));}protected normalizeStoredWorktreeDirectory(worktreeDirectory: string- ): Promise<Result<string, UpdateProjectSettingsError>> {+ ): Promise<Result<string, UpdateLocationSettingsError>> {return Promise.resolve(ok(pathPosix.normalize(worktreeDirectory)));}}diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/settings/sharing/codex-config-migration.ts b/dash/apps/switchdash-desktop/src/main/core/locations/settings/sharing/codex-config-migration.tssimilarity index 67%rename from dash/apps/switchdash-desktop/src/main/core/projects/settings/sharing/codex-config-migration.tsrename to dash/apps/switchdash-desktop/src/main/core/locations/settings/sharing/codex-config-migration.tsindex 2fe8cb86d..a25c0b5fa 100644--- a/dash/apps/switchdash-desktop/src/main/core/projects/settings/sharing/codex-config-migration.ts+++ b/dash/apps/switchdash-desktop/src/main/core/locations/settings/sharing/codex-config-migration.ts@@ -4,16 +4,16 @@ import z from 'zod';import type { FileSystemProvider } from '@main/core/fs/types';import { log } from '@main/lib/logger';import {- type MigrateProjectConfigRequest,- type ProjectConfigMigration,- type ShareableProjectSettings,- type ShareableProjectSettingsWriteField,-} from '@shared/core/project-settings/project-settings';-import { mergeShareableProjectSettings } from '@shared/core/project-settings/project-settings-fields';-import type { UpdateProjectSettingsError } from '@shared/projects';-import type { ProjectProvider } from '../../project-provider';-import type { ProjectConfigMigrator } from './config-migration';-import { CONFIG_FILE } from './workspace-config-file';+ type MigrateLocationConfigRequest,+ type LocationConfigMigration,+ type ShareableLocationSettings,+ type ShareableLocationSettingsWriteField,+} from '@shared/core/location-settings/location-settings';+import { mergeShareableLocationSettings } from '@shared/core/location-settings/location-settings-fields';+import type { UpdateLocationSettingsError } from '@shared/core/locations/locations';+import type { LocationProvider } from '../../location-provider';+import type { LocationConfigMigrator } from './config-migration';+import { CONFIG_FILE } from './switchdash-config-file';const CODEX_ENVIRONMENT_FILE = '.codex/environments/environment.toml';@@ -40,13 +40,13 @@ const codexEnvironmentSchema = z.passthrough();type CodexMigrationData = {- settings: ShareableProjectSettings;+ settings: ShareableLocationSettings;files: string[];- fields: ShareableProjectSettingsWriteField[];+ fields: ShareableLocationSettingsWriteField[];unsupportedFields: string[];};-function writeConfigFailed(message: string): Result<never, UpdateProjectSettingsError> {+function writeConfigFailed(message: string): Result<never, UpdateLocationSettingsError> {return err({ type: 'write-config-failed', message });}@@ -56,8 +56,8 @@ function trimmedText(value: string | undefined): string | undefined {}function setScript(- settings: ShareableProjectSettings,- field: ShareableProjectSettingsWriteField,+ settings: ShareableLocationSettings,+ field: ShareableLocationSettingsWriteField,value: string): void {settings.scripts ??= {};@@ -67,7 +67,7 @@ function setScript(function addScript(data: CodexMigrationData,- field: ShareableProjectSettingsWriteField,+ field: ShareableLocationSettingsWriteField,value: string | undefined): void {if (!value) return;@@ -93,7 +93,7 @@ function addUnsupportedActions(});}-function toCodexMigration(data: CodexMigrationData): ProjectConfigMigration | null {+function toCodexMigration(data: CodexMigrationData): LocationConfigMigration | null {if (data.fields.length === 0) return null;return {provider: 'codex',@@ -128,20 +128,20 @@ async function readCodexMigrationData(}async function migrateCodexConfig(- project: ProjectProvider,- request: MigrateProjectConfigRequest-): Promise<Result<ProjectConfigMigration, UpdateProjectSettingsError>> {+ location: LocationProvider,+ request: MigrateLocationConfigRequest+): Promise<Result<LocationConfigMigration, UpdateLocationSettingsError>> {try {- const data = await readCodexMigrationData(project.fs);+ const data = await readCodexMigrationData(location.fs);const migration = toCodexMigration(data);if (!migration) {return writeConfigFailed('No supported Codex settings were found.');}if (request.destination === 'local') {- const currentSettings = await project.settings.get();- const shareableSettings = mergeShareableProjectSettings(currentSettings, data.settings);- const updateResult = await project.settings.update({+ const currentSettings = await location.settings.get();+ const shareableSettings = mergeShareableLocationSettings(currentSettings, data.settings);+ const updateResult = await location.settings.update({...currentSettings,...shareableSettings,});@@ -149,29 +149,31 @@ async function migrateCodexConfig(return ok(migration);}- const writeResult = await project.fs.write(+ const writeResult = await location.fs.write(CONFIG_FILE,`${JSON.stringify(data.settings, null, 2)}\n`);if (!writeResult.success) {- log.warn('Failed to write migrated project config file', writeResult.error);+ log.warn('Failed to write migrated location config file', writeResult.error);return writeConfigFailed(writeResult.error ?? `Failed to write ${CONFIG_FILE}.`);}- const clearResult = await project.settings.patch({ clearShareableFields: data.fields });+ const clearResult = await location.settings.patch({ clearShareableFields: data.fields });if (!clearResult.success) {- log.warn('Failed to clear imported local project settings', clearResult.error);- return writeConfigFailed(`Wrote ${CONFIG_FILE}, but failed to clear local project settings.`);+ log.warn('Failed to clear imported local location settings', clearResult.error);+ return writeConfigFailed(+ `Wrote ${CONFIG_FILE}, but failed to clear local location settings.`+ );}return ok(migration);} catch (error) {- log.warn('Failed to migrate Codex config to project config', error);+ log.warn('Failed to migrate Codex config to location config', error);return writeConfigFailed(error instanceof Error ? error.message : String(error));}}-export const codexConfigMigrator: ProjectConfigMigrator = {+export const codexConfigMigrator: LocationConfigMigrator = {provider: 'codex',inspect: async (fs) => toCodexMigration(await readCodexMigrationData(fs)),migrate: migrateCodexConfig,diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/settings/sharing/conductor-config-migration.ts b/dash/apps/switchdash-desktop/src/main/core/locations/settings/sharing/conductor-config-migration.tssimilarity index 69%rename from dash/apps/switchdash-desktop/src/main/core/projects/settings/sharing/conductor-config-migration.tsrename to dash/apps/switchdash-desktop/src/main/core/locations/settings/sharing/conductor-config-migration.tsindex cee396f6d..920292a0c 100644--- a/dash/apps/switchdash-desktop/src/main/core/projects/settings/sharing/conductor-config-migration.ts+++ b/dash/apps/switchdash-desktop/src/main/core/locations/settings/sharing/conductor-config-migration.ts@@ -3,17 +3,17 @@ import z from 'zod';import type { FileSystemProvider } from '@main/core/fs/types';import { log } from '@main/lib/logger';import {- type MigrateProjectConfigRequest,- type ProjectConfigMigration,- type ShareableProjectSettings,- type ShareableProjectSettingsWriteField,-} from '@shared/core/project-settings/project-settings';-import { mergeShareableProjectSettings } from '@shared/core/project-settings/project-settings-fields';-import type { UpdateProjectSettingsError } from '@shared/projects';-import type { ProjectProvider } from '../../project-provider';-import { parseJsonObject } from '../project-settings-json';-import type { ProjectConfigMigrator } from './config-migration';-import { CONFIG_FILE } from './workspace-config-file';+ type MigrateLocationConfigRequest,+ type LocationConfigMigration,+ type ShareableLocationSettings,+ type ShareableLocationSettingsWriteField,+} from '@shared/core/location-settings/location-settings';+import { mergeShareableLocationSettings } from '@shared/core/location-settings/location-settings-fields';+import type { UpdateLocationSettingsError } from '@shared/core/locations/locations';+import type { LocationProvider } from '../../location-provider';+import { parseJsonObject } from '../location-settings-json';+import type { LocationConfigMigrator } from './config-migration';+import { CONFIG_FILE } from './switchdash-config-file';const CONDUCTOR_CONFIG_FILE = 'conductor.json';const CONDUCTOR_WORKTREE_INCLUDE_FILE = '.worktreeinclude';@@ -33,13 +33,13 @@ const conductorConfigSchema = z.passthrough();type ConductorMigrationData = {- settings: ShareableProjectSettings;+ settings: ShareableLocationSettings;files: string[];- fields: ShareableProjectSettingsWriteField[];+ fields: ShareableLocationSettingsWriteField[];unsupportedFields: string[];};-function writeConfigFailed(message: string): Result<never, UpdateProjectSettingsError> {+function writeConfigFailed(message: string): Result<never, UpdateLocationSettingsError> {return err({ type: 'write-config-failed', message });}@@ -55,7 +55,7 @@ function parseWorktreeInclude(content: string): string[] {.filter((line) => line && !line.startsWith('#'));}-function toConductorMigration(data: ConductorMigrationData): ProjectConfigMigration | null {+function toConductorMigration(data: ConductorMigrationData): LocationConfigMigration | null {if (data.fields.length === 0) return null;return {provider: 'conductor',@@ -122,20 +122,20 @@ async function readConductorMigrationData(}async function migrateConductorConfig(- project: ProjectProvider,- request: MigrateProjectConfigRequest-): Promise<Result<ProjectConfigMigration, UpdateProjectSettingsError>> {+ location: LocationProvider,+ request: MigrateLocationConfigRequest+): Promise<Result<LocationConfigMigration, UpdateLocationSettingsError>> {try {- const data = await readConductorMigrationData(project.fs);+ const data = await readConductorMigrationData(location.fs);const migration = toConductorMigration(data);if (!migration) {return writeConfigFailed('No supported Conductor settings were found.');}if (request.destination === 'local') {- const currentSettings = await project.settings.get();- const shareableSettings = mergeShareableProjectSettings(currentSettings, data.settings);- const updateResult = await project.settings.update({+ const currentSettings = await location.settings.get();+ const shareableSettings = mergeShareableLocationSettings(currentSettings, data.settings);+ const updateResult = await location.settings.update({...currentSettings,...shareableSettings,});@@ -143,29 +143,31 @@ async function migrateConductorConfig(return ok(migration);}- const writeResult = await project.fs.write(+ const writeResult = await location.fs.write(CONFIG_FILE,`${JSON.stringify(data.settings, null, 2)}\n`);if (!writeResult.success) {- log.warn('Failed to write migrated project config file', writeResult.error);+ log.warn('Failed to write migrated location config file', writeResult.error);return writeConfigFailed(writeResult.error ?? `Failed to write ${CONFIG_FILE}.`);}- const clearResult = await project.settings.patch({ clearShareableFields: data.fields });+ const clearResult = await location.settings.patch({ clearShareableFields: data.fields });if (!clearResult.success) {- log.warn('Failed to clear imported local project settings', clearResult.error);- return writeConfigFailed(`Wrote ${CONFIG_FILE}, but failed to clear local project settings.`);+ log.warn('Failed to clear imported local location settings', clearResult.error);+ return writeConfigFailed(+ `Wrote ${CONFIG_FILE}, but failed to clear local location settings.`+ );}return ok(migration);} catch (error) {- log.warn('Failed to migrate Conductor config to project config', error);+ log.warn('Failed to migrate Conductor config to location config', error);return writeConfigFailed(error instanceof Error ? error.message : String(error));}}-export const conductorConfigMigrator: ProjectConfigMigrator = {+export const conductorConfigMigrator: LocationConfigMigrator = {provider: 'conductor',inspect: async (fs) => toConductorMigration(await readConductorMigrationData(fs)),migrate: migrateConductorConfig,diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/settings/sharing/config-migration.test.ts b/dash/apps/switchdash-desktop/src/main/core/locations/settings/sharing/config-migration.test.tssimilarity index 88%rename from dash/apps/switchdash-desktop/src/main/core/projects/settings/sharing/config-migration.test.tsrename to dash/apps/switchdash-desktop/src/main/core/locations/settings/sharing/config-migration.test.tsindex 10661a31d..0e7d59949 100644--- a/dash/apps/switchdash-desktop/src/main/core/projects/settings/sharing/config-migration.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/locations/settings/sharing/config-migration.test.ts@@ -1,7 +1,7 @@import { describe, expect, it, vi } from 'vitest';import {- inspectProjectConfigMigrations,- migrateProjectConfigFromProvider,+ inspectLocationConfigMigrations,+ migrateLocationConfigFromProvider,} from './config-migration';vi.mock('@main/lib/logger', () => ({@@ -56,7 +56,7 @@ describe('config migration', () => {`,});- await expect(inspectProjectConfigMigrations(fs)).resolves.toEqual([+ await expect(inspectLocationConfigMigrations(fs)).resolves.toEqual([{provider: 'conductor',label: 'Conductor',@@ -80,7 +80,7 @@ describe('config migration', () => {});const patch = vi.fn().mockResolvedValue({ success: true });- const result = await migrateProjectConfigFromProvider(+ const result = await migrateLocationConfigFromProvider({fs,settings: {@@ -118,7 +118,7 @@ describe('config migration', () => {}),});- await expect(inspectProjectConfigMigrations(fs)).resolves.toEqual([+ await expect(inspectLocationConfigMigrations(fs)).resolves.toEqual([{provider: 'conductor',label: 'Conductor',@@ -129,7 +129,7 @@ describe('config migration', () => {]);const patch = vi.fn().mockResolvedValue({ success: true });- const result = await migrateProjectConfigFromProvider(+ const result = await migrateLocationConfigFromProvider({fs,settings: {@@ -150,7 +150,7 @@ describe('config migration', () => {});});- it('imports Conductor settings into local project settings', async () => {+ it('imports Conductor settings into local location settings', async () => {const fs = createFs({'conductor.json': JSON.stringify({scripts: {@@ -161,7 +161,7 @@ describe('config migration', () => {});const update = vi.fn().mockResolvedValue({ success: true });- const result = await migrateProjectConfigFromProvider(+ const result = await migrateLocationConfigFromProvider({fs,settings: {@@ -198,7 +198,7 @@ describe('config migration', () => {}),});- await expect(inspectProjectConfigMigrations(fs)).resolves.toEqual([+ await expect(inspectLocationConfigMigrations(fs)).resolves.toEqual([{provider: 'superset',label: 'Superset',@@ -219,7 +219,7 @@ describe('config migration', () => {});const patch = vi.fn().mockResolvedValue({ success: true });- const result = await migrateProjectConfigFromProvider(+ const result = await migrateLocationConfigFromProvider({fs,settings: {@@ -242,7 +242,7 @@ describe('config migration', () => {});});- it('imports Superset settings into local project settings', async () => {+ it('imports Superset settings into local location settings', async () => {const fs = createFs({'.superset/config.json': JSON.stringify({run: ['./.superset/run.sh'],@@ -250,7 +250,7 @@ describe('config migration', () => {});const update = vi.fn().mockResolvedValue({ success: true });- const result = await migrateProjectConfigFromProvider(+ const result = await migrateLocationConfigFromProvider({fs,settings: {@@ -288,9 +288,9 @@ describe('config migration', () => {}),});- await expect(inspectProjectConfigMigrations(fs)).resolves.toEqual([]);+ await expect(inspectLocationConfigMigrations(fs)).resolves.toEqual([]);await expect(- migrateProjectConfigFromProvider({ fs } as never, {+ migrateLocationConfigFromProvider({ fs } as never, {provider: 'superset',destination: 'shared',})@@ -318,7 +318,7 @@ describe('config migration', () => {}),});- await expect(inspectProjectConfigMigrations(fs)).resolves.toEqual([+ await expect(inspectLocationConfigMigrations(fs)).resolves.toEqual([{provider: 'paseo',label: 'Paseo',@@ -350,7 +350,7 @@ describe('config migration', () => {});const patch = vi.fn().mockResolvedValue({ success: true });- const result = await migrateProjectConfigFromProvider(+ const result = await migrateLocationConfigFromProvider({fs,settings: {@@ -372,7 +372,7 @@ describe('config migration', () => {});});- it('imports Paseo settings into local project settings', async () => {+ it('imports Paseo settings into local location settings', async () => {const fs = createFs({'paseo.json': JSON.stringify({worktree: {@@ -385,7 +385,7 @@ describe('config migration', () => {});const update = vi.fn().mockResolvedValue({ success: true });- const result = await migrateProjectConfigFromProvider(+ const result = await migrateLocationConfigFromProvider({fs,settings: {@@ -420,9 +420,9 @@ describe('config migration', () => {}),});- await expect(inspectProjectConfigMigrations(fs)).resolves.toEqual([]);+ await expect(inspectLocationConfigMigrations(fs)).resolves.toEqual([]);await expect(- migrateProjectConfigFromProvider({ fs } as never, {+ migrateLocationConfigFromProvider({ fs } as never, {provider: 'paseo',destination: 'shared',})@@ -457,7 +457,7 @@ describe('config migration', () => {`,});- await expect(inspectProjectConfigMigrations(fs)).resolves.toEqual([+ await expect(inspectLocationConfigMigrations(fs)).resolves.toEqual([{provider: 'codex',label: 'Codex',@@ -484,7 +484,7 @@ describe('config migration', () => {});const patch = vi.fn().mockResolvedValue({ success: true });- const result = await migrateProjectConfigFromProvider(+ const result = await migrateLocationConfigFromProvider({fs,settings: {@@ -506,7 +506,7 @@ describe('config migration', () => {});});- it('imports Codex local environment settings into local project settings', async () => {+ it('imports Codex local environment settings into local location settings', async () => {const fs = createFs({'.codex/environments/environment.toml': `[setup]@@ -515,7 +515,7 @@ describe('config migration', () => {});const update = vi.fn().mockResolvedValue({ success: true });- const result = await migrateProjectConfigFromProvider(+ const result = await migrateLocationConfigFromProvider({fs,settings: {@@ -550,9 +550,9 @@ describe('config migration', () => {`,});- await expect(inspectProjectConfigMigrations(fs)).resolves.toEqual([]);+ await expect(inspectLocationConfigMigrations(fs)).resolves.toEqual([]);await expect(- migrateProjectConfigFromProvider({ fs } as never, {+ migrateLocationConfigFromProvider({ fs } as never, {provider: 'codex',destination: 'shared',})@@ -574,7 +574,7 @@ describe('config migration', () => {});await expect(- migrateProjectConfigFromProvider({ fs } as never, {+ migrateLocationConfigFromProvider({ fs } as never, {provider: 'conductor',destination: 'shared',})@@ -597,7 +597,7 @@ describe('config migration', () => {'.switchdash.json': JSON.stringify({ scripts: { run: 'pnpm dev' } }),});- const result = await migrateProjectConfigFromProvider({ fs } as never, {+ const result = await migrateLocationConfigFromProvider({ fs } as never, {provider: 'conductor',destination: 'shared',});@@ -617,7 +617,7 @@ describe('config migration', () => {const fs = createFs({});await expect(- migrateProjectConfigFromProvider({ fs } as never, {+ migrateLocationConfigFromProvider({ fs } as never, {provider: 'unknown' as never,destination: 'shared',})diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/settings/sharing/config-migration.ts b/dash/apps/switchdash-desktop/src/main/core/locations/settings/sharing/config-migration.tssimilarity index 53%rename from dash/apps/switchdash-desktop/src/main/core/projects/settings/sharing/config-migration.tsrename to dash/apps/switchdash-desktop/src/main/core/locations/settings/sharing/config-migration.tsindex a9fe2f1de..7ce96b17b 100644--- a/dash/apps/switchdash-desktop/src/main/core/projects/settings/sharing/config-migration.ts+++ b/dash/apps/switchdash-desktop/src/main/core/locations/settings/sharing/config-migration.ts@@ -2,42 +2,42 @@ import { err, type Result } from '@switchdash/shared';import type { FileSystemProvider } from '@main/core/fs/types';import { log } from '@main/lib/logger';import type {- MigrateProjectConfigRequest,- ProjectConfigMigration,-} from '@shared/core/project-settings/project-settings';-import type { UpdateProjectSettingsError } from '@shared/projects';-import type { ProjectProvider } from '../../project-provider';+ MigrateLocationConfigRequest,+ LocationConfigMigration,+} from '@shared/core/location-settings/location-settings';+import type { UpdateLocationSettingsError } from '@shared/core/locations/locations';+import type { LocationProvider } from '../../location-provider';import { codexConfigMigrator } from './codex-config-migration';import { conductorConfigMigrator } from './conductor-config-migration';import { paseoConfigMigrator } from './paseo-config-migration';import { supersetConfigMigrator } from './superset-config-migration';-import { CONFIG_FILE } from './workspace-config-file';+import { CONFIG_FILE } from './switchdash-config-file';-export type ProjectConfigMigrator = {- provider: ProjectConfigMigration['provider'];+export type LocationConfigMigrator = {+ provider: LocationConfigMigration['provider'];inspect: (fs: Pick<FileSystemProvider, 'exists' | 'read'>- ) => Promise<ProjectConfigMigration | null>;+ ) => Promise<LocationConfigMigration | null>;migrate: (- project: ProjectProvider,- request: MigrateProjectConfigRequest- ) => Promise<Result<ProjectConfigMigration, UpdateProjectSettingsError>>;+ location: LocationProvider,+ request: MigrateLocationConfigRequest+ ) => Promise<Result<LocationConfigMigration, UpdateLocationSettingsError>>;};-const PROJECT_CONFIG_MIGRATORS = [+const LOCATION_CONFIG_MIGRATORS = [conductorConfigMigrator,supersetConfigMigrator,paseoConfigMigrator,codexConfigMigrator,] as const;-function writeConfigFailed(message: string): Result<never, UpdateProjectSettingsError> {+function writeConfigFailed(message: string): Result<never, UpdateLocationSettingsError> {return err({ type: 'write-config-failed', message });}-export async function inspectProjectConfigMigrations(+export async function inspectLocationConfigMigrations(fs: Pick<FileSystemProvider, 'exists' | 'read'>-): Promise<ProjectConfigMigration[]> {+): Promise<LocationConfigMigration[]> {try {if (await fs.exists(CONFIG_FILE)) return [];} catch (error) {@@ -46,7 +46,7 @@ export async function inspectProjectConfigMigrations(}const migrations = await Promise.all(- PROJECT_CONFIG_MIGRATORS.map(async (migrator) => {+ LOCATION_CONFIG_MIGRATORS.map(async (migrator) => {try {return await migrator.inspect(fs);} catch (error) {@@ -56,26 +56,26 @@ export async function inspectProjectConfigMigrations(}));- return migrations.filter((migration): migration is ProjectConfigMigration => migration !== null);+ return migrations.filter((migration): migration is LocationConfigMigration => migration !== null);}-export async function migrateProjectConfigFromProvider(- project: ProjectProvider,- request: MigrateProjectConfigRequest-): Promise<Result<ProjectConfigMigration, UpdateProjectSettingsError>> {+export async function migrateLocationConfigFromProvider(+ location: LocationProvider,+ request: MigrateLocationConfigRequest+): Promise<Result<LocationConfigMigration, UpdateLocationSettingsError>> {try {- if (await project.fs.exists(CONFIG_FILE)) {+ if (await location.fs.exists(CONFIG_FILE)) {return writeConfigFailed(`${CONFIG_FILE} already exists.`);}- const migrator = PROJECT_CONFIG_MIGRATORS.find(+ const migrator = LOCATION_CONFIG_MIGRATORS.find((candidate) => candidate.provider === request.provider);if (!migrator) return writeConfigFailed('Unsupported config provider.');- return await migrator.migrate(project, request);+ return await migrator.migrate(location, request);} catch (error) {- log.warn(`Failed to migrate ${request.provider} config to project config`, error);+ log.warn(`Failed to migrate ${request.provider} config to location config`, error);return writeConfigFailed(error instanceof Error ? error.message : String(error));}}diff --git a/dash/apps/switchdash-desktop/src/main/core/locations/settings/sharing/location-settings-override-state.ts b/dash/apps/switchdash-desktop/src/main/core/locations/settings/sharing/location-settings-override-state.tsnew file mode 100644index 000000000..4b67c6a47--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/locations/settings/sharing/location-settings-override-state.ts@@ -0,0 +1,41 @@+import { log } from '@main/lib/logger';+import {+ emptyLocationSettingsOverrideState,+ SHAREABLE_LOCATION_SETTINGS_WRITE_FIELDS,+ shareableLocationSettingsSchema,+ type LocationSettingsOverrideState,+} from '@shared/core/location-settings/location-settings';+import { SHAREABLE_FIELD_ACCESSORS } from '@shared/core/location-settings/location-settings-fields';+import type { LocationSettingsResolvedTarget } from './location-settings-target-resolver';+import { CONFIG_FILE } from './switchdash-config-file';++export async function computeLocationSettingsOverrideState(+ targets: LocationSettingsResolvedTarget[]+): Promise<LocationSettingsOverrideState> {+ const state = emptyLocationSettingsOverrideState();++ for (const resolved of targets) {+ try {+ if (!(await resolved.fs.exists(CONFIG_FILE))) continue;++ const { content } = await resolved.fs.read(CONFIG_FILE);+ const parsed = shareableLocationSettingsSchema.safeParse(JSON.parse(content));+ if (!parsed.success) continue;++ for (const field of SHAREABLE_LOCATION_SETTINGS_WRITE_FIELDS) {+ const value = SHAREABLE_FIELD_ACCESSORS[field].displayValue(parsed.data);+ if (!value) continue;++ state[field].push({+ label: resolved.label,+ path: resolved.path,+ value,+ });+ }+ } catch (error) {+ log.warn('Failed to inspect location settings override source', error);+ }+ }++ return state;+}diff --git a/dash/apps/switchdash-desktop/src/main/core/locations/settings/sharing/location-settings-target-resolver.ts b/dash/apps/switchdash-desktop/src/main/core/locations/settings/sharing/location-settings-target-resolver.tsnew file mode 100644index 000000000..d095560c2--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/locations/settings/sharing/location-settings-target-resolver.ts@@ -0,0 +1,86 @@+import { eq } from 'drizzle-orm';+import type { FileSystemProvider } from '@main/core/fs/types';+import { db } from '@main/db/client';+import { locations as locationsTable } from '@main/db/schema';+import type {+ LocationSettingsWriteTarget,+ LocationSettingsWriteTargetOption,+ WriteLocationConfigRequest,+} from '@shared/core/location-settings/location-settings';+import type { LocationProvider } from '../../location-provider';+import { resolveLocationRuntime } from '../../utils';++export type LocationSettingsResolvedTarget = LocationSettingsWriteTargetOption & {+ fs: FileSystemProvider;+};++function stripTarget(target: LocationSettingsWriteTargetOption): LocationSettingsWriteTarget {+ if (target.type === 'location') return { type: 'location' };+ if (target.type === 'session') return { type: 'session', sessionId: target.sessionId };+ return { type: 'location-runtime', locationId: target.locationId };+}++export function stripResolvedTarget(+ target: LocationSettingsResolvedTarget+): LocationSettingsWriteTargetOption {+ const { fs: _fs, ...option } = target;+ return option;+}++function targetKey(target: LocationSettingsWriteTarget): string {+ if (target.type === 'location') return 'location';+ if (target.type === 'session') return `session:${target.sessionId}`;+ return `location-runtime:${target.locationId}`;+}++export async function resolveAllLocationSettingsTargets(+ location: LocationProvider+): Promise<LocationSettingsResolvedTarget[]> {+ const [locationRow] = await db+ .select({ name: locationsTable.name })+ .from(locationsTable)+ .where(eq(locationsTable.id, location.locationId))+ .limit(1);++ const locationTarget: LocationSettingsResolvedTarget = {+ type: 'location',+ label: locationRow?.name ?? 'Location repository',+ path: location.dir,+ fs: location.fs,+ };+ // Every switchdash session runs in the location root, so there are no+ // session-scoped settings targets distinct from the location target.+ return [locationTarget];+}++export function getLocationSettingsWriteTargets(+ targets: LocationSettingsResolvedTarget[]+): LocationSettingsWriteTargetOption[] {+ return targets.map(stripResolvedTarget);+}++export async function resolveLocationSettingsTarget(+ location: LocationProvider,+ request: Pick<WriteLocationConfigRequest, 'target'>,+ resolvedTargets: LocationSettingsResolvedTarget[]+): Promise<LocationSettingsResolvedTarget | null> {+ const target = resolvedTargets.find(+ (candidate) => targetKey(stripTarget(candidate)) === targetKey(request.target)+ );+ if (target) return target;++ if (request.target.type === 'location-runtime') {+ const runtime = resolveLocationRuntime(request.target.locationId);+ return runtime+ ? {+ type: 'location-runtime',+ locationId: request.target.locationId,+ label: 'Location runtime',+ path: runtime.path,+ fs: runtime.fs,+ }+ : null;+ }++ return null;+}diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/settings/sharing/paseo-config-migration.ts b/dash/apps/switchdash-desktop/src/main/core/locations/settings/sharing/paseo-config-migration.tssimilarity index 68%rename from dash/apps/switchdash-desktop/src/main/core/projects/settings/sharing/paseo-config-migration.tsrename to dash/apps/switchdash-desktop/src/main/core/locations/settings/sharing/paseo-config-migration.tsindex 1b1d94a7f..750b70274 100644--- a/dash/apps/switchdash-desktop/src/main/core/projects/settings/sharing/paseo-config-migration.ts+++ b/dash/apps/switchdash-desktop/src/main/core/locations/settings/sharing/paseo-config-migration.ts@@ -3,17 +3,17 @@ import z from 'zod';import type { FileSystemProvider } from '@main/core/fs/types';import { log } from '@main/lib/logger';import {- type MigrateProjectConfigRequest,- type ProjectConfigMigration,- type ShareableProjectSettings,- type ShareableProjectSettingsWriteField,-} from '@shared/core/project-settings/project-settings';-import { mergeShareableProjectSettings } from '@shared/core/project-settings/project-settings-fields';-import type { UpdateProjectSettingsError } from '@shared/projects';-import type { ProjectProvider } from '../../project-provider';-import { parseJsonObject } from '../project-settings-json';-import type { ProjectConfigMigrator } from './config-migration';-import { CONFIG_FILE } from './workspace-config-file';+ type MigrateLocationConfigRequest,+ type LocationConfigMigration,+ type ShareableLocationSettings,+ type ShareableLocationSettingsWriteField,+} from '@shared/core/location-settings/location-settings';+import { mergeShareableLocationSettings } from '@shared/core/location-settings/location-settings-fields';+import type { UpdateLocationSettingsError } from '@shared/core/locations/locations';+import type { LocationProvider } from '../../location-provider';+import { parseJsonObject } from '../location-settings-json';+import type { LocationConfigMigrator } from './config-migration';+import { CONFIG_FILE } from './switchdash-config-file';const PASEO_CONFIG_FILE = 'paseo.json';@@ -42,13 +42,13 @@ const paseoConfigSchema = z.passthrough();type PaseoMigrationData = {- settings: ShareableProjectSettings;+ settings: ShareableLocationSettings;files: string[];- fields: ShareableProjectSettingsWriteField[];+ fields: ShareableLocationSettingsWriteField[];unsupportedFields: string[];};-function writeConfigFailed(message: string): Result<never, UpdateProjectSettingsError> {+function writeConfigFailed(message: string): Result<never, UpdateLocationSettingsError> {return err({ type: 'write-config-failed', message });}@@ -61,8 +61,8 @@ function normalizeCommand(value: string | string[] | undefined): string | undefi}function setScript(- settings: ShareableProjectSettings,- field: ShareableProjectSettingsWriteField,+ settings: ShareableLocationSettings,+ field: ShareableLocationSettingsWriteField,value: string): void {settings.scripts ??= {};@@ -72,7 +72,7 @@ function setScript(function addScript(data: PaseoMigrationData,- field: ShareableProjectSettingsWriteField,+ field: ShareableLocationSettingsWriteField,value: string | undefined): void {if (!value) return;@@ -80,7 +80,7 @@ function addScript(data.fields.push(field);}-function toPaseoMigration(data: PaseoMigrationData): ProjectConfigMigration | null {+function toPaseoMigration(data: PaseoMigrationData): LocationConfigMigration | null {if (data.fields.length === 0) return null;return {provider: 'paseo',@@ -132,20 +132,20 @@ async function readPaseoMigrationData(}async function migratePaseoConfig(- project: ProjectProvider,- request: MigrateProjectConfigRequest-): Promise<Result<ProjectConfigMigration, UpdateProjectSettingsError>> {+ location: LocationProvider,+ request: MigrateLocationConfigRequest+): Promise<Result<LocationConfigMigration, UpdateLocationSettingsError>> {try {- const data = await readPaseoMigrationData(project.fs);+ const data = await readPaseoMigrationData(location.fs);const migration = toPaseoMigration(data);if (!migration) {return writeConfigFailed('No supported Paseo settings were found.');}if (request.destination === 'local') {- const currentSettings = await project.settings.get();- const shareableSettings = mergeShareableProjectSettings(currentSettings, data.settings);- const updateResult = await project.settings.update({+ const currentSettings = await location.settings.get();+ const shareableSettings = mergeShareableLocationSettings(currentSettings, data.settings);+ const updateResult = await location.settings.update({...currentSettings,...shareableSettings,});@@ -153,29 +153,31 @@ async function migratePaseoConfig(return ok(migration);}- const writeResult = await project.fs.write(+ const writeResult = await location.fs.write(CONFIG_FILE,`${JSON.stringify(data.settings, null, 2)}\n`);if (!writeResult.success) {- log.warn('Failed to write migrated project config file', writeResult.error);+ log.warn('Failed to write migrated location config file', writeResult.error);return writeConfigFailed(writeResult.error ?? `Failed to write ${CONFIG_FILE}.`);}- const clearResult = await project.settings.patch({ clearShareableFields: data.fields });+ const clearResult = await location.settings.patch({ clearShareableFields: data.fields });if (!clearResult.success) {- log.warn('Failed to clear imported local project settings', clearResult.error);- return writeConfigFailed(`Wrote ${CONFIG_FILE}, but failed to clear local project settings.`);+ log.warn('Failed to clear imported local location settings', clearResult.error);+ return writeConfigFailed(+ `Wrote ${CONFIG_FILE}, but failed to clear local location settings.`+ );}return ok(migration);} catch (error) {- log.warn('Failed to migrate Paseo config to project config', error);+ log.warn('Failed to migrate Paseo config to location config', error);return writeConfigFailed(error instanceof Error ? error.message : String(error));}}-export const paseoConfigMigrator: ProjectConfigMigrator = {+export const paseoConfigMigrator: LocationConfigMigrator = {provider: 'paseo',inspect: async (fs) => toPaseoMigration(await readPaseoMigrationData(fs)),migrate: migratePaseoConfig,diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/settings/sharing/share-project-settings-to-config.test.ts b/dash/apps/switchdash-desktop/src/main/core/locations/settings/sharing/share-location-settings-to-config.test.tssimilarity index 71%rename from dash/apps/switchdash-desktop/src/main/core/projects/settings/sharing/share-project-settings-to-config.test.tsrename to dash/apps/switchdash-desktop/src/main/core/locations/settings/sharing/share-location-settings-to-config.test.tsindex 24b18cc27..3ebdf13da 100644--- a/dash/apps/switchdash-desktop/src/main/core/projects/settings/sharing/share-project-settings-to-config.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/locations/settings/sharing/share-location-settings-to-config.test.ts@@ -1,22 +1,22 @@import { beforeEach, describe, expect, it, vi } from 'vitest';-import type { ShareableProjectSettings } from '@shared/core/project-settings/project-settings';-import { computeProjectSettingsOverrideState } from './project-settings-override-state';+import type { ShareableLocationSettings } from '@shared/core/location-settings/location-settings';+import { computeLocationSettingsOverrideState } from './location-settings-override-state';import {- getProjectSettingsWriteTargets,- resolveAllProjectSettingsTargets,-} from './project-settings-target-resolver';-import { shareProjectSettingsToConfig } from './share-project-settings-to-config';+ getLocationSettingsWriteTargets,+ resolveAllLocationSettingsTargets,+} from './location-settings-target-resolver';+import { shareLocationSettingsToConfig } from './share-location-settings-to-config';const mocks = vi.hoisted(() => ({select: vi.fn(),- workspaceGet: vi.fn(),- listForProject: vi.fn(),+ runtimeGet: vi.fn(),+ listForLocation: vi.fn(),}));-vi.mock('@main/core/workspaces/workspace-registry', () => ({- workspaceRegistry: {- get: mocks.workspaceGet,- listForProject: mocks.listForProject,+vi.mock('@main/core/locations/location-runtime-registry', () => ({+ locationRuntimeRegistry: {+ get: mocks.runtimeGet,+ listForLocation: mocks.listForLocation,},}));@@ -27,7 +27,7 @@ vi.mock('@main/db/client', () => ({}));vi.mock('../utils', () => ({- resolveWorkspace: vi.fn().mockReturnValue(null),+ resolveLocationRuntime: vi.fn().mockReturnValue(null),}));vi.mock('@main/lib/logger', () => ({@@ -36,17 +36,17 @@ vi.mock('@main/lib/logger', () => ({},}));-describe('shareProjectSettingsToConfig', () => {+describe('shareLocationSettingsToConfig', () => {beforeEach(() => {vi.clearAllMocks();- mocks.workspaceGet.mockReturnValue(undefined);- mocks.listForProject.mockReturnValue([]);+ mocks.runtimeGet.mockReturnValue(undefined);+ mocks.listForLocation.mockReturnValue([]);});- it('writes selected shareable project settings to .switchdash.json', async () => {+ it('writes selected shareable location settings to .switchdash.json', async () => {const write = vi.fn().mockResolvedValue({ success: true, bytesWritten: 100 });const patch = vi.fn().mockResolvedValue({ success: true });- const project = {+ const location = {fs: {exists: vi.fn().mockResolvedValue(false),write,@@ -67,13 +67,13 @@ describe('shareProjectSettingsToConfig', () => {},};- const result = await shareProjectSettingsToConfig(- project as never,+ const result = await shareLocationSettingsToConfig(+ location as never,{- target: { type: 'project' },+ target: { type: 'location' },fields: ['preservePatterns', 'shellSetup', 'scripts.setup', 'scripts.run'],},- [{ type: 'project', label: 'Repo Name', path: '/repo', fs: project.fs as never }]+ [{ type: 'location', label: 'Repo Name', path: '/repo', fs: location.fs as never }]);expect(result.success).toBe(true);@@ -99,7 +99,7 @@ describe('shareProjectSettingsToConfig', () => {it('preserves existing config fields when sharing a later script field to the same target', async () => {let configContent = '';- let shareableSettings: ShareableProjectSettings = {+ let shareableSettings: ShareableLocationSettings = {preservePatterns: ['.env', '.env.local'],};const fs = {@@ -110,7 +110,7 @@ describe('shareProjectSettingsToConfig', () => {return Promise.resolve({ success: true, bytesWritten: content.length });}),};- const project = {+ const location = {fs,settings: {get: vi.fn().mockImplementation(() => Promise.resolve(shareableSettings)),@@ -125,12 +125,12 @@ describe('shareProjectSettingsToConfig', () => {}),},};- const targets = [{ type: 'project' as const, label: 'Repo Name', path: '/repo', fs }];+ const targets = [{ type: 'location' as const, label: 'Repo Name', path: '/repo', fs }];- await shareProjectSettingsToConfig(- project as never,+ await shareLocationSettingsToConfig(+ location as never,{- target: { type: 'project' },+ target: { type: 'location' },fields: ['preservePatterns'],},targets as never@@ -142,10 +142,10 @@ describe('shareProjectSettingsToConfig', () => {},};- const result = await shareProjectSettingsToConfig(- project as never,+ const result = await shareLocationSettingsToConfig(+ location as never,{- target: { type: 'project' },+ target: { type: 'location' },fields: ['scripts.run'],},targets as never@@ -163,7 +163,7 @@ describe('shareProjectSettingsToConfig', () => {it('only clears fields that were actually written to .switchdash.json', async () => {const write = vi.fn().mockResolvedValue({ success: true, bytesWritten: 100 });const patch = vi.fn().mockResolvedValue({ success: true });- const project = {+ const location = {fs: {exists: vi.fn().mockResolvedValue(true),read: vi.fn().mockResolvedValue({@@ -179,13 +179,13 @@ describe('shareProjectSettingsToConfig', () => {},};- const result = await shareProjectSettingsToConfig(- project as never,+ const result = await shareLocationSettingsToConfig(+ location as never,{- target: { type: 'project' },+ target: { type: 'location' },fields: ['preservePatterns', 'scripts.run'],},- [{ type: 'project', label: 'Repo Name', path: '/repo', fs: project.fs as never }]+ [{ type: 'location', label: 'Repo Name', path: '/repo', fs: location.fs as never }]);expect(result.success).toBe(true);@@ -200,7 +200,7 @@ describe('shareProjectSettingsToConfig', () => {it('returns an error when the filesystem reports an unsuccessful write', async () => {const patch = vi.fn();- const project = {+ const location = {fs: {exists: vi.fn().mockResolvedValue(false),write: vi.fn().mockResolvedValue({@@ -217,13 +217,13 @@ describe('shareProjectSettingsToConfig', () => {},};- const result = await shareProjectSettingsToConfig(- project as never,+ const result = await shareLocationSettingsToConfig(+ location as never,{- target: { type: 'project' },+ target: { type: 'location' },fields: ['preservePatterns'],},- [{ type: 'project', label: 'Repo Name', path: '/repo', fs: project.fs as never }]+ [{ type: 'location', label: 'Repo Name', path: '/repo', fs: location.fs as never }]);expect(result).toEqual({@@ -239,7 +239,7 @@ describe('shareProjectSettingsToConfig', () => {success: false,error: { type: 'error' },});- const project = {+ const location = {fs: {exists: vi.fn().mockResolvedValue(true),read: vi.fn().mockResolvedValue({@@ -255,27 +255,27 @@ describe('shareProjectSettingsToConfig', () => {},};- const result = await shareProjectSettingsToConfig(- project as never,+ const result = await shareLocationSettingsToConfig(+ location as never,{- target: { type: 'project' },+ target: { type: 'location' },fields: ['preservePatterns'],},- [{ type: 'project', label: 'Repo Name', path: '/repo', fs: project.fs as never }]+ [{ type: 'location', label: 'Repo Name', path: '/repo', fs: location.fs as never }]);expect(result).toEqual({success: false,error: {type: 'write-config-failed',- message: 'Wrote .switchdash.json, but failed to clear shared project settings.',+ message: 'Wrote .switchdash.json, but failed to clear shared location settings.',},});expect(write).toHaveBeenCalledTimes(1);});it('returns the read/parse failure when existing .switchdash.json cannot be parsed', async () => {- const project = {+ const location = {fs: {exists: vi.fn().mockResolvedValue(true),read: vi.fn().mockResolvedValue({ content: '{ invalid json' }),@@ -287,13 +287,13 @@ describe('shareProjectSettingsToConfig', () => {},};- const result = await shareProjectSettingsToConfig(- project as never,+ const result = await shareLocationSettingsToConfig(+ location as never,{- target: { type: 'project' },+ target: { type: 'location' },fields: ['preservePatterns'],},- [{ type: 'project', label: 'Repo Name', path: '/repo', fs: project.fs as never }]+ [{ type: 'location', label: 'Repo Name', path: '/repo', fs: location.fs as never }]);if (result.success) {@@ -310,7 +310,7 @@ describe('shareProjectSettingsToConfig', () => {it('returns target resolution failures instead of rejecting the RPC', async () => {await expect(- shareProjectSettingsToConfig(+ shareLocationSettingsToConfig({settings: {get: vi.fn(),@@ -331,18 +331,17 @@ describe('shareProjectSettingsToConfig', () => {});});- it('resolves only the project target and reads its override state', async () => {- const projectRootFs = {+ it('resolves only the location target and reads its override state', async () => {+ const locationRootFs = {exists: vi.fn().mockResolvedValue(true),read: vi.fn().mockResolvedValue({content: JSON.stringify({ shellSetup: 'root setup' }),}),};- const project = {- projectId: 'project-1',- repoPath: '/repo',- fs: projectRootFs,- defaultWorkspaceType: { kind: 'local' },+ const location = {+ locationId: 'location-1',+ dir: '/repo',+ fs: locationRootFs,};mocks.select.mockReturnValueOnce({from: () => ({@@ -352,23 +351,22 @@ describe('shareProjectSettingsToConfig', () => {}),});- const resolvedTargets = await resolveAllProjectSettingsTargets(project as never);- const targets = getProjectSettingsWriteTargets(resolvedTargets);- const overrideState = await computeProjectSettingsOverrideState(resolvedTargets);+ const resolvedTargets = await resolveAllLocationSettingsTargets(location as never);+ const targets = getLocationSettingsWriteTargets(resolvedTargets);+ const overrideState = await computeLocationSettingsOverrideState(resolvedTargets);- expect(targets).toEqual([{ type: 'project', label: 'Repo Name', path: '/repo' }]);+ expect(targets).toEqual([{ type: 'location', label: 'Repo Name', path: '/repo' }]);expect(overrideState.shellSetup).toEqual([{ label: 'Repo Name', path: '/repo', value: 'root setup' },]);});- it('falls back to a default label when the project row no longer exists', async () => {+ it('falls back to a default label when the location row no longer exists', async () => {const findBranchAnywhere = vi.fn();- const project = {- projectId: 'project-1',- repoPath: '/repo',+ const location = {+ locationId: 'location-1',+ dir: '/repo',fs: {},- defaultWorkspaceType: { kind: 'local' },worktreeService: {findBranchAnywhere,},@@ -381,19 +379,19 @@ describe('shareProjectSettingsToConfig', () => {}),});- const targets = getProjectSettingsWriteTargets(- await resolveAllProjectSettingsTargets(project as never)+ const targets = getLocationSettingsWriteTargets(+ await resolveAllLocationSettingsTargets(location as never));- expect(targets).toEqual([{ type: 'project', label: 'Project repository', path: '/repo' }]);+ expect(targets).toEqual([{ type: 'location', label: 'Location repository', path: '/repo' }]);expect(mocks.select).toHaveBeenCalledTimes(1);expect(findBranchAnywhere).not.toHaveBeenCalled();});- it('detects workspace setting overrides from .switchdash.json files', async () => {- const project = {- projectId: 'project-1',- repoPath: '/repo',+ it('detects location setting overrides from .switchdash.json files', async () => {+ const location = {+ locationId: 'location-1',+ dir: '/repo',fs: {exists: vi.fn().mockResolvedValue(true),read: vi.fn().mockResolvedValue({@@ -408,7 +406,6 @@ describe('shareProjectSettingsToConfig', () => {}),}),},- defaultWorkspaceType: { kind: 'local' },worktreeService: {findBranchAnywhere: vi.fn(),},@@ -422,7 +419,9 @@ describe('shareProjectSettingsToConfig', () => {});await expect(- computeProjectSettingsOverrideState(await resolveAllProjectSettingsTargets(project as never))+ computeLocationSettingsOverrideState(+ await resolveAllLocationSettingsTargets(location as never)+ )).resolves.toEqual({preservePatterns: [{diff --git a/dash/apps/switchdash-desktop/src/main/core/locations/settings/sharing/share-location-settings-to-config.ts b/dash/apps/switchdash-desktop/src/main/core/locations/settings/sharing/share-location-settings-to-config.tsnew file mode 100644index 000000000..8f1a46b79--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/locations/settings/sharing/share-location-settings-to-config.ts@@ -0,0 +1,75 @@+import { err, ok, type Result } from '@switchdash/shared';+import { log } from '@main/lib/logger';+import type { WriteLocationConfigRequest } from '@shared/core/location-settings/location-settings';+import type { UpdateLocationSettingsError } from '@shared/core/locations/locations';+import type { LocationProvider } from '../../location-provider';+import {+ resolveLocationSettingsTarget,+ type LocationSettingsResolvedTarget,+} from './location-settings-target-resolver';+import {+ CONFIG_FILE,+ parseSwitchdashConfigObject,+ patchShareableLocationSettingsFields,+} from './switchdash-config-file';++function writeConfigFailed(message: string): Result<void, UpdateLocationSettingsError> {+ return err({ type: 'write-config-failed', message });+}++function errorMessage(error: unknown): string {+ return error instanceof Error ? error.message : String(error);+}++export async function shareLocationSettingsToConfig(+ location: LocationProvider,+ request: WriteLocationConfigRequest,+ resolvedTargets: LocationSettingsResolvedTarget[]+): Promise<Result<void, UpdateLocationSettingsError>> {+ try {+ const target = await resolveLocationSettingsTarget(location, request, resolvedTargets);+ if (!target) {+ return writeConfigFailed('Could not resolve the selected working copy.');+ }++ const localSettings = await location.settings.get();+ let config: Record<string, unknown>;+ try {+ if (await target.fs.exists(CONFIG_FILE)) {+ const { content } = await target.fs.read(CONFIG_FILE);+ config = parseSwitchdashConfigObject(content);+ } else {+ config = {};+ }+ } catch (error) {+ const message = `Could not read existing ${CONFIG_FILE}: ${errorMessage(error)}`;+ log.warn('Failed to read location config before writing', error);+ return writeConfigFailed(message);+ }++ const writtenFields = patchShareableLocationSettingsFields(+ config,+ localSettings,+ request.fields+ );++ const writeResult = await target.fs.write(CONFIG_FILE, `${JSON.stringify(config, null, 2)}\n`);+ if (!writeResult.success) {+ log.warn('Failed to write location config file', writeResult.error);+ return writeConfigFailed(writeResult.error ?? `Failed to write ${CONFIG_FILE}.`);+ }++ const clearResult = await location.settings.patch({ clearShareableFields: writtenFields });+ if (!clearResult.success) {+ log.warn('Failed to clear shareable location settings', clearResult.error);+ return writeConfigFailed(+ `Wrote ${CONFIG_FILE}, but failed to clear shared location settings.`+ );+ }++ return ok();+ } catch (error) {+ log.warn('Failed to write location config to repo', error);+ return writeConfigFailed(errorMessage(error));+ }+}diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/settings/sharing/superset-config-migration.ts b/dash/apps/switchdash-desktop/src/main/core/locations/settings/sharing/superset-config-migration.tssimilarity index 67%rename from dash/apps/switchdash-desktop/src/main/core/projects/settings/sharing/superset-config-migration.tsrename to dash/apps/switchdash-desktop/src/main/core/locations/settings/sharing/superset-config-migration.tsindex 8fea71206..9acf46298 100644--- a/dash/apps/switchdash-desktop/src/main/core/projects/settings/sharing/superset-config-migration.ts+++ b/dash/apps/switchdash-desktop/src/main/core/locations/settings/sharing/superset-config-migration.ts@@ -3,17 +3,17 @@ import z from 'zod';import type { FileSystemProvider } from '@main/core/fs/types';import { log } from '@main/lib/logger';import {- type MigrateProjectConfigRequest,- type ProjectConfigMigration,- type ShareableProjectSettings,- type ShareableProjectSettingsWriteField,-} from '@shared/core/project-settings/project-settings';-import { mergeShareableProjectSettings } from '@shared/core/project-settings/project-settings-fields';-import type { UpdateProjectSettingsError } from '@shared/projects';-import type { ProjectProvider } from '../../project-provider';-import { parseJsonObject } from '../project-settings-json';-import type { ProjectConfigMigrator } from './config-migration';-import { CONFIG_FILE } from './workspace-config-file';+ type MigrateLocationConfigRequest,+ type LocationConfigMigration,+ type ShareableLocationSettings,+ type ShareableLocationSettingsWriteField,+} from '@shared/core/location-settings/location-settings';+import { mergeShareableLocationSettings } from '@shared/core/location-settings/location-settings-fields';+import type { UpdateLocationSettingsError } from '@shared/core/locations/locations';+import type { LocationProvider } from '../../location-provider';+import { parseJsonObject } from '../location-settings-json';+import type { LocationConfigMigrator } from './config-migration';+import { CONFIG_FILE } from './switchdash-config-file';const SUPERSET_CONFIG_FILE = '.superset/config.json';@@ -37,9 +37,9 @@ const supersetConfigSchema = ztype SupersetScriptConfig = z.infer<typeof supersetScriptSchema>;type SupersetMigrationData = {- settings: ShareableProjectSettings;+ settings: ShareableLocationSettings;files: string[];- fields: ShareableProjectSettingsWriteField[];+ fields: ShareableLocationSettingsWriteField[];unsupportedFields: string[];};@@ -49,10 +49,10 @@ const SUPERSET_SCRIPT_FIELDS = [{ source: 'teardown', target: 'scripts.teardown' },] as const satisfies Array<{source: 'setup' | 'run' | 'teardown';- target: ShareableProjectSettingsWriteField;+ target: ShareableLocationSettingsWriteField;}>;-function writeConfigFailed(message: string): Result<never, UpdateProjectSettingsError> {+function writeConfigFailed(message: string): Result<never, UpdateLocationSettingsError> {return err({ type: 'write-config-failed', message });}@@ -72,8 +72,8 @@ function addUnsupportedOverrideFields(}function setScript(- settings: ShareableProjectSettings,- field: ShareableProjectSettingsWriteField,+ settings: ShareableLocationSettings,+ field: ShareableLocationSettingsWriteField,value: string): void {settings.scripts ??= {};@@ -82,7 +82,7 @@ function setScript(if (field === 'scripts.teardown') settings.scripts.teardown = value;}-function toSupersetMigration(data: SupersetMigrationData): ProjectConfigMigration | null {+function toSupersetMigration(data: SupersetMigrationData): LocationConfigMigration | null {if (data.fields.length === 0) return null;return {provider: 'superset',@@ -128,20 +128,20 @@ async function readSupersetMigrationData(}async function migrateSupersetConfig(- project: ProjectProvider,- request: MigrateProjectConfigRequest-): Promise<Result<ProjectConfigMigration, UpdateProjectSettingsError>> {+ location: LocationProvider,+ request: MigrateLocationConfigRequest+): Promise<Result<LocationConfigMigration, UpdateLocationSettingsError>> {try {- const data = await readSupersetMigrationData(project.fs);+ const data = await readSupersetMigrationData(location.fs);const migration = toSupersetMigration(data);if (!migration) {return writeConfigFailed('No supported Superset settings were found.');}if (request.destination === 'local') {- const currentSettings = await project.settings.get();- const shareableSettings = mergeShareableProjectSettings(currentSettings, data.settings);- const updateResult = await project.settings.update({+ const currentSettings = await location.settings.get();+ const shareableSettings = mergeShareableLocationSettings(currentSettings, data.settings);+ const updateResult = await location.settings.update({...currentSettings,...shareableSettings,});@@ -149,29 +149,31 @@ async function migrateSupersetConfig(return ok(migration);}- const writeResult = await project.fs.write(+ const writeResult = await location.fs.write(CONFIG_FILE,`${JSON.stringify(data.settings, null, 2)}\n`);if (!writeResult.success) {- log.warn('Failed to write migrated project config file', writeResult.error);+ log.warn('Failed to write migrated location config file', writeResult.error);return writeConfigFailed(writeResult.error ?? `Failed to write ${CONFIG_FILE}.`);}- const clearResult = await project.settings.patch({ clearShareableFields: data.fields });+ const clearResult = await location.settings.patch({ clearShareableFields: data.fields });if (!clearResult.success) {- log.warn('Failed to clear imported local project settings', clearResult.error);- return writeConfigFailed(`Wrote ${CONFIG_FILE}, but failed to clear local project settings.`);+ log.warn('Failed to clear imported local location settings', clearResult.error);+ return writeConfigFailed(+ `Wrote ${CONFIG_FILE}, but failed to clear local location settings.`+ );}return ok(migration);} catch (error) {- log.warn('Failed to migrate Superset config to project config', error);+ log.warn('Failed to migrate Superset config to location config', error);return writeConfigFailed(error instanceof Error ? error.message : String(error));}}-export const supersetConfigMigrator: ProjectConfigMigrator = {+export const supersetConfigMigrator: LocationConfigMigrator = {provider: 'superset',inspect: async (fs) => toSupersetMigration(await readSupersetMigrationData(fs)),migrate: migrateSupersetConfig,diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/settings/sharing/workspace-config-file.ts b/dash/apps/switchdash-desktop/src/main/core/locations/settings/sharing/switchdash-config-file.tssimilarity index 57%rename from dash/apps/switchdash-desktop/src/main/core/projects/settings/sharing/workspace-config-file.tsrename to dash/apps/switchdash-desktop/src/main/core/locations/settings/sharing/switchdash-config-file.tsindex ae079da99..7b4ae1d1a 100644--- a/dash/apps/switchdash-desktop/src/main/core/projects/settings/sharing/workspace-config-file.ts+++ b/dash/apps/switchdash-desktop/src/main/core/locations/settings/sharing/switchdash-config-file.ts@@ -1,13 +1,13 @@import {- type ProjectSettings,- type ShareableProjectSettingsWriteField,-} from '@shared/core/project-settings/project-settings';-import { SHAREABLE_FIELD_ACCESSORS } from '@shared/core/project-settings/project-settings-fields';-import { parseJsonObject } from '../project-settings-json';+ type LocationSettings,+ type ShareableLocationSettingsWriteField,+} from '@shared/core/location-settings/location-settings';+import { SHAREABLE_FIELD_ACCESSORS } from '@shared/core/location-settings/location-settings-fields';+import { parseJsonObject } from '../location-settings-json';export const CONFIG_FILE = '.switchdash.json';-export function parseWorkspaceConfigObject(raw: string): Record<string, unknown> {+export function parseSwitchdashConfigObject(raw: string): Record<string, unknown> {return parseJsonObject(raw) as Record<string, unknown>;}@@ -23,12 +23,12 @@ function setNested(obj: Record<string, unknown>, path: string[], value: unknown)cursor[path[path.length - 1]] = value;}-export function patchShareableProjectSettingsFields(+export function patchShareableLocationSettingsFields(config: Record<string, unknown>,- settings: ProjectSettings,- fields: ShareableProjectSettingsWriteField[]-): ShareableProjectSettingsWriteField[] {- const writtenFields: ShareableProjectSettingsWriteField[] = [];+ settings: LocationSettings,+ fields: ShareableLocationSettingsWriteField[]+): ShareableLocationSettingsWriteField[] {+ const writtenFields: ShareableLocationSettingsWriteField[] = [];for (const field of fields) {const accessor = SHAREABLE_FIELD_ACCESSORS[field];const value = accessor.get(settings);diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/settings/worktree-directory.test.ts b/dash/apps/switchdash-desktop/src/main/core/locations/settings/worktree-directory.test.tssimilarity index 100%rename from dash/apps/switchdash-desktop/src/main/core/projects/settings/worktree-directory.test.tsrename to dash/apps/switchdash-desktop/src/main/core/locations/settings/worktree-directory.test.tsdiff --git a/dash/apps/switchdash-desktop/src/main/core/projects/settings/worktree-directory.ts b/dash/apps/switchdash-desktop/src/main/core/locations/settings/worktree-directory.tssimilarity index 91%rename from dash/apps/switchdash-desktop/src/main/core/projects/settings/worktree-directory.tsrename to dash/apps/switchdash-desktop/src/main/core/locations/settings/worktree-directory.tsindex 4dc73eeec..513fe26ef 100644--- a/dash/apps/switchdash-desktop/src/main/core/projects/settings/worktree-directory.ts+++ b/dash/apps/switchdash-desktop/src/main/core/locations/settings/worktree-directory.ts@@ -1,7 +1,7 @@import type path from 'node:path';import { err, ok, type Result } from '@switchdash/shared';import type { FileSystemProvider } from '@main/core/fs/types';-import type { UpdateProjectSettingsError } from '@shared/projects';+import type { UpdateLocationSettingsError } from '@shared/core/locations/locations';export type PathPlatform = 'posix' | 'win32';@@ -32,7 +32,7 @@ export async function normalizeWorktreeDirectory(homeDirectory?: string;resolveHomeDirectory?: () => Promise<string>;}-): Promise<Result<string, UpdateProjectSettingsError>> {+): Promise<Result<string, UpdateLocationSettingsError>> {try {const trimmed = input.trim();let normalized = trimmed;@@ -61,7 +61,7 @@ export async function normalizeWorktreeDirectory(export async function canonicalizeWorktreeDirectory(directory: string,fs: Pick<FileSystemProvider, 'mkdir' | 'realPath'>-): Promise<Result<string, UpdateProjectSettingsError>> {+): Promise<Result<string, UpdateLocationSettingsError>> {try {await fs.mkdir(directory, { recursive: true });return ok(await fs.realPath(directory));@@ -79,7 +79,7 @@ export async function resolveAndValidateWorktreeDirectory(homeDirectory?: string;resolveHomeDirectory?: () => Promise<string>;}-): Promise<Result<string | undefined, UpdateProjectSettingsError>> {+): Promise<Result<string | undefined, UpdateLocationSettingsError>> {const trimmed = input?.trim();if (!trimmed) {return ok(undefined);diff --git a/dash/apps/switchdash-desktop/src/main/core/locations/store.ts b/dash/apps/switchdash-desktop/src/main/core/locations/store.tsnew file mode 100644index 000000000..640bc40c5--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/locations/store.ts@@ -0,0 +1,63 @@+import { randomUUID } from 'node:crypto';+import { and, desc, eq } from 'drizzle-orm';+import { db } from '@main/db/client';+import { locations, type LocationRow } from '@main/db/schema';+import type { Location } from '@shared/core/locations/locations';++function rowToLocation(row: LocationRow): Location {+ return {+ id: row.id,+ name: row.name,+ sshHost: row.sshHost === '' ? null : row.sshHost,+ dir: row.dir,+ createdAt: row.createdAt,+ updatedAt: row.updatedAt,+ };+}++export async function getLocations(): Promise<Location[]> {+ const rows = await db.select().from(locations).orderBy(desc(locations.updatedAt));+ return rows.map(rowToLocation);+}++export async function getLocationById(locationId: string): Promise<Location | undefined> {+ const [row] = await db.select().from(locations).where(eq(locations.id, locationId)).limit(1);+ if (!row) return undefined;+ return rowToLocation(row);+}++export async function getLocationByHostDir(+ sshHost: string | null,+ dir: string+): Promise<Location | undefined> {+ const [row] = await db+ .select()+ .from(locations)+ .where(and(eq(locations.sshHost, sshHost ?? ''), eq(locations.dir, dir)))+ .limit(1);+ if (!row) return undefined;+ return rowToLocation(row);+}++/**+ * Find the location for (sshHost, dir), creating it if none exists. The name+ * is only applied on create — an existing location keeps its name.+ */+export async function ensureLocation(params: {+ sshHost: string | null;+ dir: string;+ name: string;+}): Promise<Location> {+ const existing = await getLocationByHostDir(params.sshHost, params.dir);+ if (existing) return existing;+ const [row] = await db+ .insert(locations)+ .values({+ id: randomUUID(),+ name: params.name,+ sshHost: params.sshHost ?? '',+ dir: params.dir,+ })+ .returning();+ return rowToLocation(row!);+}diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/utils.ts b/dash/apps/switchdash-desktop/src/main/core/locations/utils.tssimilarity index 80%rename from dash/apps/switchdash-desktop/src/main/core/projects/utils.tsrename to dash/apps/switchdash-desktop/src/main/core/locations/utils.tsindex 39872752e..a349b13c0 100644--- a/dash/apps/switchdash-desktop/src/main/core/projects/utils.ts+++ b/dash/apps/switchdash-desktop/src/main/core/locations/utils.ts@@ -1,12 +1,12 @@-import { workspaceRegistry } from '@main/core/workspaces/workspace-registry';+import { locationRuntimeRegistry } from '@main/core/locations/location-runtime-registry';import { sessionRuntimeManager } from '../sessions/session-runtime-manager';-export function resolveSessionAgent(_projectId: string, sessionId: string) {+export function resolveSessionAgent(sessionId: string) {return sessionRuntimeManager.getAgent(sessionId) ?? null;}-export function resolveWorkspace(_projectId: string, workspaceId: string) {- return workspaceRegistry.get(workspaceId) ?? null;+export function resolveLocationRuntime(locationId: string) {+ return locationRuntimeRegistry.get(locationId) ?? null;}export class TimeoutSignal extends Error {diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/controller.ts b/dash/apps/switchdash-desktop/src/main/core/projects/controller.tsdeleted file mode 100644index 17a2e423c..000000000--- a/dash/apps/switchdash-desktop/src/main/core/projects/controller.ts+++ /dev/null@@ -1,26 +0,0 @@-import { createRPCController } from '@shared/lib/ipc/rpc';-import { createProject, inspectProjectPath } from './operations/createProject';-import { deleteProject } from './operations/deleteProject';-import { getProjects } from './operations/getProjects';-import { openProject } from './operations/openProject';-import { countProjectsUsingGithubAccount } from './settings/count-projects-using-github-account';-import { projectSettingsService } from './settings/project-settings-service';--export const projectController = createRPCController({- createProject,- inspectProjectPath,- getProjects,- deleteProject,- getProjectSettingsPage: (projectId: string) =>- projectSettingsService.getProjectSettingsPage(projectId),- updateProjectSettings: (projectId, settings) =>- projectSettingsService.updateProjectSettings(projectId, settings),- patchProjectSettings: (projectId, patch) =>- projectSettingsService.patchProjectSettings(projectId, patch),- shareProjectSettingsToConfig: (projectId, request) =>- projectSettingsService.shareProjectSettingsToConfig(projectId, request),- migrateProjectConfig: (projectId, request) =>- projectSettingsService.migrateProjectConfig(projectId, request),- countProjectsUsingGithubAccount,- openProject,-});diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/create-project-provider.ts b/dash/apps/switchdash-desktop/src/main/core/projects/create-project-provider.tsdeleted file mode 100644index 1b495ea07..000000000--- a/dash/apps/switchdash-desktop/src/main/core/projects/create-project-provider.ts+++ /dev/null@@ -1,110 +0,0 @@-import { getAgents } from '@main/core/agents/getAgents';-import { LocalExecutionContext } from '@main/core/execution-context/local-execution-context';-import { SshExecutionContext } from '@main/core/execution-context/ssh-execution-context';-import { LocalFileSystem } from '@main/core/fs/impl/local-fs';-import { SshFileSystem } from '@main/core/fs/impl/ssh-fs';-import type { FileSystemProvider } from '@main/core/fs/types';-import type { MachineRef } from '@main/core/runtime/types';-import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';-import { agentSshConnectionId } from '@main/core/workspaces/resolve-agent-workspace';-import type { AgentRemoteConfig } from '@shared/core/agents/agent-connection';-import type { LocalProject } from '@shared/projects';-import { ProjectProvider, type ProjectProviderTransport } from './project-provider';-import type { ProjectSettingsProvider } from './settings/provider';-import { LocalProjectSettingsProvider } from './settings/providers/local-project-settings-provider';-import { RemoteProjectSettingsProvider } from './settings/providers/remote-project-settings-provider';--export async function createProvider(project: LocalProject): Promise<ProjectProvider> {- // A project whose agent runs remotely (CHOO-1059) has its working directory,- // git, scripts, search and Switch config on the SSH host — not locally (it may- // have no local path at all). Build an SSH-backed provider so everything- // operates on the remote dir. Otherwise fall back to the local provider.- const agents = await getAgents(project.id);- const remoteAgent = agents.find((agent) => agent.connection === 'remote');- if (remoteAgent?.remoteConfig) {- return createSshProvider(project, remoteAgent.remoteConfig);- }- return createLocalProvider(project);-}--async function createLocalProvider(project: LocalProject): Promise<ProjectProvider> {- if (project.path === null) {- throw new Error(- `Project ${project.id} has no local path and no remote agent — cannot build a provider`- );- }- const localFs = new LocalFileSystem(project.path);- const ctx = new LocalExecutionContext({ root: project.path });- const projectMachine: MachineRef = { kind: 'local' };-- const settings = new LocalProjectSettingsProvider(project.id, project.path);- await settings.ensure();-- return buildProvider(- project.id,- project.path,- {- kind: 'local',- projectMachine,- defaultWorkspaceType: { kind: 'local' },- defaultWorkspaceMachine: projectMachine,- ctx,- },- localFs,- settings,- () => {}- );-}--async function createSshProvider(- project: LocalProject,- remoteConfig: AgentRemoteConfig-): Promise<ProjectProvider> {- const { sshHost, remoteRepoDir } = remoteConfig;- const connectionId = agentSshConnectionId(sshHost);- const proxy = await ensureSshConnected(connectionId, sshHost);- const ctx = new SshExecutionContext(proxy, { root: remoteRepoDir });- const remoteFs = new SshFileSystem(proxy, remoteRepoDir);- // Mirror the SSH wiring resolveAgentWorkspace uses for remote sessions: the- // workspace type is keyed by (host, remoteRepoDir, pooled connection id), and- // the machine ref carries the host + connection.- const projectMachine: MachineRef = { kind: 'ssh', host: sshHost, connectionId };-- const settings = new RemoteProjectSettingsProvider(project.id, remoteRepoDir, remoteFs);- await settings.ensure();-- return buildProvider(- project.id,- remoteRepoDir,- {- kind: 'ssh',- projectMachine,- defaultWorkspaceType: { kind: 'ssh', host: sshHost, remoteRepoDir, connectionId },- defaultWorkspaceMachine: projectMachine,- ctx,- },- remoteFs,- settings,- () => {}- );-}--function buildProvider(- projectId: string,- repoPath: string,- transportMeta: Pick<- ProjectProviderTransport,- 'kind' | 'projectMachine' | 'defaultWorkspaceType' | 'defaultWorkspaceMachine' | 'ctx'- >,- projectFs: FileSystemProvider,- settings: ProjectSettingsProvider,- dispose: () => void-): ProjectProvider {- const transport: ProjectProviderTransport = {- ...transportMeta,- fs: projectFs,- settings,- };-- return new ProjectProvider(projectId, repoPath, transport, dispose);-}diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/operations/create-local-project.ts b/dash/apps/switchdash-desktop/src/main/core/projects/operations/create-local-project.tsdeleted file mode 100644index 541a89a31..000000000--- a/dash/apps/switchdash-desktop/src/main/core/projects/operations/create-local-project.ts+++ /dev/null@@ -1,236 +0,0 @@-import { randomUUID } from 'node:crypto';-import path from 'node:path';-import { err, ok } from '@switchdash/shared';-import { sql } from 'drizzle-orm';-import { createAgent } from '@main/core/agents/createAgent';-import { detectSwitchAgent } from '@main/core/agents/detect';-import { detectSwitchAgentRemote } from '@main/core/agents/detect-remote';-import { reconcileAgentAutoSessionFromGateway } from '@main/core/agents/setAgentAutoSession';-import { setAgentConnection } from '@main/core/agents/setAgentConnection';-import { projectEvents } from '@main/core/projects/project-events';-import { projectManager } from '@main/core/projects/project-manager';-import { agentExistsOnServer, GatewayError } from '@main/core/switch-servers/gateway-client';-import { getServer } from '@main/core/switch-servers/servers-store';-import { db } from '@main/db/client';-import { projects } from '@main/db/schema';-import { log } from '@main/lib/logger';-import type { AgentRemoteConfig } from '@shared/core/agents/agent-connection';-import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';-import { basenameFromAnyPath } from '@shared/path-name';-import type { CreateProjectError, CreateProjectResult, ProjectPathStatus } from '@shared/projects';-import { checkIsValidDirectory } from '../path-utils';--export type CreateLocalProjectParams = {- id?: string;- /** The local working directory. Omit for a remote agent (see `remoteConfig`). */- path?: string;- name: string;- /** The registered Switch server the user chose for this agent. */- serverId: string;- /** The agent type (CLI provider) chosen at onboarding. */- providerId: AgentProviderId;- /** When set, the agent runs remotely on this SSH host + working dir, and there- * is no local directory. */- remoteConfig?: AgentRemoteConfig;-};--/**- * Gate agent creation on the chosen server actually owning the detected agent- * (and on being signed in). Every agent in the app is bound to a usable server- * it provably exists on. `dir` is used only for error reporting.- */-async function verifyAgentOnServer(- serverId: string,- agentId: string,- dir: string | null-): Promise<CreateProjectError | null> {- const server = await getServer(serverId);- if (!server) {- throw new Error(`No Switch server with id ${serverId}`);- }- try {- const exists = await agentExistsOnServer(server, agentId);- if (!exists) {- return {- type: 'switch-agent-not-on-server',- path: dir ?? '',- serverId: server.id,- serverName: server.name,- agentId,- };- }- return null;- } catch (cause) {- if (cause instanceof GatewayError && cause.kind === 'unauthorized') {- return {- type: 'switch-server-unauthenticated',- path: dir ?? '',- serverId: server.id,- serverName: server.name,- };- }- throw cause;- }-}--export async function createLocalProject(- params: CreateLocalProjectParams-): Promise<CreateProjectResult> {- return params.remoteConfig- ? createRemoteProject(params, params.remoteConfig)- : createLocalOnlyProject(params);-}--async function createLocalOnlyProject(- params: CreateLocalProjectParams-): Promise<CreateProjectResult> {- const localPath = params.path;- if (!localPath) {- return err({ type: 'invalid-directory', path: '', message: 'A directory is required' });- }-- const isValidDirectory = checkIsValidDirectory(localPath);- if (!isValidDirectory) {- return err({ type: 'invalid-directory', path: localPath, message: 'Invalid directory' });- }-- // Adding a directory == onboarding a Switch agent. Reject directories that are- // not configured as a Switch agent (no `.claude/settings.local.json` block).- const switchAgent = await detectSwitchAgent(localPath);- if (!switchAgent) {- return err({- type: 'invalid-directory',- path: localPath,- message:- 'This directory is not configured as a Switch agent. Configure the agent first (run the switch-connector configure skill) before adding it.',- });- }-- const serverError = await verifyAgentOnServer(params.serverId, switchAgent.agentId, localPath);- if (serverError) return err(serverError);-- const [row] = await db- .insert(projects)- .values({- id: params.id ?? randomUUID(),- name: params.name,- path: localPath,- updatedAt: sql`CURRENT_TIMESTAMP`,- })- .returning();-- const project = rowToLocalProject(row);-- const agent = await createAgent({- id: randomUUID(),- projectId: project.id,- name: path.basename(localPath) || params.providerId,- providerId: params.providerId,- switchAgentId: switchAgent.agentId,- apiEndpoint: switchAgent.apiEndpoint,- serverId: params.serverId,- });-- // Seed the local auto_session mirror + start the watcher from the gateway- // profile so an agent registered with auto_session on starts watching now,- // without the operator toggling it off→on (CHOO-1185). Best-effort: a gateway- // hiccup must not fail project creation — the settings panel reconciles later.- await reconcileAgentAutoSessionFromGateway(agent.id).catch((error) => {- log.warn('createLocalProject: failed to reconcile auto_session for new agent', {- agentId: agent.id,- error: String(error),- });- });-- await projectManager.openProject(project);- projectEvents._emit('project:created', project);- return ok(project);-}--async function createRemoteProject(- params: CreateLocalProjectParams,- remoteConfig: AgentRemoteConfig-): Promise<CreateProjectResult> {- // A remote agent has no local directory: detect + validate its Switch config- // in the remote working dir over SSH. Its `.claude/settings.local.json`- // already lives on the host (creds are not copied from a local dir).- const switchAgent = await detectSwitchAgentRemote(- remoteConfig.sshHost,- remoteConfig.remoteRepoDir- );- if (!switchAgent) {- return err({- type: 'invalid-directory',- path: remoteConfig.remoteRepoDir,- message: `The remote directory ${remoteConfig.remoteRepoDir} on ${remoteConfig.sshHost} is not configured as a Switch agent.`,- });- }-- const serverError = await verifyAgentOnServer(- params.serverId,- switchAgent.agentId,- remoteConfig.remoteRepoDir- );- if (serverError) return err(serverError);-- const [row] = await db- .insert(projects)- .values({- id: params.id ?? randomUUID(),- name: params.name,- path: null,- updatedAt: sql`CURRENT_TIMESTAMP`,- })- .returning();-- const project = rowToLocalProject(row);-- const agent = await createAgent({- id: randomUUID(),- projectId: project.id,- name: basenameFromAnyPath(remoteConfig.remoteRepoDir) || params.providerId,- providerId: params.providerId,- switchAgentId: switchAgent.agentId,- apiEndpoint: switchAgent.apiEndpoint,- serverId: params.serverId,- });-- // Record the remote connection. The Switch creds already live on the host, so- // there is no local→remote copy (setupRemoteAgent is intentionally skipped).- await setAgentConnection({- agentId: agent.id,- connection: 'remote',- remoteConfig,- });-- // Reconcile auto_session after the connection is recorded as remote so the- // remote branch (ensureRemoteWatcher → sidecar + watch-enabled marker file)- // runs for a fresh remote agent registered with auto_session on (CHOO-1185).- // Best-effort: an unreachable VM must not fail project creation.- await reconcileAgentAutoSessionFromGateway(agent.id).catch((error) => {- log.warn('createRemoteProject: failed to reconcile auto_session for new agent', {- agentId: agent.id,- error: String(error),- });- });-- await projectManager.openProject(project);- projectEvents._emit('project:created', project);- return ok(project);-}--function rowToLocalProject(row: typeof projects.$inferSelect) {- return {- type: 'local' as const,- id: row.id,- name: row.name,- path: row.path,- repositoryWorkspaceId: null,- createdAt: row.createdAt,- updatedAt: row.updatedAt,- };-}--export async function getLocalProjectPathStatus(path: string): Promise<ProjectPathStatus> {- return { isDirectory: checkIsValidDirectory(path) };-}diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/operations/createProject.test.ts b/dash/apps/switchdash-desktop/src/main/core/projects/operations/createProject.test.tsdeleted file mode 100644index 3a7fd82bb..000000000--- a/dash/apps/switchdash-desktop/src/main/core/projects/operations/createProject.test.ts+++ /dev/null@@ -1,288 +0,0 @@-import fs from 'node:fs';-import os from 'node:os';-import path from 'node:path';-import type { Result } from '@switchdash/shared';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { createLocalProject } from './create-local-project';--const { GatewayErrorStub, mocks } = vi.hoisted(() => {- class GatewayErrorStub extends Error {- constructor(- readonly kind: 'unauthorized' | 'http' | 'network',- message: string- ) {- super(message);- this.name = 'GatewayError';- }- }- return {- GatewayErrorStub,- mocks: {- openProjectMock: vi.fn(),- getProjectMock: vi.fn(),- insertMock: vi.fn(),- valuesMock: vi.fn(),- returningMock: vi.fn(),- detectSwitchAgentMock: vi.fn(),- createAgentMock: vi.fn(),- getServerMock: vi.fn(),- agentExistsOnServerMock: vi.fn(),- reconcileAutoSessionMock: vi.fn(),- },- };-});--vi.mock('@main/core/projects/project-manager', () => ({- projectManager: {- openProject: mocks.openProjectMock,- getProject: mocks.getProjectMock,- },-}));--vi.mock('@main/db/client', () => ({- db: {- insert: mocks.insertMock,- },-}));--vi.mock('@main/core/agents/detect', () => ({- detectSwitchAgent: mocks.detectSwitchAgentMock,-}));--vi.mock('@main/core/agents/createAgent', () => ({- createAgent: mocks.createAgentMock,-}));--vi.mock('@main/core/agents/setAgentAutoSession', () => ({- reconcileAgentAutoSessionFromGateway: mocks.reconcileAutoSessionMock,-}));--vi.mock('@main/core/switch-servers/servers-store', () => ({- getServer: mocks.getServerMock,-}));--vi.mock('@main/core/switch-servers/gateway-client', () => ({- agentExistsOnServer: mocks.agentExistsOnServerMock,- GatewayError: GatewayErrorStub,-}));--function expectOk<T, E>(result: Result<T, E>): T {- expect(result.success).toBe(true);- if (!result.success) throw new Error(`Expected success, got ${JSON.stringify(result.error)}`);- return result.data;-}--beforeEach(() => {- vi.clearAllMocks();-- mocks.insertMock.mockReturnValue({ values: mocks.valuesMock });- mocks.valuesMock.mockReturnValue({ returning: mocks.returningMock });- mocks.openProjectMock.mockResolvedValue(undefined);- mocks.getProjectMock.mockReturnValue(undefined);- mocks.createAgentMock.mockResolvedValue({ id: 'agent-1' });- mocks.reconcileAutoSessionMock.mockResolvedValue(true);- // Default: the chosen server exists and owns the agent (signed in).- mocks.getServerMock.mockResolvedValue({- id: 'server-1',- name: 'Pilot',- gatewayUrl: 'https://switch-gateway.example.com',- apiUrl: 'https://switch-api.example.com',- createdAt: '2026-04-16T00:00:00.000Z',- updatedAt: '2026-04-16T00:00:00.000Z',- });- mocks.agentExistsOnServerMock.mockResolvedValue(true);-});--describe('createLocalProject', () => {- const tempDirs: string[] = [];-- afterEach(() => {- for (const dir of tempDirs.splice(0)) {- fs.rmSync(dir, { recursive: true, force: true });- }- });-- it('onboards a directory configured as a Switch agent', async () => {- const projectPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-project-'));- tempDirs.push(projectPath);- mocks.detectSwitchAgentMock.mockResolvedValue({- agentId: 'switch-agent-1',- apiEndpoint: 'https://switch.example.com',- dir: projectPath,- });- const row = {- id: 'project-id',- name: 'Project',- path: projectPath,- createdAt: '2026-04-16T00:00:00.000Z',- updatedAt: '2026-04-16T00:00:00.000Z',- };- mocks.returningMock.mockResolvedValue([row]);-- const created = expectOk(- await createLocalProject({- id: 'project-id',- name: 'Project',- path: projectPath,- serverId: 'server-1',- providerId: 'claude',- })- );-- expect(mocks.valuesMock).toHaveBeenCalledWith(- expect.objectContaining({ id: 'project-id', name: 'Project', path: projectPath })- );- expect(created).toMatchObject({- id: 'project-id',- name: 'Project',- path: projectPath,- type: 'local',- });- expect(mocks.createAgentMock).toHaveBeenCalledWith(- expect.objectContaining({- projectId: 'project-id',- providerId: 'claude',- switchAgentId: 'switch-agent-1',- apiEndpoint: 'https://switch.example.com',- serverId: 'server-1',- })- );- expect(mocks.openProjectMock).toHaveBeenCalledWith(- expect.objectContaining({ id: 'project-id', type: 'local' })- );- // The new agent's auto_session state is reconciled from the gateway so a- // fresh agent registered with auto_session on starts watching immediately- // (CHOO-1185), without the operator toggling it off→on.- expect(mocks.reconcileAutoSessionMock).toHaveBeenCalledWith('agent-1');- });-- it('does not fail project creation when auto_session reconcile fails', async () => {- const projectPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-project-'));- tempDirs.push(projectPath);- mocks.detectSwitchAgentMock.mockResolvedValue({- agentId: 'switch-agent-1',- apiEndpoint: 'https://switch.example.com',- dir: projectPath,- });- mocks.returningMock.mockResolvedValue([- {- id: 'project-id',- name: 'Project',- path: projectPath,- createdAt: '2026-04-16T00:00:00.000Z',- updatedAt: '2026-04-16T00:00:00.000Z',- },- ]);- mocks.reconcileAutoSessionMock.mockRejectedValue(new Error('gateway unreachable'));-- const created = expectOk(- await createLocalProject({- id: 'project-id',- name: 'Project',- path: projectPath,- serverId: 'server-1',- providerId: 'claude',- })- );-- expect(created).toMatchObject({ id: 'project-id', type: 'local' });- expect(mocks.openProjectMock).toHaveBeenCalled();- });-- it('rejects when the chosen server does not have the agent', async () => {- const projectPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-project-'));- tempDirs.push(projectPath);- mocks.detectSwitchAgentMock.mockResolvedValue({- agentId: 'switch-agent-1',- apiEndpoint: 'https://switch.example.com',- dir: projectPath,- });- mocks.agentExistsOnServerMock.mockResolvedValue(false);-- const result = await createLocalProject({- id: 'project-id',- name: 'Project',- path: projectPath,- serverId: 'server-1',- providerId: 'claude',- });-- expect(result.success).toBe(false);- if (!result.success) {- expect(result.error.type).toBe('switch-agent-not-on-server');- }- expect(mocks.insertMock).not.toHaveBeenCalled();- expect(mocks.createAgentMock).not.toHaveBeenCalled();- });-- it('rejects when not signed in to the chosen server', async () => {- const projectPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-project-'));- tempDirs.push(projectPath);- mocks.detectSwitchAgentMock.mockResolvedValue({- agentId: 'switch-agent-1',- apiEndpoint: 'https://switch.example.com',- dir: projectPath,- });- mocks.agentExistsOnServerMock.mockRejectedValue(- new GatewayErrorStub('unauthorized', 'Not signed in.')- );-- const result = await createLocalProject({- id: 'project-id',- name: 'Project',- path: projectPath,- serverId: 'server-1',- providerId: 'claude',- });-- expect(result.success).toBe(false);- if (!result.success) {- expect(result.error.type).toBe('switch-server-unauthenticated');- }- expect(mocks.insertMock).not.toHaveBeenCalled();- expect(mocks.createAgentMock).not.toHaveBeenCalled();- });-- it('rejects a directory that is not configured as a Switch agent', async () => {- const projectPath = fs.mkdtempSync(path.join(os.tmpdir(), 'switchdash-project-'));- tempDirs.push(projectPath);- mocks.detectSwitchAgentMock.mockResolvedValue(null);-- const result = await createLocalProject({- id: 'project-id',- name: 'Project',- path: projectPath,- serverId: 'server-1',- providerId: 'claude',- });-- expect(result.success).toBe(false);- if (!result.success) {- expect(result.error.type).toBe('invalid-directory');- }- expect(mocks.insertMock).not.toHaveBeenCalled();- expect(mocks.createAgentMock).not.toHaveBeenCalled();- });-- it('rejects a path that is not a valid directory', async () => {- const missingPath = path.join(os.tmpdir(), 'switchdash-project-does-not-exist-xyz');-- const result = await createLocalProject({- id: 'project-id',- name: 'Project',- path: missingPath,- serverId: 'server-1',- providerId: 'claude',- });-- expect(result).toEqual({- success: false,- error: {- type: 'invalid-directory',- path: missingPath,- message: 'Invalid directory',- },- });- expect(mocks.insertMock).not.toHaveBeenCalled();- });-});diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/operations/createProject.ts b/dash/apps/switchdash-desktop/src/main/core/projects/operations/createProject.tsdeleted file mode 100644index b8ec674f3..000000000--- a/dash/apps/switchdash-desktop/src/main/core/projects/operations/createProject.ts+++ /dev/null@@ -1,26 +0,0 @@-import { detectSwitchAgent } from '@main/core/agents/detect';-import type {- CreateProjectParams,- CreateProjectResult,- InspectProjectPathParams,- ProjectPathInspection,-} from '@shared/projects';-import { createLocalProject, getLocalProjectPathStatus } from './create-local-project';-import { getLocalProjectByPath } from './getProjects';--export async function createProject(params: CreateProjectParams): Promise<CreateProjectResult> {- const { type: _type, ...localParams } = params;- return createLocalProject(localParams);-}--export async function inspectProjectPath(- params: InspectProjectPathParams-): Promise<ProjectPathInspection> {- const [status, existingProject, switchAgent] = await Promise.all([- getLocalProjectPathStatus(params.path),- getLocalProjectByPath(params.path),- detectSwitchAgent(params.path),- ]);-- return { ...status, existingProject, switchAgent };-}diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/operations/deleteProject.test.ts b/dash/apps/switchdash-desktop/src/main/core/projects/operations/deleteProject.test.tsdeleted file mode 100644index 32ef370bd..000000000--- a/dash/apps/switchdash-desktop/src/main/core/projects/operations/deleteProject.test.ts+++ /dev/null@@ -1,84 +0,0 @@-import { ok } from '@switchdash/shared';-import { beforeEach, describe, expect, it, vi } from 'vitest';-import { deleteProject } from './deleteProject';--const mocks = vi.hoisted(() => ({- closeProject: vi.fn(),- deleteProjectRow: vi.fn(),- deleteWhere: vi.fn(),- delViewState: vi.fn(),- getProject: vi.fn(),- getSessions: vi.fn(),- projectEmit: vi.fn(),- teardownSession: vi.fn(),-}));--vi.mock('@main/core/projects/project-events', () => ({- projectEvents: { _emit: mocks.projectEmit },-}));--vi.mock('@main/db/client', () => ({- db: {- delete: mocks.deleteProjectRow,- },-}));--vi.mock('@main/core/sessions/operations/getSessions', () => ({- getSessions: mocks.getSessions,-}));--vi.mock('@main/core/projects/project-manager', () => ({- projectManager: {- getProject: mocks.getProject,- closeProject: mocks.closeProject,- },-}));--vi.mock('@main/core/sessions/session-runtime-manager', () => ({- sessionRuntimeManager: {- teardownSession: mocks.teardownSession,- },-}));--vi.mock('@main/core/view-state/view-state-service', () => ({- viewStateService: {- del: mocks.delViewState,- },-}));--describe('deleteProject', () => {- beforeEach(() => {- vi.clearAllMocks();-- mocks.deleteProjectRow.mockReturnValue({ where: mocks.deleteWhere });- mocks.deleteWhere.mockResolvedValue(undefined);- mocks.getSessions.mockResolvedValue([{ id: 'session-1' }]);- mocks.getProject.mockReturnValue({ projectId: 'project-1' });- mocks.closeProject.mockResolvedValue(ok());- mocks.teardownSession.mockResolvedValue(ok());- mocks.delViewState.mockResolvedValue(undefined);- });-- it('closes a mounted project before deleting its database row', async () => {- await deleteProject('project-1');-- expect(mocks.closeProject).toHaveBeenCalledWith('project-1');- expect(mocks.deleteWhere).toHaveBeenCalledTimes(1);- const closeOrder = mocks.closeProject.mock.invocationCallOrder[0];- const deleteOrder = mocks.deleteWhere.mock.invocationCallOrder[0];- expect(closeOrder).toBeDefined();- expect(deleteOrder).toBeDefined();- expect(closeOrder!).toBeLessThan(deleteOrder!);- });-- it('deletes an unmounted project without closing a provider', async () => {- mocks.getProject.mockReturnValue(undefined);-- await deleteProject('project-1');-- expect(mocks.closeProject).not.toHaveBeenCalled();- expect(mocks.getSessions).not.toHaveBeenCalled();- expect(mocks.teardownSession).not.toHaveBeenCalled();- expect(mocks.deleteWhere).toHaveBeenCalledTimes(1);- });-});diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/operations/deleteProject.ts b/dash/apps/switchdash-desktop/src/main/core/projects/operations/deleteProject.tsdeleted file mode 100644index 6390b8767..000000000--- a/dash/apps/switchdash-desktop/src/main/core/projects/operations/deleteProject.ts+++ /dev/null@@ -1,24 +0,0 @@-import { eq } from 'drizzle-orm';-import { projectEvents } from '@main/core/projects/project-events';-import { projectManager } from '@main/core/projects/project-manager';-import { getSessions } from '@main/core/sessions/operations/getSessions';-import { sessionRuntimeManager } from '@main/core/sessions/session-runtime-manager';-import { viewStateService } from '@main/core/view-state/view-state-service';-import { db } from '@main/db/client';-import { projects } from '@main/db/schema';--export async function deleteProject(id: string): Promise<void> {- const provider = projectManager.getProject(id);- if (provider) {- const projectSessions = await getSessions(id);- await Promise.allSettled([- ...projectSessions.map((t) => sessionRuntimeManager.teardownSession(t.id)),- ...projectSessions.map((t) => viewStateService.del(`session:${t.id}`)),- ]);- await projectManager.closeProject(id);- }-- await db.delete(projects).where(eq(projects.id, id));- void viewStateService.del(`project:${id}`);- projectEvents._emit('project:deleted', id);-}diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/operations/getProjects.ts b/dash/apps/switchdash-desktop/src/main/core/projects/operations/getProjects.tsdeleted file mode 100644index 07493f94e..000000000--- a/dash/apps/switchdash-desktop/src/main/core/projects/operations/getProjects.ts+++ /dev/null@@ -1,33 +0,0 @@-import { desc, eq } from 'drizzle-orm';-import { db } from '@main/db/client';-import { projects } from '@main/db/schema';-import type { LocalProject } from '@shared/projects';--function rowToLocalProject(row: typeof projects.$inferSelect): LocalProject {- return {- type: 'local' as const,- id: row.id,- name: row.name,- path: row.path,- repositoryWorkspaceId: null,- createdAt: row.createdAt,- updatedAt: row.updatedAt,- };-}--export async function getProjects(): Promise<LocalProject[]> {- const rows = await db.select().from(projects).orderBy(desc(projects.updatedAt));- return rows.map(rowToLocalProject);-}--export async function getProjectById(projectId: string): Promise<LocalProject | undefined> {- const [row] = await db.select().from(projects).where(eq(projects.id, projectId)).limit(1);- if (!row) return undefined;- return rowToLocalProject(row);-}--export async function getLocalProjectByPath(path: string): Promise<LocalProject | undefined> {- const [row] = await db.select().from(projects).where(eq(projects.path, path)).limit(1);- if (!row) return undefined;- return rowToLocalProject(row);-}diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/operations/openProject.ts b/dash/apps/switchdash-desktop/src/main/core/projects/operations/openProject.tsdeleted file mode 100644index 7678ee9ef..000000000--- a/dash/apps/switchdash-desktop/src/main/core/projects/operations/openProject.ts+++ /dev/null@@ -1,23 +0,0 @@-import { err, ok, type Result } from '@switchdash/shared';-import { projectManager } from '@main/core/projects/project-manager';-import type { OpenProjectError, OpenProjectSuccess } from '@shared/projects';-import { checkIsValidDirectory } from '../path-utils';-import { getProjectById } from './getProjects';--export async function openProject(- projectId: string-): Promise<Result<OpenProjectSuccess, OpenProjectError>> {- const project = await getProjectById(projectId);- if (!project) return err({ type: 'error', message: `Project not found: ${projectId}` });- // Remote-only projects have no local path — their working dir lives on the- // host, so there is nothing to validate here; provisioning handles the remote.- if (project.path !== null && !checkIsValidDirectory(project.path)) {- return err({ type: 'path-not-found', path: project.path });- }- const result = await projectManager.openProject(project);- if (!result.success) {- return err({ type: 'error', message: result.error.message });- }-- return ok({ repositoryWorkspaceId: null });-}diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/project-events.ts b/dash/apps/switchdash-desktop/src/main/core/projects/project-events.tsdeleted file mode 100644index 1fda88640..000000000--- a/dash/apps/switchdash-desktop/src/main/core/projects/project-events.ts+++ /dev/null@@ -1,24 +0,0 @@-import { HookCore, type Hookable } from '@main/lib/hookable';-import { log } from '@main/lib/logger';-import type { Project } from '@shared/projects';--export type ProjectCrudHooks = {- 'project:created': (project: Project) => void | Promise<void>;- 'project:deleted': (projectId: string) => void | Promise<void>;-};--class ProjectEvents implements Hookable<ProjectCrudHooks> {- private readonly _core = new HookCore<ProjectCrudHooks>((name, e) =>- log.error(`ProjectEvents: ${String(name)} hook error`, e)- );-- on<K extends keyof ProjectCrudHooks>(name: K, handler: ProjectCrudHooks[K]) {- return this._core.on(name, handler);- }-- _emit<K extends keyof ProjectCrudHooks>(name: K, ...args: Parameters<ProjectCrudHooks[K]>): void {- this._core.callHookBackground(name, ...args);- }-}--export const projectEvents = new ProjectEvents();diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/project-manager.ts b/dash/apps/switchdash-desktop/src/main/core/projects/project-manager.tsdeleted file mode 100644index 88970a7b0..000000000--- a/dash/apps/switchdash-desktop/src/main/core/projects/project-manager.ts+++ /dev/null@@ -1,102 +0,0 @@-import { err, ok, type Result } from '@switchdash/shared';-import type { IDisposable } from '@switchdash/shared';-import { HookCore, type Hookable } from '@main/lib/hookable';-import { LifecycleMap } from '@main/lib/lifecycle-map';-import { log } from '@main/lib/logger';-import type { LocalProject } from '@shared/projects';-import { createProvider } from './create-project-provider';-import type { ProjectProvider } from './project-provider';-import { TimeoutSignal, withTimeout } from './utils';--const LOCAL_PROVIDER_TIMEOUT_MS = 20_000;-const TEARDOWN_PROVIDER_TIMEOUT_MS = 60_000;--type ProjectSessionManagerHooks = {- projectOpened: (projectId: string, provider: ProjectProvider) => void | Promise<void>;- projectClosed: (projectId: string) => void | Promise<void>;-};--type ProviderLifecycleError =- | { type: 'timeout'; message: string; timeout: number }- | { type: 'error'; message: string };--function toInitError(e: unknown): ProviderLifecycleError {- if (e instanceof TimeoutSignal) return { type: 'timeout', message: e.message, timeout: e.ms };- return { type: 'error', message: e instanceof Error ? e.message : String(e) };-}--function toTeardownError(e: unknown): ProviderLifecycleError {- if (e instanceof TimeoutSignal) return { type: 'timeout', message: e.message, timeout: e.ms };- return { type: 'error', message: e instanceof Error ? e.message : String(e) };-}--class ProjectSessionManager implements Hookable<ProjectSessionManagerHooks>, IDisposable {- private readonly _hooks = new HookCore<ProjectSessionManagerHooks>((name, e) =>- log.error(`ProjectManager: ${String(name)} hook error`, e)- );- private readonly _lifecycle = new LifecycleMap<- ProjectProvider,- ProviderLifecycleError,- ProviderLifecycleError- >({- postProvision: (id, provider) => this._hooks.callHookBackground('projectOpened', id, provider),- postTeardown: (id) => this._hooks.callHookBackground('projectClosed', id),- });-- on<K extends keyof ProjectSessionManagerHooks>(name: K, handler: ProjectSessionManagerHooks[K]) {- return this._hooks.on(name, handler);- }-- async openProject(- project: LocalProject- ): Promise<Result<ProjectProvider, ProviderLifecycleError>> {- return this._lifecycle.provision(project.id, async () => {- try {- const provider = await withTimeout(createProvider(project), LOCAL_PROVIDER_TIMEOUT_MS);- return ok(provider);- } catch (e) {- const initError = toInitError(e);- log.error('ProjectManager: error during project initialization', {- projectId: project.id,- ...initError,- });- return err(initError);- }- });- }-- async closeProject(projectId: string): Promise<Result<void, ProviderLifecycleError>> {- return (- this._lifecycle.teardown(projectId, async (provider) => {- try {- await withTimeout(provider.dispose(), TEARDOWN_PROVIDER_TIMEOUT_MS);- return ok();- } catch (e) {- const error = toTeardownError(e);- log.error('ProjectManager: error during project teardown', { projectId, ...error });- return err(error);- }- }) ?? ok()- );- }-- getProject(projectId: string): ProjectProvider | undefined {- return this._lifecycle.get(projectId);- }-- async dispose(): Promise<void> {- const ids = Array.from(this._lifecycle.keys());- await Promise.allSettled(ids.map((id) => this.closeProject(id)));- for (const id of ids) {- const status = this._lifecycle.teardownStatus(id);- if (status.status === 'error') {- log.error('ProjectManager: project teardown error recorded after dispose', {- projectId: id,- message: status.error.message,- });- }- }- }-}--export const projectManager = new ProjectSessionManager();diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/project-provider.ts b/dash/apps/switchdash-desktop/src/main/core/projects/project-provider.tsdeleted file mode 100644index 98b0334f4..000000000--- a/dash/apps/switchdash-desktop/src/main/core/projects/project-provider.ts+++ /dev/null@@ -1,84 +0,0 @@-import type { IDisposable } from '@switchdash/shared';-import { getAgents } from '@main/core/agents/getAgents';-import type { IExecutionContext } from '@main/core/execution-context/types';-import type { FileSystemProvider } from '@main/core/fs/types';-import type { MachineRef } from '@main/core/runtime/types';-import { workspaceRegistry } from '@main/core/workspaces/workspace-registry';-import type { WorkspaceProviderData } from '@shared/core/workspaces/workspace-provider-data';-import type { AgentRuntimeProvider } from '../agent-runtime/types';-import { sessionRuntimeManager } from '../sessions/session-runtime-manager';-import type { WorkspaceType } from '../workspaces/workspace-factory';-import type { ProjectSettingsProvider } from './settings/provider';--export type { WorkspaceProviderData };--export type ProvisionResult = {- agent: AgentRuntimeProvider;- persistData: {- workspaceId: string;- workspaceProviderData?: WorkspaceProviderData;- worktreeGitDir?: string;- };-};--/**- * Transport-specific dependencies: the only things that differ between local and SSH.- * Pure data — no lifecycle methods.- */-export type ProjectProviderTransport = {- readonly kind: string;- readonly projectMachine: MachineRef;- readonly defaultWorkspaceType: WorkspaceType;- readonly defaultWorkspaceMachine: MachineRef;- readonly ctx: IExecutionContext;- readonly fs: FileSystemProvider;- readonly settings: ProjectSettingsProvider;-};--export class ProjectProvider implements IDisposable {- readonly type: string;- readonly projectId: string;- readonly repoPath: string;- readonly projectMachine: MachineRef;- readonly settings: ProjectSettingsProvider;- readonly fs: FileSystemProvider;- /** Workspace type for standard sessions. BYOI sessions use their own remote workspace type. */- readonly defaultWorkspaceType: WorkspaceType;- readonly defaultWorkspaceMachine: MachineRef;-- private readonly _ctx: IExecutionContext;-- constructor(- projectId: string,- repoPath: string,- transport: ProjectProviderTransport,- private readonly _dispose: () => void- ) {- this.type = transport.kind;- this.projectId = projectId;- this.repoPath = repoPath;- this.projectMachine = transport.projectMachine;- this._ctx = transport.ctx;- this.settings = transport.settings;- this.fs = transport.fs;- this.defaultWorkspaceType = transport.defaultWorkspaceType;- this.defaultWorkspaceMachine = transport.defaultWorkspaceMachine;- }-- get ctx(): IExecutionContext {- return this._ctx;- }-- async dispose(): Promise<void> {- this._dispose();- const projectSettings = await this.settings.get();- // Detach (don't terminate) when work should outlive the app: tmux sessions,- // and remote agents whose on-VM sidecar must keep listening to Switch while- // switchdash is closed (CHOO-1059). Terminate only cleans up the local pane.- const agents = await getAgents(this.projectId);- const hasRemoteAgent = agents.some((agent) => agent.connection === 'remote');- const mode = projectSettings.tmux || hasRemoteAgent ? 'detach' : 'terminate';- await sessionRuntimeManager.teardownAllForProject(this.projectId, mode);- await workspaceRegistry.releaseAllForProject(this.projectId, mode);- }-}diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/settings/count-projects-using-github-account.db.test.ts b/dash/apps/switchdash-desktop/src/main/core/projects/settings/count-projects-using-github-account.db.test.tsdeleted file mode 100644index da9332deb..000000000--- a/dash/apps/switchdash-desktop/src/main/core/projects/settings/count-projects-using-github-account.db.test.ts+++ /dev/null@@ -1,99 +0,0 @@-import { openFixture } from '@tooling/utils/db';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import type { AppDb } from '@main/db/client';-import { projectSettings, projects } from '@main/db/schema';-import { countProjectsUsingGithubAccount } from './count-projects-using-github-account';--const mocks = vi.hoisted(() => ({- db: undefined as AppDb | undefined,-}));--vi.mock('@main/db/client', () => ({- get db() {- if (!mocks.db) throw new Error('Test database not initialized');- return mocks.db;- },-}));--const TARGET_ACCOUNT_ID = 'github.com:42';-const OTHER_ACCOUNT_ID = 'github.com:99';--function baseSettingsJson(githubAccountId?: string | null): string {- const settings: Record<string, unknown> = {- defaultBranch: 'main',- baseRemote: 'origin',- };- if (githubAccountId !== undefined) {- settings.githubAccountId = githubAccountId;- }- return JSON.stringify(settings);-}--describe('countProjectsUsingGithubAccount', () => {- let fixture: Awaited<ReturnType<typeof openFixture>>;-- beforeEach(async () => {- fixture = await openFixture('empty');- mocks.db = fixture.db;- });-- afterEach(() => {- fixture.close();- mocks.db = undefined;- });-- it('counts only persisted projects pinned to the target account', async () => {- await fixture.db.insert(projects).values([- { id: 'project-match-1', name: 'Match 1', path: '/repo/match-1' },- { id: 'project-match-2', name: 'Match 2', path: '/repo/match-2' },- { id: 'project-null', name: 'Null', path: '/repo/null' },- { id: 'project-other', name: 'Other', path: '/repo/other' },- { id: 'project-unconfigured', name: 'Unconfigured', path: '/repo/unconfigured' },- ]);- await fixture.db.insert(projectSettings).values([- {- projectId: 'project-match-1',- baseProjectSettingsJson: baseSettingsJson(TARGET_ACCOUNT_ID),- },- {- projectId: 'project-match-2',- baseProjectSettingsJson: baseSettingsJson(` ${TARGET_ACCOUNT_ID} `),- },- {- projectId: 'project-null',- baseProjectSettingsJson: baseSettingsJson(null),- },- {- projectId: 'project-other',- baseProjectSettingsJson: baseSettingsJson(OTHER_ACCOUNT_ID),- },- {- projectId: 'project-unconfigured',- baseProjectSettingsJson: baseSettingsJson(),- },- ]);-- await expect(countProjectsUsingGithubAccount(TARGET_ACCOUNT_ID)).resolves.toBe(2);- await expect(countProjectsUsingGithubAccount(OTHER_ACCOUNT_ID)).resolves.toBe(1);- await expect(countProjectsUsingGithubAccount('github.com:missing')).resolves.toBe(0);- });-- it('skips malformed base settings JSON', async () => {- await fixture.db.insert(projects).values([- { id: 'project-malformed', name: 'Malformed', path: '/repo/malformed' },- { id: 'project-valid', name: 'Valid', path: '/repo/valid' },- ]);- await fixture.db.insert(projectSettings).values([- {- projectId: 'project-malformed',- baseProjectSettingsJson: '{not-json',- },- {- projectId: 'project-valid',- baseProjectSettingsJson: baseSettingsJson(TARGET_ACCOUNT_ID),- },- ]);-- await expect(countProjectsUsingGithubAccount(TARGET_ACCOUNT_ID)).resolves.toBe(1);- });-});diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/settings/effective-session-settings.ts b/dash/apps/switchdash-desktop/src/main/core/projects/settings/effective-session-settings.tsdeleted file mode 100644index b4f1b8117..000000000--- a/dash/apps/switchdash-desktop/src/main/core/projects/settings/effective-session-settings.ts+++ /dev/null@@ -1,32 +0,0 @@-import type { FileSystemProvider } from '@main/core/fs/types';-import { log } from '@main/lib/logger';-import {- defaultShareableProjectSettings,- shareableProjectSettingsSchema,- type ProjectSettings,-} from '@shared/core/project-settings/project-settings';-import { mergeShareableProjectSettings } from '@shared/core/project-settings/project-settings-fields';-import type { ProjectSettingsProvider } from './provider';--export async function getEffectiveSessionSettings(args: {- projectSettings: ProjectSettingsProvider;- sessionFs: FileSystemProvider;-}): Promise<ProjectSettings> {- const { projectSettings, sessionFs } = args;- const parsedSettings = shareableProjectSettingsSchema.safeParse(await projectSettings.get());- const localShareableSettings = parsedSettings.success ? parsedSettings.data : {};- const defaults = defaultShareableProjectSettings();- const exists = await sessionFs.exists('.switchdash.json');- if (!exists) {- return mergeShareableProjectSettings(defaults, localShareableSettings);- }-- try {- const { content } = await sessionFs.read('.switchdash.json');- const projectFileSettings = shareableProjectSettingsSchema.parse(JSON.parse(content));- return mergeShareableProjectSettings(defaults, projectFileSettings, localShareableSettings);- } catch (err) {- log.warn('Failed to parse session .switchdash.json, falling back to project settings', err);- return mergeShareableProjectSettings(defaults, localShareableSettings);- }-}diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/settings/legacy-project-settings-migration.ts b/dash/apps/switchdash-desktop/src/main/core/projects/settings/legacy-project-settings-migration.tsdeleted file mode 100644index 253a80bd3..000000000--- a/dash/apps/switchdash-desktop/src/main/core/projects/settings/legacy-project-settings-migration.ts+++ /dev/null@@ -1,122 +0,0 @@-import type { Result } from '@switchdash/shared';-import type { FileSystemProvider } from '@main/core/fs/types';-import { log } from '@main/lib/logger';-import {- baseProjectSettingsSchema,- legacyBaseProjectSettingsSchema,- legacyProjectConfigSchema,- shareableProjectSettingsSchema,- type BaseProjectSettings,- type ShareableProjectSettings,-} from '@shared/core/project-settings/project-settings';-import { mergeShareableProjectSettings } from '@shared/core/project-settings/project-settings-fields';-import type { UpdateProjectSettingsError } from '@shared/projects';-import {- hasLegacyShareableConfigMigrated,- serializeShareableProjectSettings,-} from './legacy-shareable-migration-marker';-import { compactUndefined, parseJsonObject, readJson } from './project-settings-json';-import type { ProjectSettingsStorage, StoredProjectSettings } from './project-settings-storage';--export type LegacyProjectSettingsMigrationArgs = {- projectId: string;- row: StoredProjectSettings | undefined;- configReader: Pick<FileSystemProvider, 'exists' | 'read'> | undefined;- storage: ProjectSettingsStorage;- git?: ProjectSettingsGitInspector;- normalizeStoredWorktreeDirectory: (- worktreeDirectory: string- ) => Promise<Result<string, UpdateProjectSettingsError>>;-};--export type ProjectSettingsGitInspector = {- isFileCleanlyTracked(filePath: string): Promise<boolean>;-};--async function readLegacyProjectConfig(- configReader: Pick<FileSystemProvider, 'exists' | 'read'> | undefined-): Promise<BaseProjectSettings | undefined> {- if (!configReader) return undefined;- try {- if (!(await configReader.exists('.switchdash.json'))) return undefined;- const { content } = await configReader.read('.switchdash.json');- const parsed = legacyProjectConfigSchema.safeParse(parseJsonObject(content));- if (!parsed.success) {- log.warn('Failed to parse legacy .switchdash.json for migration', parsed.error);- return undefined;- }- return parsed.data;- } catch (error) {- log.warn('Failed to read legacy .switchdash.json for migration', error);- return undefined;- }-}--export async function migrateLegacyProjectSettingsIfNeeded({- projectId,- row,- configReader,- storage,- git,- normalizeStoredWorktreeDirectory,-}: LegacyProjectSettingsMigrationArgs): Promise<void> {- if (!row) return;-- const baseAlreadyMigrated = Boolean(row.legacyConfigMigratedAt);- const shareableAlreadyMigrated = hasLegacyShareableConfigMigrated(- row.shareableProjectSettingsJson- );- if (baseAlreadyMigrated && shareableAlreadyMigrated) return;-- const current = readJson(- row.baseProjectSettingsJson,- legacyBaseProjectSettingsSchema,- 'base project settings'- );- const currentShareable = readJson(- row.shareableProjectSettingsJson,- shareableProjectSettingsSchema,- 'shareable project settings'- );- const legacy = await readLegacyProjectConfig(configReader);- const next: BaseProjectSettings = baseProjectSettingsSchema.parse(current);- let nextShareable: ShareableProjectSettings | undefined;-- if (legacy && !baseAlreadyMigrated) {- if (legacy.worktreeDirectory !== undefined) {- const normalized = await normalizeStoredWorktreeDirectory(legacy.worktreeDirectory);- if (normalized.success) next.worktreeDirectory = normalized.data;- }- if (legacy.tmux !== undefined) next.tmux = legacy.tmux;- if (legacy.workspaceProvider !== undefined) {- next.workspaceProvider = legacy.workspaceProvider;- }- }-- if (legacy && !shareableAlreadyMigrated) {- if ((await git?.isFileCleanlyTracked('.switchdash.json')) === false) {- const legacyShareable = shareableProjectSettingsSchema.parse(legacy);- nextShareable = mergeShareableProjectSettings(currentShareable, legacyShareable);- }- }-- const update: Partial<StoredProjectSettings> = {- ...(nextShareable- ? {- shareableProjectSettingsJson: serializeShareableProjectSettings(nextShareable, {- previousRaw: row.shareableProjectSettingsJson,- markLegacyShareableConfigMigrated: true,- }),- }- : {}),- };-- if (!baseAlreadyMigrated) {- update.baseProjectSettingsJson = JSON.stringify(compactUndefined(next));- update.legacyConfigMigratedAt = new Date().toISOString();- }-- if (Object.keys(update).length > 0) {- await storage.update(projectId, update);- }-}diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/settings/project-settings-service.ts b/dash/apps/switchdash-desktop/src/main/core/projects/settings/project-settings-service.tsdeleted file mode 100644index 34acb214b..000000000--- a/dash/apps/switchdash-desktop/src/main/core/projects/settings/project-settings-service.ts+++ /dev/null@@ -1,164 +0,0 @@-import { err, ok, type Result } from '@switchdash/shared';-import type { IInitializable } from '@switchdash/shared';-import { events } from '@main/lib/events';-import { HookCore, type Hookable } from '@main/lib/hookable';-import { log } from '@main/lib/logger';-import {- type MigrateProjectConfigRequest,- type MigrateProjectConfigResult,- type ProjectSettingsPatch,- type ProjectSettings,- type ProjectSettingsPage,- type WriteProjectConfigRequest,-} from '@shared/core/project-settings/project-settings';-import { hasConfiguredShareableProjectSettings } from '@shared/core/project-settings/project-settings-fields';-import { projectSettingsChangedChannel } from '@shared/core/projects/projectEvents';-import type { UpdateProjectSettingsError } from '@shared/projects';-import { projectManager } from '../project-manager';-import type { ProjectProvider } from '../project-provider';-import {- inspectProjectConfigMigrations,- migrateProjectConfigFromProvider,-} from './sharing/config-migration';-import { computeProjectSettingsOverrideState } from './sharing/project-settings-override-state';-import {- getProjectSettingsWriteTargets,- resolveAllProjectSettingsTargets,-} from './sharing/project-settings-target-resolver';-import { shareProjectSettingsToConfig as writeSharedProjectSettingsToConfig } from './sharing/share-project-settings-to-config';--export type ProjectSettingsHooks = {- 'project-settings:changed': (event: {- projectId: string;- settings: ProjectSettings;- }) => void | Promise<void>;-};--export class ProjectSettingsService implements Hookable<ProjectSettingsHooks>, IInitializable {- private readonly _hooks = new HookCore<ProjectSettingsHooks>((name, e) =>- log.error(`ProjectSettingsService: ${String(name)} hook error`, e)- );- private _disposeRendererBridge: (() => void) | null = null;-- on<K extends keyof ProjectSettingsHooks>(name: K, handler: ProjectSettingsHooks[K]) {- return this._hooks.on(name, handler);- }-- initialize(): void {- this._disposeRendererBridge?.();- this._disposeRendererBridge = this.on('project-settings:changed', ({ projectId }) => {- events.emit(projectSettingsChangedChannel, { projectId });- });- }-- async getProjectSettingsPage(- projectId: string- ): Promise<Result<ProjectSettingsPage, UpdateProjectSettingsError>> {- const project = this.requireProject(projectId);- if (!project.success) return project;- return ok(await this.getProjectSettingsPageForProject(project.data));- }-- async updateProjectSettings(- projectId: string,- settings: ProjectSettings- ): Promise<Result<ProjectSettings, UpdateProjectSettingsError>> {- const project = this.requireProject(projectId);- if (!project.success) return project;-- const result = await project.data.settings.update(settings);- if (!result.success) return result;-- const updatedSettings = await project.data.settings.get();- this.emitSettingsChanged(projectId, updatedSettings);- return ok(updatedSettings);- }-- async patchProjectSettings(- projectId: string,- patch: ProjectSettingsPatch- ): Promise<Result<ProjectSettings, UpdateProjectSettingsError>> {- const project = this.requireProject(projectId);- if (!project.success) return project;-- const result = await project.data.settings.patch(patch);- if (!result.success) return result;-- const updatedSettings = await project.data.settings.get();- this.emitSettingsChanged(projectId, updatedSettings);- return ok(updatedSettings);- }-- async shareProjectSettingsToConfig(- projectId: string,- request: WriteProjectConfigRequest- ): Promise<Result<ProjectSettingsPage, UpdateProjectSettingsError>> {- const project = this.requireProject(projectId);- if (!project.success) return project;-- const resolvedTargets = await resolveAllProjectSettingsTargets(project.data);- const result = await writeSharedProjectSettingsToConfig(project.data, request, resolvedTargets);- if (!result.success) return result;-- const page = await this.getProjectSettingsPageForProject(project.data);- this.emitSettingsChanged(projectId, page.settings);- return ok(page);- }-- async migrateProjectConfig(- projectId: string,- request: MigrateProjectConfigRequest- ): Promise<Result<MigrateProjectConfigResult, UpdateProjectSettingsError>> {- const project = this.requireProject(projectId);- if (!project.success) return project;-- const settings = await project.data.settings.get();- if (hasConfiguredShareableProjectSettings(settings)) {- return err({- type: 'write-config-failed',- message: 'Shareable project settings are already configured.',- });- }-- const result = await migrateProjectConfigFromProvider(project.data, request);- if (!result.success) return result;-- const page = await this.getProjectSettingsPageForProject(project.data);- this.emitSettingsChanged(projectId, page.settings);- return ok({ page, migration: result.data });- }-- private requireProject(projectId: string): Result<ProjectProvider, UpdateProjectSettingsError> {- const project = projectManager.getProject(projectId);- return project ? ok(project) : err({ type: 'project-not-found' });- }-- private async getProjectSettingsPageForProject(- project: ProjectProvider- ): Promise<ProjectSettingsPage> {- const settings = await project.settings.get();- const defaults = {- worktreeDirectory: await project.settings.getDefaultWorktreeDirectory(),- };- const resolvedTargets = await resolveAllProjectSettingsTargets(project);- const writeTargets = getProjectSettingsWriteTargets(resolvedTargets);- const overrideState = await computeProjectSettingsOverrideState(resolvedTargets);- const configMigrations = hasConfiguredShareableProjectSettings(settings)- ? []- : await inspectProjectConfigMigrations(project.fs);- return {- settings,- defaults,- writeTargets,- overrideState,- configMigrations,- shouldPromptConfigMigration: configMigrations.length > 0,- };- }-- private emitSettingsChanged(projectId: string, settings: ProjectSettings): void {- this._hooks.callHookBackground('project-settings:changed', { projectId, settings });- }-}--export const projectSettingsService = new ProjectSettingsService();diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/settings/project-settings-storage.ts b/dash/apps/switchdash-desktop/src/main/core/projects/settings/project-settings-storage.tsdeleted file mode 100644index 06296459c..000000000--- a/dash/apps/switchdash-desktop/src/main/core/projects/settings/project-settings-storage.ts+++ /dev/null@@ -1,54 +0,0 @@-import { eq, sql } from 'drizzle-orm';-import { db } from '@main/db/client';-import { projectSettings as projectSettingsTable } from '@main/db/schema';--export type StoredProjectSettings = {- baseProjectSettingsJson: string;- shareableProjectSettingsJson: string;- legacyConfigMigratedAt: string | null;-};--export interface ProjectSettingsStorage {- get(projectId: string): Promise<StoredProjectSettings | undefined>;- insertIfMissing(projectId: string, settings: StoredProjectSettings): Promise<void>;- update(projectId: string, settings: Partial<StoredProjectSettings>): Promise<void>;-}--export class ProjectSettingsRepository implements ProjectSettingsStorage {- async get(projectId: string): Promise<StoredProjectSettings | undefined> {- const row = db- .select()- .from(projectSettingsTable)- .where(eq(projectSettingsTable.projectId, projectId))- .get();- if (!row) return undefined;- return {- baseProjectSettingsJson: row.baseProjectSettingsJson,- shareableProjectSettingsJson: row.shareableProjectSettingsJson,- legacyConfigMigratedAt: row.legacyConfigMigratedAt,- };- }-- async insertIfMissing(projectId: string, settings: StoredProjectSettings): Promise<void> {- await db- .insert(projectSettingsTable)- .values({- projectId,- baseProjectSettingsJson: settings.baseProjectSettingsJson,- shareableProjectSettingsJson: settings.shareableProjectSettingsJson,- legacyConfigMigratedAt: settings.legacyConfigMigratedAt,- updatedAt: sql`CURRENT_TIMESTAMP`,- })- .onConflictDoNothing();- }-- async update(projectId: string, settings: Partial<StoredProjectSettings>): Promise<void> {- await db- .update(projectSettingsTable)- .set({- ...settings,- updatedAt: sql`CURRENT_TIMESTAMP`,- })- .where(eq(projectSettingsTable.projectId, projectId));- }-}diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/settings/provider.ts b/dash/apps/switchdash-desktop/src/main/core/projects/settings/provider.tsdeleted file mode 100644index ecef3562d..000000000--- a/dash/apps/switchdash-desktop/src/main/core/projects/settings/provider.ts+++ /dev/null@@ -1,16 +0,0 @@-import type { Result } from '@switchdash/shared';-import type {- ProjectSettings,- ProjectSettingsPatch,-} from '@shared/core/project-settings/project-settings';-import type { UpdateProjectSettingsError } from '@shared/projects';-export type { ProjectSettingsPatch };--export interface ProjectSettingsProvider {- getDefaultWorktreeDirectory(): Promise<string>;- getWorktreeDirectory(): Promise<string>;- get(): Promise<ProjectSettings>;- update(settings: ProjectSettings): Promise<Result<void, UpdateProjectSettingsError>>;- patch(patch: ProjectSettingsPatch): Promise<Result<void, UpdateProjectSettingsError>>;- ensure(): Promise<void>;-}diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/settings/providers/db-project-settings-provider.ts b/dash/apps/switchdash-desktop/src/main/core/projects/settings/providers/db-project-settings-provider.tsdeleted file mode 100644index 3f086d419..000000000--- a/dash/apps/switchdash-desktop/src/main/core/projects/settings/providers/db-project-settings-provider.ts+++ /dev/null@@ -1,256 +0,0 @@-import { err, ok, type Result } from '@switchdash/shared';-import type { FileSystemProvider } from '@main/core/fs/types';-import { appSettingsService } from '@main/core/settings/settings-service';-import { log } from '@main/lib/logger';-import {- baseProjectSettingsSchema,- DEFAULT_PRESERVE_PATTERNS,- legacyBaseProjectSettingsSchema,- projectSettingsSchema,- shareableProjectSettingsSchema,- type BaseProjectSettings,- type ProjectSettings,- type ShareableProjectSettings,-} from '@shared/core/project-settings/project-settings';-import { SHAREABLE_FIELD_ACCESSORS } from '@shared/core/project-settings/project-settings-fields';-import type { UpdateProjectSettingsError } from '@shared/projects';-import {- migrateLegacyProjectSettingsIfNeeded,- type ProjectSettingsGitInspector,-} from '../legacy-project-settings-migration';-import { serializeShareableProjectSettings } from '../legacy-shareable-migration-marker';-import { compactUndefined, parseJsonObject, readJson } from '../project-settings-json';-import { ProjectSettingsRepository } from '../project-settings-storage';-import type { ProjectSettingsPatch, ProjectSettingsProvider } from '../provider';-import { CONFIG_FILE } from '../sharing/workspace-config-file';--export type DbProjectSettingsProviderOptions = {- git?: ProjectSettingsGitInspector;-};--export abstract class DbProjectSettingsProvider implements ProjectSettingsProvider {- private legacyMigrationPromise: Promise<void> | undefined;- private readonly storage = new ProjectSettingsRepository();-- protected constructor(- private readonly projectId: string,- protected readonly projectPath: string,- private readonly configReader: Pick<FileSystemProvider, 'exists' | 'read'> | undefined,- private readonly options: DbProjectSettingsProviderOptions = {}- ) {}-- protected abstract defaultWorktreeDirectory(): Promise<string>;-- protected abstract validateWorktreeDirectory(- worktreeDirectory: string | undefined- ): Promise<Result<string | undefined, UpdateProjectSettingsError>>;-- protected abstract normalizeStoredWorktreeDirectory(- worktreeDirectory: string- ): Promise<Result<string, UpdateProjectSettingsError>>;-- protected async initialBaseProjectSettings(): Promise<BaseProjectSettings> {- const projectDefaults = await appSettingsService.get('project');- return {- tmux: projectDefaults.tmuxByDefault,- };- }-- private async hasSharedPreservePatterns(): Promise<boolean> {- if (!this.configReader) return false;- try {- if (!(await this.configReader.exists(CONFIG_FILE))) return false;- const { content } = await this.configReader.read(CONFIG_FILE);- const parsed = shareableProjectSettingsSchema.safeParse(parseJsonObject(content));- if (!parsed.success) {- log.warn('Failed to inspect shared project settings during initialization', parsed.error);- return false;- }- return parsed.data.preservePatterns !== undefined;- } catch (error) {- log.warn('Failed to inspect shared project settings during initialization', error);- return false;- }- }-- private async ensureRow(): Promise<void> {- if (await this.storage.get(this.projectId)) return;-- const baseSettings = await this.initialBaseProjectSettings();- const shareableSettings = (await this.hasSharedPreservePatterns())- ? {}- : { preservePatterns: [...DEFAULT_PRESERVE_PATTERNS] };- await this.storage.insertIfMissing(this.projectId, {- baseProjectSettingsJson: JSON.stringify(compactUndefined(baseSettings)),- shareableProjectSettingsJson: serializeShareableProjectSettings(shareableSettings),- legacyConfigMigratedAt: null,- });- }-- private async readSettingsRow(): Promise<{- base: BaseProjectSettings;- shareable: ShareableProjectSettings;- legacyConfigMigratedAt: string | null;- }> {- await this.ensureRow();- await this.migrateLegacyConfigIfNeeded();- const row = await this.storage.get(this.projectId);- if (!row) {- return {- base: await this.initialBaseProjectSettings(),- shareable: {},- legacyConfigMigratedAt: null,- };- }- const baseSettings = readJson(- row.baseProjectSettingsJson,- legacyBaseProjectSettingsSchema,- 'base project settings'- );-- return {- base: baseProjectSettingsSchema.parse(baseSettings),- shareable: readJson(- row.shareableProjectSettingsJson,- shareableProjectSettingsSchema,- 'shareable project settings'- ),- legacyConfigMigratedAt: row.legacyConfigMigratedAt,- };- }-- private async migrateLegacyConfigIfNeeded(git = this.options.git): Promise<void> {- if (this.legacyMigrationPromise) {- await this.legacyMigrationPromise;- return;- }-- this.legacyMigrationPromise = (async () => {- const row = await this.storage.get(this.projectId);- await migrateLegacyProjectSettingsIfNeeded({- projectId: this.projectId,- row,- configReader: this.configReader,- storage: this.storage,- git,- normalizeStoredWorktreeDirectory: (worktreeDirectory) =>- this.normalizeStoredWorktreeDirectory(worktreeDirectory),- });- })();-- try {- await this.legacyMigrationPromise;- } catch (error) {- this.legacyMigrationPromise = undefined;- throw error;- }- }-- async ensure(options: DbProjectSettingsProviderOptions = {}): Promise<void> {- await this.ensureRow();- await this.migrateLegacyConfigIfNeeded(options.git);- }-- async get(): Promise<ProjectSettings> {- const { base, shareable } = await this.readSettingsRow();- return projectSettingsSchema.parse({ ...base, ...shareable });- }-- async update(settings: ProjectSettings): Promise<Result<void, UpdateProjectSettingsError>> {- const parsed = projectSettingsSchema.safeParse(settings);- if (!parsed.success) {- return err({ type: 'invalid-settings' });- }-- const nextSettings = parsed.data;- const worktreeDirectoryResult = await this.validateWorktreeDirectory(- nextSettings.worktreeDirectory- );- if (!worktreeDirectoryResult.success) {- return worktreeDirectoryResult;- }- nextSettings.worktreeDirectory = worktreeDirectoryResult.data;-- const base = baseProjectSettingsSchema.parse(nextSettings);- const shareable = shareableProjectSettingsSchema.parse(nextSettings);-- try {- await this.ensure();- const row = await this.storage.get(this.projectId);- await this.storage.update(this.projectId, {- baseProjectSettingsJson: JSON.stringify(compactUndefined(base)),- shareableProjectSettingsJson: serializeShareableProjectSettings(shareable, {- previousRaw: row?.shareableProjectSettingsJson,- }),- });- return ok();- } catch (error) {- log.warn('Failed to update project settings', error);- return err({ type: 'error' });- }- }-- async patch(patch: ProjectSettingsPatch): Promise<Result<void, UpdateProjectSettingsError>> {- try {- await this.ensure();- const row = await this.storage.get(this.projectId);- const base = row- ? readJson(- row.baseProjectSettingsJson,- legacyBaseProjectSettingsSchema,- 'base project settings'- )- : await this.initialBaseProjectSettings();- const shareable = row- ? readJson(- row.shareableProjectSettingsJson,- shareableProjectSettingsSchema,- 'shareable project settings'- )- : {};-- for (const field of patch.clearShareableFields ?? []) {- SHAREABLE_FIELD_ACCESSORS[field].clear(shareable);- }-- const nextBase = baseProjectSettingsSchema.parse({- ...base,- ...(Object.hasOwn(patch, 'githubAccountId')- ? { githubAccountId: patch.githubAccountId }- : {}),- });-- await this.storage.update(this.projectId, {- baseProjectSettingsJson: JSON.stringify(compactUndefined(nextBase)),- shareableProjectSettingsJson: serializeShareableProjectSettings(shareable, {- previousRaw: row?.shareableProjectSettingsJson,- }),- });- return ok();- } catch (error) {- log.warn('Failed to clear shareable project settings', error);- return err({ type: 'error' });- }- }-- async getDefaultWorktreeDirectory(): Promise<string> {- return this.defaultWorktreeDirectory();- }-- async getWorktreeDirectory(): Promise<string> {- const settings = await this.get();- const defaultWorktreeDirectory = await this.getDefaultWorktreeDirectory();- if (settings.worktreeDirectory) {- const normalized = await this.normalizeStoredWorktreeDirectory(settings.worktreeDirectory);- if (normalized.success) {- return normalized.data;- }- log.warn('ProjectSettingsProvider: invalid worktreeDirectory, falling back to default', {- worktreeDirectory: settings.worktreeDirectory,- defaultWorktreeDirectory,- error: normalized.error.type,- });- }- return defaultWorktreeDirectory;- }-}diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/settings/sharing/project-settings-override-state.ts b/dash/apps/switchdash-desktop/src/main/core/projects/settings/sharing/project-settings-override-state.tsdeleted file mode 100644index ce7c8a68b..000000000--- a/dash/apps/switchdash-desktop/src/main/core/projects/settings/sharing/project-settings-override-state.ts+++ /dev/null@@ -1,41 +0,0 @@-import { log } from '@main/lib/logger';-import {- emptyProjectSettingsOverrideState,- SHAREABLE_PROJECT_SETTINGS_WRITE_FIELDS,- shareableProjectSettingsSchema,- type ProjectSettingsOverrideState,-} from '@shared/core/project-settings/project-settings';-import { SHAREABLE_FIELD_ACCESSORS } from '@shared/core/project-settings/project-settings-fields';-import type { ProjectSettingsResolvedTarget } from './project-settings-target-resolver';-import { CONFIG_FILE } from './workspace-config-file';--export async function computeProjectSettingsOverrideState(- targets: ProjectSettingsResolvedTarget[]-): Promise<ProjectSettingsOverrideState> {- const state = emptyProjectSettingsOverrideState();-- for (const resolved of targets) {- try {- if (!(await resolved.fs.exists(CONFIG_FILE))) continue;-- const { content } = await resolved.fs.read(CONFIG_FILE);- const parsed = shareableProjectSettingsSchema.safeParse(JSON.parse(content));- if (!parsed.success) continue;-- for (const field of SHAREABLE_PROJECT_SETTINGS_WRITE_FIELDS) {- const value = SHAREABLE_FIELD_ACCESSORS[field].displayValue(parsed.data);- if (!value) continue;-- state[field].push({- label: resolved.label,- path: resolved.path,- value,- });- }- } catch (error) {- log.warn('Failed to inspect project settings override source', error);- }- }-- return state;-}diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/settings/sharing/project-settings-target-resolver.ts b/dash/apps/switchdash-desktop/src/main/core/projects/settings/sharing/project-settings-target-resolver.tsdeleted file mode 100644index e1cd2235f..000000000--- a/dash/apps/switchdash-desktop/src/main/core/projects/settings/sharing/project-settings-target-resolver.ts+++ /dev/null@@ -1,86 +0,0 @@-import { eq } from 'drizzle-orm';-import type { FileSystemProvider } from '@main/core/fs/types';-import { db } from '@main/db/client';-import { projects as projectsTable } from '@main/db/schema';-import type {- ProjectSettingsWriteTarget,- ProjectSettingsWriteTargetOption,- WriteProjectConfigRequest,-} from '@shared/core/project-settings/project-settings';-import type { ProjectProvider } from '../../project-provider';-import { resolveWorkspace } from '../../utils';--export type ProjectSettingsResolvedTarget = ProjectSettingsWriteTargetOption & {- fs: FileSystemProvider;-};--function stripTarget(target: ProjectSettingsWriteTargetOption): ProjectSettingsWriteTarget {- if (target.type === 'project') return { type: 'project' };- if (target.type === 'session') return { type: 'session', sessionId: target.sessionId };- return { type: 'workspace', workspaceId: target.workspaceId };-}--export function stripResolvedTarget(- target: ProjectSettingsResolvedTarget-): ProjectSettingsWriteTargetOption {- const { fs: _fs, ...option } = target;- return option;-}--function targetKey(target: ProjectSettingsWriteTarget): string {- if (target.type === 'project') return 'project';- if (target.type === 'session') return `session:${target.sessionId}`;- return `workspace:${target.workspaceId}`;-}--export async function resolveAllProjectSettingsTargets(- project: ProjectProvider-): Promise<ProjectSettingsResolvedTarget[]> {- const [projectRow] = await db- .select({ name: projectsTable.name })- .from(projectsTable)- .where(eq(projectsTable.id, project.projectId))- .limit(1);-- const projectTarget: ProjectSettingsResolvedTarget = {- type: 'project',- label: projectRow?.name ?? 'Project repository',- path: project.repoPath,- fs: project.fs,- };- // Every switchdash session runs in the project root, so there are no- // session-scoped settings targets distinct from the project target.- return [projectTarget];-}--export function getProjectSettingsWriteTargets(- targets: ProjectSettingsResolvedTarget[]-): ProjectSettingsWriteTargetOption[] {- return targets.map(stripResolvedTarget);-}--export async function resolveProjectSettingsTarget(- project: ProjectProvider,- request: Pick<WriteProjectConfigRequest, 'target'>,- resolvedTargets: ProjectSettingsResolvedTarget[]-): Promise<ProjectSettingsResolvedTarget | null> {- const target = resolvedTargets.find(- (candidate) => targetKey(stripTarget(candidate)) === targetKey(request.target)- );- if (target) return target;-- if (request.target.type === 'workspace') {- const workspace = resolveWorkspace(project.projectId, request.target.workspaceId);- return workspace- ? {- type: 'workspace',- workspaceId: request.target.workspaceId,- label: 'Workspace',- path: workspace.path,- fs: workspace.fs,- }- : null;- }-- return null;-}diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/settings/sharing/share-project-settings-to-config.ts b/dash/apps/switchdash-desktop/src/main/core/projects/settings/sharing/share-project-settings-to-config.tsdeleted file mode 100644index a957a231c..000000000--- a/dash/apps/switchdash-desktop/src/main/core/projects/settings/sharing/share-project-settings-to-config.ts+++ /dev/null@@ -1,75 +0,0 @@-import { err, ok, type Result } from '@switchdash/shared';-import { log } from '@main/lib/logger';-import type { WriteProjectConfigRequest } from '@shared/core/project-settings/project-settings';-import type { UpdateProjectSettingsError } from '@shared/projects';-import type { ProjectProvider } from '../../project-provider';-import {- resolveProjectSettingsTarget,- type ProjectSettingsResolvedTarget,-} from './project-settings-target-resolver';-import {- CONFIG_FILE,- parseWorkspaceConfigObject,- patchShareableProjectSettingsFields,-} from './workspace-config-file';--function writeConfigFailed(message: string): Result<void, UpdateProjectSettingsError> {- return err({ type: 'write-config-failed', message });-}--function errorMessage(error: unknown): string {- return error instanceof Error ? error.message : String(error);-}--export async function shareProjectSettingsToConfig(- project: ProjectProvider,- request: WriteProjectConfigRequest,- resolvedTargets: ProjectSettingsResolvedTarget[]-): Promise<Result<void, UpdateProjectSettingsError>> {- try {- const target = await resolveProjectSettingsTarget(project, request, resolvedTargets);- if (!target) {- return writeConfigFailed('Could not resolve the selected working copy.');- }-- const localSettings = await project.settings.get();- let config: Record<string, unknown>;- try {- if (await target.fs.exists(CONFIG_FILE)) {- const { content } = await target.fs.read(CONFIG_FILE);- config = parseWorkspaceConfigObject(content);- } else {- config = {};- }- } catch (error) {- const message = `Could not read existing ${CONFIG_FILE}: ${errorMessage(error)}`;- log.warn('Failed to read project config before writing', error);- return writeConfigFailed(message);- }-- const writtenFields = patchShareableProjectSettingsFields(- config,- localSettings,- request.fields- );-- const writeResult = await target.fs.write(CONFIG_FILE, `${JSON.stringify(config, null, 2)}\n`);- if (!writeResult.success) {- log.warn('Failed to write project config file', writeResult.error);- return writeConfigFailed(writeResult.error ?? `Failed to write ${CONFIG_FILE}.`);- }-- const clearResult = await project.settings.patch({ clearShareableFields: writtenFields });- if (!clearResult.success) {- log.warn('Failed to clear shareable project settings', clearResult.error);- return writeConfigFailed(- `Wrote ${CONFIG_FILE}, but failed to clear shared project settings.`- );- }-- return ok();- } catch (error) {- log.warn('Failed to write project config to repo', error);- return writeConfigFailed(errorMessage(error));- }-}diff --git a/dash/apps/switchdash-desktop/src/main/core/pty/controller.ts b/dash/apps/switchdash-desktop/src/main/core/pty/controller.tsindex af3f040d9..f0a447c40 100644--- a/dash/apps/switchdash-desktop/src/main/core/pty/controller.ts+++ b/dash/apps/switchdash-desktop/src/main/core/pty/controller.ts@@ -1,12 +1,12 @@import { randomUUID } from 'node:crypto';import { basename } from 'node:path';import { err, ok } from '@switchdash/shared';+import { locationRuntimeRegistry } from '@main/core/locations/location-runtime-registry';import { sessionHooks } from '@main/core/sessions/session-hooks';import { log } from '@main/lib/logger';import { parsePtySessionId } from '@shared/core/pty/ptySessionId';import { createRPCController } from '@shared/lib/ipc/rpc';import { sessionRuntimeManager } from '../sessions/session-runtime-manager';-import { workspaceRegistry } from '../workspaces/workspace-registry';import { recordHumanInput } from './human-activity';import {cleanupExpiredDroppedBlobs,@@ -34,7 +34,6 @@ export const ptyController = createRPCController({const parsed = parsePtySessionId(sessionId);if (parsed) {sessionHooks._emit('session:input-submitted', {- projectId: parsed.projectId,sessionId: parsed.scopeId,providerId: meta.providerId,});@@ -100,6 +99,8 @@ export const ptyController = createRPCController({return err({ type: 'invalid_session' as const });}+ // Lifecycle scripts are the only PTYs stopped here (no session match) and+ // never respawn, so a raw kill is sufficient and safe.const pty = ptySessionRegistry.get(sessionId);if (pty) {try {@@ -117,7 +118,7 @@ export const ptyController = createRPCController({* and return their remote paths. Uses the SFTP subsystem of the already-* connected ssh2 client — no local ssh/scp binaries are involved.*- * The session ID encodes the project and scope (`projectId:scopeId:leafId`),+ * The session ID encodes the location and scope (`locationId:scopeId:leafId`),* where `scopeId` is a session ID for agent-session uploads.*/uploadFiles: async (args: { sessionId: string; localPaths: string[] }) => {@@ -130,15 +131,15 @@ export const ptyController = createRPCController({if (!sessionRuntimeManager.getAgent(scopeId)) return err({ type: 'not_ssh' as const });- const workspaceId = sessionRuntimeManager.getWorkspaceId(scopeId) ?? '';- const workspace = workspaceRegistry.get(workspaceId);- if (!workspace?.fs.copyLocalFile) return err({ type: 'not_ssh' as const });+ const locationId = sessionRuntimeManager.getLocationId(scopeId) ?? '';+ const runtime = locationRuntimeRegistry.get(locationId);+ if (!runtime?.fs.copyLocalFile) return err({ type: 'not_ssh' as const });const remotePaths = await Promise.all(args.localPaths.map(async (localPath) => {const remoteName = `${randomUUID()}-${basename(localPath)}`;- await workspace.fs.copyLocalFile!(localPath, remoteName);- return `${workspace.path}/${remoteName}`;+ await runtime.fs.copyLocalFile!(localPath, remoteName);+ return `${runtime.path}/${remoteName}`;}));return ok({ remotePaths });diff --git a/dash/apps/switchdash-desktop/src/main/core/pty/tmux-session-name.test.ts b/dash/apps/switchdash-desktop/src/main/core/pty/tmux-session-name.test.tsindex db5e9de60..863d240df 100644--- a/dash/apps/switchdash-desktop/src/main/core/pty/tmux-session-name.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/pty/tmux-session-name.test.ts@@ -60,9 +60,9 @@ describe('buildTmuxShellLine', () => {describe('makeAgentTmuxSessionName', () => {const sessionId = 'c1fc96ca-d642-4a5e-a392-8205391e2d11';- it('derives the pane name from the sessionId alone (no projectId)', () => {+ it('derives the pane name from the sessionId alone (no locationId)', () => {// The core CHOO-1181 guarantee: two switchdash clients with DIFFERENT local- // projectIds/scopeIds must compute the SAME tmux name for the same shared+ // locationIds/scopeIds must compute the SAME tmux name for the same shared// session, so they attach to one pane instead of each spawning a blank// one. So the name must be a pure function of the sessionId.const name = makeAgentTmuxSessionName(sessionId);diff --git a/dash/apps/switchdash-desktop/src/main/core/pty/tmux-session-name.ts b/dash/apps/switchdash-desktop/src/main/core/pty/tmux-session-name.tsindex 5097d3ea4..abd72ee70 100644--- a/dash/apps/switchdash-desktop/src/main/core/pty/tmux-session-name.ts+++ b/dash/apps/switchdash-desktop/src/main/core/pty/tmux-session-name.ts@@ -69,7 +69,7 @@ export function makeTmuxSessionName(sessionId: string): string {* the session) and is shared verbatim across every switchdash client and the* sidecar, so all of them compute the identical tmux name and attach to the* SAME pane — enabling concurrent multi-client access (CHOO-1181). It must NOT- * fold in projectId: that is a switchdash-instance-local id that differs per+ * fold in locationId: that is a switchdash-instance-local id that differs per* client, which would give each client a different pane name and silently* spawn a fresh blank session on attach.*/diff --git a/dash/apps/switchdash-desktop/src/main/core/remote-hosts/controller.ts b/dash/apps/switchdash-desktop/src/main/core/remote-hosts/controller.tsindex 13d43e331..ed937db95 100644--- a/dash/apps/switchdash-desktop/src/main/core/remote-hosts/controller.ts+++ b/dash/apps/switchdash-desktop/src/main/core/remote-hosts/controller.ts@@ -13,6 +13,7 @@ import {remoteDependencyDescriptor,} from '@main/core/dependencies/remote-dependency-manager';import { SshExecutionContext } from '@main/core/execution-context/ssh-execution-context';+import { sshConnectionIdForHost } from '@main/core/locations/location-transport';import { ptySessionRegistry } from '@main/core/pty/pty-session-registry';import { openSsh2Pty } from '@main/core/pty/ssh2-pty';import { ensureSshConnected, forceSshReconnect } from '@main/core/ssh/connect/connect-agent-ssh';@@ -22,7 +23,6 @@ import {getRemoteSwitchSetupService,type RemoteSwitchSetupService,} from '@main/core/switch-setup/remote-switch-setup';-import { agentSshConnectionId } from '@main/core/workspaces/resolve-agent-workspace';import type { ConnectionState, SshHealthState } from '@shared/core/ssh/ssh';import { createRPCController } from '@shared/lib/ipc/rpc';import type { SwitchAgentConfig } from '@shared/switch-agents';@@ -60,7 +60,7 @@ export type HostConnectionStatus = {};function hostConnectionStatus(sshHost: string): HostConnectionStatus {- const connectionId = agentSshConnectionId(sshHost);+ const connectionId = sshConnectionIdForHost(sshHost);return {state: sshConnectionManager.getConnectionState(connectionId),health: sshConnectionManager.getAllHealthStates()[connectionId] ?? { status: 'ok' },@@ -77,7 +77,7 @@ const GH_AUTH_ACCOUNT_RE = /Logged in to \S+ (?:account|as) (\S+)/;* connection is not evidence of a missing login.*/async function probeGhAuth(sshHost: string): Promise<GhAuthStatus> {- const proxy = await ensureSshConnected(agentSshConnectionId(sshHost), sshHost);+ const proxy = await ensureSshConnected(sshConnectionIdForHost(sshHost), sshHost);const ctx = new SshExecutionContext(proxy);try {const { stdout, stderr } = await ctx.exec('gh', ['auth', 'status']);@@ -91,7 +91,7 @@ async function probeGhAuth(sshHost: string): Promise<GhAuthStatus> {async function testConnection(sshHost: string): Promise<TestConnectionResult> {try {- const proxy = await ensureSshConnected(agentSshConnectionId(sshHost), sshHost);+ const proxy = await ensureSshConnected(sshConnectionIdForHost(sshHost), sshHost);const ctx = new SshExecutionContext(proxy);await ctx.exec('uname', ['-s']);return { ok: true };@@ -204,7 +204,7 @@ async function getHostSetup(sshHost: string): Promise<HostSetupStatus> {* URL in their own browser and enters the code. Returns the PTY session id.*/async function startGhAuth(sshHost: string): Promise<{ sessionId: string }> {- const proxy = await ensureSshConnected(agentSshConnectionId(sshHost), sshHost);+ const proxy = await ensureSshConnected(sshConnectionIdForHost(sshHost), sshHost);const profile = await proxy.getRemoteShellProfile();const remoteCommand = buildRemoteShellCommand(profile,@@ -247,7 +247,7 @@ export const remoteHostsController = createRPCController({* post-rebuild status.*/reconnectHost: async (sshHost: string): Promise<HostConnectionStatus> => {- await forceSshReconnect(agentSshConnectionId(sshHost), sshHost);+ await forceSshReconnect(sshConnectionIdForHost(sshHost), sshHost);return hostConnectionStatus(sshHost);},diff --git a/dash/apps/switchdash-desktop/src/main/core/resource-monitor/resource-sampler.test.ts b/dash/apps/switchdash-desktop/src/main/core/resource-monitor/resource-sampler.test.tsindex 336213183..0b7058048 100644--- a/dash/apps/switchdash-desktop/src/main/core/resource-monitor/resource-sampler.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/resource-monitor/resource-sampler.test.ts@@ -82,7 +82,7 @@ describe('resource sampler', () => {setPlatform('linux');registryState.active = [{- sessionId: 'project-1:session-1',+ sessionId: 'location-1:session-1',pid: 100,metadata: { providerId: 'amp', title: 'Amp' },},@@ -111,7 +111,7 @@ describe('resource sampler', () => {expect(pidusageMock).toHaveBeenCalledWith([100, 101, 102]);expect(snapshot.entries).toHaveLength(1);expect(snapshot.entries[0]).toMatchObject({- sessionId: 'project-1:session-1',+ sessionId: 'location-1:session-1',pid: 100,ppid: 1,cpu: 7,@@ -142,12 +142,12 @@ describe('resource sampler', () => {it('attributes separate process trees to separate active sessions', async () => {registryState.active = [{- sessionId: 'project-1:session-1',+ sessionId: 'location-1:session-1',pid: 100,metadata: { providerId: 'amp', title: 'Amp 1' },},{- sessionId: 'project-2:session-2',+ sessionId: 'location-2:session-2',pid: 200,metadata: { providerId: 'amp', title: 'Amp 2' },},@@ -166,7 +166,7 @@ describe('resource sampler', () => {expect(pidusageMock).toHaveBeenCalledWith([100, 102, 101, 200, 201]);expect(snapshot.entries).toHaveLength(2);expect(snapshot.entries[0]).toMatchObject({- sessionId: 'project-1:session-1',+ sessionId: 'location-1:session-1',pid: 100,ppid: 1,cpu: 6,@@ -174,7 +174,7 @@ describe('resource sampler', () => {title: 'Amp 1',});expect(snapshot.entries[1]).toMatchObject({- sessionId: 'project-2:session-2',+ sessionId: 'location-2:session-2',pid: 200,ppid: 1,cpu: 9,diff --git a/dash/apps/switchdash-desktop/src/main/core/resource-monitor/resource-sampler.ts b/dash/apps/switchdash-desktop/src/main/core/resource-monitor/resource-sampler.tsindex c03a0a49f..26e4a92cb 100644--- a/dash/apps/switchdash-desktop/src/main/core/resource-monitor/resource-sampler.ts+++ b/dash/apps/switchdash-desktop/src/main/core/resource-monitor/resource-sampler.ts@@ -42,7 +42,7 @@ export async function sampleOnce(): Promise<ResourceSnapshot> {if (isStaleLocalPty(a.pid, u)) continue;entries.push({sessionId: a.sessionId,- projectId: parsed.projectId,+ locationId: parsed.locationId,scopeId: parsed.scopeId,leafId: parsed.leafId,pid: a.pid,diff --git a/dash/apps/switchdash-desktop/src/main/core/runtime/types.ts b/dash/apps/switchdash-desktop/src/main/core/runtime/types.tsdeleted file mode 100644index 50d55e59d..000000000--- a/dash/apps/switchdash-desktop/src/main/core/runtime/types.ts+++ /dev/null@@ -1,5 +0,0 @@-/**- * The machine a project/workspace runs on: this machine, or an SSH host for a- * remote agent (CHOO-1059). Retained as a seam in the provider transport.- */-export type MachineRef = { kind: 'local' } | { kind: 'ssh'; host: string; connectionId: string };diff --git a/dash/apps/switchdash-desktop/src/main/core/search/location-file-index-service.ts b/dash/apps/switchdash-desktop/src/main/core/search/location-file-index-service.tsnew file mode 100644index 000000000..ddcf741d7--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/search/location-file-index-service.ts@@ -0,0 +1,209 @@+import { basename } from 'node:path';+import { fsEvents } from '@main/core/fs/fs-events';+import type { LocationRuntime } from '@main/core/locations/location-runtime';+import { locationRuntimeRegistry } from '@main/core/locations/location-runtime-registry';+import { sqlite } from '@main/db/client';+import { log } from '@main/lib/logger';++const STALE_DAYS = 14;+const MAX_FILES = 50_000;+const CRAWL_TIMEOUT_MS = 30_000;+const REINDEX_DEBOUNCE_MS = 3_000;++const CRAWL_IGNORED_DIRS = new Set([+ 'node_modules',+ '.git',+ '.svn',+ '.hg',+ 'dist',+ 'build',+ '.next',+ '.nuxt',+ 'coverage',+ '.cache',+ '.parcel-cache',+ '__pycache__',+ '.pytest_cache',+ 'venv',+ '.venv',+ 'target',+ '.terraform',+ '.serverless',+ 'worktrees',+ '.switchdash',+ '.conductor',+ '.cursor',+ '.claude',+ '.amp',+ '.codex',+ '.aider',+ '.continue',+ '.cody',+ '.windsurf',+]);++type FileHit = { path: string; filename: string };++class LocationFileIndexService {+ private crawling = new Set<string>();+ private debounceTimers = new Map<string, ReturnType<typeof setTimeout>>();++ initialize(): void {+ this.evictStale();++ fsEvents.on('watch:event', ({ locationId }) => {+ this.scheduleReindex(locationId);+ });+ }++ async onRuntimeCreated(locationId: string, runtime: LocationRuntime): Promise<void> {+ const alreadyIndexed = sqlite+ .prepare(`SELECT 1 FROM location_file_index_meta WHERE location_id = ?`)+ .get(locationId);++ if (alreadyIndexed) {+ this.touchMeta(locationId);+ return;+ }++ await this.crawl(locationId, runtime);+ }++ onRuntimeDestroyed(_locationId: string): void {+ // Intentionally a no-op: the index ages out 14 days after the last provision.+ // Calling touchMeta here would reset the staleness clock on every destroy,+ // preventing eviction of stale entries for frequently-cycled locations.+ }++ deleteIndex(locationId: string): void {+ try {+ sqlite.transaction(() => {+ sqlite.prepare(`DELETE FROM location_file_index WHERE location_id = ?`).run(locationId);+ sqlite+ .prepare(`DELETE FROM location_file_index_meta WHERE location_id = ?`)+ .run(locationId);+ })();+ log.info('LocationFileIndexService: deleted index', { locationId });+ } catch (e) {+ log.warn('LocationFileIndexService: deleteIndex failed', { locationId, error: String(e) });+ }+ }++ search(locationId: string, query: string): FileHit[] {+ const terms = query+ .trim()+ .split(/[\s\-_/]+/)+ .filter((t) => t.length >= 3);++ if (terms.length === 0) return [];++ const ftsQuery = terms.map((t) => `"${t}"`).join(' AND ');+ try {+ return sqlite+ .prepare(+ `SELECT path, filename+ FROM location_file_index+ WHERE location_file_index MATCH ?+ AND location_id = ?+ ORDER BY bm25(location_file_index, 1.0, 2.0)+ LIMIT 20`+ )+ .all(ftsQuery, locationId) as FileHit[];+ } catch (e) {+ log.warn('LocationFileIndexService: search failed', { locationId, error: String(e) });+ return [];+ }+ }++ private async crawl(locationId: string, runtime: LocationRuntime): Promise<void> {+ if (this.crawling.has(locationId)) return;+ this.crawling.add(locationId);++ try {+ const result = await runtime.fs.list('', {+ recursive: true,+ maxEntries: MAX_FILES,+ timeBudgetMs: CRAWL_TIMEOUT_MS,+ });++ const files = result.entries.filter(+ (e) => e.type === 'file' && !e.path.split('/').some((seg) => CRAWL_IGNORED_DIRS.has(seg))+ );++ sqlite.transaction(() => {+ sqlite.prepare(`DELETE FROM location_file_index WHERE location_id = ?`).run(locationId);+ const stmt = sqlite.prepare(+ `INSERT INTO location_file_index(location_id, path, filename) VALUES (?, ?, ?)`+ );+ for (const f of files) {+ stmt.run(locationId, f.path, basename(f.path));+ }+ })();++ this.touchMeta(locationId);+ log.info('LocationFileIndexService: indexed runtime', {+ locationId,+ count: files.length,+ truncated: result.truncated ?? false,+ });+ } catch (e) {+ log.warn('LocationFileIndexService: crawl failed', { locationId, error: String(e) });+ } finally {+ this.crawling.delete(locationId);+ }+ }++ private scheduleReindex(locationId: string): void {+ const existing = this.debounceTimers.get(locationId);+ if (existing) clearTimeout(existing);++ this.debounceTimers.set(+ locationId,+ setTimeout(() => {+ this.debounceTimers.delete(locationId);+ const ws = locationRuntimeRegistry.get(locationId);+ if (ws) void this.crawl(locationId, ws);+ }, REINDEX_DEBOUNCE_MS)+ );+ }++ private touchMeta(locationId: string): void {+ try {+ sqlite+ .prepare(+ `INSERT OR REPLACE INTO location_file_index_meta (location_id, indexed_at)+ VALUES (?, unixepoch())`+ )+ .run(locationId);+ } catch (e) {+ log.warn('LocationFileIndexService: touchMeta failed', { locationId, error: String(e) });+ }+ }++ private evictStale(): void {+ try {+ const cutoff = Math.floor(Date.now() / 1000) - STALE_DAYS * 86400;+ const stale = sqlite+ .prepare(`SELECT location_id FROM location_file_index_meta WHERE indexed_at < ?`)+ .all(cutoff) as Array<{ location_id: string }>;++ if (stale.length > 0) {+ sqlite.transaction(() => {+ const delIndex = sqlite.prepare(`DELETE FROM location_file_index WHERE location_id = ?`);+ const delMeta = sqlite.prepare(+ `DELETE FROM location_file_index_meta WHERE location_id = ?`+ );+ for (const row of stale) {+ delIndex.run(row.location_id);+ delMeta.run(row.location_id);+ }+ })();+ log.info('LocationFileIndexService: evicted stale indexes', { count: stale.length });+ }+ } catch (e) {+ log.warn('LocationFileIndexService: evictStale failed', { error: String(e) });+ }+ }+}++export const locationFileIndexService = new LocationFileIndexService();diff --git a/dash/apps/switchdash-desktop/src/main/core/search/search-service.ts b/dash/apps/switchdash-desktop/src/main/core/search/search-service.tsindex 93b55c947..c1eeb6da6 100644--- a/dash/apps/switchdash-desktop/src/main/core/search/search-service.ts+++ b/dash/apps/switchdash-desktop/src/main/core/search/search-service.ts@@ -1,20 +1,20 @@import { eq } from 'drizzle-orm';import { db, sqlite } from '@main/db/client';-import { agents, projects, sessions } from '@main/db/schema';+import { agents, locations, sessions } from '@main/db/schema';import { log } from '@main/lib/logger';import { ALL_COMMAND_DEFS } from '@shared/commands';+import type { Location } from '@shared/core/locations/locations';import type { CommandPaletteQuery, SearchItem, SearchItemKind } from '@shared/core/search';import type { Session } from '@shared/core/sessions/sessions';-import type { Project } from '@shared/projects';-import { projectEvents } from '../projects/project-events';+import { locationEvents } from '../locations/location-events';import { sessionHooks } from '../sessions/session-hooks';import { sessionService } from '../sessions/session-service';-import { workspaceFileIndexService } from './workspace-file-index-service';+import { locationFileIndexService } from './location-file-index-service';type FtsRow = {item_type: string;item_id: string;- project_id: string | null;+ location_id: string | null;session_id: string | null;title: string;rank: number;@@ -23,7 +23,7 @@ type FtsRow = {type RecentSessionRow = {id: string;title: string;- project_id: string;+ location_id: string;};class SearchService {@@ -36,8 +36,10 @@ class SearchService {// reconciler pruning a VM session) must also leave the index.sessionHooks.on('session:deleted', (sessionId) => this.removeByType('session', sessionId));- projectEvents.on('project:created', (project) => this.upsertProject(project));- projectEvents.on('project:deleted', (projectId) => this.removeByType('project', projectId));+ locationEvents.on('location:created', (location) => this.upsertLocation(location));+ locationEvents.on('location:deleted', (locationId) =>+ this.removeByType('location', locationId)+ );this.backfill();this.seedCommands();@@ -62,7 +64,7 @@ class SearchService {try {rows = sqlite.prepare(- `SELECT item_type, item_id, project_id, session_id, title, bm25(search_index) AS rank+ `SELECT item_type, item_id, location_id, session_id, title, bm25(search_index) AS rankFROM search_indexWHERE search_index MATCH ?ORDER BY rank@@ -77,20 +79,20 @@ class SearchService {const results: SearchItem[] = rows.map((r) => ({kind: r.item_type as SearchItemKind,id: r.item_id,- projectId: r.project_id,+ locationId: r.location_id,sessionId: r.session_id,title: r.title,subtitle: '',score: r.rank,}));- if (context?.workspaceId) {- const fileHits = workspaceFileIndexService.search(context.workspaceId, query);+ if (context?.locationId) {+ const fileHits = locationFileIndexService.search(context.locationId, query);for (const h of fileHits) {results.push({kind: 'file',id: h.path,- projectId: context.projectId ?? null,+ locationId: context.locationId ?? null,sessionId: context.sessionId ?? null,title: h.filename,subtitle: h.path,@@ -103,17 +105,17 @@ class SearchService {}private recents(context?: CommandPaletteQuery['context']): SearchItem[] {- const sessionStmt = context?.projectId+ const sessionStmt = context?.locationId? sqlite.prepare(- `SELECT s.id, s.title, a.project_id+ `SELECT s.id, s.title, a.location_idFROM sessions sJOIN agents a ON a.id = s.agent_id- WHERE s.archived_at IS NULL AND a.project_id = ?+ WHERE s.archived_at IS NULL AND a.location_id = ?ORDER BY s.last_interacted_at DESCLIMIT 10`): sqlite.prepare(- `SELECT s.id, s.title, a.project_id+ `SELECT s.id, s.title, a.location_idFROM sessions sJOIN agents a ON a.id = s.agent_idWHERE s.archived_at IS NULL@@ -124,7 +126,7 @@ class SearchService {let sessionRows: RecentSessionRow[];try {sessionRows = (- context?.projectId ? sessionStmt.all(context.projectId) : sessionStmt.all()+ context?.locationId ? sessionStmt.all(context.locationId) : sessionStmt.all()) as RecentSessionRow[];} catch (e) {log.warn('SearchService: recents query failed', { error: String(e) });@@ -134,7 +136,7 @@ class SearchService {return sessionRows.map((r) => ({kind: 'session' as const,id: r.id,- projectId: r.project_id,+ locationId: r.location_id,sessionId: null,title: r.title,subtitle: '',@@ -145,33 +147,33 @@ class SearchService {private upsertSession(session: Session): void {try {const [agent] = db- .select({ projectId: agents.projectId })+ .select({ locationId: agents.locationId }).from(agents).where(eq(agents.id, session.agentId)).all();if (!agent) return;sqlite.prepare(- `INSERT OR REPLACE INTO search_index(item_type, item_id, project_id, session_id, title, keywords)+ `INSERT OR REPLACE INTO search_index(item_type, item_id, location_id, session_id, title, keywords)VALUES ('session', ?, ?, NULL, ?, '')`)- .run(session.id, agent.projectId, session.title);+ .run(session.id, agent.locationId, session.title);} catch (e) {log.warn('SearchService: upsertSession failed', { sessionId: session.id, error: String(e) });}}- private upsertProject(project: Project): void {+ private upsertLocation(location: Location): void {try {sqlite.prepare(- `INSERT OR REPLACE INTO search_index(item_type, item_id, project_id, session_id, title, keywords)- VALUES ('project', ?, NULL, NULL, ?, ?)`+ `INSERT OR REPLACE INTO search_index(item_type, item_id, location_id, session_id, title, keywords)+ VALUES ('location', ?, NULL, NULL, ?, ?)`)- .run(project.id, project.name, project.path);+ .run(location.id, location.name, location.dir);} catch (e) {- log.warn('SearchService: upsertProject failed', {- projectId: project.id,+ log.warn('SearchService: upsertLocation failed', {+ locationId: location.id,error: String(e),});}@@ -192,7 +194,7 @@ class SearchService {sqlite.transaction(() => {sqlite.prepare(`DELETE FROM search_index WHERE item_type = 'command'`).run();const stmt = sqlite.prepare(- `INSERT INTO search_index (item_type, item_id, project_id, session_id, title, keywords)+ `INSERT INTO search_index (item_type, item_id, location_id, session_id, title, keywords)VALUES ('command', ?, NULL, NULL, ?, ?)`);for (const def of ALL_COMMAND_DEFS) {@@ -216,33 +218,33 @@ class SearchService {const allSessions = db.select({id: sessions.id,- projectId: agents.projectId,+ locationId: agents.locationId,title: sessions.title,archivedAt: sessions.archivedAt,}).from(sessions).innerJoin(agents, eq(sessions.agentId, agents.id)).all();- const allProjects = db.select().from(projects).all();+ const allLocations = db.select().from(locations).all();const upsertStmt = sqlite.prepare(- `INSERT OR REPLACE INTO search_index(item_type, item_id, project_id, session_id, title, keywords)+ `INSERT OR REPLACE INTO search_index(item_type, item_id, location_id, session_id, title, keywords)VALUES (?, ?, ?, ?, ?, ?)`);sqlite.transaction(() => {for (const t of allSessions) {if (t.archivedAt) continue;- upsertStmt.run('session', t.id, t.projectId, null, t.title, '');+ upsertStmt.run('session', t.id, t.locationId, null, t.title, '');}- for (const p of allProjects) {- upsertStmt.run('project', p.id, null, null, p.name, p.path);+ for (const l of allLocations) {+ upsertStmt.run('location', l.id, null, null, l.name, l.dir);}})();log.info('SearchService: backfilled search index', {sessions: allSessions.filter((t) => !t.archivedAt).length,- projects: allProjects.length,+ locations: allLocations.length,});} catch (e) {log.warn('SearchService: backfill failed', { error: String(e) });diff --git a/dash/apps/switchdash-desktop/src/main/core/search/workspace-file-index-service.ts b/dash/apps/switchdash-desktop/src/main/core/search/workspace-file-index-service.tsdeleted file mode 100644index 653602d4b..000000000--- a/dash/apps/switchdash-desktop/src/main/core/search/workspace-file-index-service.ts+++ /dev/null@@ -1,211 +0,0 @@-import { basename } from 'node:path';-import { fsEvents } from '@main/core/fs/fs-events';-import type { Workspace } from '@main/core/workspaces/workspace';-import { workspaceRegistry } from '@main/core/workspaces/workspace-registry';-import { sqlite } from '@main/db/client';-import { log } from '@main/lib/logger';--const STALE_DAYS = 14;-const MAX_FILES = 50_000;-const CRAWL_TIMEOUT_MS = 30_000;-const REINDEX_DEBOUNCE_MS = 3_000;--const CRAWL_IGNORED_DIRS = new Set([- 'node_modules',- '.git',- '.svn',- '.hg',- 'dist',- 'build',- '.next',- '.nuxt',- 'coverage',- '.cache',- '.parcel-cache',- '__pycache__',- '.pytest_cache',- 'venv',- '.venv',- 'target',- '.terraform',- '.serverless',- 'worktrees',- '.switchdash',- '.conductor',- '.cursor',- '.claude',- '.amp',- '.codex',- '.aider',- '.continue',- '.cody',- '.windsurf',-]);--type FileHit = { path: string; filename: string };--class WorkspaceFileIndexService {- private crawling = new Set<string>();- private debounceTimers = new Map<string, ReturnType<typeof setTimeout>>();-- initialize(): void {- this.evictStale();-- fsEvents.on('watch:event', ({ workspaceId }) => {- this.scheduleReindex(workspaceId);- });- }-- async onWorkspaceCreated(workspaceId: string, workspace: Workspace): Promise<void> {- const alreadyIndexed = sqlite- .prepare(`SELECT 1 FROM workspace_file_index_meta WHERE workspace_id = ?`)- .get(workspaceId);-- if (alreadyIndexed) {- this.touchMeta(workspaceId);- return;- }-- await this.crawl(workspaceId, workspace);- }-- onWorkspaceDestroyed(_workspaceId: string): void {- // Intentionally a no-op: the index ages out 14 days after the last provision.- // Calling touchMeta here would reset the staleness clock on every destroy,- // preventing eviction of stale entries for frequently-cycled workspaces.- }-- deleteIndex(workspaceId: string): void {- try {- sqlite.transaction(() => {- sqlite.prepare(`DELETE FROM workspace_file_index WHERE workspace_id = ?`).run(workspaceId);- sqlite- .prepare(`DELETE FROM workspace_file_index_meta WHERE workspace_id = ?`)- .run(workspaceId);- })();- log.info('WorkspaceFileIndexService: deleted index', { workspaceId });- } catch (e) {- log.warn('WorkspaceFileIndexService: deleteIndex failed', { workspaceId, error: String(e) });- }- }-- search(workspaceId: string, query: string): FileHit[] {- const terms = query- .trim()- .split(/[\s\-_/]+/)- .filter((t) => t.length >= 3);-- if (terms.length === 0) return [];-- const ftsQuery = terms.map((t) => `"${t}"`).join(' AND ');- try {- return sqlite- .prepare(- `SELECT path, filename- FROM workspace_file_index- WHERE workspace_file_index MATCH ?- AND workspace_id = ?- ORDER BY bm25(workspace_file_index, 1.0, 2.0)- LIMIT 20`- )- .all(ftsQuery, workspaceId) as FileHit[];- } catch (e) {- log.warn('WorkspaceFileIndexService: search failed', { workspaceId, error: String(e) });- return [];- }- }-- private async crawl(workspaceId: string, workspace: Workspace): Promise<void> {- if (this.crawling.has(workspaceId)) return;- this.crawling.add(workspaceId);-- try {- const result = await workspace.fs.list('', {- recursive: true,- maxEntries: MAX_FILES,- timeBudgetMs: CRAWL_TIMEOUT_MS,- });-- const files = result.entries.filter(- (e) => e.type === 'file' && !e.path.split('/').some((seg) => CRAWL_IGNORED_DIRS.has(seg))- );-- sqlite.transaction(() => {- sqlite.prepare(`DELETE FROM workspace_file_index WHERE workspace_id = ?`).run(workspaceId);- const stmt = sqlite.prepare(- `INSERT INTO workspace_file_index(workspace_id, path, filename) VALUES (?, ?, ?)`- );- for (const f of files) {- stmt.run(workspaceId, f.path, basename(f.path));- }- })();-- this.touchMeta(workspaceId);- log.info('WorkspaceFileIndexService: indexed workspace', {- workspaceId,- count: files.length,- truncated: result.truncated ?? false,- });- } catch (e) {- log.warn('WorkspaceFileIndexService: crawl failed', { workspaceId, error: String(e) });- } finally {- this.crawling.delete(workspaceId);- }- }-- private scheduleReindex(workspaceId: string): void {- const existing = this.debounceTimers.get(workspaceId);- if (existing) clearTimeout(existing);-- this.debounceTimers.set(- workspaceId,- setTimeout(() => {- this.debounceTimers.delete(workspaceId);- const ws = workspaceRegistry.get(workspaceId);- if (ws) void this.crawl(workspaceId, ws);- }, REINDEX_DEBOUNCE_MS)- );- }-- private touchMeta(workspaceId: string): void {- try {- sqlite- .prepare(- `INSERT OR REPLACE INTO workspace_file_index_meta (workspace_id, indexed_at)- VALUES (?, unixepoch())`- )- .run(workspaceId);- } catch (e) {- log.warn('WorkspaceFileIndexService: touchMeta failed', { workspaceId, error: String(e) });- }- }-- private evictStale(): void {- try {- const cutoff = Math.floor(Date.now() / 1000) - STALE_DAYS * 86400;- const stale = sqlite- .prepare(`SELECT workspace_id FROM workspace_file_index_meta WHERE indexed_at < ?`)- .all(cutoff) as Array<{ workspace_id: string }>;-- if (stale.length > 0) {- sqlite.transaction(() => {- const delIndex = sqlite.prepare(- `DELETE FROM workspace_file_index WHERE workspace_id = ?`- );- const delMeta = sqlite.prepare(- `DELETE FROM workspace_file_index_meta WHERE workspace_id = ?`- );- for (const row of stale) {- delIndex.run(row.workspace_id);- delMeta.run(row.workspace_id);- }- })();- log.info('WorkspaceFileIndexService: evicted stale indexes', { count: stale.length });- }- } catch (e) {- log.warn('WorkspaceFileIndexService: evictStale failed', { error: String(e) });- }- }-}--export const workspaceFileIndexService = new WorkspaceFileIndexService();diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/controller.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/controller.tsindex ded64abd9..d9ee2ca04 100644--- a/dash/apps/switchdash-desktop/src/main/core/sessions/controller.ts+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/controller.ts@@ -15,23 +15,23 @@ export const sessionController = createRPCController({async createSession(params: CreateSessionParams) {return sessionService.createSession(params);},- async getSessions(projectId?: string) {- return sessionService.getSessions(projectId);+ async getSessions(locationId?: string) {+ return sessionService.getSessions(locationId);},- async deleteSession(projectId: string, sessionId: string) {- return sessionService.deleteSession(projectId, sessionId);+ async deleteSession(sessionId: string) {+ return sessionService.deleteSession(sessionId);},- async deleteSessions(projectId: string, sessionIds: string[]) {- return sessionService.deleteSessions(projectId, sessionIds);+ async deleteSessions(sessionIds: string[]) {+ return sessionService.deleteSessions(sessionIds);},- async archiveSession(projectId: string, sessionId: string) {- return sessionService.archiveSession(projectId, sessionId);+ async archiveSession(sessionId: string) {+ return sessionService.archiveSession(sessionId);},async restoreSession(id: string) {return sessionService.restoreSession(id);},- async renameSession(projectId: string, sessionId: string, newTitle: string) {- return sessionService.renameSession(projectId, sessionId, newTitle);+ async renameSession(sessionId: string, newTitle: string) {+ return sessionService.renameSession(sessionId, newTitle);},async updateSessionStatus(sessionId: string, status: SessionLifecycleStatus) {return sessionService.updateSessionStatus(sessionId, status);@@ -39,14 +39,14 @@ export const sessionController = createRPCController({async setSessionPinned(sessionId: string, isPinned: boolean) {return sessionService.setSessionPinned(sessionId, isPinned);},- async teardownSession(_projectId: string, sessionId: string) {+ async teardownSession(sessionId: string) {return sessionService.teardown(sessionId, 'terminate');},async stopAgent(sessionId: string) {return sessionService.stopAgent(sessionId);},- async provisionWorkspace(sessionId: string) {- return sessionService.provisionWorkspace(sessionId);+ async provisionSession(sessionId: string) {+ return sessionService.provisionSession(sessionId);},generateSessionName,});diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/archiveSession.test.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/archiveSession.test.tsindex 34c0bc532..73861715b 100644--- a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/archiveSession.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/archiveSession.test.ts@@ -36,17 +36,17 @@ describe('archiveSession', () => {mocks.updateWhere.mockResolvedValue(undefined);});- it('archives by detaching runtime without deleting workspace assets', async () => {+ it('archives by detaching runtime without deleting location assets', async () => {mocks.selectLimit.mockResolvedValueOnce([{id: 'session-1',- workspaceId: 'workspace-1',+ locationId: 'location-1',status: 'done',},]);mocks.teardownSession.mockResolvedValue({ success: true });- await archiveSession('project-1', 'session-1');+ await archiveSession('session-1');expect(mocks.updateSet).toHaveBeenCalledWith(expect.objectContaining({diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/archiveSession.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/archiveSession.tsindex 7220b650a..14e11cbc4 100644--- a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/archiveSession.ts+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/archiveSession.ts@@ -4,7 +4,7 @@ import { db } from '@main/db/client';import { sessions } from '@main/db/schema';import { log } from '@main/lib/logger';-export async function archiveSession(projectId: string, sessionId: string): Promise<void> {+export async function archiveSession(sessionId: string): Promise<void> {const [session] = await db.select().from(sessions).where(eq(sessions.id, sessionId)).limit(1);if (!session) return;diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/createSession.test.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/createSession.test.tsindex a17062e36..af0c4c099 100644--- a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/createSession.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/createSession.test.ts@@ -4,7 +4,7 @@ import { createSession } from './createSession';const mocks = vi.hoisted(() => ({getAgentById: vi.fn(),- getProject: vi.fn(),+ getLocation: vi.fn(),insert: vi.fn(),deleteFn: vi.fn(),provisionSessionRuntime: vi.fn(),@@ -16,8 +16,8 @@ vi.mock('@main/core/agents/getAgentById', () => ({getAgentById: mocks.getAgentById,}));-vi.mock('@main/core/projects/project-manager', () => ({- projectManager: { getProject: mocks.getProject },+vi.mock('@main/core/locations/location-manager', () => ({+ locationManager: { getLocation: mocks.getLocation },}));vi.mock('@main/db/client', () => ({@@ -78,13 +78,13 @@ describe('createSession', () => {vi.clearAllMocks();mocks.getAgentById.mockResolvedValue({id: 'agent-1',- projectId: 'project-1',+ locationId: 'loc-1',providerId: 'claude',});- mocks.getProject.mockReturnValue({ projectId: 'project-1', repoPath: '/repo', ctx: {} });+ mocks.getLocation.mockReturnValue({ locationId: 'loc-1', dir: '/repo', ctx: {} });mocks.provisionSessionRuntime.mockResolvedValue({path: '/repo',- workspaceId: 'project-1',+ locationId: 'loc-1',agent: { start: mocks.startSession },});mocks.registerSession.mockResolvedValue(undefined);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 da68a8dc0..7726d80dc 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@@ -1,7 +1,7 @@import { err, ok, type Result } from '@switchdash/shared';import { eq, sql } from 'drizzle-orm';import { getAgentById } from '@main/core/agents/getAgentById';-import { projectManager } from '@main/core/projects/project-manager';+import { locationManager } from '@main/core/locations/location-manager';import { db } from '@main/db/client';import { sessions } from '@main/db/schema';import type { SessionConfig } from '@shared/core/sessions/session-config';@@ -16,9 +16,8 @@ import { mapSessionRowToSession } from '../utils/utils';/*** Eager create (decision A): inserts the session row and immediately provisions- * the runtime in the project root, then spawns the agent. There is no separate- * workspace to provision — every session runs in the project directory resolved- * via session → agent → project.+ * the runtime in the location dir, then spawns the agent. Every session runs in+ * the directory resolved via session → agent → location.*/export async function createSession(params: CreateSessionParams@@ -26,8 +25,8 @@ export async function createSession(const agent = await getAgentById(params.agentId);if (!agent) return err({ type: 'agent-not-found' });- const project = projectManager.getProject(agent.projectId);- if (!project) return err({ type: 'agent-not-found' });+ const location = locationManager.getLocation(agent.locationId);+ if (!location) return err({ type: 'agent-not-found' });const configObj: SessionConfig = {};if (params.autoApprove !== undefined) configObj.autoApprove = params.autoApprove;@@ -61,8 +60,8 @@ export async function createSession(const session = mapSessionRowToSession(row, agent.providerId);try {- const built = await provisionSessionRuntime(session, project);- await sessionRuntimeManager.registerSession(session.id, built, project.projectId, project.ctx);+ const built = await provisionSessionRuntime(session, location);+ await sessionRuntimeManager.registerSession(session.id, built, location.ctx);await built.agent.start(session, params.initialSize, false, params.initialPrompt);} catch (e) {diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/dehydrateSession.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/dehydrateSession.tsindex 289fce4d3..2f31c9b10 100644--- a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/dehydrateSession.ts+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/dehydrateSession.ts@@ -1,6 +1,6 @@-import { resolveSessionAgent } from '../../projects/utils';+import { resolveSessionAgent } from '../../locations/utils';-export async function dehydrateSession(projectId: string, sessionId: string): Promise<void> {- const agent = resolveSessionAgent(projectId, sessionId);+export async function dehydrateSession(sessionId: string): Promise<void> {+ const agent = resolveSessionAgent(sessionId);await agent?.dehydrate();}diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/deleteSession.test.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/deleteSession.test.tsindex 676dda824..d81f04f88 100644--- a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/deleteSession.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/deleteSession.test.ts@@ -3,7 +3,6 @@ import { deleteSession } from './deleteSession';const mocks = vi.hoisted(() => ({deleteWhere: vi.fn(),- getProject: vi.fn(),selectLimit: vi.fn(),teardownSession: vi.fn(),viewStateDel: vi.fn(),@@ -24,12 +23,6 @@ vi.mock('@main/db/client', () => ({},}));-vi.mock('@main/core/projects/project-manager', () => ({- projectManager: {- getProject: mocks.getProject,- },-}));-vi.mock('@main/core/sessions/session-runtime-manager', () => ({sessionRuntimeManager: {teardownSession: mocks.teardownSession,@@ -46,19 +39,20 @@ describe('deleteSession', () => {beforeEach(() => {vi.clearAllMocks();mocks.deleteWhere.mockResolvedValue(undefined);- mocks.getProject.mockReturnValue(undefined);mocks.viewStateDel.mockResolvedValue(undefined);});it('does nothing when the session does not exist', async () => {mocks.selectLimit.mockResolvedValueOnce([]);- await deleteSession('project-1', 'missing');+ await deleteSession('missing');expect(mocks.deleteWhere).not.toHaveBeenCalled();});it('deletes the session row when it exists', async () => {mocks.selectLimit.mockResolvedValueOnce([{ id: 'session-1', agentId: 'agent-1' }]);- await deleteSession('project-1', 'session-1');+ mocks.teardownSession.mockResolvedValueOnce({ success: true });+ await deleteSession('session-1');+ expect(mocks.teardownSession).toHaveBeenCalledWith('session-1', 'terminate');expect(mocks.deleteWhere).toHaveBeenCalledTimes(1);});});diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/deleteSession.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/deleteSession.tsindex 823ba5877..42f4237cd 100644--- a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/deleteSession.ts+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/deleteSession.ts@@ -1,31 +1,26 @@import { eq } from 'drizzle-orm';-import { projectManager } from '@main/core/projects/project-manager';import { sessionRuntimeManager } from '@main/core/sessions/session-runtime-manager';import { viewStateService } from '@main/core/view-state/view-state-service';import { db } from '@main/db/client';import { sessions } from '@main/db/schema';import { log } from '@main/lib/logger';-export async function deleteSession(projectId: string, sessionId: string): Promise<void> {+export async function deleteSession(sessionId: string): Promise<void> {const [session] = await db.select().from(sessions).where(eq(sessions.id, sessionId)).limit(1);if (!session) return;- const project = projectManager.getProject(projectId);+ const teardownResult = await sessionRuntimeManager+ .teardownSession(sessionId, 'terminate')+ .catch((e) => {+ log.warn('deleteSession: teardown failed', { sessionId, error: String(e) });+ return null;+ });- if (project) {- const teardownResult = await sessionRuntimeManager- .teardownSession(sessionId, 'terminate')- .catch((e) => {- log.warn('deleteSession: teardown failed', { sessionId, error: String(e) });- return null;- });-- if (teardownResult && !teardownResult.success) {- log.warn('deleteSession: teardown failed', {- sessionId,- error: teardownResult.error.message,- });- }+ if (teardownResult && !teardownResult.success) {+ log.warn('deleteSession: teardown failed', {+ sessionId,+ error: teardownResult.error.message,+ });}await db.delete(sessions).where(eq(sessions.id, sessionId));diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/getSessions.db.test.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/getSessions.db.test.tsindex 7db98a402..01a46746b 100644--- a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/getSessions.db.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/getSessions.db.test.ts@@ -23,15 +23,15 @@ describe('getSessions', () => {fixture.sqlite.prepare(- `INSERT INTO projects (id, name, path, created_at, updated_at)- VALUES ('project-1', 'Project', '/repo', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)`+ `INSERT INTO locations (id, name, ssh_host, dir, created_at, updated_at)+ VALUES ('loc-1', 'Location', '', '/repo', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)`).run();fixture.sqlite.prepare(- `INSERT INTO agents (id, project_id, name, provider_id, created_at, updated_at)- VALUES ('agent-1', 'project-1', 'Agent', 'claude', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)`+ `INSERT INTO agents (id, location_id, name, provider_id, created_at, updated_at)+ VALUES ('agent-1', 'loc-1', 'Agent', 'claude', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)`).run();});@@ -65,7 +65,7 @@ describe('getSessions', () => {).run();- const rows = await getSessions('project-1');+ const rows = await getSessions('loc-1');expect(rows).toHaveLength(1);expect(rows[0]!.title).toBe('My Session');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 6749ea263..06cc7fdcd 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@@ -4,14 +4,14 @@ import { agents, sessions } from '@main/db/schema';import { type Session } from '@shared/core/sessions/sessions';import { mapSessionRowToSession } from '../utils/utils';-export async function getSessions(projectId?: string): Promise<Session[]> {+export async function getSessions(locationId?: string): Promise<Session[]> {const base = db.select({ session: sessions, providerId: agents.providerId }).from(sessions).innerJoin(agents, eq(sessions.agentId, agents.id));- const rows = projectId- ? await base.where(eq(agents.projectId, projectId)).orderBy(desc(sessions.updatedAt))+ const rows = locationId+ ? 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));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 b987a5cb0..a3ba2a263 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@@ -1,12 +1,12 @@import { eq } from 'drizzle-orm';import { db } from '@main/db/client';import { sessions } from '@main/db/schema';-import { resolveSessionAgent } from '../../projects/utils';+import { resolveSessionAgent } from '../../locations/utils';import { loadSessionWithAgent } from '../session-join';import { mapSessionRowToSession } from '../utils/utils';-export async function hydrateSession(projectId: string, sessionId: string): Promise<void> {- const agent = resolveSessionAgent(projectId, sessionId);+export async function hydrateSession(sessionId: string): Promise<void> {+ const agent = resolveSessionAgent(sessionId);if (!agent) throw new Error('Session not found');const loaded = await loadSessionWithAgent(sessionId);diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/renameSession.test.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/renameSession.test.tsindex b2fcc01aa..c2f7efdc5 100644--- a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/renameSession.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/renameSession.test.ts@@ -63,7 +63,7 @@ describe('renameSession', () => {mockSelectRows([{ providerId: 'claude' }]);const update = mockUpdateRows([updatedRow]);- const result = await renameSession('project-1', 'session-1', 'new-title');+ const result = await renameSession('session-1', 'new-title');expect(result.success).toBe(true);if (!result.success) return;@@ -74,7 +74,7 @@ describe('renameSession', () => {it('returns session-not-found when the session does not exist', async () => {mockSelectRows([]);- const result = await renameSession('project-1', 'missing-session', 'new-title');+ const result = await renameSession('missing-session', 'new-title');expect(result).toEqual({success: false,diff --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 5ae07dd5e..a9ff8d0c8 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@@ -6,7 +6,6 @@ import { agents, sessions } from '@main/db/schema';import type { RenameSessionError, RenameSessionSuccess } from '@shared/core/sessions/sessions';export async function renameSession(- _projectId: string,sessionId: string,newTitle: string): Promise<Result<RenameSessionSuccess, RenameSessionError>> {diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/save-provider-session-id.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/save-provider-session-id.tsindex 7a1513efe..0ea57e16c 100644--- a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/save-provider-session-id.ts+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/save-provider-session-id.ts@@ -32,7 +32,6 @@ export async function saveProviderSessionId(events.emit(sessionChangedChannel, {sessionId,- projectId: loaded.projectId,changes: { providerSessionId },});}diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/provision-session-error.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/provision-session-error.tsindex 0db042dd7..cacc12fc7 100644--- a/dash/apps/switchdash-desktop/src/main/core/sessions/provision-session-error.ts+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/provision-session-error.ts@@ -1,5 +1,5 @@import type { ProvisionStep } from '@shared/core/sessions/sessionEvents';-import { TimeoutSignal } from '../projects/utils';+import { TimeoutSignal } from '../locations/utils';export const SESSION_TIMEOUT_MS = 600_000;export const TEARDOWN_SCRIPT_WAIT_MS = 10_000;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 59b66197b..0a221312f 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@@ -1,7 +1,7 @@-import { getAgentById } from '@main/core/agents/getAgentById';-import { resolveAgentWorkspace } from '@main/core/workspaces/resolve-agent-workspace';-import type { Workspace } from '@main/core/workspaces/workspace';-import { workspaceRegistry } from '@main/core/workspaces/workspace-registry';+import type { LocationProvider } from '@main/core/locations/location-provider';+import type { LocationRuntime } from '@main/core/locations/location-runtime';+import { locationRuntimeRegistry } from '@main/core/locations/location-runtime-registry';+import type { LocationTransport } from '@main/core/locations/location-transport';import { events } from '@main/lib/events';import {sessionProvisionProgressChannel,@@ -9,104 +9,78 @@ import {} from '@shared/core/sessions/sessionEvents';import type { Session } from '@shared/core/sessions/sessions';import type { AgentRuntimeProvider } from '../agent-runtime/types';-import type { ProjectProvider } from '../projects/project-provider';-import type { ProjectSettingsProvider } from '../projects/settings/provider';import {buildAgentRuntime,- createWorkspaceFactory,+ createLocationRuntimeFactory,resolveSessionEnv,- type WorkspaceType,-} from '../workspaces/workspace-factory';+} from '../locations/location-runtime-factory';+import type { LocationSettingsProvider } from '../locations/settings/provider';import { sessionProvisionEvents } from './session-provision-events';/**- * The runtime artefacts of a provisioned session. In switchdash every session- * runs in the project root directory; the "workspace" is keyed per project dir- * (decision B) and shared by all of that project's sessions.+ * The runtime artefacts of a provisioned session. Every session runs in its+ * agent's location dir; the location runtime is keyed per location and shared+ * by all sessions there.*/export type SessionRuntimeResult = {path: string;- workspaceId: string;- worktreeGitDir?: string;+ locationId: string;agent: AgentRuntimeProvider;};/**- * Provisions the runtime for a session: acquires the project-dir workspace- * (running lifecycle scripts once per project dir) and builds the session's- * agent runtime in the project root.+ * Provisions the runtime for a session: acquires the location runtime (running+ * lifecycle scripts once per location) and builds the session's agent runtime+ * in the location dir.*/export async function provisionSessionRuntime(session: Session,- project: ProjectProvider+ location: LocationProvider): Promise<SessionRuntimeResult> {- // The transport is the agent's, not the project's: a remote agent runs its- // sessions on its SSH host even though the project lives locally.- const agent = await getAgentById(session.agentId);- if (!agent) {- throw new Error(- `provisionSessionRuntime: agent ${session.agentId} not found for session ${session.id}`- );- }- const { type, workspaceId, workDir } = resolveAgentWorkspace(agent, {- projectId: project.projectId,- repoPath: project.repoPath,- });+ const locationId = location.locationId;+ const transport = location.transport;+ const workDir = location.dir;emitSessionProvisionProgress({sessionId: session.id,- projectId: project.projectId,- step: 'initialising-workspace',- message: 'Initialising workspace…',+ step: 'initialising-location',+ message: 'Initialising location…',});- const workspace = await workspaceRegistry.acquire(- workspaceId,- project.projectId,- createWorkspaceFactory(workspaceId, type, {+ const runtime = await locationRuntimeRegistry.acquire(+ locationId,+ createLocationRuntimeFactory(locationId, transport, {session,workDir,- projectId: project.projectId,- projectPath: project.repoPath,- settings: project.settings,+ settings: location.settings,logPrefix: 'provisionSessionRuntime',}));emitSessionProvisionProgress({sessionId: session.id,- projectId: project.projectId,step: 'starting-sessions',message: 'Preparing session…',});let buildSucceeded = false;try {- const runtime = await buildSessionFromWorkspace(- session,- workspace,- type,- project.projectId,- project.repoPath,- project.settings- );+ const agent = await buildSessionFromRuntime(session, runtime, transport, location.settings);buildSucceeded = true;return {path: workDir,- workspaceId,- worktreeGitDir: undefined,- agent: runtime,+ locationId,+ agent,};} finally {if (!buildSucceeded) {- await workspaceRegistry.release(workspaceId, 'terminate').catch(() => {});+ await locationRuntimeRegistry.release(locationId, 'terminate').catch(() => {});}}}export function emitSessionProvisionProgress(data: {sessionId: string;- projectId: string;step: ProvisionStep;message: string;}): void {@@ -116,27 +90,24 @@ export function emitSessionProvisionProgress(data: {/*** Shared tail of the provision flow — builds the session's agent runtime from- * an already-acquired workspace. Works for both local and SSH transports.+ * an already-acquired location runtime. Works for both local and SSH transports.*/-export async function buildSessionFromWorkspace(+export async function buildSessionFromRuntime(session: Session,- workspace: Workspace,- type: WorkspaceType,- projectId: string,- projectPath: string,- settings: ProjectSettingsProvider+ runtime: LocationRuntime,+ transport: LocationTransport,+ settings: LocationSettingsProvider): Promise<AgentRuntimeProvider> {const { sessionEnvVars, tmuxEnabled, shellSetup } = await resolveSessionEnv(session,- workspace,- projectPath,+ runtime,settings);- return buildAgentRuntime(type, {- projectId,+ return buildAgentRuntime(transport, {+ locationId: runtime.id,sessionId: session.id,- sessionPath: workspace.path,+ sessionPath: runtime.path,tmuxEnabled,shellSetup,sessionEnvVars,diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/session-hooks.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/session-hooks.tsindex b59dbbdab..6285c464d 100644--- a/dash/apps/switchdash-desktop/src/main/core/sessions/session-hooks.ts+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/session-hooks.ts@@ -19,7 +19,7 @@ export type SessionHookMap = {* row does not linger and get re-attached into a blank tmux session.*/'session:remote-terminated': (params: {- projectId: string;+ locationId: string;sessionId: string;terminatedSessionId: string;}) => void | Promise<void>;@@ -29,7 +29,6 @@ export type SessionHookMap = {*/'session:agent-exited': (params: { sessionId: string }) => void | Promise<void>;'session:input-submitted': (params: {- projectId: string;sessionId: string;providerId: AgentProviderId;}) => void | Promise<void>;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 f0e1c0e33..8f817c8ea 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@@ -5,23 +5,23 @@ import type { AgentProviderId } from '@shared/core/providers/agent-provider-regiexport type SessionWithAgent = {row: SessionRow;- projectId: string;+ locationId: string;providerId: AgentProviderId;};/*** Loads a session row joined with its owning agent, exposing the agent's- * `projectId` and `providerId` (denormalised onto the session view).+ * `locationId` and `providerId` (denormalised onto the session view).*/export async function loadSessionWithAgent(sessionId: string): Promise<SessionWithAgent | undefined> {const [joined] = await db- .select({ session: sessions, projectId: agents.projectId, providerId: agents.providerId })+ .select({ session: sessions, locationId: agents.locationId, providerId: agents.providerId }).from(sessions).innerJoin(agents, eq(sessions.agentId, agents.id)).where(eq(sessions.id, sessionId)).limit(1);if (!joined) return undefined;- return { row: joined.session, projectId: joined.projectId, providerId: joined.providerId };+ return { row: joined.session, locationId: joined.locationId, providerId: joined.providerId };}diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/session-provision-events.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/session-provision-events.tsindex a769e1f9a..37733c3b5 100644--- a/dash/apps/switchdash-desktop/src/main/core/sessions/session-provision-events.ts+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/session-provision-events.ts@@ -4,7 +4,6 @@ import type { ProvisionStep } from '@shared/core/sessions/sessionEvents';type SessionProvisionProgress = {sessionId: string;- projectId: string;step: ProvisionStep;message: string;};diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/session-runtime-manager.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/session-runtime-manager.tsindex e8b85bc6a..d96eab38c 100644--- a/dash/apps/switchdash-desktop/src/main/core/sessions/session-runtime-manager.ts+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/session-runtime-manager.ts@@ -1,15 +1,16 @@import { ok, type Result } from '@switchdash/shared';import type { AgentRuntimeProvider } from '@main/core/agent-runtime/types';import type { IExecutionContext } from '@main/core/execution-context/types';+import {+ locationRuntimeRegistry,+ type TeardownMode,+} from '@main/core/locations/location-runtime-registry';import { killTmuxSession, makeAgentTmuxSessionName } from '@main/core/pty/tmux-session-name';import type { SessionRuntimeResult } from '@main/core/sessions/session-builder';-import { workspaceRegistry, type TeardownMode } from '@main/core/workspaces/workspace-registry';import { LifecycleMap } from '@main/lib/lifecycle-map';import { log } from '@main/lib/logger';import type { SessionBootstrapStatus } from '@shared/core/sessions/sessions';-import type { WorkspaceType as SharedWorkspaceType } from '@shared/core/workspaces/workspaces';-import type { ProvisionResult } from '../projects/project-provider';-import { withTimeout } from '../projects/utils';+import { withTimeout } from '../locations/utils';import {formatProvisionSessionError,formatTeardownSessionError,@@ -19,17 +20,15 @@ import {type TeardownSessionError,} from './provision-session-error';-export type WorkspaceHint = {- id: string;- type: SharedWorkspaceType;- path?: string;+type StoredSession = {+ agent: AgentRuntimeProvider;+ locationId: string;+ ctx: IExecutionContext;};-type StoredSession = ProvisionResult & { projectId: string; ctx: IExecutionContext };-async function executeTeardown(agent: AgentRuntimeProvider,- workspaceId: string,+ locationId: string,mode: TeardownMode): Promise<void> {if (mode === 'detach') {@@ -37,14 +36,10 @@ async function executeTeardown(} else {await agent.destroy();}- await workspaceRegistry.release(workspaceId, mode);+ await locationRuntimeRegistry.release(locationId, mode);}-async function cleanupDetachedSessions(- _projectId: string,- sessionId: string,- ctx: IExecutionContext-): Promise<void> {+async function cleanupDetachedSessions(sessionId: string, ctx: IExecutionContext): Promise<void> {// The agent pane is keyed on the shared session id, so all clients converge// on one tmux session.await killTmuxSession(ctx, makeAgentTmuxSessionName(sessionId));@@ -57,10 +52,10 @@ class SessionRuntimeManager {TeardownSessionError>({postTeardown: (sessionId, stored) => {- this._sessionsByProject.get(stored.projectId)?.delete(sessionId);+ this._sessionsByLocation.get(stored.locationId)?.delete(sessionId);},});- private readonly _sessionsByProject = new Map<string, Set<string>>();+ private readonly _sessionsByLocation = new Map<string, Set<string>>();/*** Registers a fully-provisioned session into the lifecycle map.@@ -69,61 +64,50 @@ class SessionRuntimeManager {async registerSession(sessionId: string,result: SessionRuntimeResult,- projectId: string,ctx: IExecutionContext): Promise<void> {const stored: StoredSession = {agent: result.agent,- persistData: {- workspaceId: result.workspaceId,- worktreeGitDir: result.worktreeGitDir,- },- projectId,+ locationId: result.locationId,ctx,};// Use provision() for deduplication: if already active, returns existing immediately.await this._lifecycle.provision(sessionId, async () => ok(stored));- const byProject = this._sessionsByProject.get(projectId) ?? new Set<string>();- byProject.add(sessionId);- this._sessionsByProject.set(projectId, byProject);+ const byLocation = this._sessionsByLocation.get(result.locationId) ?? new Set<string>();+ byLocation.add(sessionId);+ this._sessionsByLocation.set(result.locationId, byLocation);}async teardownSession(sessionId: string,mode: TeardownMode = 'terminate'): Promise<Result<void, TeardownSessionError>> {- const result = this._lifecycle.teardown(- sessionId,- async ({ agent, persistData, projectId, ctx }) => {- try {- await withTimeout(- executeTeardown(agent, persistData.workspaceId, mode),- SESSION_TIMEOUT_MS- );- return ok();- } catch (e) {- log.error('SessionManager: failed to teardown session', { sessionId, error: String(e) });- await cleanupDetachedSessions(projectId, sessionId, ctx).catch((cleanupError) => {- log.warn('SessionManager: fallback cleanup failed', {- sessionId,- error: String(cleanupError),- });+ const result = this._lifecycle.teardown(sessionId, async ({ agent, locationId, ctx }) => {+ try {+ await withTimeout(executeTeardown(agent, locationId, mode), SESSION_TIMEOUT_MS);+ return ok();+ } catch (e) {+ log.error('SessionManager: failed to teardown session', { sessionId, error: String(e) });+ await cleanupDetachedSessions(sessionId, ctx).catch((cleanupError) => {+ log.warn('SessionManager: fallback cleanup failed', {+ sessionId,+ error: String(cleanupError),});- return { success: false as const, error: toTeardownError(e) };- }+ });+ return { success: false as const, error: toTeardownError(e) };}- );+ });return result ?? ok();}- async teardownAllForProject(projectId: string, mode: TeardownMode): Promise<void> {- const sessionIds = Array.from(this._sessionsByProject.get(projectId) ?? []);+ async teardownAllForLocation(locationId: string, mode: TeardownMode): Promise<void> {+ const sessionIds = Array.from(this._sessionsByLocation.get(locationId) ?? []);if (mode === 'detach') {- // Detach sessions but leave workspaces alive; provider.cleanup() will call- // workspaceRegistry.releaseAllForProject to handle workspace teardown.+ // Detach sessions but leave the location runtime alive; the provider's+ // dispose() releases it via locationRuntimeRegistry.releaseAll.await Promise.all(sessionIds.flatMap((id) => {const stored = this._lifecycle.get(id);@@ -131,15 +115,15 @@ class SessionRuntimeManager {return [stored.agent.detach()];}));- // Remove entries from lifecycle maps without running workspace teardown.- this._sessionsByProject.delete(projectId);+ // Remove entries from lifecycle maps without running runtime teardown.+ this._sessionsByLocation.delete(locationId);await Promise.all(sessionIds.map((id) => this._lifecycle.teardown(id, async () => ok()) ?? Promise.resolve(ok())));} else {- // teardownSession handles _sessionsByProject cleanup in onFinally.+ // teardownSession handles _sessionsByLocation cleanup in postTeardown.await Promise.all(sessionIds.map((id) => this.teardownSession(id, 'terminate')));}}@@ -149,12 +133,8 @@ class SessionRuntimeManager {return this._lifecycle.get(sessionId)?.agent;}- getWorkspaceId(sessionId: string): string | undefined {- return this._lifecycle.get(sessionId)?.persistData.workspaceId;- }-- getPersistData(sessionId: string): ProvisionResult['persistData'] | undefined {- return this._lifecycle.get(sessionId)?.persistData;+ getLocationId(sessionId: string): string | undefined {+ return this._lifecycle.get(sessionId)?.locationId;}getBootstrapStatus(sessionId: string): SessionBootstrapStatus {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 6bfa88865..6a294b4cf 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@@ -1,7 +1,7 @@import { ok, type Result } from '@switchdash/shared';import { eq, sql } from 'drizzle-orm';import { getAgentById } from '@main/core/agents/getAgentById';-import { projectManager } from '@main/core/projects/project-manager';+import { locationManager } from '@main/core/locations/location-manager';import { db } from '@main/db/client';import { sessions } from '@main/db/schema';import { events } from '@main/lib/events';@@ -34,15 +34,15 @@ import { mapSessionRowToSession } from './utils/utils';export type ProvisionResult = {path: string;- workspaceId: string;+ locationId: string;};export type SessionLifecycleHooks = {'session:created': (session: Session, params: CreateSessionParams) => void | Promise<void>;'session:updated': (session: Session) => void | Promise<void>;- 'session:archived': (sessionId: string, projectId: string) => void | Promise<void>;- 'session:deleted': (sessionId: string, projectId: string) => void | Promise<void>;- 'session:workspace-ready': (sessionId: string, result: ProvisionResult) => void | Promise<void>;+ 'session:archived': (sessionId: string) => void | Promise<void>;+ 'session:deleted': (sessionId: string) => void | Promise<void>;+ 'session:runtime-ready': (sessionId: string, result: ProvisionResult) => void | Promise<void>;};export class SessionService implements Hookable<SessionLifecycleHooks> {@@ -72,73 +72,60 @@ export class SessionService implements Hookable<SessionLifecycleHooks> {}/**- * Provisions the runtime for a session: builds the agent runtime- * in the project root and registers the session. Idempotent —- * fast-paths when already live. Fires the `session:workspace-ready` hook and+ * Provisions the runtime for a session: builds the agent runtime in the+ * location root and registers the session. Idempotent — fast-paths when+ * already live. Fires the `session:runtime-ready` hook and* emits the `session:provisioned` IPC event on success.*/- async provisionWorkspace(+ async provisionSession(sessionId: string): Promise<Result<ProvisionResult, TeardownSessionError>> {const session = await this._loadSession(sessionId);- const project = projectManager.getProject(session.agentProjectId);- if (!project) throw new Error(`Project not found: ${session.agentProjectId}`);+ const location = locationManager.getLocation(session.agentLocationId);+ if (!location) throw new Error(`Location not open: ${session.agentLocationId}`);// Idempotency: session is already live — return current state.if (sessionRuntimeManager.getAgent(sessionId)) {- const pd = sessionRuntimeManager.getPersistData(sessionId);const provisionResult: ProvisionResult = {- path: project.repoPath,- workspaceId: pd?.workspaceId ?? project.projectId,+ path: location.dir,+ locationId: sessionRuntimeManager.getLocationId(sessionId) ?? location.locationId,};- this._hooks.callHookBackground('session:workspace-ready', sessionId, provisionResult);- events.emit(sessionProvisionedChannel, {- sessionId,- projectId: project.projectId,- ...provisionResult,- });+ this._hooks.callHookBackground('session:runtime-ready', sessionId, provisionResult);+ events.emit(sessionProvisionedChannel, { sessionId, ...provisionResult });return ok(provisionResult);}- const built = await provisionSessionRuntime(session.session, project);- await this._registerAndPersist(sessionId, project.projectId, built);+ const built = await provisionSessionRuntime(session.session, location);+ await this._registerAndPersist(sessionId, built);- const provisionResult: ProvisionResult = { path: built.path, workspaceId: built.workspaceId };- this._hooks.callHookBackground('session:workspace-ready', sessionId, provisionResult);- events.emit(sessionProvisionedChannel, {- sessionId,- projectId: project.projectId,- ...provisionResult,- });+ const provisionResult: ProvisionResult = { path: built.path, locationId: built.locationId };+ this._hooks.callHookBackground('session:runtime-ready', sessionId, provisionResult);+ events.emit(sessionProvisionedChannel, { sessionId, ...provisionResult });return ok(provisionResult);}async launch(sessionId: string): Promise<Result<ProvisionResult, TeardownSessionError>> {- return this.provisionWorkspace(sessionId);+ return this.provisionSession(sessionId);}private async _loadSession(sessionId: string- ): Promise<{ session: Session; agentProjectId: string }> {+ ): Promise<{ session: Session; agentLocationId: string }> {const [row] = await db.select().from(sessions).where(eq(sessions.id, sessionId)).limit(1);if (!row) throw new Error(`Session not found: ${sessionId}`);const agent = await getAgentById(row.agentId);if (!agent) throw new Error(`Agent not found: ${row.agentId}`);return {session: mapSessionRowToSession(row, agent.providerId),- agentProjectId: agent.projectId,+ agentLocationId: agent.locationId,};}- private async _registerAndPersist(- sessionId: string,- projectId: string,- data: SessionRuntimeResult- ): Promise<void> {- const project = projectManager.getProject(projectId);- if (!project) throw new Error(`Project not found: ${projectId}`);+ private async _registerAndPersist(sessionId: string, data: SessionRuntimeResult): Promise<void> {+ const location = locationManager.getLocation(data.locationId);+ if (!location) throw new Error(`Location not open: ${data.locationId}`);- await sessionRuntimeManager.registerSession(sessionId, data, projectId, project.ctx);+ await sessionRuntimeManager.registerSession(sessionId, data, location.ctx);await db.update(sessions)@@ -165,19 +152,19 @@ export class SessionService implements Hookable<SessionLifecycleHooks> {await agent.stop();}- async deleteSession(projectId: string, sessionId: string): Promise<void> {- await deleteSession(projectId, sessionId);- this._hooks.callHookBackground('session:deleted', sessionId, projectId);+ async deleteSession(sessionId: string): Promise<void> {+ await deleteSession(sessionId);+ this._hooks.callHookBackground('session:deleted', sessionId);}- async deleteSessions(projectId: string, sessionIds: string[]): Promise<void> {- await Promise.all(sessionIds.map((id) => deleteSession(projectId, id)));- sessionIds.forEach((id) => this._hooks.callHookBackground('session:deleted', id, projectId));+ async deleteSessions(sessionIds: string[]): Promise<void> {+ await Promise.all(sessionIds.map((id) => deleteSession(id)));+ sessionIds.forEach((id) => this._hooks.callHookBackground('session:deleted', id));}- async archiveSession(projectId: string, sessionId: string): Promise<void> {- await archiveSession(projectId, sessionId);- this._hooks.callHookBackground('session:archived', sessionId, projectId);+ async archiveSession(sessionId: string): Promise<void> {+ await archiveSession(sessionId);+ this._hooks.callHookBackground('session:archived', sessionId);}async restoreSession(id: string): Promise<void> {@@ -186,11 +173,10 @@ export class SessionService implements Hookable<SessionLifecycleHooks> {}async renameSession(- projectId: string,sessionId: string,newTitle: string): Promise<Result<RenameSessionSuccess, RenameSessionError>> {- const result = await renameSession(projectId, sessionId, newTitle);+ const result = await renameSession(sessionId, newTitle);if (result.success) this._hooks.callHookBackground('session:updated', result.data.session);return result;}diff --git a/dash/apps/switchdash-desktop/src/main/core/settings/schema.ts b/dash/apps/switchdash-desktop/src/main/core/settings/schema.tsindex 8de1a608e..e4c819213 100644--- a/dash/apps/switchdash-desktop/src/main/core/settings/schema.ts+++ b/dash/apps/switchdash-desktop/src/main/core/settings/schema.ts@@ -10,12 +10,12 @@ import { openInAppIdSchema } from '@shared/openInApps';import { APP_SHORTCUTS } from '@shared/shortcuts';import { DEFAULT_AGENT_ID } from './settings-registry';-export const projectSettingsSchema = z.object({+export const locationSettingsSchema = z.object({tmuxByDefault: z.boolean(),});-export const localProjectSettingsSchema = z.object({- defaultProjectsDirectory: z.string(),+export const localLocationSettingsSchema = z.object({+ defaultLocationsDirectory: z.string(),defaultWorktreeDirectory: z.string(),writeAgentConfigToGitIgnore: z.boolean(),});@@ -133,8 +133,8 @@ export const openInSettingsSchema = z.object({});export const APP_SETTINGS_SCHEMA_MAP = {- localProject: localProjectSettingsSchema,- project: projectSettingsSchema,+ localLocation: localLocationSettingsSchema,+ location: locationSettingsSchema,sessions: sessionSettingsSchema,agentAutoApproveDefaults: agentAutoApproveDefaultsSchema,defaultAgent: defaultAgentSchema,@@ -151,8 +151,8 @@ export const APP_SETTINGS_SCHEMA_MAP = {} as const;export const appSettingsSchema = z.object({- localProject: localProjectSettingsSchema,- project: projectSettingsSchema,+ localLocation: localLocationSettingsSchema,+ location: locationSettingsSchema,sessions: sessionSettingsSchema,agentAutoApproveDefaults: agentAutoApproveDefaultsSchema,defaultAgent: defaultAgentSchema,diff --git a/dash/apps/switchdash-desktop/src/main/core/settings/settings-registry.ts b/dash/apps/switchdash-desktop/src/main/core/settings/settings-registry.tsindex 1b89caef0..401d33228 100644--- a/dash/apps/switchdash-desktop/src/main/core/settings/settings-registry.ts+++ b/dash/apps/switchdash-desktop/src/main/core/settings/settings-registry.ts@@ -13,11 +13,11 @@ type SettingsDefaultsMap = {};export const SETTINGS_DEFAULTS = {- project: {+ location: {tmuxByDefault: false,},- localProject: () => ({- defaultProjectsDirectory: join(homedir(), 'switchdash', 'repositories'),+ localLocation: () => ({+ defaultLocationsDirectory: join(homedir(), 'switchdash', 'repositories'),defaultWorktreeDirectory: getDefaultLocalWorktreeDirectory(),writeAgentConfigToGitIgnore: true,}),diff --git a/dash/apps/switchdash-desktop/src/main/core/settings/worktree-defaults.ts b/dash/apps/switchdash-desktop/src/main/core/settings/worktree-defaults.tsindex 0a7e47a0b..7f802d6f2 100644--- a/dash/apps/switchdash-desktop/src/main/core/settings/worktree-defaults.ts+++ b/dash/apps/switchdash-desktop/src/main/core/settings/worktree-defaults.ts@@ -3,12 +3,12 @@ import path from 'node:path';export const WORKTREE_POOL_DIR_NAME = 'worktrees';export const LOCAL_WORKTREE_ROOT_DIR_NAME = 'switchdash';-export const SSH_PROJECT_STATE_DIR_NAME = '.switchdash';+export const SSH_LOCATION_STATE_DIR_NAME = '.switchdash';export function getDefaultLocalWorktreeDirectory(homeDirectory: string = homedir()): string {return path.join(homeDirectory, LOCAL_WORKTREE_ROOT_DIR_NAME, WORKTREE_POOL_DIR_NAME);}-export function getDefaultSshWorktreeDirectory(projectPath: string): string {- return path.posix.join(projectPath, SSH_PROJECT_STATE_DIR_NAME, WORKTREE_POOL_DIR_NAME);+export function getDefaultSshWorktreeDirectory(rootPath: string): string {+ return path.posix.join(rootPath, SSH_LOCATION_STATE_DIR_NAME, WORKTREE_POOL_DIR_NAME);}diff --git a/dash/apps/switchdash-desktop/src/main/core/subagents/controller.ts b/dash/apps/switchdash-desktop/src/main/core/subagents/controller.tsindex d2cf7a745..50214268c 100644--- a/dash/apps/switchdash-desktop/src/main/core/subagents/controller.ts+++ b/dash/apps/switchdash-desktop/src/main/core/subagents/controller.ts@@ -16,7 +16,7 @@ import {type RegisterSubagentsParams,type RegisterSubagentsRemoteParams,} from './register-subagents';-import { openRemoteSubagentFs, resolveSubagentWorkspace } from './resolve-workspace';+import { openRemoteSubagentFs, resolveSubagentFs } from './resolve-subagent-fs';import {getSubagentAutoSession,setSubagentAutoSession,@@ -65,13 +65,13 @@ async function readDefinition(params: {parentAgentId: string;name: string;}): Promise<SubagentAttributes | null> {- const workspace = await resolveSubagentWorkspace(params.parentAgentId);+ const ctx = await resolveSubagentFs(params.parentAgentId);try {- const subagents = getPlugin(workspace.agent.providerId).behavior.subagents;+ const subagents = getPlugin(ctx.agent.providerId).behavior.subagents;if (!subagents) return null;- return await subagents.readDefinition(workspace.fs, params.name);+ return await subagents.readDefinition(ctx.fs, params.name);} finally {- workspace.close();+ ctx.close();}}diff --git a/dash/apps/switchdash-desktop/src/main/core/subagents/create-subagent.test.ts b/dash/apps/switchdash-desktop/src/main/core/subagents/create-subagent.test.tsindex a335f6fa5..5b09cd7b4 100644--- a/dash/apps/switchdash-desktop/src/main/core/subagents/create-subagent.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/subagents/create-subagent.test.ts@@ -3,14 +3,16 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';const getPlugin = vi.hoisted(() => vi.fn());const getServer = vi.hoisted(() => vi.fn());const registerSubagentsCore = vi.hoisted(() => vi.fn());-const resolveSubagentWorkspace = vi.hoisted(() => vi.fn());+const resolveSubagentFs = vi.hoisted(() => vi.fn());const applyLocalSubagentAutoSessionState = vi.hoisted(() => vi.fn(async () => {}));+const getRemoteAgentLocation = vi.hoisted(() => vi.fn(async () => null));const logWarn = vi.hoisted(() => vi.fn());vi.mock('@main/core/providers/plugin-registry', () => ({ getPlugin }));vi.mock('@main/core/switch-servers/servers-store', () => ({ getServer }));+vi.mock('@main/core/agents/agent-location', () => ({ getRemoteAgentLocation }));vi.mock('./register-subagents', () => ({ registerSubagentsCore }));-vi.mock('./resolve-workspace', () => ({ resolveSubagentWorkspace }));+vi.mock('./resolve-subagent-fs', () => ({ resolveSubagentFs }));vi.mock('./setSubagentAutoSession', () => ({ applyLocalSubagentAutoSessionState }));vi.mock('@main/lib/logger', () => ({ log: { warn: logWarn, error: vi.fn() } }));@@ -22,8 +24,8 @@ const behavior = {removeLocal: vi.fn(async () => {}),};-function mockWorkspace(agent: Record<string, unknown>) {- resolveSubagentWorkspace.mockResolvedValue({ agent, fs: {}, close: vi.fn() });+function mockSubagentFs(agent: Record<string, unknown>) {+ resolveSubagentFs.mockResolvedValue({ agent, fs: {}, close: vi.fn() });}const LOCAL_PARENT = {@@ -31,7 +33,7 @@ const LOCAL_PARENT = {providerId: 'claude',serverId: 'srv-1',switchAgentId: 'sw-parent',- connection: 'local',+ locationId: 'loc-1',};const PARAMS = {@@ -46,10 +48,11 @@ describe('createSubagent', () => {getServer.mockResolvedValue({ id: 'srv-1', apiUrl: 'https://switch.example.com' });behavior.readDefinition.mockResolvedValue(null);registerSubagentsCore.mockResolvedValue({ registered: ['code-reviewer'] });+ getRemoteAgentLocation.mockResolvedValue(null);});it('registers with auto_session on and starts the watcher for a local parent', async () => {- mockWorkspace(LOCAL_PARENT);+ mockSubagentFs(LOCAL_PARENT);const result = await createSubagent(PARAMS);@@ -69,7 +72,15 @@ describe('createSubagent', () => {});it('registers with auto_session off and starts no watcher for a remote parent', async () => {- mockWorkspace({ ...LOCAL_PARENT, connection: 'remote' });+ mockSubagentFs(LOCAL_PARENT);+ getRemoteAgentLocation.mockResolvedValueOnce({+ id: 'loc-remote',+ name: 'r',+ sshHost: 'vm',+ dir: '/home/dev/r',+ createdAt: '',+ updatedAt: '',+ } as never);await createSubagent(PARAMS);@@ -80,7 +91,7 @@ describe('createSubagent', () => {});it('does not fail creation when starting the watcher fails', async () => {- mockWorkspace(LOCAL_PARENT);+ mockSubagentFs(LOCAL_PARENT);applyLocalSubagentAutoSessionState.mockRejectedValueOnce(new Error('watcher boom'));const result = await createSubagent(PARAMS);@@ -93,7 +104,7 @@ describe('createSubagent', () => {});it('removes the written definition when registration fails', async () => {- mockWorkspace(LOCAL_PARENT);+ mockSubagentFs(LOCAL_PARENT);registerSubagentsCore.mockRejectedValueOnce(new Error('gateway boom'));await expect(createSubagent(PARAMS)).rejects.toThrow('gateway boom');diff --git a/dash/apps/switchdash-desktop/src/main/core/subagents/create-subagent.ts b/dash/apps/switchdash-desktop/src/main/core/subagents/create-subagent.tsindex 59693d11d..44781ddc0 100644--- a/dash/apps/switchdash-desktop/src/main/core/subagents/create-subagent.ts+++ b/dash/apps/switchdash-desktop/src/main/core/subagents/create-subagent.ts@@ -1,9 +1,10 @@import type { SubagentAttributes } from '@switchdash/core/agents/plugins';+import { getRemoteAgentLocation } from '@main/core/agents/agent-location';import { getPlugin } from '@main/core/providers/plugin-registry';import { getServer } from '@main/core/switch-servers/servers-store';import { log } from '@main/lib/logger';import { registerSubagentsCore } from './register-subagents';-import { resolveSubagentWorkspace } from './resolve-workspace';+import { resolveSubagentFs } from './resolve-subagent-fs';import { applyLocalSubagentAutoSessionState } from './setSubagentAutoSession';export type CreateSubagentParams = {@@ -34,9 +35,9 @@ export async function createSubagent(params: CreateSubagentParams): Promise<{ naif (!name) throw new Error('A subagent name is required.');if (!description) throw new Error('A subagent description is required.');- const workspace = await resolveSubagentWorkspace(params.parentAgentId);+ const ctx = await resolveSubagentFs(params.parentAgentId);try {- const { agent } = workspace;+ const { agent } = ctx;const behavior = getPlugin(agent.providerId).behavior.subagents;if (!behavior) {throw new Error(`Provider ${agent.providerId} does not support subagents.`);@@ -48,15 +49,15 @@ export async function createSubagent(params: CreateSubagentParams): Promise<{ nathrow new Error(`Agent ${params.parentAgentId} has no Switch identity.`);}- if (await behavior.readDefinition(workspace.fs, name)) {+ if (await behavior.readDefinition(ctx.fs, name)) {throw new Error(`A subagent named "${name}" already exists.`);}- await behavior.writeDefinition(workspace.fs, params.attributes);+ await behavior.writeDefinition(ctx.fs, params.attributes);// Subagents of remote parents register with auto_session off: neither the- // local watcher (no project path) nor the on-VM sidecar watches subagents.- const autoSession = agent.connection !== 'remote';+ // local watcher (no local dir) nor the on-VM sidecar watches subagents.+ const autoSession = (await getRemoteAgentLocation(agent)) === null;try {const server = await getServer(agent.serverId);if (!server) throw new Error(`No Switch server with id ${agent.serverId}`);@@ -64,12 +65,12 @@ export async function createSubagent(params: CreateSubagentParams): Promise<{ nabehavior,server,parentSwitchAgentId: agent.switchAgentId,- fs: workspace.fs,+ fs: ctx.fs,subagents: [{ name, description }],autoSession,});} catch (error) {- await behavior.removeLocal(workspace.fs, name);+ await behavior.removeLocal(ctx.fs, name);throw error;}@@ -88,6 +89,6 @@ export async function createSubagent(params: CreateSubagentParams): Promise<{ nareturn { name };} finally {- workspace.close();+ ctx.close();}}diff --git a/dash/apps/switchdash-desktop/src/main/core/subagents/delete-subagent.ts b/dash/apps/switchdash-desktop/src/main/core/subagents/delete-subagent.tsindex 4819bba07..9b86cea5b 100644--- a/dash/apps/switchdash-desktop/src/main/core/subagents/delete-subagent.ts+++ b/dash/apps/switchdash-desktop/src/main/core/subagents/delete-subagent.ts@@ -1,7 +1,7 @@import { getPlugin } from '@main/core/providers/plugin-registry';import { deleteAgent } from '@main/core/switch-servers/gateway-client';import { getServer } from '@main/core/switch-servers/servers-store';-import { resolveSubagentWorkspace } from './resolve-workspace';+import { resolveSubagentFs } from './resolve-subagent-fs';export type DeleteSubagentParams = {/** The parent agent the subagent belongs to. */@@ -20,24 +20,24 @@ export type DeleteSubagentParams = {* surfaces before the local files are removed.*/export async function deleteSubagent(params: DeleteSubagentParams): Promise<void> {- const workspace = await resolveSubagentWorkspace(params.parentAgentId);+ const ctx = await resolveSubagentFs(params.parentAgentId);try {- const behavior = getPlugin(workspace.agent.providerId).behavior.subagents;+ const behavior = getPlugin(ctx.agent.providerId).behavior.subagents;if (!behavior) {- throw new Error(`Provider ${workspace.agent.providerId} does not support subagents.`);+ throw new Error(`Provider ${ctx.agent.providerId} does not support subagents.`);}if (params.switchAgentId) {- if (!workspace.agent.serverId) {+ if (!ctx.agent.serverId) {throw new Error(`Agent ${params.parentAgentId} is not linked to a Switch server.`);}- const server = await getServer(workspace.agent.serverId);- if (!server) throw new Error(`No Switch server with id ${workspace.agent.serverId}`);+ const server = await getServer(ctx.agent.serverId);+ if (!server) throw new Error(`No Switch server with id ${ctx.agent.serverId}`);await deleteAgent(server, params.switchAgentId);}- await behavior.removeLocal(workspace.fs, params.name);+ await behavior.removeLocal(ctx.fs, params.name);} finally {- workspace.close();+ ctx.close();}}diff --git a/dash/apps/switchdash-desktop/src/main/core/subagents/edit-subagent.ts b/dash/apps/switchdash-desktop/src/main/core/subagents/edit-subagent.tsindex ed6161f16..8edce8ad9 100644--- a/dash/apps/switchdash-desktop/src/main/core/subagents/edit-subagent.ts+++ b/dash/apps/switchdash-desktop/src/main/core/subagents/edit-subagent.ts@@ -1,6 +1,6 @@import type { SubagentAttributes } from '@switchdash/core/agents/plugins';import { getPlugin } from '@main/core/providers/plugin-registry';-import { resolveSubagentWorkspace } from './resolve-workspace';+import { resolveSubagentFs } from './resolve-subagent-fs';export type EditSubagentParams = {/** The parent agent whose subagent definition to rewrite. */@@ -20,19 +20,19 @@ export async function editSubagent(params: EditSubagentParams): Promise<void> {const name = typeof params.attributes.name === 'string' ? params.attributes.name.trim() : '';if (!name) throw new Error('A subagent name is required.');- const workspace = await resolveSubagentWorkspace(params.parentAgentId);+ const ctx = await resolveSubagentFs(params.parentAgentId);try {- const behavior = getPlugin(workspace.agent.providerId).behavior.subagents;+ const behavior = getPlugin(ctx.agent.providerId).behavior.subagents;if (!behavior) {- throw new Error(`Provider ${workspace.agent.providerId} does not support subagents.`);+ throw new Error(`Provider ${ctx.agent.providerId} does not support subagents.`);}- if (!(await behavior.readDefinition(workspace.fs, name))) {+ if (!(await behavior.readDefinition(ctx.fs, name))) {throw new Error(`No subagent definition named "${name}".`);}- await behavior.writeDefinition(workspace.fs, params.attributes);+ await behavior.writeDefinition(ctx.fs, params.attributes);} finally {- workspace.close();+ ctx.close();}}diff --git a/dash/apps/switchdash-desktop/src/main/core/subagents/list-subagents.ts b/dash/apps/switchdash-desktop/src/main/core/subagents/list-subagents.tsindex 84269d9ed..bea4a65ca 100644--- a/dash/apps/switchdash-desktop/src/main/core/subagents/list-subagents.ts+++ b/dash/apps/switchdash-desktop/src/main/core/subagents/list-subagents.ts@@ -6,7 +6,7 @@ import { getServer } from '@main/core/switch-servers/servers-store';import { log } from '@main/lib/logger';import type { SubagentListResult } from '@shared/core/subagents/subagents';import { reconcileSubagents } from './reconcile';-import { resolveSubagentWorkspace } from './resolve-workspace';+import { resolveSubagentFs } from './resolve-subagent-fs';/*** List a parent agent's Claude Code subagents: discover them from the parent's@@ -27,11 +27,11 @@ export async function listSubagents(parentAgentId: string): Promise<SubagentListlet local: LocalSubagent[] = [];if (subagentsBehavior) {try {- const workspace = await resolveSubagentWorkspace(parentAgentId);+ const ctx = await resolveSubagentFs(parentAgentId);try {- local = await subagentsBehavior.discoverLocal(workspace.fs, workspace.homeFs);+ local = await subagentsBehavior.discoverLocal(ctx.fs, ctx.homeFs);} finally {- workspace.close();+ ctx.close();}} catch (error) {// Discovery is best-effort: an unreachable host or a parent without adiff --git a/dash/apps/switchdash-desktop/src/main/core/subagents/register-subagents.test.ts b/dash/apps/switchdash-desktop/src/main/core/subagents/register-subagents.test.tsindex fb86a4321..411ac29d8 100644--- a/dash/apps/switchdash-desktop/src/main/core/subagents/register-subagents.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/subagents/register-subagents.test.ts@@ -10,7 +10,7 @@ const writeSettings = vi.hoisted(() => vi.fn(async () => {}));const remoteClose = vi.hoisted(() => vi.fn());const remoteRead = vi.hoisted(() => vi.fn());const getAgents = vi.hoisted(() => vi.fn());-const getLocalProjectByPath = vi.hoisted(() => vi.fn());+const getLocationByHostDir = vi.hoisted(() => vi.fn());const applyLocalSubagentAutoSessionState = vi.hoisted(() => vi.fn(async () => {}));const logWarn = vi.hoisted(() => vi.fn());@@ -22,9 +22,9 @@ vi.mock('@main/core/switch-rooms/switch-credentials', () => ({parseSwitchAgentCredentials,readSwitchAgentCredentials,}));-vi.mock('./resolve-workspace', () => ({ openRemoteSubagentFs }));+vi.mock('./resolve-subagent-fs', () => ({ openRemoteSubagentFs }));vi.mock('@main/core/agents/getAgents', () => ({ getAgents }));-vi.mock('@main/core/projects/operations/getProjects', () => ({ getLocalProjectByPath }));+vi.mock('@main/core/locations/store', () => ({ getLocationByHostDir }));vi.mock('./setSubagentAutoSession', () => ({ applyLocalSubagentAutoSessionState }));vi.mock('@main/lib/logger', () => ({ log: { warn: logWarn, error: vi.fn() } }));@@ -131,7 +131,7 @@ describe('registerSubagents', () => {{ subagentName: 'code-reviewer', id: 'child-1', apiKey: 'key-1' },{ subagentName: 'doc-writer', id: 'child-2', apiKey: 'key-2' },]);- getLocalProjectByPath.mockResolvedValueOnce({ id: 'proj-1' });+ getLocationByHostDir.mockResolvedValueOnce({ id: 'loc-1' });getAgents.mockResolvedValueOnce([{ id: 'local-other', switchAgentId: 'sw-other' },{ id: 'local-parent', switchAgentId: 'sw-parent' },@@ -149,7 +149,7 @@ describe('registerSubagents', () => {expect.objectContaining({ apiUrl: 'https://switch.example.com' }),expect.objectContaining({ parentAgentId: 'sw-parent', autoSession: true }));- expect(getLocalProjectByPath).toHaveBeenCalledWith('/home/dev/r');+ expect(getLocationByHostDir).toHaveBeenCalledWith(null, '/home/dev/r');expect(applyLocalSubagentAutoSessionState).toHaveBeenCalledTimes(2);expect(applyLocalSubagentAutoSessionState).toHaveBeenCalledWith('local-parent',@@ -168,7 +168,7 @@ describe('registerSubagents', () => {registerSubagentsBulk.mockResolvedValueOnce([{ subagentName: 'code-reviewer', id: 'child-1', apiKey: 'key-1' },]);- getLocalProjectByPath.mockResolvedValueOnce(undefined);+ getLocationByHostDir.mockResolvedValueOnce(undefined);const result = await registerSubagents({...LOCAL,@@ -187,7 +187,7 @@ describe('registerSubagents', () => {registerSubagentsBulk.mockResolvedValueOnce([{ subagentName: 'code-reviewer', id: 'child-1', apiKey: 'key-1' },]);- getLocalProjectByPath.mockResolvedValueOnce({ id: 'proj-1' });+ getLocationByHostDir.mockResolvedValueOnce({ id: 'loc-1' });getAgents.mockResolvedValueOnce([{ id: 'local-parent', switchAgentId: 'sw-parent' }]);applyLocalSubagentAutoSessionState.mockRejectedValueOnce(new Error('watcher boom'));diff --git a/dash/apps/switchdash-desktop/src/main/core/subagents/register-subagents.ts b/dash/apps/switchdash-desktop/src/main/core/subagents/register-subagents.tsindex 03b1e2988..ec9faf02a 100644--- a/dash/apps/switchdash-desktop/src/main/core/subagents/register-subagents.ts+++ b/dash/apps/switchdash-desktop/src/main/core/subagents/register-subagents.ts@@ -1,6 +1,6 @@import type { ISubagentsBehavior, PluginFs } from '@switchdash/core/agents/plugins';import { getAgents } from '@main/core/agents/getAgents';-import { getLocalProjectByPath } from '@main/core/projects/operations/getProjects';+import { getLocationByHostDir } from '@main/core/locations/store';import { createPluginFs } from '@main/core/providers/plugin-fs';import { getPlugin } from '@main/core/providers/plugin-registry';import {@@ -11,7 +11,7 @@ import { registerSubagentsBulk } from '@main/core/switch-servers/gateway-client'import { getServer } from '@main/core/switch-servers/servers-store';import { log } from '@main/lib/logger';import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';-import { openRemoteSubagentFs } from './resolve-workspace';+import { openRemoteSubagentFs } from './resolve-subagent-fs';import { applyLocalSubagentAutoSessionState } from './setSubagentAutoSession';// Remote hosts are POSIX; use a forward-slash literal rather than path.join@@ -79,7 +79,7 @@ export async function registerSubagentsCore(params: {* Seed the local auto_session mirror + start the watcher for freshly-registered* subagents, so they begin watching now without an off→on toggle (CHOO-1397).* The mirror and watcher are keyed by the parent's LOCAL agent id, resolved from- * the parent's directory — present in the onboarding flow because the project is+ * the parent's directory — present in the onboarding flow because the location is* created before its subagents are registered. Best-effort: a failure here must* not fail the registration (the settings panel reconciles from the gateway).*/@@ -88,9 +88,9 @@ async function startAutoSessionWatchers(parentSwitchAgentId: string,names: string[]): Promise<void> {- const project = await getLocalProjectByPath(dir);- const localParent = project- ? (await getAgents(project.id)).find((a) => a.switchAgentId === parentSwitchAgentId)+ const location = await getLocationByHostDir(null, dir);+ const localParent = location+ ? (await getAgents(location.id)).find((a) => a.switchAgentId === parentSwitchAgentId): undefined;if (!localParent) {log.warn(@@ -192,7 +192,7 @@ export async function registerSubagentsRemote();}// Subagents of remote parents register with auto_session off: neither the- // local watcher (no project path) nor the on-VM sidecar watches subagents,+ // local watcher (no location path) nor the on-VM sidecar watches subagents,// so an auto_session profile would advertise a capability nothing serves.return await registerSubagentsCore({behavior,diff --git a/dash/apps/switchdash-desktop/src/main/core/subagents/resolve-workspace.test.ts b/dash/apps/switchdash-desktop/src/main/core/subagents/resolve-subagent-fs.test.tssimilarity index 64%rename from dash/apps/switchdash-desktop/src/main/core/subagents/resolve-workspace.test.tsrename to dash/apps/switchdash-desktop/src/main/core/subagents/resolve-subagent-fs.test.tsindex 88c69f7eb..f8b370ade 100644--- a/dash/apps/switchdash-desktop/src/main/core/subagents/resolve-workspace.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/subagents/resolve-subagent-fs.test.ts@@ -1,15 +1,19 @@import { beforeEach, describe, expect, it, vi } from 'vitest';import type { Agent } from '@shared/core/agents/agents';+import type { Location } from '@shared/core/locations/locations';const getAgentById = vi.hoisted(() => vi.fn());+const getRemoteAgentLocation = vi.hoisted(() => vi.fn());+const getLocationById = vi.hoisted(() => vi.fn());const ensureSshConnected = vi.hoisted(() => vi.fn(async () => ({ proxy: true })));const sshClose = vi.hoisted(() => vi.fn());const SshFileSystemCtor = vi.hoisted(() => vi.fn());const createPluginFs = vi.hoisted(() => vi.fn((root: string) => ({ __local: root })));const createRemotePluginFs = vi.hoisted(() => vi.fn(() => ({ __remote: true })));-const dbSelect = vi.hoisted(() => vi.fn());vi.mock('@main/core/agents/getAgentById', () => ({ getAgentById }));+vi.mock('@main/core/agents/agent-location', () => ({ getRemoteAgentLocation }));+vi.mock('@main/core/locations/store', () => ({ getLocationById }));vi.mock('@main/core/ssh/connect/connect-agent-ssh', () => ({ ensureSshConnected }));vi.mock('@main/core/fs/impl/ssh-fs', () => ({SshFileSystem: vi.fn(function (this: Record<string, unknown>, proxy: unknown, root: unknown) {@@ -19,51 +23,56 @@ vi.mock('@main/core/fs/impl/ssh-fs', () => ({}));vi.mock('@main/core/providers/plugin-fs', () => ({ createPluginFs }));vi.mock('@main/core/providers/remote-plugin-fs', () => ({ createRemotePluginFs }));-vi.mock('@main/db/client', () => ({ db: { select: dbSelect } }));-vi.mock('@main/db/schema', () => ({ projects: {} }));-const { resolveSubagentWorkspace, openRemoteSubagentFs } = await import('./resolve-workspace');+const { resolveSubagentFs, openRemoteSubagentFs } = await import('./resolve-subagent-fs');function agent(overrides: Partial<Agent>): Agent {return {id: 'agent-1',- projectId: 'proj-1',+ locationId: 'loc-1',name: 'parent',providerId: 'claude',switchAgentId: 'sw-1',apiEndpoint: 'https://switch.example.com',serverId: 'srv-1',status: null,- connection: 'local',- remoteConfig: null,createdAt: '',updatedAt: '',...overrides,};}-/** Stub the drizzle select().from().where() chain to resolve to `rows`. */-function stubProjectPath(rows: { path: string | null }[]) {- dbSelect.mockReturnValue({ from: () => ({ where: () => Promise.resolve(rows) }) });+function location(overrides: Partial<Location>): Location {+ return {+ id: 'loc-1',+ name: 'parent',+ sshHost: null,+ dir: '/local/proj',+ createdAt: '',+ updatedAt: '',+ ...overrides,+ };}-describe('resolveSubagentWorkspace', () => {+describe('resolveSubagentFs', () => {beforeEach(() => {vi.clearAllMocks();createPluginFs.mockImplementation((root: string) => ({ __local: root }));createRemotePluginFs.mockReturnValue({ __remote: true });+ getRemoteAgentLocation.mockResolvedValue(null);});it('throws when the agent does not exist', async () => {getAgentById.mockResolvedValueOnce(undefined);- await expect(resolveSubagentWorkspace('missing')).rejects.toThrow(/No agent with id missing/);+ await expect(resolveSubagentFs('missing')).rejects.toThrow(/No agent with id missing/);});- it('resolves a local agent to its project dir on disk', async () => {- getAgentById.mockResolvedValueOnce(agent({ connection: 'local' }));- stubProjectPath([{ path: '/local/proj' }]);+ it('resolves a local agent to its location dir on disk', async () => {+ getAgentById.mockResolvedValueOnce(agent({}));+ getRemoteAgentLocation.mockResolvedValueOnce(null);+ getLocationById.mockResolvedValueOnce(location({ dir: '/local/proj' }));- const ws = await resolveSubagentWorkspace('agent-1');+ const ws = await resolveSubagentFs('agent-1');expect(createPluginFs).toHaveBeenCalledWith('/local/proj');expect(ws.fs).toEqual({ __local: '/local/proj' });@@ -72,21 +81,22 @@ describe('resolveSubagentWorkspace', () => {expect(() => ws.close()).not.toThrow();});- it('throws when a local agent has no project directory', async () => {- getAgentById.mockResolvedValueOnce(agent({ connection: 'local' }));- stubProjectPath([{ path: null }]);- await expect(resolveSubagentWorkspace('agent-1')).rejects.toThrow(/no project directory/);+ it('throws when a local agent has no location on disk', async () => {+ getAgentById.mockResolvedValueOnce(agent({}));+ getRemoteAgentLocation.mockResolvedValueOnce(null);+ getLocationById.mockResolvedValueOnce(undefined);+ await expect(resolveSubagentFs('agent-1')).rejects.toThrow(/no location on disk/);});it('resolves a remote agent over SFTP and closes the channel', async () => {- getAgentById.mockResolvedValueOnce(- agent({- connection: 'remote',- remoteConfig: { sshHost: 'box', remoteRepoDir: '/home/dev/r' },- })+ getAgentById.mockResolvedValueOnce(agent({ locationId: 'loc-remote' }));+ getRemoteAgentLocation.mockResolvedValueOnce(+ location({ id: 'loc-remote', sshHost: 'box', dir: '/home/dev/r' }) as Location & {+ sshHost: string;+ });- const ws = await resolveSubagentWorkspace('agent-1');+ const ws = await resolveSubagentFs('agent-1');expect(ensureSshConnected).toHaveBeenCalledWith('agent-ssh:box', 'box');expect(SshFileSystemCtor).toHaveBeenCalledWith(expect.anything(), '/home/dev/r');@@ -98,11 +108,6 @@ describe('resolveSubagentWorkspace', () => {ws.close();expect(sshClose).toHaveBeenCalledTimes(1);});-- it('throws when a remote agent has no remote config', async () => {- getAgentById.mockResolvedValueOnce(agent({ connection: 'remote', remoteConfig: null }));- await expect(resolveSubagentWorkspace('agent-1')).rejects.toThrow(/no remote config/);- });});describe('openRemoteSubagentFs', () => {diff --git a/dash/apps/switchdash-desktop/src/main/core/subagents/resolve-workspace.ts b/dash/apps/switchdash-desktop/src/main/core/subagents/resolve-subagent-fs.tssimilarity index 61%rename from dash/apps/switchdash-desktop/src/main/core/subagents/resolve-workspace.tsrename to dash/apps/switchdash-desktop/src/main/core/subagents/resolve-subagent-fs.tsindex 8fd4b1a55..ca7d21286 100644--- a/dash/apps/switchdash-desktop/src/main/core/subagents/resolve-workspace.ts+++ b/dash/apps/switchdash-desktop/src/main/core/subagents/resolve-subagent-fs.ts@@ -1,19 +1,18 @@import { homedir } from 'node:os';import type { PluginFs } from '@switchdash/core/agents/plugins';-import { eq } from 'drizzle-orm';+import { getRemoteAgentLocation } from '@main/core/agents/agent-location';import { getAgentById } from '@main/core/agents/getAgentById';import { SshFileSystem } from '@main/core/fs/impl/ssh-fs';+import { sshConnectionIdForHost } from '@main/core/locations/location-transport';+import { getLocationById } from '@main/core/locations/store';import { createPluginFs } from '@main/core/providers/plugin-fs';import { createRemotePluginFs } from '@main/core/providers/remote-plugin-fs';import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';-import { agentSshConnectionId } from '@main/core/workspaces/resolve-agent-workspace';-import { db } from '@main/db/client';-import { projects } from '@main/db/schema';import type { Agent } from '@shared/core/agents/agents';/*** A PluginFs that resolves nothing. Used for the user (home) scope of a remote- * agent, whose VM home dir is not mounted here — project-scoped subagent IO,+ * agent, whose VM home dir is not mounted here — location-scoped subagent IO,* which is what switchdash authors, is unaffected.*/const EMPTY_PLUGIN_FS: PluginFs = {@@ -24,7 +23,7 @@ const EMPTY_PLUGIN_FS: PluginFs = {list: () => Promise.resolve([]),};-export type SubagentWorkspace = {+export type SubagentFsContext = {agent: Agent;/** FS rooted at the parent's working dir — local disk or the remote repo dir. */fs: PluginFs;@@ -37,57 +36,45 @@ export type SubagentWorkspace = {/*** Open a {@link PluginFs} rooted at a remote agent's working dir over SFTP,* without needing a switchdash agent record — used at onboarding time (keyed on- * ssh host + repo dir) as well as by {@link resolveSubagentWorkspace}. Callers+ * ssh host + repo dir) as well as by {@link resolveSubagentFs}. Callers* MUST invoke `close()` in a `finally` to release the SFTP channel.*/export async function openRemoteSubagentFs(sshHost: string,remoteRepoDir: string): Promise<{ fs: PluginFs; close: () => void }> {- const proxy = await ensureSshConnected(agentSshConnectionId(sshHost), sshHost);+ const proxy = await ensureSshConnected(sshConnectionIdForHost(sshHost), sshHost);const sshFs = new SshFileSystem(proxy, remoteRepoDir);return { fs: createRemotePluginFs(sshFs), close: () => sshFs.close() };}-async function getProjectPath(projectId: string): Promise<string | null> {- const [row] = await db- .select({ path: projects.path })- .from(projects)- .where(eq(projects.id, projectId));- return row?.path ?? null;-}-/*** Resolve the filesystem where a parent agent's subagent definitions and* credentials live, transparently for local and remote agents. Local agents use- * their project dir on disk; remote agents use their SSH host's repo dir over- * SFTP (the same connect seam the remote credential shipping in setupRemoteAgent- * uses).+ * their location dir on disk; remote agents use their SSH host's repo dir over+ * SFTP (the same connect seam remote agents use for their location IO).** Callers MUST invoke `close()` in a `finally` — for remote agents it releases* the SFTP channel, which otherwise leaks and eventually exhausts the host's* MaxSessions.*/-export async function resolveSubagentWorkspace(parentAgentId: string): Promise<SubagentWorkspace> {+export async function resolveSubagentFs(parentAgentId: string): Promise<SubagentFsContext> {const agent = await getAgentById(parentAgentId);if (!agent) throw new Error(`No agent with id ${parentAgentId}`);- if (agent.connection === 'remote') {- if (!agent.remoteConfig) {- throw new Error(`Remote agent ${parentAgentId} has no remote config.`);- }- const { sshHost, remoteRepoDir } = agent.remoteConfig;- const remote = await openRemoteSubagentFs(sshHost, remoteRepoDir);+ const remoteLocation = await getRemoteAgentLocation(agent);+ if (remoteLocation) {+ const remote = await openRemoteSubagentFs(remoteLocation.sshHost, remoteLocation.dir);return { agent, fs: remote.fs, homeFs: EMPTY_PLUGIN_FS, close: remote.close };}- const projectPath = await getProjectPath(agent.projectId);- if (!projectPath) {- throw new Error(`Local agent ${parentAgentId} has no project directory on disk.`);+ const location = await getLocationById(agent.locationId);+ if (!location) {+ throw new Error(`Agent ${parentAgentId} has no location on disk.`);}return {agent,- fs: createPluginFs(projectPath),+ fs: createPluginFs(location.dir),homeFs: createPluginFs(homedir()),close: () => {},};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 6ac04df9b..910b4b85f 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@@ -1,11 +1,10 @@import { randomUUID } from 'node:crypto';import path from 'node:path';-import { eq } from 'drizzle-orm';+import { getRemoteAgentLocation } from '@main/core/agents/agent-location';import { getAgentById } from '@main/core/agents/getAgentById';import { SWITCH_SUBAGENTS_DIR_RELATIVE } from '@main/core/agents/switch-settings-paths';+import { getLocationById } from '@main/core/locations/store';import { sessionService } from '@main/core/sessions/session-service';-import { db } from '@main/db/client';-import { projects } from '@main/db/schema';import { events } from '@main/lib/events';import { log } from '@main/lib/logger';import { sessionRoomChangedChannel } from '@shared/core/switch-rooms/switchRoomEvents';@@ -57,16 +56,13 @@ function subagentWatcherKey(parentAgentId: string, name: string): string {return `${parentAgentId}::${name}`;}-/** Resolve the working-directory path of a local agent's project. */-async function getAgentProjectPath(localAgentId: string): Promise<string | null> {+/** Resolve the working-directory path of a local agent's location. */+async function getAgentLocalDir(localAgentId: string): Promise<string | null> {const agent = await getAgentById(localAgentId);if (!agent) return null;- const [project] = await db- .select({ path: projects.path })- .from(projects)- .where(eq(projects.id, agent.projectId))- .limit(1);- return project?.path ?? null;+ const location = await getLocationById(agent.locationId);+ if (!location || location.sshHost !== null) return null;+ return location.dir;}/** Refresh the agent's global "watching" heartbeat. Throws on non-OK. */@@ -188,23 +184,23 @@ class AutoSessionWatcher {// it keeps auto-starting sessions while switchdash is closed. Watching them// here too would double-poll the agent's notification stream, so skip.const agent = await getAgentById(localAgentId);- if (agent?.connection === 'remote') {+ if (agent && (await getRemoteAgentLocation(agent))) {log.debug('AutoSessionWatcher: skipping remote agent (watched on its VM)', { localAgentId });return;}- const projectPath = await getAgentProjectPath(localAgentId);- if (!projectPath) {- log.warn('AutoSessionWatcher: no project dir for agent; cannot read credentials', {+ const rootPath = await getAgentLocalDir(localAgentId);+ if (!rootPath) {+ log.warn('AutoSessionWatcher: no local dir for agent; cannot read credentials', {localAgentId,});return;}- const creds = await readSwitchAgentCredentials(projectPath, log);+ const creds = await readSwitchAgentCredentials(rootPath, log);if (!creds) {log.warn('AutoSessionWatcher: missing Switch credentials; cannot watch', {localAgentId,- dir: projectPath,+ dir: rootPath,});return;}@@ -221,16 +217,16 @@ class AutoSessionWatcher {const key = subagentWatcherKey(parentAgentId, name);if (this.watchers.has(key)) return;- const projectPath = await getAgentProjectPath(parentAgentId);- if (!projectPath) {- log.warn('AutoSessionWatcher: no project dir for parent agent; cannot watch subagent', {+ const rootPath = await getAgentLocalDir(parentAgentId);+ if (!rootPath) {+ log.warn('AutoSessionWatcher: no local dir for parent agent; cannot watch subagent', {parentAgentId,name,});return;}const settingsPath = path.join(- projectPath,+ rootPath,SWITCH_SUBAGENTS_DIR_RELATIVE,`${name}.settings.json`);@@ -411,11 +407,11 @@ class AutoSessionWatcher {});// createSession provisions the runtime inline but emits only// session:created — not session:provisioned. Without the latter an- // open renderer leaves the session stuck "Setting up workspace…"- // (it never reconciles to ready). provisionWorkspace is idempotent+ // open renderer leaves the session stuck "Setting up session…"+ // (it never reconciles to ready). provisionSession is idempotent// (fast-paths on the already-registered runtime) and emits the// provisioned event the renderer needs.- await sessionService.provisionWorkspace(result.data.session.id).catch((error) => {+ await sessionService.provisionSession(result.data.session.id).catch((error) => {log.warn('AutoSessionWatcher: post-spawn provision-reconcile failed', {roomId,sessionId: result.data.session.id,diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/injection-sink.test.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/injection-sink.test.tsindex 157a82899..347401019 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/injection-sink.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/injection-sink.test.ts@@ -15,15 +15,15 @@ describe('PtyInjectionSink', () => {const pty = { write: vi.fn() };vi.mocked(ptySessionRegistry.get).mockReturnValue(pty as never);- const sink = new PtyInjectionSink('project-1:session-1');+ const sink = new PtyInjectionSink('location-1:session-1');expect(sink.acquire()).toBe(pty);- expect(ptySessionRegistry.get).toHaveBeenCalledWith('project-1:session-1');+ expect(ptySessionRegistry.get).toHaveBeenCalledWith('location-1:session-1');});it('returns null when no PTY is live', () => {vi.mocked(ptySessionRegistry.get).mockReturnValue(undefined as never);- const sink = new PtyInjectionSink('project-1:session-1');+ const sink = new PtyInjectionSink('location-1:session-1');expect(sink.acquire()).toBeNull();});});diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/restore-sessions.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/restore-sessions.tsindex d0f1eee7c..79019e87a 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/restore-sessions.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/restore-sessions.ts@@ -1,5 +1,5 @@-import { getProjectById } from '@main/core/projects/operations/getProjects';-import { projectManager } from '@main/core/projects/project-manager';+import { locationManager } from '@main/core/locations/location-manager';+import { getLocationById } from '@main/core/locations/store';import { hydrateSession } from '@main/core/sessions/operations/hydrateSession';import { loadSessionWithAgent } from '@main/core/sessions/session-join';import { sessionService } from '@main/core/sessions/session-service';@@ -10,9 +10,9 @@ import { switchRoomService } from './switch-room-service';* Launch every session that was connected to a Switch room before the last* shutdown, so it receives and responds to room events without the user opening* its terminal. Replays the renderer's open sequence from the main process:- * mount the project → provision the session runtime → hydrate the session+ * open the location → provision the session runtime → hydrate the session* (which spawns the PTY and, via the session-launch path, restarts the room- * poller). Sessions whose row or project no longer exist are pruned.+ * poller). Sessions whose row or location no longer exist are pruned.** This deliberately spawns the agent process for each room-connected session at* startup — keystroke injection requires a live TUI, so there is no lighter way@@ -33,26 +33,26 @@ export async function restoreSwitchRoomSessions(): Promise<void> {continue;}- const project = await getProjectById(loaded.projectId);- if (!project) {+ const location = await getLocationById(loaded.locationId);+ if (!location) {stale.push(sessionId);continue;}- if (!projectManager.getProject(loaded.projectId)) {- const opened = await projectManager.openProject(project);+ if (!locationManager.getLocation(loaded.locationId)) {+ const opened = await locationManager.openLocation(location);if (!opened.success) {- log.warn('restoreSwitchRoomSessions: failed to open project; skipping session', {+ log.warn('restoreSwitchRoomSessions: failed to open location; skipping session', {sessionId,- projectId: loaded.projectId,+ locationId: loaded.locationId,error: opened.error,});continue;}}- await sessionService.provisionWorkspace(sessionId);- await hydrateSession(loaded.projectId, sessionId);+ await sessionService.provisionSession(sessionId);+ await hydrateSession(sessionId);launched += 1;} catch (error) {log.warn('restoreSwitchRoomSessions: failed to launch room-connected session', {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 6fa2ae44f..a45a67179 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@@ -3,9 +3,11 @@ import * as path from 'node:path';import { eq } from 'drizzle-orm';import { DEEPLINK_SCHEME } from '@main/app/deeplinks';import { 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 { projects, sessions } from '@main/db/schema';+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';@@ -28,7 +30,7 @@ import type { SessionRoomContext } from './switch-room-service';* channel's own poll loop).** This is a thin manager over per-room `RoomConnection`s: it resolves the- * session's Switch credentials from the project's settings file, wires a+ * session's Switch credentials from the location's settings file, wires a* PTY-backed injection sink, and routes agent status changes to the matching* connection. The transport-agnostic poll/queue/runtime-state logic lives in* `RoomConnection`, which the on-VM sidecar reuses over a tmux-backed sink.@@ -72,28 +74,24 @@ class SwitchNotificationPoller {roomId: string,roomName: string | null): Promise<void> {- const [project] = await db- .select({ path: projects.path })- .from(projects)- .where(eq(projects.id, ctx.projectId))- .limit(1);- if (!project) {- log.warn('SwitchNotificationPoller: no project dir for session; cannot read credentials', {+ const loaded = await loadSessionWithAgent(ctx.sessionId);+ const location = loaded ? await getLocationById(loaded.locationId) : undefined;+ if (!location) {+ log.warn('SwitchNotificationPoller: no location for session; cannot read credentials', {sessionId: ctx.sessionId,- projectId: ctx.projectId,});return;}- if (project.path === null) {+ if (location.sshHost !== null) {// Remote agents poll from their on-host sidecar (CHOO-1059); the local- // poller reads local credential files, which a remote-only agent has none of.- log.debug('SwitchNotificationPoller: remote-only project; local poller does not apply', {+ // poller reads local credential files, which a remote agent has none of.+ log.debug('SwitchNotificationPoller: remote location; local poller does not apply', {sessionId: ctx.sessionId,- projectId: ctx.projectId,+ locationId: location.id,});return;}- const projectPath = project.path;+ 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@@ -107,19 +105,19 @@ class SwitchNotificationPoller {const creds = subagentName? await readSwitchAgentCredentialsFromSettings(- subagentSettingsPath(projectPath, subagentName),+ subagentSettingsPath(rootPath, subagentName),log)- : await readSwitchAgentCredentials(projectPath, 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: project.path, roomId, subagentName }+ { sessionId: ctx.sessionId, dir: rootPath, roomId, subagentName });return;}- const ptySessionId = makeAgentPtySessionId(ctx.projectId, ctx.sessionId);+ const ptySessionId = makeAgentPtySessionId(location.id, ctx.sessionId);const connection = new RoomConnection({creds,roomId,diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-room-service.test.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-room-service.test.tsindex 387b7bdc4..0f1b9aded 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-room-service.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-room-service.test.ts@@ -27,7 +27,7 @@ const { switchRoomService } = await import('./switch-room-service');const ctx = {sessionId: 'session-1',- projectId: 'proj-1',+ locationId: 'proj-1',providerId: 'claude',ptyId: 'claude-session-session-1',};diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-room-service.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-room-service.tsindex 3709ed284..8b790b647 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-room-service.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-room-service.ts@@ -10,14 +10,12 @@ import { switchNotificationPoller } from './switch-notification-poller';export type SessionRoomContext = {sessionId: string;- projectId: string;providerId: string;ptyId: string;};type ConnectionState = SessionRoomConnection & {roomName: string | null;- projectId: string;providerId: string;ptyId: string;};@@ -62,7 +60,6 @@ class SwitchRoomService implements IDisposable {roomId,agentId,roomName,- projectId: ctx.projectId,providerId: ctx.providerId,ptyId: ctx.ptyId,});diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-servers/controller.ts b/dash/apps/switchdash-desktop/src/main/core/switch-servers/controller.tsindex 25bcea42c..3fe9d85a9 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-servers/controller.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-servers/controller.ts@@ -4,8 +4,8 @@ import { resolveAgentServers } from '@main/core/agents/resolve-servers';import { writeRemoteSwitchSettings } from '@main/core/agents/write-remote-switch-settings';import { writeSwitchSettings } from '@main/core/agents/write-switch-settings';import { SshFileSystem } from '@main/core/fs/impl/ssh-fs';+import { sshConnectionIdForHost } from '@main/core/locations/location-transport';import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';-import { agentSshConnectionId } from '@main/core/workspaces/resolve-agent-workspace';import type { AgentProviderKind } from '@shared/core/switch-servers/switch-servers';import type {AddServerParams,@@ -237,7 +237,7 @@ export const switchServersController = createRPCController({});if (registered.kind !== 'created') return registered;- const proxy = await ensureSshConnected(agentSshConnectionId(params.sshHost), params.sshHost);+ const proxy = await ensureSshConnected(sshConnectionIdForHost(params.sshHost), params.sshHost);const fs = new SshFileSystem(proxy, params.remoteRepoDir);try {await writeRemoteSwitchSettings(fs, {diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-setup/remote-switch-setup.ts b/dash/apps/switchdash-desktop/src/main/core/switch-setup/remote-switch-setup.tsindex 0d1e1fd21..14e760ac9 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-setup/remote-switch-setup.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-setup/remote-switch-setup.ts@@ -1,8 +1,8 @@import { resolveCommandPath } from '@switchdash/core/deps/runtime';import semver from 'semver';import { SshExecutionContext } from '@main/core/execution-context/ssh-execution-context';+import { sshConnectionIdForHost } from '@main/core/locations/location-transport';import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';-import { agentSshConnectionId } from '@main/core/workspaces/resolve-agent-workspace';import { log } from '@main/lib/logger';import { getPlugin, listPlugins } from '../providers/plugin-registry';import type {@@ -268,7 +268,7 @@ export class RemoteSwitchSetupService {const serviceCache = new Map<string, Promise<RemoteSwitchSetupService>>();async function build(sshHost: string): Promise<RemoteSwitchSetupService> {- const proxy = await ensureSshConnected(agentSshConnectionId(sshHost), sshHost);+ const proxy = await ensureSshConnected(sshConnectionIdForHost(sshHost), sshHost);return new RemoteSwitchSetupService(new SshExecutionContext(proxy));}diff --git a/dash/apps/switchdash-desktop/src/main/core/terminals/impl/local-terminal-provider.test.ts b/dash/apps/switchdash-desktop/src/main/core/terminals/impl/local-terminal-provider.test.tsindex 37222ea67..ba526f082 100644--- a/dash/apps/switchdash-desktop/src/main/core/terminals/impl/local-terminal-provider.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/terminals/impl/local-terminal-provider.test.ts@@ -35,7 +35,7 @@ vi.mock('@main/core/pty/terminal-color-scheme', () => ({const terminal: Terminal = {id: 'terminal-1',- projectId: 'project-1',+ locationId: 'location-1',sessionId: 'session-1',shellId: 'system',name: 'Terminal 1',@@ -65,7 +65,7 @@ describe('LocalTerminalProvider', () => {command: 'echo ready',});- const sessionId = makePtySessionId(terminal.projectId, terminal.sessionId, terminal.id);+ const sessionId = makePtySessionId(terminal.locationId, terminal.sessionId, terminal.id);expect((provider as unknown as { shellProfiles: Map<string, unknown> }).shellProfiles.has(sessionId)).toBe(true);diff --git a/dash/apps/switchdash-desktop/src/main/core/terminals/impl/local-terminal-provider.ts b/dash/apps/switchdash-desktop/src/main/core/terminals/impl/local-terminal-provider.tsindex a4ffe1140..9c0164fa5 100644--- a/dash/apps/switchdash-desktop/src/main/core/terminals/impl/local-terminal-provider.ts+++ b/dash/apps/switchdash-desktop/src/main/core/terminals/impl/local-terminal-provider.ts@@ -96,7 +96,7 @@ export class LocalTerminalProvider implements TerminalProvider {metadata: PtySessionMetadata | undefined,policy: SpawnPolicy): Promise<void> {- const sessionId = makePtySessionId(terminal.projectId, terminal.sessionId, terminal.id);+ const sessionId = makePtySessionId(terminal.locationId, terminal.sessionId, terminal.id);this.knownSessionIds.add(sessionId);if (this.sessions.has(sessionId)) return;const shellProfile = await this.getSessionShellProfile(sessionId, shellIntent);diff --git a/dash/apps/switchdash-desktop/src/main/core/terminals/impl/ssh-terminal-provider.test.ts b/dash/apps/switchdash-desktop/src/main/core/terminals/impl/ssh-terminal-provider.test.tsindex 8067781b6..e2529234d 100644--- a/dash/apps/switchdash-desktop/src/main/core/terminals/impl/ssh-terminal-provider.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/terminals/impl/ssh-terminal-provider.test.ts@@ -40,7 +40,7 @@ vi.mock('@main/core/pty/terminal-color-scheme', () => ({const terminal: Terminal = {id: 'terminal-1',- projectId: 'project-1',+ locationId: 'location-1',sessionId: 'session-1',shellId: 'system',name: 'Terminal 1',@@ -85,7 +85,7 @@ describe('SshTerminalProvider', () => {command: 'echo ready',});- const sessionId = makePtySessionId(terminal.projectId, terminal.sessionId, terminal.id);+ const sessionId = makePtySessionId(terminal.locationId, terminal.sessionId, terminal.id);expect((provider as unknown as { shellProfiles: Map<string, unknown> }).shellProfiles.has(sessionId)).toBe(true);@@ -110,7 +110,7 @@ describe('SshTerminalProvider', () => {command: 'echo ready',});- const sessionId = makePtySessionId(terminal.projectId, terminal.sessionId, terminal.id);+ const sessionId = makePtySessionId(terminal.locationId, terminal.sessionId, terminal.id);expect(ptySessionRegistry.register).toHaveBeenCalledWith(sessionId,expect.anything(),diff --git a/dash/apps/switchdash-desktop/src/main/core/terminals/impl/ssh-terminal-provider.ts b/dash/apps/switchdash-desktop/src/main/core/terminals/impl/ssh-terminal-provider.tsindex bffdf5d20..a34760c6d 100644--- a/dash/apps/switchdash-desktop/src/main/core/terminals/impl/ssh-terminal-provider.ts+++ b/dash/apps/switchdash-desktop/src/main/core/terminals/impl/ssh-terminal-provider.ts@@ -100,7 +100,7 @@ export class SshTerminalProvider implements TerminalProvider {metadata: PtySessionMetadata | undefined,policy: SpawnPolicy): Promise<void> {- const sessionId = makePtySessionId(terminal.projectId, terminal.sessionId, terminal.id);+ const sessionId = makePtySessionId(terminal.locationId, terminal.sessionId, terminal.id);this.knownSessionIds.add(sessionId);if (this.sessions.has(sessionId)) return;diff --git a/dash/apps/switchdash-desktop/src/main/core/terminals/lifecycle-script-coordinator.test.ts b/dash/apps/switchdash-desktop/src/main/core/terminals/lifecycle-script-coordinator.test.tsindex f7169dc3a..da93407b8 100644--- a/dash/apps/switchdash-desktop/src/main/core/terminals/lifecycle-script-coordinator.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/terminals/lifecycle-script-coordinator.test.ts@@ -1,12 +1,12 @@import { beforeEach, describe, expect, it, vi } from 'vitest';import { ptySessionRegistry } from '@main/core/pty/pty-session-registry';import { lifecycleScriptStatusChannel } from '@shared/core/sessions/sessionEvents';-import type { Pty, PtyExitInfo } from '../pty/pty';-import type { LifecycleScriptSpawnRequest, TerminalProvider } from '../terminals/terminal-provider';import {LifecycleScriptService,type LifecycleScriptExecutionResult,-} from '../workspaces/workspace-lifecycle-service';+} from '../locations/lifecycle-service';+import type { Pty, PtyExitInfo } from '../pty/pty';+import type { LifecycleScriptSpawnRequest, TerminalProvider } from '../terminals/terminal-provider';import {runLifecycleScriptWithPolicy,stopLifecycleScriptSession,@@ -83,7 +83,7 @@ function makeTerminalProvider(): {spawned.push(pty);requests.push(request);ptySessionRegistry.register(- `${terminal.projectId}:${terminal.sessionId}:${terminal.id}`,+ `${terminal.locationId}:${terminal.sessionId}:${terminal.id}`,pty,{preserveBufferOnExit: true,@@ -96,7 +96,7 @@ function makeTerminalProvider(): {return { provider, spawned, requests };}-function makeWorkspace(runLifecycleScript = vi.fn()) {+function makeRuntime(runLifecycleScript = vi.fn()) {return {lifecycleService: {runLifecycleScript,@@ -106,10 +106,9 @@ function makeWorkspace(runLifecycleScript = vi.fn()) {function baseArgs(runLifecycleScript = vi.fn()) {return {- workspace: makeWorkspace(runLifecycleScript),- projectId: 'project-1',+ runtime: makeRuntime(runLifecycleScript),+ locationId: 'loc-1',sessionId: 'session-1',- workspaceId: 'workspace-1',type: 'run' as const,script: 'pnpm dev',origin: 'manual' as const,@@ -147,7 +146,7 @@ describe('runLifecycleScriptWithPolicy', () => {'test: run script failed',expect.objectContaining({sessionId: 'session-1',- workspaceId: 'workspace-1',+ locationId: 'loc-1',exitCode: 2,outputTail: 'redacted:install failed',})@@ -199,7 +198,7 @@ describe('runLifecycleScriptWithPolicy', () => {...baseArgs(runLifecycleScript),type: 'teardown',script: 'pnpm cleanup',- origin: 'workspace-destroy',+ origin: 'location-destroy',policy: {timeoutMs: 100,logFailure: true,@@ -232,7 +231,7 @@ describe('runLifecycleScriptWithPolicy', () => {);const coordinatorPromise = runLifecycleScriptWithPolicy(baseArgs(runLifecycleScript));- const sessionId = 'project-1:workspace-1:script-lifecycle-run';+ const sessionId = 'loc-1:loc-1:script-lifecycle-run';const pty = {write: vi.fn(),resize: vi.fn(),@@ -244,18 +243,16 @@ describe('runLifecycleScriptWithPolicy', () => {expect(stopLifecycleScriptSession({- projectId: 'project-1',+ locationId: 'loc-1',sessionId: 'session-1',- workspaceId: 'workspace-1',type: 'run',origin: 'manual',})).toBe(true);expect(stopLifecycleScriptSession({- projectId: 'project-1',+ locationId: 'loc-1',sessionId: 'session-1',- workspaceId: 'workspace-1',type: 'run',origin: 'manual',})@@ -306,19 +303,16 @@ describe('runLifecycleScriptWithPolicy', () => {it('runs a manual respawn policy script again after the first PTY exits', async () => {const { provider, spawned } = makeTerminalProvider();- const projectId = 'project-rerun';- const workspaceId = 'workspace-rerun';+ const locationId = 'loc-rerun';const service = new LifecycleScriptService({- projectId,- workspaceId,+ locationId,terminals: provider,});- const workspace = { lifecycleService: service } as never;+ const runtime = { lifecycleService: service } as never;const args = {- workspace,- projectId,+ runtime,+ locationId,sessionId: 'session-rerun',- workspaceId,type: 'run' as const,script: 'pnpm dev',origin: 'manual' as const,@@ -343,11 +337,11 @@ describe('runLifecycleScriptWithPolicy', () => {await expect(secondRun).resolves.toMatchObject({ kind: 'succeeded' });await expect.poll(() => spawned.length).toBe(3);- ptySessionRegistry.unregister('project-rerun:workspace-rerun:script-lifecycle-run');+ ptySessionRegistry.unregister('loc-rerun:loc-rerun:script-lifecycle-run');});it('does not record a stale stopped state when stopping an idle lifecycle prompt', async () => {- const sessionId = 'project-idle:workspace-idle:script-lifecycle-run';+ const sessionId = 'loc-idle:loc-idle:script-lifecycle-run';const pty = {write: vi.fn(),resize: vi.fn(),@@ -359,9 +353,8 @@ describe('runLifecycleScriptWithPolicy', () => {expect(stopLifecycleScriptSession({- projectId: 'project-idle',+ locationId: 'loc-idle',sessionId: 'session-idle',- workspaceId: 'workspace-idle',type: 'run',origin: 'manual',})@@ -376,9 +369,8 @@ describe('runLifecycleScriptWithPolicy', () => {await expect(runLifecycleScriptWithPolicy({...baseArgs(runLifecycleScript),- projectId: 'project-idle',+ locationId: 'loc-idle',sessionId: 'session-idle',- workspaceId: 'workspace-idle',})).resolves.toMatchObject({ kind: 'succeeded' });diff --git a/dash/apps/switchdash-desktop/src/main/core/terminals/lifecycle-script-coordinator.ts b/dash/apps/switchdash-desktop/src/main/core/terminals/lifecycle-script-coordinator.tsindex 5ea7025ce..af6cd277f 100644--- a/dash/apps/switchdash-desktop/src/main/core/terminals/lifecycle-script-coordinator.ts+++ b/dash/apps/switchdash-desktop/src/main/core/terminals/lifecycle-script-coordinator.ts@@ -1,5 +1,5 @@+import type { LocationRuntime } from '@main/core/locations/location-runtime';import { ptySessionRegistry } from '@main/core/pty/pty-session-registry';-import type { Workspace } from '@main/core/workspaces/workspace';import { events } from '@main/lib/events';import { redactDiagnosticLog } from '@main/lib/file-logger';import { log } from '@main/lib/logger';@@ -10,7 +10,7 @@ import {type LifecycleScriptType,} from '@shared/core/sessions/sessionEvents';import { createLifecycleScriptTerminalId } from '@shared/core/terminals/terminals';-import type { LifecycleScriptExecutionResult } from '../workspaces/workspace-lifecycle-service';+import type { LifecycleScriptExecutionResult } from '../locations/lifecycle-service';export type LifecycleScriptPolicy = {exit?: boolean;@@ -46,31 +46,27 @@ function withLifecycleTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {}function lifecycleScriptSessionId({- projectId,- workspaceId,+ locationId,type,}: {- projectId: string;- workspaceId: string;+ locationId: string;type: LifecycleScriptType;}): string {- return makePtySessionId(projectId, workspaceId, createLifecycleScriptTerminalId(type));+ return makePtySessionId(locationId, locationId, createLifecycleScriptTerminalId(type));}export function stopLifecycleScriptSession({- projectId,+ locationId,sessionId,- workspaceId,type,origin,}: {- projectId: string;+ locationId: string;sessionId: string;- workspaceId: string;type: LifecycleScriptType;origin: LifecycleScriptOrigin;}): boolean {- const ptySessionId = lifecycleScriptSessionId({ projectId, workspaceId, type });+ const ptySessionId = lifecycleScriptSessionId({ locationId, type });const pty = ptySessionRegistry.get(ptySessionId);if (!pty) return false;if (!activeSessions.has(ptySessionId)) return false;@@ -79,9 +75,8 @@ export function stopLifecycleScriptSession({stoppedSessions.add(ptySessionId);pty.kill();events.emit(lifecycleScriptStatusChannel, {- projectId,+ locationId,sessionId,- workspaceId,type,origin,status: 'stopped',@@ -107,10 +102,9 @@ function failureMessage(type: LifecycleScriptType, result: LifecycleScriptExecut}export async function runLifecycleScriptWithPolicy({- workspace,- projectId,+ runtime,+ locationId,sessionId,- workspaceId,type,script,shellSetup,@@ -118,10 +112,9 @@ export async function runLifecycleScriptWithPolicy({policy,logPrefix,}: {- workspace: Workspace;- projectId: string;+ runtime: LocationRuntime;+ locationId: string;sessionId: string;- workspaceId: string;type: LifecycleScriptType;script: string;shellSetup?: string;@@ -129,16 +122,15 @@ export async function runLifecycleScriptWithPolicy({policy: LifecycleScriptPolicy;logPrefix: string;}): Promise<LifecycleScriptCoordinatorResult> {- const ptySessionId = lifecycleScriptSessionId({ projectId, workspaceId, type });+ const ptySessionId = lifecycleScriptSessionId({ locationId, type });if (activeSessions.has(ptySessionId)) {return { kind: 'already-running' };}activeSessions.add(ptySessionId);events.emit(lifecycleScriptStatusChannel, {- projectId,+ locationId,sessionId,- workspaceId,type,origin,status: 'running',@@ -146,7 +138,7 @@ export async function runLifecycleScriptWithPolicy({let result: LifecycleScriptExecutionResult | undefined;try {- const execution = workspace.lifecycleService.runLifecycleScript(+ const execution = runtime.lifecycleService.runLifecycleScript({ type, script, shellSetup },{exit: policy.exit ?? true,@@ -169,9 +161,8 @@ export async function runLifecycleScriptWithPolicy({if (isSuccessfulResult(result)) {events.emit(lifecycleScriptStatusChannel, {- projectId,+ locationId,sessionId,- workspaceId,type,origin,status: 'succeeded',@@ -181,9 +172,8 @@ export async function runLifecycleScriptWithPolicy({}return handleFailure({- projectId,+ locationId,sessionId,- workspaceId,type,origin,policy,@@ -204,9 +194,8 @@ export async function runLifecycleScriptWithPolicy({: `${labelFor(type)} script failed to run.`;return handleFailure({- projectId,+ locationId,sessionId,- workspaceId,type,origin,policy,@@ -222,9 +211,8 @@ export async function runLifecycleScriptWithPolicy({}function handleFailure({- projectId,+ locationId,sessionId,- workspaceId,type,origin,policy,@@ -233,9 +221,8 @@ function handleFailure({result,error,}: {- projectId: string;+ locationId: string;sessionId: string;- workspaceId: string;type: LifecycleScriptType;origin: LifecycleScriptOrigin;policy: LifecycleScriptPolicy;@@ -252,7 +239,7 @@ function handleFailure({if (policy.logFailure) {log.error(`${logPrefix}: ${type} script failed`, {sessionId,- workspaceId,+ locationId,error: message,exitCode: result?.kind === 'exited' ? result.exitCode : undefined,signal: result?.kind === 'exited' ? result.signal : undefined,@@ -261,9 +248,8 @@ function handleFailure({}events.emit(lifecycleScriptStatusChannel, {- projectId,+ locationId,sessionId,- workspaceId,type,origin,status: 'failed',diff --git a/dash/apps/switchdash-desktop/src/main/core/terminals/lifecycle-script-settings.ts b/dash/apps/switchdash-desktop/src/main/core/terminals/lifecycle-script-settings.tsindex 87f425c83..d7723ed09 100644--- a/dash/apps/switchdash-desktop/src/main/core/terminals/lifecycle-script-settings.ts+++ b/dash/apps/switchdash-desktop/src/main/core/terminals/lifecycle-script-settings.ts@@ -1,19 +1,19 @@-import type { Workspace } from '@main/core/workspaces/workspace';+import type { LocationRuntime } from '@main/core/locations/location-runtime';import type { LifecycleScriptType } from '@shared/core/sessions/sessionEvents';-import { getEffectiveSessionSettings } from '../projects/settings/effective-session-settings';-import { resolveWorkspace } from '../projects/utils';+import { getEffectiveSessionSettings } from '../locations/settings/effective-session-settings';+import { resolveLocationRuntime } from '../locations/utils';/**- * Reads the effective lifecycle script config for an already-resolved workspace.- * This is used by callers that already have a Workspace, such as workspace setup/teardown hooks.+ * Reads the effective lifecycle script config for an already-resolved location+ * runtime. Used by callers that already have one, such as setup/teardown hooks.*/-export async function resolveLifecycleScriptForWorkspace(- workspace: Workspace,+export async function resolveLifecycleScriptForRuntime(+ runtime: LocationRuntime,type: LifecycleScriptType): Promise<{ script?: string; shellSetup?: string }> {const settings = await getEffectiveSessionSettings({- projectSettings: workspace.settings,- sessionFs: workspace.fs,+ locationSettings: runtime.settings,+ sessionFs: runtime.fs,});return {script: settings.scripts?.[type],@@ -22,21 +22,19 @@ export async function resolveLifecycleScriptForWorkspace(}/**- * Resolves a workspace by id, then reads the effective lifecycle script config for it.- * This is used by RPC adapters that only receive ids from the renderer.+ * Resolves a location runtime by id, then reads the effective lifecycle script+ * config for it. Used by RPC adapters that only receive ids from the renderer.*/export async function resolveLifecycleScript({- projectId,- workspaceId,+ locationId,type,}: {- projectId: string;- workspaceId: string;+ locationId: string;type: LifecycleScriptType;-}): Promise<{ workspace: Workspace; script?: string; shellSetup?: string }> {- const workspace = resolveWorkspace(projectId, workspaceId);- if (!workspace) throw new Error('Workspace not found');+}): Promise<{ runtime: LocationRuntime; script?: string; shellSetup?: string }> {+ const runtime = resolveLocationRuntime(locationId);+ if (!runtime) throw new Error(`No live runtime for location ${locationId}`);- const settings = await resolveLifecycleScriptForWorkspace(workspace, type);- return { workspace, ...settings };+ const settings = await resolveLifecycleScriptForRuntime(runtime, type);+ return { runtime, ...settings };}diff --git a/dash/apps/switchdash-desktop/src/main/core/terminals/prepareLifecycleScript.ts b/dash/apps/switchdash-desktop/src/main/core/terminals/prepareLifecycleScript.tsindex e4e2a68ea..0245b7387 100644--- a/dash/apps/switchdash-desktop/src/main/core/terminals/prepareLifecycleScript.ts+++ b/dash/apps/switchdash-desktop/src/main/core/terminals/prepareLifecycleScript.ts@@ -1,22 +1,19 @@import { resolveLifecycleScript } from './lifecycle-script-settings';export async function prepareLifecycleScript({- projectId,- workspaceId,+ locationId,type,}: {- projectId: string;- workspaceId: string;+ locationId: string;type: 'setup' | 'run' | 'teardown';}): Promise<void> {- const { workspace, script, shellSetup } = await resolveLifecycleScript({- projectId,- workspaceId,+ const { runtime, script, shellSetup } = await resolveLifecycleScript({+ locationId,type,});if (!script) return;- await workspace.lifecycleService.prepareLifecycleScript({+ await runtime.lifecycleService.prepareLifecycleScript({type,script,shellSetup,diff --git a/dash/apps/switchdash-desktop/src/main/core/terminals/runLifecycleScript.test.ts b/dash/apps/switchdash-desktop/src/main/core/terminals/runLifecycleScript.test.tsindex 9a1368cc9..8a0ecc9b4 100644--- a/dash/apps/switchdash-desktop/src/main/core/terminals/runLifecycleScript.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/terminals/runLifecycleScript.test.ts@@ -1,11 +1,11 @@import { beforeEach, describe, expect, it, vi } from 'vitest';-import { getEffectiveSessionSettings } from '../projects/settings/effective-session-settings';-import { resolveWorkspace } from '../projects/utils';+import { getEffectiveSessionSettings } from '../locations/settings/effective-session-settings';+import { resolveLocationRuntime } from '../locations/utils';import { runLifecycleScript } from './runLifecycleScript';const runCoordinator = vi.hoisted(() =>- vi.fn(async ({ workspace, type, script, shellSetup, policy }) => {- await workspace.lifecycleService.runLifecycleScript(+ vi.fn(async ({ runtime, type, script, shellSetup, policy }) => {+ await runtime.lifecycleService.runLifecycleScript({ type, script, shellSetup },{exit: policy.exit ?? true,@@ -16,12 +16,12 @@ const runCoordinator = vi.hoisted(() =>}));-vi.mock('../projects/settings/effective-session-settings', () => ({+vi.mock('../locations/settings/effective-session-settings', () => ({getEffectiveSessionSettings: vi.fn(),}));-vi.mock('../projects/utils', () => ({- resolveWorkspace: vi.fn(),+vi.mock('../locations/utils', () => ({+ resolveLocationRuntime: vi.fn(),}));vi.mock('./lifecycle-script-coordinator', () => ({@@ -35,7 +35,7 @@ describe('runLifecycleScript', () => {it('runs manual lifecycle scripts with exit and restores the prompt afterward', async () => {const lifecycleRun = vi.fn(async () => {});- vi.mocked(resolveWorkspace).mockReturnValue({+ vi.mocked(resolveLocationRuntime).mockReturnValue({settings: {},fs: {},lifecycleService: {@@ -50,9 +50,8 @@ describe('runLifecycleScript', () => {} as never);await runLifecycleScript({- projectId: 'project-1',+ locationId: 'loc-1',sessionId: 'session-1',- workspaceId: 'branch:feature',type: 'run',});@@ -61,10 +60,9 @@ describe('runLifecycleScript', () => {{ exit: true, waitForExit: true, respawnAfterExit: true });expect(runCoordinator).toHaveBeenCalledWith({- workspace: expect.any(Object),- projectId: 'project-1',+ runtime: expect.any(Object),+ locationId: 'loc-1',sessionId: 'session-1',- workspaceId: 'branch:feature',type: 'run',script: 'pnpm dev',shellSetup: 'source .envrc',diff --git a/dash/apps/switchdash-desktop/src/main/core/terminals/runLifecycleScript.ts b/dash/apps/switchdash-desktop/src/main/core/terminals/runLifecycleScript.tsindex bfc0c9914..66060f5ce 100644--- a/dash/apps/switchdash-desktop/src/main/core/terminals/runLifecycleScript.ts+++ b/dash/apps/switchdash-desktop/src/main/core/terminals/runLifecycleScript.ts@@ -2,27 +2,23 @@ import { runLifecycleScriptWithPolicy } from './lifecycle-script-coordinator';import { resolveLifecycleScript } from './lifecycle-script-settings';export async function runLifecycleScript({- projectId,+ locationId,sessionId,- workspaceId,type,}: {- projectId: string;+ locationId: string;sessionId: string;- workspaceId: string;type: 'setup' | 'run' | 'teardown';}) {- const { workspace, script, shellSetup } = await resolveLifecycleScript({- projectId,- workspaceId,+ const { runtime, script, shellSetup } = await resolveLifecycleScript({+ locationId,type,});if (!script) return;await runLifecycleScriptWithPolicy({- workspace,- projectId,+ runtime,+ locationId,sessionId,- workspaceId,type,script,shellSetup,diff --git a/dash/apps/switchdash-desktop/src/main/core/terminals/terminal-provider.ts b/dash/apps/switchdash-desktop/src/main/core/terminals/terminal-provider.tsindex 8050c5aef..be4062efc 100644--- a/dash/apps/switchdash-desktop/src/main/core/terminals/terminal-provider.ts+++ b/dash/apps/switchdash-desktop/src/main/core/terminals/terminal-provider.ts@@ -11,8 +11,8 @@ export type LifecycleScriptSpawnRequest = {};/**- * Spawns lifecycle-script PTYs (setup/run/teardown) for a workspace. One- * instance per workspace, owned by its LifecycleScriptService.+ * Spawns lifecycle-script PTYs (setup/run/teardown) for a location. One+ * instance per location, owned by its LifecycleScriptService.*/export interface TerminalProvider {readonly kind: 'local' | 'ssh';diff --git a/dash/apps/switchdash-desktop/src/main/core/view-state/view-state-service.ts b/dash/apps/switchdash-desktop/src/main/core/view-state/view-state-service.tsindex ee8f5e43c..b218d5a74 100644--- a/dash/apps/switchdash-desktop/src/main/core/view-state/view-state-service.ts+++ b/dash/apps/switchdash-desktop/src/main/core/view-state/view-state-service.ts@@ -21,7 +21,7 @@ export const viewStateService = {sql`DELETE FROM kv WHERE key LIKE 'view-state:session:%' AND SUBSTR(key, LENGTH('view-state:session:') + 1) NOT IN (SELECT id FROM sessions)`);db.run(- sql`DELETE FROM kv WHERE key LIKE 'view-state:project:%' AND SUBSTR(key, LENGTH('view-state:project:') + 1) NOT IN (SELECT id FROM projects)`+ sql`DELETE FROM kv WHERE key LIKE 'view-state:location:%' AND SUBSTR(key, LENGTH('view-state:location:') + 1) NOT IN (SELECT id FROM locations)`);},};diff --git a/dash/apps/switchdash-desktop/src/main/core/workspaces/project-settings-controller.ts b/dash/apps/switchdash-desktop/src/main/core/workspaces/project-settings-controller.tsdeleted file mode 100644index 3f4d03d41..000000000--- a/dash/apps/switchdash-desktop/src/main/core/workspaces/project-settings-controller.ts+++ /dev/null@@ -1,20 +0,0 @@-import { getEffectiveSessionSettings } from '@main/core/projects/settings/effective-session-settings';-import { workspaceRegistry } from '@main/core/workspaces/workspace-registry';-import type { ProjectSettings } from '@shared/core/project-settings/project-settings';-import { createRPCController } from '@shared/lib/ipc/rpc';--async function getSettings(workspaceId: string): Promise<ProjectSettings> {- const workspace = workspaceRegistry.get(workspaceId);- if (!workspace) {- throw new Error(`Workspace ${workspaceId} not found`);- }-- return getEffectiveSessionSettings({- projectSettings: workspace.settings,- sessionFs: workspace.fs,- });-}--export const projectSettingsController = createRPCController({- getSettings,-});diff --git a/dash/apps/switchdash-desktop/src/main/core/workspaces/resolve-agent-workspace.test.ts b/dash/apps/switchdash-desktop/src/main/core/workspaces/resolve-agent-workspace.test.tsdeleted file mode 100644index f41b9f049..000000000--- a/dash/apps/switchdash-desktop/src/main/core/workspaces/resolve-agent-workspace.test.ts+++ /dev/null@@ -1,52 +0,0 @@-import { describe, expect, it } from 'vitest';-import type { Agent } from '@shared/core/agents/agents';-import { agentSshConnectionId, resolveAgentWorkspace } from './resolve-agent-workspace';--const PROJECT = { projectId: 'proj-1', repoPath: '/local/repo' };--function agent(- overrides: Partial<Pick<Agent, 'connection' | 'remoteConfig'>>-): Pick<Agent, 'connection' | 'remoteConfig'> {- return { connection: 'local', remoteConfig: null, ...overrides };-}--describe('resolveAgentWorkspace', () => {- it('keys a local agent by project id and runs in the project dir', () => {- const result = resolveAgentWorkspace(agent({ connection: 'local' }), PROJECT);- expect(result).toEqual({- type: { kind: 'local' },- workspaceId: 'proj-1',- workDir: '/local/repo',- });- });-- it('keys a remote agent by host+dir and runs in the remote dir', () => {- const result = resolveAgentWorkspace(- agent({- connection: 'remote',- remoteConfig: { sshHost: 'box', remoteRepoDir: '/home/dev/r' },- }),- PROJECT- );- expect(result).toEqual({- type: {- kind: 'ssh',- host: 'box',- remoteRepoDir: '/home/dev/r',- connectionId: 'agent-ssh:box',- },- workspaceId: 'proj-1:ssh:box:/home/dev/r',- workDir: '/home/dev/r',- });- });-- it('shares one pooled connection id per host', () => {- expect(agentSshConnectionId('box')).toBe('agent-ssh:box');- });-- it('fails loud when a remote agent has no remoteConfig', () => {- expect(() => resolveAgentWorkspace(agent({ connection: 'remote' }), PROJECT)).toThrow(- /remoteConfig is missing/- );- });-});diff --git a/dash/apps/switchdash-desktop/src/main/core/workspaces/resolve-agent-workspace.ts b/dash/apps/switchdash-desktop/src/main/core/workspaces/resolve-agent-workspace.tsdeleted file mode 100644index eac87ce9c..000000000--- a/dash/apps/switchdash-desktop/src/main/core/workspaces/resolve-agent-workspace.ts+++ /dev/null@@ -1,57 +0,0 @@-import type { WorkspaceType } from '@main/core/workspaces/workspace-factory';-import type { Agent } from '@shared/core/agents/agents';--export type ResolvedAgentWorkspace = {- type: WorkspaceType;- workspaceId: string;- workDir: string;-};--/**- * Maps an agent's connection (CHOO-1059) to the workspace its sessions run in.- *- * Local agents run in the project directory and key their workspace by project- * id, exactly as switchdash always has. Remote agents run on an SSH host and- * key their workspace by (host, remoteRepoDir) — NOT the local project dir — so- * a project's local and remote sessions never collapse onto the same shared- * workspace. The SSH connection id is derived from the host so every remote- * session on the same host reuses one pooled connection.- *- * Fails loud if a `remote` agent has no `remoteConfig`: that is a corrupt record- * we cannot provision, not a case to silently fall back to local.- */-export function resolveAgentWorkspace(- agent: Pick<Agent, 'connection' | 'remoteConfig'>,- project: { projectId: string; repoPath: string }-): ResolvedAgentWorkspace {- if (agent.connection === 'local') {- return {- type: { kind: 'local' },- workspaceId: project.projectId,- workDir: project.repoPath,- };- }-- const remote = agent.remoteConfig;- if (!remote) {- throw new Error(- "agent connection is 'remote' but remoteConfig is missing — cannot provision a remote session"- );- }-- return {- type: {- kind: 'ssh',- host: remote.sshHost,- remoteRepoDir: remote.remoteRepoDir,- connectionId: agentSshConnectionId(remote.sshHost),- },- workspaceId: `${project.projectId}:ssh:${remote.sshHost}:${remote.remoteRepoDir}`,- workDir: remote.remoteRepoDir,- };-}--/** Pooled SSH connection id for a host — shared by every remote session on it. */-export function agentSshConnectionId(sshHost: string): string {- return `agent-ssh:${sshHost}`;-}diff --git a/dash/apps/switchdash-desktop/src/main/core/workspaces/workspace-registry.test.ts b/dash/apps/switchdash-desktop/src/main/core/workspaces/workspace-registry.test.tsdeleted file mode 100644index 0cbf354eb..000000000--- a/dash/apps/switchdash-desktop/src/main/core/workspaces/workspace-registry.test.ts+++ /dev/null@@ -1,280 +0,0 @@-import { describe, expect, it, vi } from 'vitest';-import type { Workspace } from './workspace';-import { WorkspaceRegistry } from './workspace-registry';--function makeWorkspace(id: string): {- workspace: Workspace;- dispose: ReturnType<typeof vi.fn>;-} {- const dispose = vi.fn(async () => {});-- return {- workspace: {- id,- path: `/tmp/${id}`,- fs: {} as Workspace['fs'],- settings: {} as Workspace['settings'],- lifecycleService: {- dispose,- } as unknown as Workspace['lifecycleService'],- },- dispose,- };-}--describe('WorkspaceRegistry', () => {- it('creates once and increments ref count on repeated acquire', async () => {- const registry = new WorkspaceRegistry();- const { workspace } = makeWorkspace('branch:main');- const factory = vi.fn(async () => ({ workspace }));-- const first = await registry.acquire('branch:main', 'test-project', factory);- const second = await registry.acquire('branch:main', 'test-project', factory);-- expect(first).toBe(workspace);- expect(second).toBe(workspace);- expect(factory).toHaveBeenCalledTimes(1);- expect(registry.get('branch:main')).toBe(workspace);- expect(registry.refCount('branch:main')).toBe(2);- });-- it('coalesces concurrent acquires for the same key', async () => {- const registry = new WorkspaceRegistry();- const { workspace } = makeWorkspace('branch:main');- let resolveFactory: ((value: { workspace: Workspace }) => void) | undefined;- const factory = vi.fn(- () =>- new Promise<{ workspace: Workspace }>((resolve) => {- resolveFactory = resolve;- })- );-- const first = registry.acquire('branch:main', 'test-project', factory);- const second = registry.acquire('branch:main', 'test-project', factory);-- expect(factory).toHaveBeenCalledTimes(1);- resolveFactory?.({ workspace });-- await expect(first).resolves.toBe(workspace);- await expect(second).resolves.toBe(workspace);- expect(registry.refCount('branch:main')).toBe(2);- });-- it('disposes workspace resources when ref count reaches zero', async () => {- const registry = new WorkspaceRegistry();- const { workspace, dispose } = makeWorkspace('branch:main');- const factory = vi.fn(async () => ({ workspace }));-- await registry.acquire('branch:main', 'test-project', factory);- await registry.acquire('branch:main', 'test-project', factory);-- await registry.release('branch:main');- expect(dispose).not.toHaveBeenCalled();- expect(registry.refCount('branch:main')).toBe(1);-- await registry.release('branch:main');- expect(dispose).toHaveBeenCalledTimes(1);- expect(registry.get('branch:main')).toBeUndefined();- expect(registry.refCount('branch:main')).toBe(0);- });-- it('releaseAll disposes each workspace once and clears the registry', async () => {- const registry = new WorkspaceRegistry();- const first = makeWorkspace('branch:main');- const second = makeWorkspace('root:');-- await registry.acquire('branch:main', 'test-project', async () => ({- workspace: first.workspace,- }));- await registry.acquire('branch:main', 'test-project', async () => ({- workspace: first.workspace,- }));- await registry.acquire('root:', 'test-project', async () => ({ workspace: second.workspace }));-- await registry.releaseAll();-- expect(first.dispose).toHaveBeenCalledTimes(1);- expect(second.dispose).toHaveBeenCalledTimes(1);- expect(registry.refCount('branch:main')).toBe(0);- expect(registry.refCount('root:')).toBe(0);- });-- it('ignores release for unknown keys', async () => {- const registry = new WorkspaceRegistry();- await expect(registry.release('missing')).resolves.toBeUndefined();- });-- it('calls onCreateSideEffect once on first acquire and not on re-acquire', async () => {- const registry = new WorkspaceRegistry();- const { workspace } = makeWorkspace('branch:main');- const onCreateSideEffect = vi.fn();- const factory = vi.fn(async () => ({ workspace, onCreateSideEffect }));-- await registry.acquire('branch:main', 'test-project', factory);- expect(onCreateSideEffect).toHaveBeenCalledTimes(1);- expect(onCreateSideEffect).toHaveBeenCalledWith(workspace);-- await registry.acquire('branch:main', 'test-project', factory);- expect(onCreateSideEffect).toHaveBeenCalledTimes(1);- });-- it('awaits onCreate before acquire resolves', async () => {- const registry = new WorkspaceRegistry();- const { workspace } = makeWorkspace('branch:main');- const order: string[] = [];-- const onCreate = vi.fn(async () => {- order.push('onCreate');- });- const factory = vi.fn(async () => ({ workspace, onCreate }));-- const acquired = registry.acquire('branch:main', 'test-project', factory).then((ws) => {- order.push('acquired');- return ws;- });-- await acquired;-- expect(order).toEqual(['onCreate', 'acquired']);- expect(onCreate).toHaveBeenCalledWith(workspace);- });-- it('does not call onCreate on re-acquire', async () => {- const registry = new WorkspaceRegistry();- const { workspace } = makeWorkspace('branch:main');- const onCreate = vi.fn(async () => {});- const factory = vi.fn(async () => ({ workspace, onCreate }));-- await registry.acquire('branch:main', 'test-project', factory);- await registry.acquire('branch:main', 'test-project', factory);-- expect(onCreate).toHaveBeenCalledTimes(1);- });-- it('calls onDestroy once at final release, not on earlier releases', async () => {- const registry = new WorkspaceRegistry();- const { workspace } = makeWorkspace('branch:main');- const onDestroy = vi.fn(async () => {});- const factory = vi.fn(async () => ({ workspace, onDestroy }));-- await registry.acquire('branch:main', 'test-project', factory);- await registry.acquire('branch:main', 'test-project', factory);-- await registry.release('branch:main');- expect(onDestroy).not.toHaveBeenCalled();-- await registry.release('branch:main');- expect(onDestroy).toHaveBeenCalledTimes(1);- expect(onDestroy).toHaveBeenCalledWith(workspace);- });-- it('calls onDestroy before lifecycleService.dispose', async () => {- const registry = new WorkspaceRegistry();- const { workspace, dispose } = makeWorkspace('branch:main');- const order: string[] = [];-- dispose.mockImplementation(() => {- order.push('lifecycleDispose');- return undefined;- });-- const onDestroy = vi.fn(() => {- order.push('onDestroy');- return Promise.resolve();- });- const factory = vi.fn(async () => ({ workspace, onDestroy }));-- await registry.acquire('branch:main', 'test-project', factory);- await registry.release('branch:main');-- expect(order).toEqual(['onDestroy', 'lifecycleDispose']);- });-- it('calls onDestroy for each entry in releaseAll', async () => {- const registry = new WorkspaceRegistry();- const first = makeWorkspace('branch:main');- const second = makeWorkspace('root:');- const onDestroyFirst = vi.fn(async () => {});- const onDestroySecond = vi.fn(async () => {});-- await registry.acquire('branch:main', 'test-project', async () => ({- workspace: first.workspace,- onDestroy: onDestroyFirst,- }));- await registry.acquire('root:', 'test-project', async () => ({- workspace: second.workspace,- onDestroy: onDestroySecond,- }));-- await registry.releaseAll();-- expect(onDestroyFirst).toHaveBeenCalledTimes(1);- expect(onDestroyFirst).toHaveBeenCalledWith(first.workspace);- expect(onDestroySecond).toHaveBeenCalledTimes(1);- expect(onDestroySecond).toHaveBeenCalledWith(second.workspace);- });-- it('calls onDetach (not onDestroy) when releasing with detach mode', async () => {- const registry = new WorkspaceRegistry();- const { workspace } = makeWorkspace('branch:main');- const onDestroy = vi.fn(async () => {});- const onDetach = vi.fn(async () => {});- const factory = vi.fn(async () => ({ workspace, onDestroy, onDetach }));-- await registry.acquire('branch:main', 'test-project', factory);- await registry.release('branch:main', 'detach');-- expect(onDetach).toHaveBeenCalledTimes(1);- expect(onDetach).toHaveBeenCalledWith(workspace);- expect(onDestroy).not.toHaveBeenCalled();- });-- it('calls onDestroy (not onDetach) when releasing with terminate mode', async () => {- const registry = new WorkspaceRegistry();- const { workspace } = makeWorkspace('branch:main');- const onDestroy = vi.fn(async () => {});- const onDetach = vi.fn(async () => {});- const factory = vi.fn(async () => ({ workspace, onDestroy, onDetach }));-- await registry.acquire('branch:main', 'test-project', factory);- await registry.release('branch:main', 'terminate');-- expect(onDestroy).toHaveBeenCalledTimes(1);- expect(onDestroy).toHaveBeenCalledWith(workspace);- expect(onDetach).not.toHaveBeenCalled();- });-- it('does not call onDetach when ref count has not reached zero', async () => {- const registry = new WorkspaceRegistry();- const { workspace } = makeWorkspace('branch:main');- const onDetach = vi.fn(async () => {});- const factory = vi.fn(async () => ({ workspace, onDetach }));-- await registry.acquire('branch:main', 'test-project', factory);- await registry.acquire('branch:main', 'test-project', factory);-- await registry.release('branch:main', 'detach');- expect(onDetach).not.toHaveBeenCalled();-- await registry.release('branch:main', 'detach');- expect(onDetach).toHaveBeenCalledTimes(1);- });-- it('releaseAllForProject passes detach mode to hooks', async () => {- const registry = new WorkspaceRegistry();- const { workspace } = makeWorkspace('branch:main');- const onDestroy = vi.fn(async () => {});- const onDetach = vi.fn(async () => {});-- await registry.acquire('branch:main', 'test-project', async () => ({- workspace,- onDestroy,- onDetach,- }));-- await registry.releaseAllForProject('test-project', 'detach');-- expect(onDetach).toHaveBeenCalledTimes(1);- expect(onDestroy).not.toHaveBeenCalled();- });-});diff --git a/dash/apps/switchdash-desktop/src/main/core/workspaces/workspace-registry.ts b/dash/apps/switchdash-desktop/src/main/core/workspaces/workspace-registry.tsdeleted file mode 100644index 69f405f6e..000000000--- a/dash/apps/switchdash-desktop/src/main/core/workspaces/workspace-registry.ts+++ /dev/null@@ -1,132 +0,0 @@-import type { Workspace } from './workspace';--export type TeardownMode = 'detach' | 'terminate';--type WorkspaceHooks = {- onCreate?: (workspace: Workspace) => Promise<void>;- onCreateSideEffect?: (workspace: Workspace) => void;- onDestroy?: (workspace: Workspace) => Promise<void>;- onDetach?: (workspace: Workspace) => Promise<void>;-};--export type WorkspaceFactoryResult = { workspace: Workspace } & WorkspaceHooks;--type WorkspaceEntry = {- workspace: Workspace;- refCount: number;- projectId: string;- onDestroy?: (workspace: Workspace) => Promise<void>;- onDetach?: (workspace: Workspace) => Promise<void>;-};--export class WorkspaceRegistry {- private entries = new Map<string, WorkspaceEntry>();- private acquiring = new Map<string, Promise<Workspace>>();-- async acquire(- key: string,- projectId: string,- factory: () => Promise<WorkspaceFactoryResult>- ): Promise<Workspace> {- const existing = this.entries.get(key);- if (existing) {- existing.refCount += 1;- return existing.workspace;- }-- const inFlight = this.acquiring.get(key);- if (inFlight) {- const workspace = await inFlight;- const current = this.entries.get(key);- if (current) current.refCount += 1;- return workspace;- }-- const pending = factory()- .then(async (result) => {- this.entries.set(key, {- workspace: result.workspace,- refCount: 1,- projectId,- onDestroy: result.onDestroy,- onDetach: result.onDetach,- });- result.onCreateSideEffect?.(result.workspace);- await result.onCreate?.(result.workspace);- return result.workspace;- })- .finally(() => {- this.acquiring.delete(key);- });-- this.acquiring.set(key, pending);- return pending;- }-- async release(key: string, mode: TeardownMode = 'terminate'): Promise<void> {- const entry = this.entries.get(key);- if (!entry) {- const inFlight = this.acquiring.get(key);- if (inFlight) {- await inFlight;- await this.release(key, mode);- }- return;- }-- if (entry.refCount > 1) {- entry.refCount -= 1;- return;- }-- this.entries.delete(key);- if (mode === 'terminate') {- await entry.onDestroy?.(entry.workspace);- }- await entry.workspace.dispose?.();- await entry.workspace.lifecycleService.dispose();- if (mode === 'detach') {- await entry.onDetach?.(entry.workspace);- }- }-- get(key: string): Workspace | undefined {- return this.entries.get(key)?.workspace;- }-- listForProject(projectId: string): { workspaceId: string; path: string }[] {- return Array.from(this.entries.entries())- .filter(([, entry]) => entry.projectId === projectId)- .map(([workspaceId, entry]) => ({ workspaceId, path: entry.workspace.path }));- }-- refCount(key: string): number {- return this.entries.get(key)?.refCount ?? 0;- }-- async releaseAllForProject(projectId: string, mode: TeardownMode = 'terminate'): Promise<void> {- const keys = Array.from(this.entries.entries())- .filter(([, e]) => e.projectId === projectId)- .map(([k]) => k);- await Promise.all(keys.map((k) => this.release(k, mode)));- }-- async releaseAll(mode: TeardownMode = 'terminate'): Promise<void> {- const entries = Array.from(this.entries.values());- this.entries.clear();- await Promise.all(- entries.map(async (entry) => {- if (mode === 'terminate') {- await entry.onDestroy?.(entry.workspace);- }- await entry.workspace.dispose?.();- await entry.workspace.lifecycleService.dispose();- if (mode === 'detach') {- await entry.onDetach?.(entry.workspace);- }- })- );- }-}--export const workspaceRegistry = new WorkspaceRegistry();diff --git a/dash/apps/switchdash-desktop/src/main/core/workspaces/workspace.ts b/dash/apps/switchdash-desktop/src/main/core/workspaces/workspace.tsdeleted file mode 100644index 86b1202fd..000000000--- a/dash/apps/switchdash-desktop/src/main/core/workspaces/workspace.ts+++ /dev/null@@ -1,12 +0,0 @@-import type { FileSystemProvider } from '@main/core/fs/types';-import type { ProjectSettingsProvider } from '@main/core/projects/settings/provider';-import type { LifecycleScriptService } from './workspace-lifecycle-service';--export interface Workspace {- readonly id: string;- readonly path: string;- readonly fs: FileSystemProvider;- readonly settings: ProjectSettingsProvider;- readonly lifecycleService: LifecycleScriptService;- dispose?(): void | Promise<void>;-}diff --git a/dash/apps/switchdash-desktop/src/main/db/initialize.ts b/dash/apps/switchdash-desktop/src/main/db/initialize.tsindex c07b8d85f..9829af7b0 100644--- a/dash/apps/switchdash-desktop/src/main/db/initialize.ts+++ b/dash/apps/switchdash-desktop/src/main/db/initialize.ts@@ -67,7 +67,7 @@ function runBundledMigrations(connection: BetterSqlite3.Database): void {function ensureSearchIndex(connection: BetterSqlite3.Database): void {// Bump this version string whenever the FTS schema changes — the table is// dropped and recreated, and backfill() + seedCommands() repopulate it.- const SEARCH_INDEX_VERSION = '3';+ const SEARCH_INDEX_VERSION = '4';const row = connection.prepare(`SELECT value FROM kv WHERE key = 'fts_version'`).get() as| { value: string }@@ -78,9 +78,9 @@ function ensureSearchIndex(connection: BetterSqlite3.Database): void {connection.exec(`CREATE VIRTUAL TABLE search_index USING fts5(item_type,- item_id UNINDEXED,- project_id UNINDEXED,- session_id UNINDEXED,+ item_id UNINDEXED,+ location_id UNINDEXED,+ session_id UNINDEXED,title,keywords,tokenize = 'trigram case_sensitive 0'@@ -95,13 +95,13 @@ function ensureSearchIndex(connection: BetterSqlite3.Database): void {}/**- * Creates the FTS5 virtual table and companion meta table used for workspace+ * Creates the FTS5 virtual table and companion meta table used for location* file indexing. Managed outside Drizzle (same reason as ensureSearchIndex).* Version-gated via `kv` so the tables can be dropped and recreated on schema* changes without a full Drizzle migration.*/function ensureFileIndex(connection: BetterSqlite3.Database): void {- const FILE_INDEX_VERSION = '1';+ const FILE_INDEX_VERSION = '2';const row = connection.prepare(`SELECT value FROM kv WHERE key = 'file_index_version'`).get() as| { value: string }@@ -109,20 +109,21 @@ function ensureFileIndex(connection: BetterSqlite3.Database): void {if (row?.value === FILE_INDEX_VERSION) return;- connection.exec(`DROP TABLE IF EXISTS workspace_file_index`);+ connection.exec(`DROP TABLE IF EXISTS location_file_index`);connection.exec(`DROP TABLE IF EXISTS workspace_file_index_meta`);+ connection.exec(`DROP TABLE IF EXISTS location_file_index_meta`);connection.exec(`- CREATE VIRTUAL TABLE workspace_file_index USING fts5(- workspace_id UNINDEXED,+ CREATE VIRTUAL TABLE location_file_index USING fts5(+ location_id UNINDEXED,path,filename,tokenize = 'trigram case_sensitive 0')`);connection.exec(`- CREATE TABLE workspace_file_index_meta (- workspace_id TEXT PRIMARY KEY,- indexed_at INTEGER NOT NULL+ CREATE TABLE location_file_index_meta (+ location_id TEXT PRIMARY KEY,+ indexed_at INTEGER NOT NULL)`);connectiondiff --git a/dash/apps/switchdash-desktop/src/main/db/schema.ts b/dash/apps/switchdash-desktop/src/main/db/schema.tsindex 19b219d87..423904e0d 100644--- a/dash/apps/switchdash-desktop/src/main/db/schema.ts+++ b/dash/apps/switchdash-desktop/src/main/db/schema.ts@@ -1,32 +1,43 @@import { sql } from 'drizzle-orm';import { index, integer, sqliteTable, text, uniqueIndex } from 'drizzle-orm/sqlite-core';import { versionedJsonColumn } from '@main/db/versioned-column';-import { agentRemoteConfig, type AgentConnectionKind } from '@shared/core/agents/agent-connection';import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';import { sessionConfig } from '@shared/core/sessions/session-config';import type { TerminalShellId } from '@shared/core/terminals/terminal-settings';// ----------------------------------------------------------------------------// Data model (switchdash rework — diverges from switchdash; see-// agents/architecture/data-model.md for the full switchdash → switchdash map):+// Data model (switchdash rework — diverges from upstream; see+// agents/architecture/data-model.md for the full map)://-// projects — a directory on disk-// └─ agents — a Switch agent identity (one provider each; many per dir)+// locations — a working directory on a host (this machine or an SSH host)+// └─ agents — a Switch agent identity (one provider each; many per+// │ location)// └─ sessions — an instantiation/run of an agent (was "conversation";// │ one session == one terminal, folded in)// └─ messages//-// Dropped from switchdash: the worktree-era `sessions` grouping, the `terminals`-// table (folded 1:1 into a session), and the `workspaces` execution-location-// abstraction (switchdash runs every session in the project root).+// Dropped from upstream: the worktree-era `sessions` grouping, the `terminals`+// table (folded 1:1 into a session), and the location/workspace split (a+// `locations` identity table plus a runtime workspace keyed off it) — both+// collapsed into `locations` (CHOO-1426). Every session runs in its agent's+// location dir.// ----------------------------------------------------------------------------export const projects = sqliteTable(- 'projects',+/**+ * A Location: where an agent's sessions run — a working directory on a host.+ * `sshHost` is the `~/.ssh/config` Host alias for remote locations and the+ * empty string for the local machine (a sentinel rather than NULL so the+ * (ssh_host, dir) unique index actually enforces one row per place — SQLite+ * treats NULLs as distinct in unique indexes). Multiple agents may share one+ * location.+ */+export const locations = sqliteTable(+ 'locations',{id: text('id').primaryKey(),name: text('name').notNull(),- path: text('path'),+ sshHost: text('ssh_host').notNull().default(''),+ dir: text('dir').notNull(),createdAt: text('created_at').notNull().default(sql`CURRENT_TIMESTAMP`),@@ -35,16 +46,16 @@ export const projects = sqliteTable(.default(sql`CURRENT_TIMESTAMP`),},(table) => ({- pathIdx: uniqueIndex('idx_projects_path').on(table.path),+ hostDirIdx: uniqueIndex('idx_locations_host_dir').on(table.sshHost, table.dir),}));-export const projectSettings = sqliteTable('project_settings', {- projectId: text('project_id')+export const locationSettings = sqliteTable('location_settings', {+ locationId: text('location_id').primaryKey()- .references(() => projects.id, { onDelete: 'cascade' }),- baseProjectSettingsJson: text('base_project_settings_json').notNull().default('{}'),- shareableProjectSettingsJson: text('shareable_project_settings_json').notNull().default('{}'),+ .references(() => locations.id, { onDelete: 'cascade' }),+ baseSettingsJson: text('base_settings_json').notNull().default('{}'),+ shareableSettingsJson: text('shareable_settings_json').notNull().default('{}'),legacyConfigMigratedAt: text('legacy_config_migrated_at'),createdAt: text('created_at').notNull()@@ -105,10 +116,10 @@ export const switchServers = sqliteTable();/**- * A Switch agent: an agent identity bound to a single provider, living in a- * project directory. Many agents may share a directory (e.g. a Claude Code and- * a Codex agent in the same repo). `switchAgentId` / `apiEndpoint` are populated- * when the directory is configured as a Switch agent (detected from+ * A Switch agent: an agent identity bound to a single provider, living at a+ * location. Many agents may share a location (e.g. a Claude Code and a Codex+ * agent in the same repo). `switchAgentId` / `apiEndpoint` are populated when+ * the location dir is configured as a Switch agent (detected from* `.claude/settings.local.json`); they are null for a plain local agent.** `serverId` binds the agent to the one registered Switch server it belongs to.@@ -121,19 +132,15 @@ export const agents = sqliteTable('agents',{id: text('id').primaryKey(),- projectId: text('project_id')+ locationId: text('location_id').notNull()- .references(() => projects.id, { onDelete: 'cascade' }),+ .references(() => locations.id),name: text('name').notNull(),providerId: text('provider_id').$type<AgentProviderId>().notNull(),switchAgentId: text('switch_agent_id'),apiEndpoint: text('api_endpoint'),serverId: text('server_id').references(() => switchServers.id, { onDelete: 'set null' }),status: text('status'),- /** Where this agent's sessions run: `local` (default) or `remote` over SSH. */- connection: text('connection').$type<AgentConnectionKind>().notNull().default('local'),- /** SSH host + remote working dir; null for local agents. See agent-connection.ts. */- remoteConfigJson: versionedJsonColumn(agentRemoteConfig)('remote_config_json'),createdAt: text('created_at').notNull().default(sql`CURRENT_TIMESTAMP`),@@ -142,7 +149,7 @@ export const agents = sqliteTable(.default(sql`CURRENT_TIMESTAMP`),},(table) => ({- projectIdIdx: index('idx_agents_project_id').on(table.projectId),+ locationIdIdx: index('idx_agents_location_id').on(table.locationId),serverIdIdx: index('idx_agents_server_id').on(table.serverId),}));@@ -250,9 +257,10 @@ export const appSecrets = sqliteTable(}));-export type ProjectRow = typeof projects.$inferSelect;-export type ProjectSettingsRow = typeof projectSettings.$inferSelect;-export type ProjectSettingsInsert = typeof projectSettings.$inferInsert;+export type LocationRow = typeof locations.$inferSelect;+export type LocationInsert = typeof locations.$inferInsert;+export type LocationSettingsRow = typeof locationSettings.$inferSelect;+export type LocationSettingsInsert = typeof locationSettings.$inferInsert;export type AgentRow = typeof agents.$inferSelect;export type AgentInsert = typeof agents.$inferInsert;export type SessionRow = typeof sessions.$inferSelect;diff --git a/dash/apps/switchdash-desktop/src/main/db/tests/migrations/0028-agent-connection.test.ts b/dash/apps/switchdash-desktop/src/main/db/tests/migrations/0028-agent-connection.test.tsdeleted file mode 100644index 7bea381a3..000000000--- a/dash/apps/switchdash-desktop/src/main/db/tests/migrations/0028-agent-connection.test.ts+++ /dev/null@@ -1,65 +0,0 @@-/**- * Migration 0028 — adds `connection` + `remote_config_json` to `agents`- * (CHOO-1059, remote-SSH agents). Applies the migration on top of the- * pre-0028 fixture and asserts existing rows pick up the `local` default and- * the new nullable remote-config column.- */--import { openFixture } from '@tooling/utils/db';-import { eq } from 'drizzle-orm';-import { afterEach, describe, expect, it } from 'vitest';-import { agents } from '@main/db/schema';--describe('migration 0028: agent connection', () => {- let fixture: Awaited<ReturnType<typeof openFixture>>;-- afterEach(() => {- fixture?.close();- });-- it('adds the connection columns to the agents table', async () => {- fixture = await openFixture('pre-0028');-- const columns = fixture.sqlite.prepare(`PRAGMA table_info('agents')`).all() as {- name: string;- }[];- const columnNames = columns.map((c) => c.name);-- expect(columnNames).toContain('connection');- expect(columnNames).toContain('remote_config_json');- });-- it('defaults pre-existing agents to local with no remote config', async () => {- fixture = await openFixture('pre-0028');-- const rows = await fixture.db.select().from(agents);- expect(rows.length).toBeGreaterThan(0);- for (const row of rows) {- expect(row.connection).toBe('local');- expect(row.remoteConfigJson).toBeNull();- }- });-- it('round-trips a remote agent config through the versioned column', async () => {- fixture = await openFixture('pre-0028');-- const [existing] = await fixture.db.select().from(agents).limit(1);- expect(existing).toBeDefined();-- await fixture.db- .update(agents)- .set({- connection: 'remote',- remoteConfigJson: { sshHost: 'dev-vm', remoteRepoDir: '/home/agent/repo' },- })- .where(eq(agents.id, existing!.id));-- const [updated] = await fixture.db.select().from(agents).where(eq(agents.id, existing!.id));-- expect(updated!.connection).toBe('remote');- expect(updated!.remoteConfigJson).toEqual({- sshHost: 'dev-vm',- remoteRepoDir: '/home/agent/repo',- });- });-});diff --git a/dash/apps/switchdash-desktop/src/main/db/tests/migrations/0030-nullable-project-path.test.ts b/dash/apps/switchdash-desktop/src/main/db/tests/migrations/0030-nullable-project-path.test.tsdeleted file mode 100644index ceae4654e..000000000--- a/dash/apps/switchdash-desktop/src/main/db/tests/migrations/0030-nullable-project-path.test.ts+++ /dev/null@@ -1,47 +0,0 @@-/**- * Migration 0030 — makes `projects.path` nullable so a remote-only Switch agent- * (CHOO-1059) can be added without any local directory. Applies all migrations- * on a fresh schema and asserts the column is nullable and round-trips a- * null-path row alongside a normal local one.- */--import { openFixture } from '@tooling/utils/db';-import { isNull } from 'drizzle-orm';-import { afterEach, describe, expect, it } from 'vitest';-import { projects } from '@main/db/schema';--describe('migration 0030: nullable project path', () => {- let fixture: Awaited<ReturnType<typeof openFixture>>;-- afterEach(() => {- fixture?.close();- });-- it('makes the projects.path column nullable', async () => {- fixture = await openFixture('empty');-- const columns = fixture.sqlite.prepare(`PRAGMA table_info('projects')`).all() as {- name: string;- notnull: number;- }[];- const pathColumn = columns.find((c) => c.name === 'path');-- expect(pathColumn).toBeDefined();- expect(pathColumn!.notnull).toBe(0);- });-- it('round-trips a remote-only project with a null path', async () => {- fixture = await openFixture('empty');-- await fixture.db.insert(projects).values([- { id: 'local-1', name: 'Local agent', path: '/home/me/repo' },- { id: 'remote-1', name: 'Remote agent', path: null },- ]);-- const nullPathRows = await fixture.db.select().from(projects).where(isNull(projects.path));-- expect(nullPathRows).toHaveLength(1);- expect(nullPathRows[0]!.id).toBe('remote-1');- expect(nullPathRows[0]!.path).toBeNull();- });-});diff --git a/dash/apps/switchdash-desktop/src/main/db/tests/migrations/0031-locations.test.ts b/dash/apps/switchdash-desktop/src/main/db/tests/migrations/0031-locations.test.tsnew file mode 100644index 000000000..6759b7668--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/db/tests/migrations/0031-locations.test.ts@@ -0,0 +1,106 @@+/**+ * Migrations 0031–0034 — collapse projects + per-agent connection into+ * first-class locations (CHOO-1426). 0031 adds `locations`/`location_settings`+ * and a nullable `agents.location_id`; 0032 backfills them from+ * `projects` + `agents.connection`/`remote_config_json`; 0033 drops the+ * projects tables and old agent columns; 0034 recreates `agents` to enforce+ * NOT NULL on `location_id`.+ *+ * The pre-0031 fixture holds two local projects (with local agents) and one+ * remote project (path NULL, agent connection='remote' with+ * remote_config_json {sshHost: build-vm, remoteRepoDir: /srv/agents/remote-worker}).+ */++import { openFixture } from '@tooling/utils/db';+import { afterEach, describe, expect, it } from 'vitest';+import { agents, locations, locationSettings } from '@main/db/schema';++describe('migrations 0031-0034: first-class locations', () => {+ let fixture: Awaited<ReturnType<typeof openFixture>>;++ afterEach(() => {+ fixture?.close();+ });++ it('creates one location per project, lifting host+dir from remote agents', async () => {+ fixture = await openFixture('pre-0031');++ const rows = await fixture.db.select().from(locations);+ const byId = new Map(rows.map((r) => [r.id, r]));++ expect(rows).toHaveLength(3);+ expect(byId.get('11111111-1111-1111-1111-111111111111')).toMatchObject({+ name: 'emdash',+ sshHost: '',+ dir: '/home/dev/projects/emdash',+ });+ expect(byId.get('22222222-2222-2222-2222-222222222222')).toMatchObject({+ name: 'my-api',+ sshHost: '',+ dir: '/home/dev/projects/my-api',+ });+ expect(byId.get('33333333-3333-3333-3333-333333333333')).toMatchObject({+ name: 'remote-worker',+ sshHost: 'build-vm',+ dir: '/srv/agents/remote-worker',+ });+ });++ it('re-points agents at their location and drops the old columns', async () => {+ fixture = await openFixture('pre-0031');++ const rows = await fixture.db.select().from(agents);+ const byId = new Map(rows.map((r) => [r.id, r]));++ expect(rows).toHaveLength(3);+ expect(byId.get('a9e70001-0000-0000-0000-000000000000')!.locationId).toBe(+ '11111111-1111-1111-1111-111111111111'+ );+ expect(byId.get('a9e70002-0000-0000-0000-000000000000')!.locationId).toBe(+ '22222222-2222-2222-2222-222222222222'+ );+ expect(byId.get('a9e70003-0000-0000-0000-000000000000')!.locationId).toBe(+ '33333333-3333-3333-3333-333333333333'+ );++ const columns = fixture.sqlite.prepare(`PRAGMA table_info('agents')`).all() as {+ name: string;+ notnull: number;+ }[];+ const names = columns.map((c) => c.name);+ expect(names).not.toContain('project_id');+ expect(names).not.toContain('connection');+ expect(names).not.toContain('remote_config_json');+ expect(columns.find((c) => c.name === 'location_id')!.notnull).toBe(1);+ });++ it('moves project_settings to location_settings and drops the projects tables', async () => {+ fixture = await openFixture('pre-0031');++ const settings = await fixture.db.select().from(locationSettings);+ const settingsIds = settings.map((s) => s.locationId).sort();+ expect(settingsIds).toEqual([+ '11111111-1111-1111-1111-111111111111',+ '22222222-2222-2222-2222-222222222222',+ ]);++ const tables = fixture.sqlite+ .prepare(`SELECT name FROM sqlite_master WHERE type = 'table'`)+ .all() as { name: string }[];+ const tableNames = tables.map((t) => t.name);+ expect(tableNames).not.toContain('projects');+ expect(tableNames).not.toContain('project_settings');+ expect(tableNames).toContain('locations');+ expect(tableNames).toContain('location_settings');+ });++ it('enforces (ssh_host, dir) uniqueness on locations', async () => {+ fixture = await openFixture('pre-0031');++ await expect(+ fixture.db+ .insert(locations)+ .values([{ id: 'dupe', name: 'dupe', sshHost: '', dir: '/home/dev/projects/my-api' }])+ ).rejects.toThrow(/UNIQUE/i);+ });+});diff --git a/dash/apps/switchdash-desktop/src/main/db/tests/migrations/0036-location-provider.test.ts b/dash/apps/switchdash-desktop/src/main/db/tests/migrations/0036-location-provider.test.tsnew file mode 100644index 000000000..106826854--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/db/tests/migrations/0036-location-provider.test.ts@@ -0,0 +1,64 @@+/**+ * Migration 0036 — renames the base location setting `workspaceProvider` to+ * `locationProvider` (CHOO-1426). The value lives inside the+ * `location_settings.base_settings_json` blob (not a column), so the migration+ * rewrites persisted blobs rather than altering DDL.+ *+ * openFixture('empty') already applied 0036 over an empty dataset (a no-op), so+ * this test seeds representative pre-0036 blobs and re-applies the committed+ * migration SQL to assert the transform: the nested object moves to the new key+ * unchanged, and rows without the old key are untouched.+ */++import { readFileSync } from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { openFixture } from '@tooling/utils/db';+import { afterEach, describe, expect, it } from 'vitest';++const MIGRATION_SQL = readFileSync(+ path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ '../../../../../drizzle/0036_rename_workspace_provider_setting.sql'+ ),+ 'utf8'+);++const PROVIDER = { type: 'script', provisionCommand: 'up', terminateCommand: 'down' };++describe('migration 0036: workspaceProvider -> locationProvider', () => {+ let fixture: Awaited<ReturnType<typeof openFixture>>;++ afterEach(() => {+ fixture?.close();+ });++ function seedLocation(id: string, baseSettings: Record<string, unknown>) {+ fixture.sqlite+ .prepare(`INSERT INTO locations (id, name, ssh_host, dir) VALUES (?, ?, '', ?)`)+ .run(id, id, `/tmp/${id}`);+ fixture.sqlite+ .prepare(`INSERT INTO location_settings (location_id, base_settings_json) VALUES (?, ?)`)+ .run(id, JSON.stringify(baseSettings));+ }++ function baseSettings(id: string): Record<string, unknown> {+ const [row] = fixture.sqlite+ .prepare(`SELECT base_settings_json AS json FROM location_settings WHERE location_id = ?`)+ .all(id) as { json: string }[];+ return JSON.parse(row.json);+ }++ it('moves the provider object to locationProvider and drops the old key', async () => {+ fixture = await openFixture('empty');+ seedLocation('with-provider', { tmux: true, workspaceProvider: PROVIDER });+ seedLocation('no-provider', { tmux: false });+ seedLocation('empty', {});++ fixture.sqlite.exec(MIGRATION_SQL);++ expect(baseSettings('with-provider')).toEqual({ tmux: true, locationProvider: PROVIDER });+ expect(baseSettings('no-provider')).toEqual({ tmux: false });+ expect(baseSettings('empty')).toEqual({});+ });+});diff --git a/dash/apps/switchdash-desktop/src/main/db/tests/migrations/example.test.ts b/dash/apps/switchdash-desktop/src/main/db/tests/migrations/example.test.tsindex b67018228..16d547c4d 100644--- a/dash/apps/switchdash-desktop/src/main/db/tests/migrations/example.test.ts+++ b/dash/apps/switchdash-desktop/src/main/db/tests/migrations/example.test.ts@@ -26,7 +26,7 @@import { openFixture } from '@tooling/utils/db';import { count } from 'drizzle-orm';import { afterEach, describe, expect, it } from 'vitest';-import { projects, sessions } from '@main/db/schema';+import { locations, sessions } from '@main/db/schema';describe('baseline fixture integrity', () => {let fixture: Awaited<ReturnType<typeof openFixture>>;@@ -43,27 +43,27 @@ describe('baseline fixture integrity', () => {.all() as { name: string }[];const tableNames = tables.map((t) => t.name);- expect(tableNames).toContain('projects');+ expect(tableNames).toContain('locations');expect(tableNames).toContain('agents');expect(tableNames).toContain('sessions');expect(tableNames).toContain('__drizzle_migrations');});- it('has seeded projects and sessions in the baseline fixture', async () => {+ it('has seeded locations and sessions in the baseline fixture', async () => {fixture = await openFixture('baseline');- const [{ value: projectCount }] = await fixture.db.select({ value: count() }).from(projects);+ const [{ value: locationCount }] = await fixture.db.select({ value: count() }).from(locations);const [{ value: sessionCount }] = await fixture.db.select({ value: count() }).from(sessions);- expect(projectCount).toBe(2);+ expect(locationCount).toBe(3);expect(sessionCount).toBe(4);});it('starts clean with the empty fixture', async () => {fixture = await openFixture('empty');- const [{ value: projectCount }] = await fixture.db.select({ value: count() }).from(projects);+ const [{ value: locationCount }] = await fixture.db.select({ value: count() }).from(locations);- expect(projectCount).toBe(0);+ expect(locationCount).toBe(0);});});diff --git a/dash/apps/switchdash-desktop/src/main/db/versioned-column.ts b/dash/apps/switchdash-desktop/src/main/db/versioned-column.tsindex c9921a275..5b9b0d96f 100644--- a/dash/apps/switchdash-desktop/src/main/db/versioned-column.ts+++ b/dash/apps/switchdash-desktop/src/main/db/versioned-column.ts@@ -77,12 +77,12 @@ export function serializeVersionedColumn<T>(** @example* ```ts- * import { workspaceConfig } from '@shared/workspace-config';+ * import { sessionConfig } from '@shared/session-config';*- * export const workspaces = sqliteTable('workspaces', {- * config: versionedJsonColumn(workspaceConfig)('config'),+ * export const sessions = sqliteTable('sessions', {+ * config: versionedJsonColumn(sessionConfig)('config'),* });- * // workspaces.config is typed as WorkspaceConfig | null+ * // sessions.config is typed as SessionConfig | null* ```*/export function versionedJsonColumn<T>(schema: VersionedSchema<T>) {diff --git a/dash/apps/switchdash-desktop/src/main/index.ts b/dash/apps/switchdash-desktop/src/main/index.tsindex 663085882..28afdd51e 100644--- a/dash/apps/switchdash-desktop/src/main/index.ts+++ b/dash/apps/switchdash-desktop/src/main/index.ts@@ -14,15 +14,15 @@ import { initializeRemoteDiscovery, initializeRemoteWatchers } from './core/agenimport { resolveAgentServers } from './core/agents/resolve-servers';import { appService } from './core/app/service';import { localDependencyManager } from './core/dependencies/dependency-managers';-import { projectManager } from './core/projects/project-manager';-import { projectSettingsService } from './core/projects/settings/project-settings-service';+import { locationManager } from './core/locations/location-manager';+import { locationSettingsService } from './core/locations/settings/location-settings-service';import { promptLibraryService } from './core/prompt-library/service';import {reconcileResourceSampler,stopResourceSampler,} from './core/resource-monitor/resource-sampler';+import { locationFileIndexService } from './core/search/location-file-index-service';import { searchService } from './core/search/search-service';-import { workspaceFileIndexService } from './core/search/workspace-file-index-service';import { appSettingsService } from './core/settings/settings-service';import { sshConnectionManager } from './core/ssh/lifecycle/production-ssh-connection-manager';import { autoSessionWatcher } from './core/switch-rooms/auto-session-watcher';@@ -91,7 +91,7 @@ void app.whenReady().then(async () => {try {await initializeDatabase();searchService.initialize();- workspaceFileIndexService.initialize();+ locationFileIndexService.initialize();try {viewStateService.pruneOrphans();} catch (e: unknown) {@@ -107,7 +107,7 @@ void app.whenReady().then(async () => {return;}- projectSettingsService.initialize();+ locationSettingsService.initialize();appService.initialize();await appSettingsService.initialize();await promptLibraryService.initialize();@@ -192,8 +192,8 @@ app.on('before-quit', (event) => {agentHookService.dispose();stopResourceSampler();updateService.dispose();- void projectManager.dispose().catch((e) => {- log.error('Failed to shutdown project manager:', e);+ void locationManager.dispose().catch((e) => {+ log.error('Failed to shutdown location manager:', e);});app.exit(0);});diff --git a/dash/apps/switchdash-desktop/src/main/lib/file-logger.test.ts b/dash/apps/switchdash-desktop/src/main/lib/file-logger.test.tsindex 1986dc9d3..4b41ac29e 100644--- a/dash/apps/switchdash-desktop/src/main/lib/file-logger.test.ts+++ b/dash/apps/switchdash-desktop/src/main/lib/file-logger.test.ts@@ -108,7 +108,7 @@ describe('redactDiagnosticLog', () => {const redacted = redactDiagnosticLog(['email [email protected]',- 'mac /Users/alice/projects/switchdash',+ 'mac /Users/alice/locations/switchdash','linux /home/bob/work/repo','win C:\\Users\\carol\\repo','ipv4 192.168.1.25',@@ -120,7 +120,7 @@ describe('redactDiagnosticLog', () => {);expect(redacted).toContain('[REDACTED_EMAIL]');- expect(redacted).toContain('/Users/[REDACTED_USER]/projects/switchdash');+ expect(redacted).toContain('/Users/[REDACTED_USER]/locations/switchdash');expect(redacted).toContain('/home/[REDACTED_USER]/work/repo');expect(redacted).toContain('C:\\Users\\[REDACTED_USER]\\repo');expect(redacted).toContain('ipv4 [REDACTED_IP]');diff --git a/dash/apps/switchdash-desktop/src/main/rpc.ts b/dash/apps/switchdash-desktop/src/main/rpc.tsindex 5eccc513b..c5bf65f4b 100644--- a/dash/apps/switchdash-desktop/src/main/rpc.ts+++ b/dash/apps/switchdash-desktop/src/main/rpc.ts@@ -2,7 +2,8 @@ import { createRPCNamespace, createRPCRouter } from '../shared/lib/ipc/rpc';import { agentsController } from './core/agents/controller';import { appController } from './core/app/controller';import { filesController } from './core/fs/controller';-import { projectController } from './core/projects/controller';+import { locationsController } from './core/locations/controller';+import { locationRuntimeSettingsController } from './core/locations/location-runtime-settings-controller';import { promptLibraryController } from './core/prompt-library/controller';import { providersController } from './core/providers/controller';import { ptyController } from './core/pty/controller';@@ -18,7 +19,6 @@ import { switchServersController } from './core/switch-servers/controller';import { switchSetupController } from './core/switch-setup/controller';import { updateController } from './core/updates/controller';import { viewStateController } from './core/view-state/controller';-import { projectSettingsController } from './core/workspaces/project-settings-controller';export const rpcRouter = createRPCRouter({providers: providersController,@@ -30,18 +30,18 @@ export const rpcRouter = createRPCRouter({pty: ptyController,resourceMonitor: resourceMonitorController,promptLibrary: promptLibraryController,- projects: projectController,+ locations: locationsController,sessions: sessionController,viewState: viewStateController,search: searchController,switchRooms: switchRoomsController,subagents: subagentsController,- projectSettings: projectSettingsController,+ locationRuntimeSettings: locationRuntimeSettingsController,switchServers: switchServersController,switchSetup: switchSetupController,remoteHosts: remoteHostsController,- workspace: createRPCNamespace({- fs: filesController,+ fs: createRPCNamespace({+ watch: filesController,}),});diff --git a/dash/apps/switchdash-desktop/src/renderer/app/app-menu-events.tsx b/dash/apps/switchdash-desktop/src/renderer/app/app-menu-events.tsxindex 6caf9f52f..5391164d6 100644--- a/dash/apps/switchdash-desktop/src/renderer/app/app-menu-events.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/app/app-menu-events.tsx@@ -63,9 +63,12 @@ export function AppMenuEvents({ onOpenSettings }: { onOpenSettings?: () => booleuseEffect(() => {const disposers = new Set<() => void>();- const unlisten = events.on(notificationFocusSessionChannel, ({ projectId, sessionId }) => {+ const unlisten = events.on(notificationFocusSessionChannel, ({ agentId, sessionId }) => {// A session shows its single terminal automatically, so navigating is enough.- navigate('session', { projectId, sessionId });+ // The event carries the agent; resolve its location to route the session view.+ void rpc.agents.getAgentById(agentId).then((agent) => {+ if (agent) navigate('session', { locationId: agent.locationId, sessionId });+ });});return () => {diff --git a/dash/apps/switchdash-desktop/src/renderer/app/home-view.tsx b/dash/apps/switchdash-desktop/src/renderer/app/home-view.tsxindex 81589e1a2..181bc13d4 100644--- a/dash/apps/switchdash-desktop/src/renderer/app/home-view.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/app/home-view.tsx@@ -6,7 +6,7 @@ import { useShowModal } from '@renderer/lib/modal/modal-provider';import { SwitchdashShimmerLogo } from '@renderer/lib/switchdash-shimmer-logo';import { ActionListItem } from '@renderer/lib/ui/action-list-item';-const PROJECT_ACTIONS = [+const LOCATION_ACTIONS = [{label: 'Add Switch agent',description: 'Onboard a local directory as a Switch agent — configuring one if needed',@@ -16,10 +16,10 @@ const PROJECT_ACTIONS = [] as const;export function HomeMainPanel() {- const showAddProjectModal = useShowModal('addProjectModal');+ const showAddLocationModal = useShowModal('addAgentModal');const { selectedIndex, setSelectedIndex } = useArrowKeyNavigation(- PROJECT_ACTIONS.length,- (index) => showAddProjectModal(PROJECT_ACTIONS[index].modalArgs)+ LOCATION_ACTIONS.length,+ (index) => showAddLocationModal(LOCATION_ACTIONS[index].modalArgs));const { effectiveTheme } = useTheme();const isDark = effectiveTheme === 'emdark';@@ -42,15 +42,15 @@ export function HomeMainPanel() {</div></div><div className="mx-auto mt-8 flex w-full max-w-md flex-col gap-1">- {PROJECT_ACTIONS.map((action, i) => (- <HomeProjectAction+ {LOCATION_ACTIONS.map((action, i) => (+ <HomeLocationActionkey={action.label}label={action.label}description={action.description}icon={action.icon}isSelected={i === selectedIndex}onMouseEnter={() => setSelectedIndex(i)}- onClick={() => showAddProjectModal(action.modalArgs)}+ onClick={() => showAddLocationModal(action.modalArgs)}/>))}</div>@@ -59,7 +59,7 @@ export function HomeMainPanel() {);}-function HomeProjectAction({+function HomeLocationAction({label,description,icon,diff --git a/dash/apps/switchdash-desktop/src/renderer/app/modal-registry.ts b/dash/apps/switchdash-desktop/src/renderer/app/modal-registry.tsindex 362e42a80..fad564cfe 100644--- a/dash/apps/switchdash-desktop/src/renderer/app/modal-registry.ts+++ b/dash/apps/switchdash-desktop/src/renderer/app/modal-registry.ts@@ -1,5 +1,5 @@import { CommandPaletteModal } from '@renderer/features/command-palette/command-palette-modal';-import { AddProjectModal } from '@renderer/features/projects/components/add-project-modal/add-project-modal';+import { AddAgentModal } from '@renderer/features/locations/components/add-agent-modal/add-agent-modal';import { CreateSessionModal } from '@renderer/features/sessions/create-session-modal/create-session-modal';import { DeleteSessionModal } from '@renderer/features/sessions/delete-session-modal';import { RenameSessionModal } from '@renderer/features/sessions/rename-session-modal';@@ -30,7 +30,7 @@ export function createModal<TProps, TResult>(export const modalRegistry = {commandPaletteModal: createModal(CommandPaletteModal, { size: 'md' }),sessionModal: createModal(CreateSessionModal),- addProjectModal: createModal(AddProjectModal),+ addAgentModal: createModal(AddAgentModal),confirmActionModal: createModal(ConfirmActionDialog, { size: 'xs' }),confirmExternalLinkModal: createModal(ExternalLinkChoiceDialog, { size: 'sm' }),unsavedChangesModal: createModal(UnsavedChangesDialog, { size: 'xs' }),diff --git a/dash/apps/switchdash-desktop/src/renderer/app/view-registry.ts b/dash/apps/switchdash-desktop/src/renderer/app/view-registry.tsindex 90daec697..9dc2dc8ea 100644--- a/dash/apps/switchdash-desktop/src/renderer/app/view-registry.ts+++ b/dash/apps/switchdash-desktop/src/renderer/app/view-registry.ts@@ -1,18 +1,18 @@import type { ComponentType, ReactNode } from 'react';import { homeView } from '@renderer/app/home-view';-import { projectView } from '@renderer/features/projects/view';+import { locationView } from '@renderer/features/locations/view';import { sessionView } from '@renderer/features/sessions/view';import { settingsView } from '@renderer/features/settings/settings-view';import { serverView } from '@renderer/features/switch-servers/view';import type { CommandProvider } from '@renderer/lib/commands/types';import { appState } from '@renderer/lib/stores/app-state';-// switchdash views: agents (project), sessions (session), home, settings,+// switchdash views: agents-at-a-location (location), sessions (session), home, settings,// server (a connected Switch gateway). Automations, library, skills, and mcp// were removed.export const views = {home: homeView,- project: projectView,+ location: locationView,session: sessionView,settings: settingsView,server: serverView,diff --git a/dash/apps/switchdash-desktop/src/renderer/features/command-palette/command-palette-modal.tsx b/dash/apps/switchdash-desktop/src/renderer/features/command-palette/command-palette-modal.tsxindex e51dced55..5ce790c81 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/command-palette/command-palette-modal.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/command-palette/command-palette-modal.tsx@@ -18,16 +18,15 @@ import { ALL_COMMAND_DEFS, type CommandDef } from '@shared/commands';import type { SearchItem } from '@shared/core/search';import { getCommandIcon } from './command-icons';import { PALETTE_ITEM_CLASS } from './palette-item-styles';+import { PaletteLocationsGroup } from './palette-locations-group';import { PaletteNotificationsGroup } from './palette-notifications-group';-import { PaletteProjectsGroup } from './palette-projects-group';import { PaletteSessionItem } from './palette-session-item';import { ResourceMonitorView } from './resource-monitor-view';import { applyContextAffinity } from './search-utils';interface CommandPaletteProps {- projectId?: string;+ locationId?: string;sessionId?: string;- workspaceId?: string;}interface PaletteAction {@@ -43,7 +42,7 @@ interface PaletteAction {const KIND_ICON: Record<string, React.ReactNode> = {action: null,session: <GitBranch size={14} className="shrink-0 text-foreground/40" />,- project: <FolderOpen size={14} className="shrink-0 text-foreground/40" />,+ location: <FolderOpen size={14} className="shrink-0 text-foreground/40" />,};const GROUP_CLASS = cn(@@ -61,13 +60,13 @@ const SESSION_SUGGESTED = ['resource-monitor','app.giveFeedback',];-const PROJECT_SUGGESTED = [+const LOCATION_SUGGESTED = ['app.newSession','app.settings','resource-monitor','app.giveFeedback',];-const APP_SUGGESTED = ['app.newProject', 'app.settings', 'resource-monitor', 'app.giveFeedback'];+const APP_SUGGESTED = ['app.newLocation', 'app.settings', 'resource-monitor', 'app.giveFeedback'];function PaletteItem({value,@@ -124,9 +123,8 @@ function PaletteFileItem({}export function CommandPaletteModal({- projectId,+ locationId,sessionId,- workspaceId,onClose,}: CommandPaletteProps & BaseModalProps) {const [view, setView] = useState<'search' | 'resource-monitor'>('search');@@ -148,20 +146,19 @@ export function CommandPaletteModal({// Prefetch recents immediately on mount so the empty-query view is instant.useEffect(() => {void queryClient.prefetchQuery({- queryKey: ['cmdk-search', '', projectId, sessionId, workspaceId],- queryFn: () =>- rpc.search.commandPalette({ query: '', context: { projectId, sessionId, workspaceId } }),+ queryKey: ['cmdk-search', '', locationId, sessionId],+ queryFn: () => rpc.search.commandPalette({ query: '', context: { locationId, sessionId } }),staleTime: 5_000,});// oxlint-disable-next-line react/exhaustive-deps}, []);const { data: dbResults = [] } = useQuery({- queryKey: ['cmdk-search', debouncedQuery, projectId, sessionId, workspaceId],+ queryKey: ['cmdk-search', debouncedQuery, locationId, sessionId],queryFn: () =>rpc.search.commandPalette({query: debouncedQuery,- context: { projectId, sessionId, workspaceId },+ context: { locationId, sessionId },}),// Keep results fresh for 5 s — re-opening the palette with the same query// returns cached data instantly rather than waiting for a round-trip.@@ -212,8 +209,8 @@ export function CommandPaletteModal({// Empty state: show the ordered context-specific suggested actions only.const suggestedIds = sessionId? SESSION_SUGGESTED- : projectId- ? PROJECT_SUGGESTED+ : locationId+ ? LOCATION_SUGGESTED: APP_SUGGESTED;const pool = resourceMonitorAction? [...registryActions, resourceMonitorAction]@@ -222,9 +219,9 @@ export function CommandPaletteModal({.filter((a) => suggestedIds.includes(a.id)).sort((a, b) => suggestedIds.indexOf(a.id) - suggestedIds.indexOf(b.id)).slice(0, 7);- }, [registryActions, resourceMonitorAction, projectId, sessionId]);+ }, [registryActions, resourceMonitorAction, locationId, sessionId]);- const rankedDb = applyContextAffinity(dbResults, { projectId });+ const rankedDb = applyContextAffinity(dbResults, { locationId });const actionResults = actions;const q = debouncedQuery.toLowerCase();@@ -238,25 +235,25 @@ export function CommandPaletteModal({const sessionResults = rankedDb.filter((r): r is SearchItem => r.kind === 'session');const handleNavigateToSession = (item: SearchItem) => {- if (!item.projectId) return;+ if (!item.locationId) return;handleClose();- navigate('session', { projectId: item.projectId, sessionId: item.id });+ navigate('session', { locationId: item.locationId, sessionId: item.id });};- const handleNavigateToProject = (item: SearchItem) => {+ const handleNavigateToLocation = (item: SearchItem) => {handleClose();- navigate('project', { projectId: item.id });+ navigate('location', { locationId: item.id });};const handleOpenFile = (item: SearchItem) => {- if (!item.projectId || !item.sessionId) return;+ if (!item.locationId || !item.sessionId) return;handleClose();- navigate('session', { projectId: item.projectId, sessionId: item.sessionId });+ navigate('session', { locationId: item.locationId, sessionId: item.sessionId });};const handleSelect = (item: SearchItem) => {if (item.kind === 'session') return handleNavigateToSession(item);- if (item.kind === 'project') return handleNavigateToProject(item);+ if (item.kind === 'location') return handleNavigateToLocation(item);if (item.kind === 'file') return handleOpenFile(item);};@@ -298,7 +295,7 @@ export function CommandPaletteModal({<Command.Inputvalue={query}onValueChange={setQuery}- placeholder="Search sessions, projects, actions…"+ placeholder="Search sessions, locations, actions…"className="w-full bg-transparent px-3 py-3 text-sm outline-none placeholder:text-foreground/40"autoFocus/>@@ -350,8 +347,8 @@ export function CommandPaletteModal({/>);}- if (item.kind === 'session' && item.projectId) {- const store = getSessionStore(item.projectId, item.id);+ if (item.kind === 'session' && item.locationId) {+ const store = getSessionStore(item.locationId, item.id);if (store) {return (<PaletteSessionItem@@ -386,7 +383,7 @@ export function CommandPaletteModal({) : (<><PaletteNotificationsGroup- currentProjectId={projectId}+ currentLocationId={locationId}currentSessionId={sessionId}onClose={handleClose}navigate={navigate}@@ -401,8 +398,8 @@ export function CommandPaletteModal({{sessionResults.length > 0 && (<Command.Group heading="Recent Sessions" className={GROUP_CLASS}>{sessionResults.slice(0, 5).map((item) => {- const store = item.projectId- ? getSessionStore(item.projectId, item.id)+ const store = item.locationId+ ? getSessionStore(item.locationId, item.id): undefined;return store ? (<PaletteSessionItem@@ -423,8 +420,8 @@ export function CommandPaletteModal({</Command.Group>)}{!sessionId && (- <PaletteProjectsGroup- currentProjectId={projectId}+ <PaletteLocationsGroup+ currentLocationId={locationId}limit={5}onClose={handleClose}navigate={navigate}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/command-palette/palette-projects-group.tsx b/dash/apps/switchdash-desktop/src/renderer/features/command-palette/palette-locations-group.tsxsimilarity index 62%rename from dash/apps/switchdash-desktop/src/renderer/features/command-palette/palette-projects-group.tsxrename to dash/apps/switchdash-desktop/src/renderer/features/command-palette/palette-locations-group.tsxindex a356ae8a1..44727f113 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/command-palette/palette-projects-group.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/command-palette/palette-locations-group.tsx@@ -3,8 +3,8 @@ import { FolderOpen } from 'lucide-react';import { useObserver } from 'mobx-react-lite';import {asMounted,- getProjectManagerStore,-} from '@renderer/features/projects/stores/project-selectors';+ getLocationManagerStore,+} from '@renderer/features/locations/stores/location-selectors';import type { NavigateFnTyped } from '@renderer/lib/layout/navigation-provider';import { cn } from '@renderer/utils/utils';import { PALETTE_ITEM_CLASS } from './palette-item-styles';@@ -15,43 +15,43 @@ const GROUP_CLASS = cn('[&_[cmdk-group-heading]]:text-foreground/50');-interface PaletteProjectsGroupProps {- /** When set, this project is excluded from the list (project scope). Undefined shows all (app scope). */- currentProjectId: string | undefined;+interface PaletteLocationsGroupProps {+ /** When set, this location is excluded from the list (location scope). Undefined shows all (app scope). */+ currentLocationId: string | undefined;limit?: number;onClose: () => void;navigate: NavigateFnTyped;}-export function PaletteProjectsGroup({- currentProjectId,+export function PaletteLocationsGroup({+ currentLocationId,limit,onClose,navigate,-}: PaletteProjectsGroupProps) {- const projects = useObserver(() => {+}: PaletteLocationsGroupProps) {+ const locations = useObserver(() => {const result: Array<{ id: string; name: string }> = [];- for (const store of getProjectManagerStore().projects.values()) {+ for (const store of getLocationManagerStore().locations.values()) {const mounted = asMounted(store);if (!mounted) continue;- if (mounted.data.id === currentProjectId) continue;+ if (mounted.data.id === currentLocationId) continue;result.push({ id: mounted.data.id, name: store.name ?? mounted.data.id });}return result;});- const visible = limit !== undefined ? projects.slice(0, limit) : projects;+ const visible = limit !== undefined ? locations.slice(0, limit) : locations;if (visible.length === 0) return null;return (- <Command.Group heading="Projects" className={GROUP_CLASS}>+ <Command.Group heading="Locations" className={GROUP_CLASS}>{visible.map((p) => (<Command.Itemkey={p.id}- value={`project:${p.id}`}+ value={`location:${p.id}`}onSelect={() => {- navigate('project', { projectId: p.id });+ navigate('location', { locationId: p.id });onClose();}}className={PALETTE_ITEM_CLASS}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/command-palette/palette-notifications-group.tsx b/dash/apps/switchdash-desktop/src/renderer/features/command-palette/palette-notifications-group.tsxindex 4d7aa6d4b..4fc064533 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/command-palette/palette-notifications-group.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/command-palette/palette-notifications-group.tsx@@ -2,15 +2,15 @@ import { Command } from 'cmdk';import { useObserver } from 'mobx-react-lite';import {asMounted,- getProjectManagerStore,-} from '@renderer/features/projects/stores/project-selectors';+ getLocationManagerStore,+} from '@renderer/features/locations/stores/location-selectors';import { sessionAgentRegistry } from '@renderer/features/sessions/stores/session-agent-registry';import { isRegistered, type SessionStore } from '@renderer/features/sessions/stores/session-store';import type { NavigateFnTyped } from '@renderer/lib/layout/navigation-provider';import { cn } from '@renderer/utils/utils';import { PaletteSessionItem } from './palette-session-item';-type NotificationItem = { projectId: string; sessionStore: SessionStore };+type NotificationItem = { locationId: string; sessionStore: SessionStore };const GROUP_CLASS = cn('[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5',@@ -19,14 +19,14 @@ const GROUP_CLASS = cn();interface PaletteNotificationsGroupProps {- currentProjectId: string | undefined;+ currentLocationId: string | undefined;currentSessionId: string | undefined;onClose: () => void;navigate: NavigateFnTyped;}export function PaletteNotificationsGroup({- currentProjectId,+ currentLocationId,currentSessionId,onClose,navigate,@@ -34,8 +34,8 @@ export function PaletteNotificationsGroup({const items = useObserver((): NotificationItem[] => {const result: NotificationItem[] = [];- for (const projectStore of getProjectManagerStore().projects.values()) {- const mounted = asMounted(projectStore);+ for (const locationStore of getLocationManagerStore().locations.values()) {+ const mounted = asMounted(locationStore);if (!mounted) continue;const pid = mounted.data.id;@@ -48,7 +48,7 @@ export function PaletteNotificationsGroup({// Only surface awaiting-input, error, completed — not working or idle.if (!status || status === 'idle' || status === 'working') continue;- result.push({ projectId: pid, sessionStore });+ result.push({ locationId: pid, sessionStore });}}@@ -66,11 +66,11 @@ export function PaletteNotificationsGroup({value={`notif:session:${item.sessionStore.data.id}`}onSelect={() => {if (- item.projectId !== currentProjectId ||+ item.locationId !== currentLocationId ||item.sessionStore.data.id !== currentSessionId) {navigate('session', {- projectId: item.projectId,+ locationId: item.locationId,sessionId: item.sessionStore.data.id,});}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/command-palette/resource-monitor-utils.ts b/dash/apps/switchdash-desktop/src/renderer/features/command-palette/resource-monitor-utils.tsindex 277d484c0..047510b3a 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/command-palette/resource-monitor-utils.ts+++ b/dash/apps/switchdash-desktop/src/renderer/features/command-palette/resource-monitor-utils.ts@@ -23,13 +23,13 @@ export type SessionBucket = {};export type Group = {- projectId: string;- projectName: string;+ locationId: string;+ locationName: string;sessions: SessionBucket[];entryCount: number;};-const UNKNOWN_PROJECT_ID = '__unknown__';+const UNKNOWN_LOCATION_ID = '__unknown__';/*** Lifecycle-script PTYs are labelled by their terminal id (see@@ -77,7 +77,7 @@ export function formatReport(snapshot: ResourceSnapshot, groups: Group[]): strinfor (const g of groups) {for (const t of g.sessions) {for (const e of t.entries) {- const path = `${g.projectName} / ${t.sessionName} / ${entryLabel(e)}`;+ const path = `${g.locationName} / ${t.sessionName} / ${entryLabel(e)}`;const parts: string[] = [];if (e.pid !== undefined) parts.push(`pid=${e.pid}`);if (e.ppid !== undefined) parts.push(`ppid=${e.ppid}`);@@ -113,36 +113,36 @@ export function sortAppProcesses(processes: ResourceAppProcess[]): ResourceAppPr}export function buildGroups(entries: ResourcePtyEntry[]): Group[] {- const projects = appState.projects.projects;- const byProject = new Map<+ const locations = appState.locations.locations;+ const byLocation = new Map<string,- { projectName: string; sessions: Map<string, SessionBucket> }+ { locationName: string; sessions: Map<string, SessionBucket> }>();for (const entry of entries) {- const projectStore = projects.get(entry.projectId);+ const locationStore = locations.get(entry.locationId);let sessionName = entry.scopeId;// The bucket key normally matches the entry's scopeId, but lifecycle- // scripts are scoped by workspaceId while agents are scoped by sessionId.+ // scripts are scoped by locationId while agents are scoped by sessionId.// Resolving both to the owning session id groups them under the same branch.let bucketKey = entry.scopeId;let providerId: AgentProviderId | undefined;let displayTitle: string | undefined;- let projectName = 'Other';- let projectKey = UNKNOWN_PROJECT_ID;+ let locationName = 'Other';+ let locationKey = UNKNOWN_LOCATION_ID;- if (projectStore) {- projectKey = entry.projectId;- projectName = projectStore.name ?? projectStore.data?.name ?? entry.projectId.slice(0, 8);- const mounted = projectStore.mountedProject;+ if (locationStore) {+ locationKey = entry.locationId;+ locationName = locationStore.name ?? locationStore.data?.name ?? entry.locationId.slice(0, 8);+ const mounted = locationStore.mountedLocation;// Agent PTYs use the session id as scopeId; lifecycle-script PTYs use the- // workspace id. Try the direct lookup first, then fall back to matching- // a session by its workspaceId so scripts attach to their owning branch.+ // location id. Try the direct lookup first, then fall back to matching+ // a session by its locationId so scripts attach to their owning branch.let sessionId = entry.scopeId;let session = mounted?.sessionManager.sessions.get(entry.scopeId);if (!session && mounted) {for (const [id, candidate] of mounted.sessionManager.sessions) {- if (candidate.workspaceId === entry.scopeId) {+ if (candidate.locationId === entry.scopeId) {sessionId = id;session = candidate;break;@@ -159,15 +159,15 @@ export function buildGroups(entries: ResourcePtyEntry[]): Group[] {}// Fall back to metadata supplied by the sampler (covers cases where the- // owning project isn't mounted, so the session/terminal join above misses).+ // owning location isn't mounted, so the session/terminal join above misses).providerId ??= entry.providerId;displayTitle ??= entry.title;- const project = byProject.get(projectKey) ?? {- projectName,+ const location = byLocation.get(locationKey) ?? {+ locationName,sessions: new Map<string, SessionBucket>(),};- const sessionBucket = project.sessions.get(bucketKey) ?? {+ const sessionBucket = location.sessions.get(bucketKey) ?? {scopeId: bucketKey,sessionName,entries: [],@@ -175,11 +175,11 @@ export function buildGroups(entries: ResourcePtyEntry[]): Group[] {};sessionBucket.entries.push({ ...entry, sessionName, providerId, displayTitle });sessionBucket.cpuSum += entry.cpu;- project.sessions.set(bucketKey, sessionBucket);- byProject.set(projectKey, project);+ location.sessions.set(bucketKey, sessionBucket);+ byLocation.set(locationKey, location);}- const groups: Group[] = Array.from(byProject.entries()).map(([projectId, p]) => {+ const groups: Group[] = Array.from(byLocation.entries()).map(([locationId, p]) => {const sessions = Array.from(p.sessions.values());for (const t of sessions) {t.entries.sort((a, b) => {@@ -192,18 +192,18 @@ export function buildGroups(entries: ResourcePtyEntry[]): Group[] {(a, b) => a.sessionName.localeCompare(b.sessionName) || a.scopeId.localeCompare(b.scopeId));return {- projectId,- projectName: p.projectName,+ locationId,+ locationName: p.locationName,sessions,entryCount: sessions.reduce((n, t) => n + t.entries.length, 0),};});- // Keep the "Other" bucket at the end so real projects render first.+ // Keep the "Other" bucket at the end so real locations render first.groups.sort((a, b) => {- if (a.projectId === UNKNOWN_PROJECT_ID) return 1;- if (b.projectId === UNKNOWN_PROJECT_ID) return -1;- return a.projectName.localeCompare(b.projectName) || a.projectId.localeCompare(b.projectId);+ if (a.locationId === UNKNOWN_LOCATION_ID) return 1;+ if (b.locationId === UNKNOWN_LOCATION_ID) return -1;+ return a.locationName.localeCompare(b.locationName) || a.locationId.localeCompare(b.locationId);});return groups;diff --git a/dash/apps/switchdash-desktop/src/renderer/features/command-palette/resource-monitor-view.tsx b/dash/apps/switchdash-desktop/src/renderer/features/command-palette/resource-monitor-view.tsxindex 93fb6c166..3e51ca2e1 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/command-palette/resource-monitor-view.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/command-palette/resource-monitor-view.tsx@@ -33,7 +33,7 @@ export const ResourceMonitorView = observer(function ResourceMonitorView({const groups = useMemo(() => buildGroups(snapshot?.entries ?? []), [snapshot]);const processes = useMemo(() => sortAppProcesses(snapshot?.appProcesses ?? []), [snapshot]);- const hasProjects = groups.length > 0;+ const hasLocations = groups.length > 0;const hasProcesses = processes.length > 0;return (@@ -67,10 +67,10 @@ export const ResourceMonitorView = observer(function ResourceMonitorView({)}<Section heading="Active sessions">- {hasProjects ? (+ {hasLocations ? (<div className="flex flex-col gap-1">{groups.map((g) => (- <ProjectRow key={g.projectId} group={g} />+ <LocationRow key={g.locationId} group={g} />))}</div>) : (@@ -121,13 +121,13 @@ function ProcessRow({ process, cpuCount }: { process: ResourceAppProcess; cpuCou);}-const ProjectRow = observer(function ProjectRow({ group }: { group: Group }) {+const LocationRow = observer(function LocationRow({ group }: { group: Group }) {return (<div className="flex flex-col"><div className="flex items-center gap-2 rounded-md px-2 py-1"><Folder size={12} className="shrink-0 text-foreground/40" /><span className="flex-1 truncate text-xs font-medium text-foreground">- {group.projectName}+ {group.locationName}</span><span className="text-[10px] text-foreground/40 tabular-nums">{group.entryCount}</span></div>diff --git a/dash/apps/switchdash-desktop/src/renderer/features/command-palette/search-utils.ts b/dash/apps/switchdash-desktop/src/renderer/features/command-palette/search-utils.tsindex 3a7fff041..48e11fc6b 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/command-palette/search-utils.ts+++ b/dash/apps/switchdash-desktop/src/renderer/features/command-palette/search-utils.ts@@ -1,16 +1,16 @@import type { SearchItem } from '@shared/core/search';/**- * Re-ranks FTS5 results by boosting items belonging to the active project.+ * Re-ranks FTS5 results by boosting items belonging to the active location.* Applied to DB results only — actions are already ordered by context relevance.*/export function applyContextAffinity(items: SearchItem[],- context: { projectId?: string }+ context: { locationId?: string }): SearchItem[] {return [...items].sort((a, b) => {const boost = (x: SearchItem) =>- x.projectId === context.projectId && context.projectId != null ? 1 : 0;+ x.locationId === context.locationId && context.locationId != null ? 1 : 0;const diff = boost(b) - boost(a);// BM25: lower (more negative) is betterreturn diff !== 0 ? diff : a.score - b.score;diff --git a/dash/apps/switchdash-desktop/src/renderer/features/projects/components/add-project-modal/add-project-modal.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsxsimilarity index 91%rename from dash/apps/switchdash-desktop/src/renderer/features/projects/components/add-project-modal/add-project-modal.tsxrename to dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsxindex 5de8bdb3a..3074b51c7 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/projects/components/add-project-modal/add-project-modal.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx@@ -2,13 +2,12 @@ import { useQuery } from '@tanstack/react-query';import { CheckCircle2, CircleAlert } from 'lucide-react';import { observer } from 'mobx-react-lite';import { useCallback, useEffect, useRef, useState } from 'react';-import { agentsStore } from '@renderer/features/projects/stores/agents-store';import type {- ProjectCreationError,- ModeData as ProjectCreationModeData,- ProjectType,-} from '@renderer/features/projects/stores/project-creation-types';-import { getProjectManagerStore } from '@renderer/features/projects/stores/project-selectors';+ AgentOnboardingError,+ ModeData as AgentOnboardingModeData,+} from '@renderer/features/locations/stores/agent-onboarding-types';+import { agentsStore } from '@renderer/features/locations/stores/agents-store';+import { getLocationManagerStore } from '@renderer/features/locations/stores/location-selectors';import type { ServerVerifyState } from '@renderer/features/switch-servers/agent-server-picker';import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';import { toast } from '@renderer/lib/hooks/use-toast';@@ -50,14 +49,12 @@ import { SubagentOnboardingSection, type SubagentSelection } from './subagent-on// switch-connector `configure` skill has set up (its `.claude/settings.local.json`// carries the SWITCH_* env block). The richer switchdash flows — SSH, clone, create// new GitHub repo — are out of scope for v0, so this modal is local + pick only.-export type AddProjectModalProps = BaseModalProps<void>;+export type AddLocationModalProps = BaseModalProps<void>;/** Sentinel `runHost` value meaning "run on this machine" (no remote host). */const LOCAL_RUN_LOCATION = 'local';-export const AddProjectModal = observer(function AddProjectModal({- onClose,-}: AddProjectModalProps) {+export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLocationModalProps) {const [submitState, setSubmitState] = useState<'idle' | 'creating'>('idle');const [verifyState, setVerifyState] = useState<ServerVerifyState>('idle');const { navigate } = useNavigate();@@ -114,8 +111,8 @@ export const AddProjectModal = observer(function AddProjectModal({const shouldCheckPathStatus = !isRemoteRun && pickState.path.trim().length > 0;const pathStatusQuery = useQuery({- queryKey: ['projectPathStatus', 'local', pickState.path],- queryFn: () => rpc.projects.inspectProjectPath({ type: 'local', path: pickState.path }),+ queryKey: ['locationPathStatus', 'local', pickState.path],+ queryFn: () => rpc.locations.inspectLocationPath({ path: pickState.path }),enabled: shouldCheckPathStatus,});@@ -189,7 +186,7 @@ export const AddProjectModal = observer(function AddProjectModal({// Remote configure gate: no agent in the remote dir yet — a valid remote// configure form + a chosen server + a provider. The server is not verified// here (the agent does not exist yet); it is verified after registration by- // the create path (createRemoteProject).+ // the create path (createRemoteLocation).const canSubmitConfigureRemote =isMissingRemoteAgent &&!isChecking &&@@ -199,7 +196,7 @@ export const AddProjectModal = observer(function AddProjectModal({trimmedRemoteDir.length > 0 &&submitState === 'idle';- const reportCreationError = (error: ProjectCreationError) => {+ const reportCreationError = (error: AgentOnboardingError) => {if (error.type === 'switch-server-unauthenticated') {toast({title: `Sign in to ${error.serverName}`,@@ -220,27 +217,26 @@ export const AddProjectModal = observer(function AddProjectModal({log.error(error);};- const finishWith = (projectId: string) => {+ const finishWith = (locationId: string) => {setCloseGuard(false);setSubmitState('idle');onClose();- navigate('project', { projectId });+ navigate('location', { locationId });};- /** Run the shared create-project path with the current pick state. Returns the- * new/existing project id, or null when there is no chosen server. */+ /** Run the shared create-location path with the current pick state. Returns the+ * new/existing location id, or null when there is no chosen server. */const startCreate = async (): Promise<string | null> => {if (!pickState.serverId || !pickState.providerId) return null;const id = crypto.randomUUID();- const projectType: ProjectType = { type: 'local' as const };- const data: ProjectCreationModeData = isRemoteRun+ const data: AgentOnboardingModeData = isRemoteRun? {mode: 'pick',name: remoteConfigureForm.agentName.trim() || basenameFromAnyPath(trimmedRemoteDir),path: undefined,serverId: pickState.serverId,providerId: pickState.providerId,- remoteConfig: { sshHost: runHost, remoteRepoDir: trimmedRemoteDir },+ remote: { sshHost: runHost, dir: trimmedRemoteDir },}: {mode: 'pick',@@ -248,15 +244,15 @@ export const AddProjectModal = observer(function AddProjectModal({path: pickState.path,serverId: pickState.serverId,providerId: pickState.providerId,- remoteConfig: undefined,+ remote: undefined,};- // The new project mounts (leaving the always-shown "unregistered" state)+ // The new location mounts (leaving the always-shown "unregistered" state)// before agentsStore re-fetches its agent, which would drop it out of the- // server-scoped sidebar. Seed the project→server mapping now so it stays+ // server-scoped sidebar. Seed the location→server mapping now so it stays// visible, and refresh the agent list once creation succeeds.- agentsStore.noteProjectServer(id, pickState.serverId);- const result = await getProjectManagerStore().startProjectCreation(projectType, data, { id });- if (result.kind === 'existing') return result.projectId;+ agentsStore.noteLocationServer(id, pickState.serverId);+ const result = await getLocationManagerStore().startAgentOnboarding(data, { id });+ if (result.kind === 'existing') return result.locationId;void result.completion.then((completion) => {if (completion.success) void agentsStore.load();@@ -265,7 +261,7 @@ export const AddProjectModal = observer(function AddProjectModal({.catch((error) => {log.error(error);});- return result.projectId;+ return result.locationId;};/** Onboard the subagents the user selected, after the parent is added. A@@ -306,10 +302,10 @@ export const AddProjectModal = observer(function AddProjectModal({setSubmitState('creating');setCloseGuard(true);try {- const projectId = await startCreate();- if (projectId) {+ const locationId = await startCreate();+ if (locationId) {await registerSelectedSubagents();- finishWith(projectId);+ finishWith(locationId);} else {setCloseGuard(false);setSubmitState('idle');@@ -380,10 +376,10 @@ export const AddProjectModal = observer(function AddProjectModal({// Credentials are now written to .claude/settings.local.json, so the// create path re-detects the agent and verifies it on the server, and the// selected subagents can be registered under the just-created parent.- const projectId = await startCreate();- if (projectId) {+ const locationId = await startCreate();+ if (locationId) {await registerSelectedSubagents();- finishWith(projectId);+ finishWith(locationId);} else {setCloseGuard(false);setSubmitState('idle');@@ -424,13 +420,13 @@ export const AddProjectModal = observer(function AddProjectModal({return;}// Credentials are now written to the remote dir's .claude/settings.local.json,- // so the create path (createRemoteProject) re-detects the agent over SSH and+ // so the create path (createRemoteLocation) re-detects the agent over SSH and// verifies it on the server, and the selected subagents can be registered// under the just-created remote parent.- const projectId = await startCreate();- if (projectId) {+ const locationId = await startCreate();+ if (locationId) {await registerSelectedSubagents();- finishWith(projectId);+ finishWith(locationId);} else {setCloseGuard(false);setSubmitState('idle');diff --git a/dash/apps/switchdash-desktop/src/renderer/features/projects/components/add-project-modal/agent-type-picker.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/agent-type-picker.tsxsimilarity index 100%rename from dash/apps/switchdash-desktop/src/renderer/features/projects/components/add-project-modal/agent-type-picker.tsxrename to dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/agent-type-picker.tsxdiff --git a/dash/apps/switchdash-desktop/src/renderer/features/projects/components/add-project-modal/configure-agent-panel.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsxsimilarity index 100%rename from dash/apps/switchdash-desktop/src/renderer/features/projects/components/add-project-modal/configure-agent-panel.tsxrename to dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsxdiff --git a/dash/apps/switchdash-desktop/src/renderer/features/projects/components/add-project-modal/content.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/content.tsxsimilarity index 100%rename from dash/apps/switchdash-desktop/src/renderer/features/projects/components/add-project-modal/content.tsxrename to dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/content.tsxdiff --git a/dash/apps/switchdash-desktop/src/renderer/features/projects/components/add-project-modal/local-directory-selector.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/local-directory-selector.tsxsimilarity index 100%rename from dash/apps/switchdash-desktop/src/renderer/features/projects/components/add-project-modal/local-directory-selector.tsxrename to dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/local-directory-selector.tsxdiff --git a/dash/apps/switchdash-desktop/src/renderer/features/projects/components/add-project-modal/modes.ts b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/modes.tssimilarity index 100%rename from dash/apps/switchdash-desktop/src/renderer/features/projects/components/add-project-modal/modes.tsrename to dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/modes.tsdiff --git a/dash/apps/switchdash-desktop/src/renderer/features/projects/components/add-project-modal/subagent-onboarding-section.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/subagent-onboarding-section.tsxsimilarity index 98%rename from dash/apps/switchdash-desktop/src/renderer/features/projects/components/add-project-modal/subagent-onboarding-section.tsxrename to dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/subagent-onboarding-section.tsxindex 2bfd4951c..6b4b4c529 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/projects/components/add-project-modal/subagent-onboarding-section.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/subagent-onboarding-section.tsx@@ -9,7 +9,7 @@ import type { AgentProviderId } from '@shared/core/providers/agent-provider-regiexport type SubagentSelection = { name: string; description: string }[];-/** Where to discover subagent definitions: a local project dir, or a remote+/** Where to discover subagent definitions: a local location dir, or a remote* agent's working dir on its SSH host (scanned over SFTP during onboarding). */export type SubagentOnboardingSource =| { kind: 'local'; dir: string }diff --git a/dash/apps/switchdash-desktop/src/renderer/features/projects/components/project-titlebar.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/location-titlebar.tsxsimilarity index 56%rename from dash/apps/switchdash-desktop/src/renderer/features/projects/components/project-titlebar.tsxrename to dash/apps/switchdash-desktop/src/renderer/features/locations/components/location-titlebar.tsxindex f433a6739..85fad46c9 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/projects/components/project-titlebar.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/location-titlebar.tsx@@ -1,12 +1,12 @@import { ChevronDown, Ellipsis, Trash2 } from 'lucide-react';import { observer } from 'mobx-react-lite';-import { useConfirmDeleteProject } from '@renderer/features/projects/hooks/use-confirm-delete-project';+import { useConfirmDeleteAgent } from '@renderer/features/locations/hooks/use-confirm-delete-agent';import {asMounted,- getProjectStore,- projectDisplayName,- projectViewKind,-} from '@renderer/features/projects/stores/project-selectors';+ getLocationStore,+ locationDisplayName,+ locationViewKind,+} from '@renderer/features/locations/stores/location-selectors';import { OpenInMenu } from '@renderer/lib/components/titlebar/open-in-menu';import { Titlebar } from '@renderer/lib/components/titlebar/Titlebar';import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';@@ -17,15 +17,15 @@ import {DropdownMenuTrigger,} from '@renderer/lib/ui/dropdown-menu';-const MountedProjectTitlebarLeft = observer(function ProjectTitlebarLeft({- projectId,+const MountedLocationTitlebarLeft = observer(function LocationTitlebarLeft({+ locationId,}: {- projectId: string;+ locationId: string;}) {const { navigate } = useNavigate();- const store = getProjectStore(projectId);- const displayName = projectDisplayName(store) ?? 'this project';- const confirmDeleteProject = useConfirmDeleteProject();+ const store = getLocationStore(locationId);+ const displayName = locationDisplayName(store) ?? 'this location';+ const confirmDeleteAgent = useConfirmDeleteAgent();return (<div className="flex h-full items-center gap-2 px-2">@@ -44,9 +44,9 @@ const MountedProjectTitlebarLeft = observer(function ProjectTitlebarLeft({<DropdownMenuItemclassName="flex items-center gap-2 text-foreground-destructive"onClick={() => {- void confirmDeleteProject({- projectId,- projectLabel: displayName,+ void confirmDeleteAgent({+ locationId,+ locationLabel: displayName,onDeleted: () => navigate('home'),});}}@@ -60,13 +60,13 @@ const MountedProjectTitlebarLeft = observer(function ProjectTitlebarLeft({);});-const ProjectTitlebarLeft = observer(function ProjectTitlebarLeft({- projectId,+const LocationTitlebarLeft = observer(function LocationTitlebarLeft({+ locationId,}: {- projectId: string;+ locationId: string;}) {- const store = getProjectStore(projectId);- const displayName = projectDisplayName(store);+ const store = getLocationStore(locationId);+ const displayName = locationDisplayName(store);return (<div className="flex items-center gap-2 px-2"><span className="text-sm text-foreground-muted">{displayName}</span>@@ -74,27 +74,27 @@ const ProjectTitlebarLeft = observer(function ProjectTitlebarLeft({);});-export const ProjectTitlebar = observer(function ProjectTitlebar() {+export const LocationTitlebar = observer(function LocationTitlebar() {const {- params: { projectId },- } = useParams('project');- const store = getProjectStore(projectId);- const kind = projectViewKind(store);+ params: { locationId },+ } = useParams('location');+ const store = getLocationStore(locationId);+ const kind = locationViewKind(store);if (kind !== 'ready') {- return <Titlebar leftSlot={<ProjectTitlebarLeft projectId={projectId} />} />;+ return <Titlebar leftSlot={<LocationTitlebarLeft locationId={locationId} />} />;}const mounted = asMounted(store);- if (!mounted) return <Titlebar leftSlot={<ProjectTitlebarLeft projectId={projectId} />} />;+ if (!mounted) return <Titlebar leftSlot={<LocationTitlebarLeft locationId={locationId} />} />;return (<Titlebar- leftSlot={<MountedProjectTitlebarLeft projectId={projectId} />}+ leftSlot={<MountedLocationTitlebarLeft locationId={locationId} />}rightSlot={<div className="mr-2 flex items-center gap-2">- {mounted.data.path !== null && (- <OpenInMenu path={mounted.data.path} className="h-7 bg-background" />+ {mounted.data.sshHost === null && (+ <OpenInMenu path={mounted.data.dir} className="h-7 bg-background" />)}</div>}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/projects/components/project-view-wrapper.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/location-view-wrapper.tsxsimilarity index 63%rename from dash/apps/switchdash-desktop/src/renderer/features/projects/components/project-view-wrapper.tsxrename to dash/apps/switchdash-desktop/src/renderer/features/locations/components/location-view-wrapper.tsxindex dfcfd6117..efd0fb36e 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/projects/components/project-view-wrapper.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/location-view-wrapper.tsx@@ -1,13 +1,13 @@import type { ReactNode } from 'react';-interface ProjectViewWrapperProps {+interface LocationViewWrapperProps {children: ReactNode;- projectId: string;- /** When set, the view is scoped to this Claude Code subagent of the project's+ locationId: string;+ /** When set, the view is scoped to this Claude Code subagent of the location's* agent: Sessions lists only its sessions and Settings shows its own config. */subagentName?: string;}-export function ProjectViewWrapper({ children }: ProjectViewWrapperProps) {+export function LocationViewWrapper({ children }: LocationViewWrapperProps) {return <>{children}</>;}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/projects/components/main-panel/active-project.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/main-panel/active-location.tsxsimilarity index 71%rename from dash/apps/switchdash-desktop/src/renderer/features/projects/components/main-panel/active-project.tsxrename to dash/apps/switchdash-desktop/src/renderer/features/locations/components/main-panel/active-location.tsxindex ec0abfff8..0f0ddddaa 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/projects/components/main-panel/active-project.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/main-panel/active-location.tsx@@ -1,27 +1,30 @@import { useQuery } from '@tanstack/react-query';import { observer } from 'mobx-react-lite';-import { SessionList } from '@renderer/features/projects/components/session-view/session-list';-import { SettingsPanel } from '@renderer/features/projects/components/settings-view/settings-panel';-import { SubagentsPanel } from '@renderer/features/projects/components/subagents-view/subagents-panel';-import { asMounted, getProjectStore } from '@renderer/features/projects/stores/project-selectors';-import type { ProjectView } from '@renderer/features/projects/stores/project-view';+import { SessionList } from '@renderer/features/locations/components/session-view/session-list';+import { SettingsPanel } from '@renderer/features/locations/components/settings-view/settings-panel';+import { SubagentsPanel } from '@renderer/features/locations/components/subagents-view/subagents-panel';+import {+ asMounted,+ getLocationStore,+} from '@renderer/features/locations/stores/location-selectors';+import type { LocationView } from '@renderer/features/locations/stores/location-view';import { rpc } from '@renderer/lib/ipc';import { useParams } from '@renderer/lib/layout/navigation-provider';import { useAgent } from '@renderer/lib/stores/use-agents';import { cn } from '@renderer/utils/utils';-function ProjectViewNav({+function LocationViewNav({items,activeView,onChange,}: {- items: Array<{ id: ProjectView; label: string }>;- activeView: ProjectView;- onChange: (view: ProjectView) => void;+ items: Array<{ id: LocationView; label: string }>;+ activeView: LocationView;+ onChange: (view: LocationView) => void;}) {return (<div className="py-10">- <nav className="flex min-h-0 w-52 flex-col gap-0.5 overflow-y-auto" aria-label="Project">+ <nav className="flex min-h-0 w-52 flex-col gap-0.5 overflow-y-auto" aria-label="Location">{items.map((item) => {const isActive = item.id === activeView;@@ -46,15 +49,15 @@ function ProjectViewNav({);}-export const ActiveProject = observer(function ActiveProject() {+export const ActiveLocation = observer(function ActiveLocation() {const {- params: { projectId, subagentName },- } = useParams('project');- const store = asMounted(getProjectStore(projectId));+ params: { locationId, subagentName },+ } = useParams('location');+ const store = asMounted(getLocationStore(locationId));const { data: agents } = useQuery({- queryKey: ['project-agents', projectId],- queryFn: () => rpc.agents.getAgents(projectId),+ queryKey: ['location-agents', locationId],+ queryFn: () => rpc.agents.getAgents(locationId),});const agent = agents?.[0] ?? null;const { data: providerMeta } = useAgent(agent?.providerId ?? '');@@ -65,7 +68,7 @@ export const ActiveProject = observer(function ActiveProject() {if (!store) return null;- const items: Array<{ id: ProjectView; label: string }> = [+ const items: Array<{ id: LocationView; label: string }> = [{ id: 'sessions', label: 'Sessions' },...(supportsSubagents ? ([{ id: 'subagents', label: 'Subagents' }] as const) : []),{ id: 'settings', label: 'Settings' },@@ -81,10 +84,10 @@ export const ActiveProject = observer(function ActiveProject() {<div className="flex h-full min-h-0 w-full flex-1 flex-col overflow-hidden"><div className="mx-auto flex h-full min-h-0 w-full max-w-[1060px] flex-col gap-6 px-8"><div className="grid min-h-0 flex-1 grid-cols-[13rem_minmax(0,1fr)] gap-8 overflow-hidden">- <ProjectViewNav+ <LocationViewNavitems={items}activeView={activeView}- onChange={(view) => store.view.setProjectView(view)}+ onChange={(view) => store.view.setLocationView(view)}/><div className="min-h-0 min-w-0 flex-1 overflow-x-hidden overflow-y-auto"><div className="mx-auto flex h-full min-h-0 w-full max-w-4xl flex-col px-1 py-10">diff --git a/dash/apps/switchdash-desktop/src/renderer/features/projects/components/main-panel/main-panel.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/main-panel/main-panel.tsxsimilarity index 57%rename from dash/apps/switchdash-desktop/src/renderer/features/projects/components/main-panel/main-panel.tsxrename to dash/apps/switchdash-desktop/src/renderer/features/locations/components/main-panel/main-panel.tsxindex 2ec64e3d9..72c974c54 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/projects/components/main-panel/main-panel.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/main-panel/main-panel.tsx@@ -1,69 +1,69 @@import { Loader2, TriangleAlert } from 'lucide-react';import { observer } from 'mobx-react-lite';-import { useConfirmDeleteProject } from '@renderer/features/projects/hooks/use-confirm-delete-project';+import { useConfirmDeleteAgent } from '@renderer/features/locations/hooks/use-confirm-delete-agent';import { useParams } from '@renderer/lib/layout/navigation-provider';-import { isUnregisteredProject } from '../../stores/project';+import { isUnregisteredLocation } from '../../stores/location';import {- getProjectStore,- projectDisplayName,- projectViewKind,+ getLocationStore,+ locationDisplayName,+ locationViewKind,unmountedMountErrorMessage,-} from '../../stores/project-selectors';-import { ActiveProject } from './active-project';-import { PendingProjectStatus } from './pending-project';+} from '../../stores/location-selectors';+import { ActiveLocation } from './active-location';+import { PendingLocationStatus } from './pending-location';-export const ProjectMainPanel = observer(function ProjectMainPanel() {+export const LocationMainPanel = observer(function LocationMainPanel() {const {- params: { projectId },- } = useParams('project');- const store = getProjectStore(projectId);- const kind = projectViewKind(store);- const displayName = projectDisplayName(store) ?? 'this project';+ params: { locationId },+ } = useParams('location');+ const store = getLocationStore(locationId);+ const kind = locationViewKind(store);+ const displayName = locationDisplayName(store) ?? 'this location';- if (kind === 'creating' && store && isUnregisteredProject(store)) {- return <PendingProjectStatus project={store} />;+ if (kind === 'creating' && store && isUnregisteredLocation(store)) {+ return <PendingLocationStatus location={store} />;}if (kind === 'bootstrapping') {- return <ProjectBootstrappingPanel />;+ return <LocationBootstrappingPanel />;}if (kind === 'path_not_found') {return (- <ProjectPathNotFoundPanel+ <LocationPathNotFoundPanelpath={store?.error ?? ''}- projectId={projectId}+ locationId={locationId}title={displayName}/>);}if (kind === 'mount_error') {- return <ProjectBootstrapErrorPanel message={unmountedMountErrorMessage(store)} />;+ return <LocationBootstrapErrorPanel message={unmountedMountErrorMessage(store)} />;}if (kind !== 'ready') {return <div className="flex flex-1 items-center justify-center text-foreground-muted" />;}- return <ActiveProject />;+ return <ActiveLocation />;});-function ProjectBootstrappingPanel() {+function LocationBootstrappingPanel() {return (<div className="flex h-full w-full flex-col items-center justify-center gap-3"><Loader2 className="h-5 w-5 animate-spin text-foreground-passive" />- <p className="font-mono text-xs text-foreground-passive">Setting up project…</p>+ <p className="font-mono text-xs text-foreground-passive">Setting up location…</p></div>);}-function ProjectBootstrapErrorPanel({ message }: { message: string }) {+function LocationBootstrapErrorPanel({ message }: { message: string }) {return (<div className="flex h-full w-full flex-col items-center justify-center p-8"><div className="flex max-w-xs flex-col items-center gap-2 text-center"><p className="font-mono text-sm font-medium text-foreground-destructive">- Failed to set up project+ Failed to set up location</p><p className="font-mono text-xs text-foreground-passive">{message}</p></div>@@ -71,36 +71,36 @@ function ProjectBootstrapErrorPanel({ message }: { message: string }) {);}-function ProjectPathNotFoundPanel({+function LocationPathNotFoundPanel({path,- projectId,+ locationId,title,}: {path: string;- projectId: string;+ locationId: string;title: string;}) {- const confirmDeleteProject = useConfirmDeleteProject();+ const confirmDeleteAgent = useConfirmDeleteAgent();return (<div className="flex h-full w-full flex-col items-center justify-center p-8"><div className="flex max-w-sm flex-col items-center gap-3 text-center"><TriangleAlert className="h-6 w-6 text-foreground-destructive" /><p className="font-mono text-sm font-medium text-foreground-destructive">- Project not found+ Location not found</p>{path && <p className="font-mono text-xs break-all text-foreground-passive">{path}</p>}<p className="text-xs text-foreground-passive">- The project directory no longer exists at the configured path.+ The location directory no longer exists at the configured path.</p><buttontype="button"className="mt-2 text-xs text-foreground-destructive underline underline-offset-2 transition-colors hover:text-foreground-destructive/80"onClick={() => {- void confirmDeleteProject({ projectId, projectLabel: title });+ void confirmDeleteAgent({ locationId, locationLabel: title });}}>- Remove Project+ Remove Location</button></div></div>diff --git a/dash/apps/switchdash-desktop/src/renderer/features/projects/components/main-panel/pending-project.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/main-panel/pending-location.tsxsimilarity index 79%rename from dash/apps/switchdash-desktop/src/renderer/features/projects/components/main-panel/pending-project.tsxrename to dash/apps/switchdash-desktop/src/renderer/features/locations/components/main-panel/pending-location.tsxindex 54f9d351e..b0e002123 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/projects/components/main-panel/pending-project.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/main-panel/pending-location.tsx@@ -1,7 +1,7 @@import { AlertCircle, Check, Loader2, X } from 'lucide-react';import { observer } from 'mobx-react-lite';-import { type UnregisteredProject } from '@renderer/features/projects/stores/project';-import { getProjectManagerStore } from '@renderer/features/projects/stores/project-selectors';+import { type UnregisteredLocation } from '@renderer/features/locations/stores/location';+import { getLocationManagerStore } from '@renderer/features/locations/stores/location-selectors';import { useNavigate } from '@renderer/lib/layout/navigation-provider';import { Button } from '@renderer/lib/ui/button';@@ -19,29 +19,29 @@ const STAGES_BY_MODE: Record<'pick' | 'clone' | 'new', Stage[]> = {new: ['creating-repo', 'cloning', 'registering'],};-export const PendingProjectStatus = observer(function PendingProjectStatus({- project,+export const PendingLocationStatus = observer(function PendingLocationStatus({+ location,}: {- project: UnregisteredProject;+ location: UnregisteredLocation;}) {const { navigate } = useNavigate();- const stages = STAGES_BY_MODE[project.mode];- const currentStageIndex = stages.indexOf(project.phase as Stage);- const isError = project.phase === 'error';+ const stages = STAGES_BY_MODE[location.mode];+ const currentStageIndex = stages.indexOf(location.phase as Stage);+ const isError = location.phase === 'error';const handleDismiss = () => {- getProjectManagerStore().removeUnregisteredProject(project.id);+ getLocationManagerStore().removeUnregisteredLocation(location.id);navigate('home');};return (<div className="flex min-w-0 flex-1 flex-col items-center justify-center gap-6 p-8"><div className="flex w-full max-w-sm min-w-0 flex-col items-center gap-3 text-center">- <h2 className="mb-2 text-base">{project.name}</h2>+ <h2 className="mb-2 text-base">{location.name}</h2>{stages.map((stage, i) => {const isDone = !isError && i < currentStageIndex;- const isActive = !isError && stage === project.phase;+ const isActive = !isError && stage === location.phase;return (<div key={stage} className="flex items-center justify-center gap-3"><div className="flex h-5 w-5 shrink-0 items-center justify-center">@@ -73,7 +73,7 @@ export const PendingProjectStatus = observer(function PendingProjectStatus({<div className="flex min-w-0 items-start gap-2 text-left"><AlertCircle className="text-destructive mt-0.5 h-4 w-4 shrink-0" /><span className="text-destructive min-w-0 text-sm break-words">- {project.error ?? 'An error occurred'}+ {location.error ?? 'An error occurred'}</span></div><Button size="sm" variant="outline" className="self-center" onClick={handleDismiss}>diff --git a/dash/apps/switchdash-desktop/src/renderer/features/projects/components/session-view/session-list-empty-state.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/session-view/session-list-empty-state.tsxsimilarity index 92%rename from dash/apps/switchdash-desktop/src/renderer/features/projects/components/session-view/session-list-empty-state.tsxrename to dash/apps/switchdash-desktop/src/renderer/features/locations/components/session-view/session-list-empty-state.tsxindex d8e0e19c5..0cdbd9a11 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/projects/components/session-view/session-list-empty-state.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/session-view/session-list-empty-state.tsx@@ -5,10 +5,10 @@ import { useShowModal } from '@renderer/lib/modal/modal-provider';import { ActionListItem } from '@renderer/lib/ui/action-list-item';export const SessionListEmptyState = observer(function SessionListEmptyState({- projectId,+ locationId,subagentName,}: {- projectId: string;+ locationId: string;subagentName?: string;}) {const showSessionModal = useShowModal('sessionModal');@@ -20,7 +20,7 @@ export const SessionListEmptyState = observer(function SessionListEmptyState({? `Spawn a claude session as ${subagentName}`: 'Spawn a claude session for this agent',icon: Plus,- onActivate: () => showSessionModal({ projectId, subagentName }),+ onActivate: () => showSessionModal({ locationId, subagentName }),},];diff --git a/dash/apps/switchdash-desktop/src/renderer/features/projects/components/session-view/session-list.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/session-view/session-list.tsxsimilarity index 94%rename from dash/apps/switchdash-desktop/src/renderer/features/projects/components/session-view/session-list.tsxrename to dash/apps/switchdash-desktop/src/renderer/features/locations/components/session-view/session-list.tsxindex 6b627ceed..62349931a 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/projects/components/session-view/session-list.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/session-view/session-list.tsx@@ -3,7 +3,10 @@ import { useVirtualizer } from '@tanstack/react-virtual';import { Archive, RotateCcw, Trash2, X } from 'lucide-react';import { observer } from 'mobx-react-lite';import { useRef } from 'react';-import { asMounted, getProjectStore } from '@renderer/features/projects/stores/project-selectors';+import {+ asMounted,+ getLocationStore,+} from '@renderer/features/locations/stores/location-selectors';import { getSessionManagerStore } from '@renderer/features/sessions/stores/session-selectors';import { useAppSettingsKey } from '@renderer/features/settings/use-app-settings-key';import { ListPopoverCard } from '@renderer/lib/components/list-popover-card';@@ -131,10 +134,10 @@ function SelectionBar({export const SessionList = observer(function SessionList() {const {- params: { projectId, subagentName },- } = useParams('project');- const store = asMounted(getProjectStore(projectId));- const sessionManager = getSessionManagerStore(projectId);+ params: { locationId, subagentName },+ } = useParams('location');+ const store = asMounted(getLocationStore(locationId));+ const sessionManager = getSessionManagerStore(locationId);const showDeleteSession = useShowModal('deleteSessionModal');const showCreateSessionModal = useShowModal('sessionModal');const { value: keyboard } = useAppSettingsKey('keyboard');@@ -181,7 +184,7 @@ export const SessionList = observer(function SessionList() {if (selectedSessions.length === 0) return;showDeleteSession({- projectId,+ locationId,sessions: selectedSessions,onSuccess: () => {void sessionManager?.deleteSessions([...sessionView.selectedIds]);@@ -234,7 +237,7 @@ export const SessionList = observer(function SessionList() {onChange={(e) => sessionView.setSearchQuery(e.target.value)}className="flex-1"/>- <Button onClick={() => showCreateSessionModal({ projectId, subagentName })}>+ <Button onClick={() => showCreateSessionModal({ locationId, subagentName })}>Create Session <BoundShortcut settingsKey="newSession" /></Button></div>@@ -242,7 +245,7 @@ export const SessionList = observer(function SessionList() {</div>{filteredSessions.length === 0 && sessionView.tab === 'active' ? (- <SessionListEmptyState projectId={projectId} subagentName={subagentName} />+ <SessionListEmptyState locationId={locationId} subagentName={subagentName} />) : (<SessionVirtualListsessions={filteredSessions}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/projects/components/session-view/session-row.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/session-view/session-row.tsxsimilarity index 95%rename from dash/apps/switchdash-desktop/src/renderer/features/projects/components/session-view/session-row.tsxrename to dash/apps/switchdash-desktop/src/renderer/features/locations/components/session-view/session-row.tsxindex 6bd3a1757..c3afc5ec3 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/projects/components/session-view/session-row.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/session-view/session-row.tsx@@ -30,7 +30,7 @@ export const SessionRow = observer(function SessionRow({const { navigate } = useNavigate();const showRename = useShowModal('renameSessionModal');const showDeleteSession = useShowModal('deleteSessionModal');- const sessionManager = getSessionManagerStore(session.projectId);+ const sessionManager = getSessionManagerStore(session.locationId);const shiftKeyRef = useRef(false);const handleArchive = () => void sessionManager?.archiveSession(session.data.id);@@ -38,13 +38,13 @@ export const SessionRow = observer(function SessionRow({const handleProvision = () => void sessionManager?.provisionSession(session.data.id);const handleDelete = () =>showDeleteSession({- projectId: session.projectId,+ locationId: session.locationId,sessions: [{ sessionId: session.data.id, sessionName: session.data.title }],onSuccess: () => void sessionManager?.deleteSessions([session.data.id]),});const handleRename = () =>showRename({- projectId: session.projectId,+ locationId: session.locationId,sessionId: session.data.id,currentName: session.data.title,});@@ -69,7 +69,7 @@ export const SessionRow = observer(function SessionRow({onClick={() => {if (isArchived) return;handleProvision();- navigate('session', { projectId: session.projectId, sessionId: session.data.id });+ navigate('session', { locationId: session.locationId, sessionId: session.data.id });}}className="group flex w-full items-center gap-2 rounded-lg p-3 transition-colors hover:bg-background-1">diff --git a/dash/apps/switchdash-desktop/src/renderer/features/projects/components/settings-view/sections/auto-session-settings-section.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/auto-session-settings-section.tsxsimilarity index 89%rename from dash/apps/switchdash-desktop/src/renderer/features/projects/components/settings-view/sections/auto-session-settings-section.tsxrename to dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/auto-session-settings-section.tsxindex 510017d15..d18cb72c2 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/projects/components/settings-view/sections/auto-session-settings-section.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/auto-session-settings-section.tsx@@ -7,15 +7,15 @@ import { log } from '@renderer/utils/logger';/*** Per-Switch-agent "auto-create session on notify" toggle. Unlike the rest of- * the project settings form (persisted to .switchdash.json / DB on Save), this+ * the location settings form (persisted to .switchdash.json / DB on Save), this* flips the agent's gateway connection model immediately on toggle — there is* no local config to stage. Renders one row per Switch-linked agent in the- * project; hidden entirely when the project has none.+ * location; hidden entirely when the location has none.*/-export function AutoSessionSettingsSection({ projectId }: { projectId: string }) {+export function AutoSessionSettingsSection({ locationId }: { locationId: string }) {const { data: agents } = useQuery({- queryKey: ['project-agents', projectId],- queryFn: () => rpc.agents.getAgents(projectId),+ queryKey: ['location-agents', locationId],+ queryFn: () => rpc.agents.getAgents(locationId),});const switchAgents = (agents ?? []).filter((a) => a.serverId && a.switchAgentId);diff --git a/dash/apps/switchdash-desktop/src/renderer/features/projects/components/settings-view/sections/subagent-auto-session-settings-section.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/subagent-auto-session-settings-section.tsxsimilarity index 94%rename from dash/apps/switchdash-desktop/src/renderer/features/projects/components/settings-view/sections/subagent-auto-session-settings-section.tsxrename to dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/subagent-auto-session-settings-section.tsxindex 6dae17b94..b6c59096f 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/projects/components/settings-view/sections/subagent-auto-session-settings-section.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/subagent-auto-session-settings-section.tsx@@ -11,18 +11,18 @@ import { log } from '@renderer/utils/logger';* {@link AutoSessionSettingsSection} but is keyed by the subagent's own Switch* agent id: toggling flips its gateway connection model and starts/stops a* watcher that spawns sessions launched as that subagent. Hidden when the- * project's agent is not linked to a Switch server.+ * location's agent is not linked to a Switch server.*/export function SubagentAutoSessionSettingsSection({- projectId,+ locationId,subagentName,}: {- projectId: string;+ locationId: string;subagentName: string;}) {const { data: agents, isLoading: agentsLoading } = useQuery({- queryKey: ['project-agents', projectId],- queryFn: () => rpc.agents.getAgents(projectId),+ queryKey: ['location-agents', locationId],+ queryFn: () => rpc.agents.getAgents(locationId),});const parent = (agents ?? []).find((a) => a.serverId && a.switchAgentId);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.tsxnew file mode 100644index 000000000..d799d86f6--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/settings-panel.tsx@@ -0,0 +1,36 @@+import { observer } from 'mobx-react-lite';+import { AutoSessionSettingsSection } from '@renderer/features/locations/components/settings-view/sections/auto-session-settings-section';+import { SubagentAutoSessionSettingsSection } from '@renderer/features/locations/components/settings-view/sections/subagent-auto-session-settings-section';+import {+ asMounted,+ getLocationStore,+} from '@renderer/features/locations/stores/location-selectors';+import { useParams } from '@renderer/lib/layout/navigation-provider';+import { Spinner } from '@renderer/lib/ui/spinner';++export const SettingsPanel = observer(function SettingsPanel() {+ const {+ params: { locationId, subagentName },+ } = useParams('location');+ const mounted = asMounted(getLocationStore(locationId));++ if (!mounted) {+ return (+ <div className="flex items-center justify-center py-10">+ <Spinner />+ </div>+ );+ }++ return (+ <div className="flex flex-col gap-6">+ {subagentName ? (+ <SubagentAutoSessionSettingsSection locationId={locationId} subagentName={subagentName} />+ ) : (+ <>+ <AutoSessionSettingsSection locationId={locationId} />+ </>+ )}+ </div>+ );+});diff --git a/dash/apps/switchdash-desktop/src/renderer/features/projects/components/subagents-view/subagents-panel.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/subagents-view/subagents-panel.tsxsimilarity index 98%rename from dash/apps/switchdash-desktop/src/renderer/features/projects/components/subagents-view/subagents-panel.tsxrename to dash/apps/switchdash-desktop/src/renderer/features/locations/components/subagents-view/subagents-panel.tsxindex deadfae87..636717e5c 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/projects/components/subagents-view/subagents-panel.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/subagents-view/subagents-panel.tsx@@ -3,7 +3,10 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';import { Plus } from 'lucide-react';import { observer } from 'mobx-react-lite';import { useMemo, useState } from 'react';-import { asMounted, getProjectStore } from '@renderer/features/projects/stores/project-selectors';+import {+ asMounted,+ getLocationStore,+} from '@renderer/features/locations/stores/location-selectors';import { useToast } from '@renderer/lib/hooks/use-toast';import { rpc } from '@renderer/lib/ipc';import { useParams } from '@renderer/lib/layout/navigation-provider';@@ -94,13 +97,13 @@ function attributesFromForm(fields: SubagentField[], state: FormState): Subagent*/export const SubagentsPanel = observer(function SubagentsPanel() {const {- params: { projectId },- } = useParams('project');- const mounted = asMounted(getProjectStore(projectId));+ params: { locationId },+ } = useParams('location');+ const mounted = asMounted(getLocationStore(locationId));const { data: agents, isLoading: agentsLoading } = useQuery({- queryKey: ['project-agents', projectId],- queryFn: () => rpc.agents.getAgents(projectId),+ queryKey: ['location-agents', locationId],+ queryFn: () => rpc.agents.getAgents(locationId),});const parent = (agents ?? []).find((a) => a.serverId && a.switchAgentId) ?? null;diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/hooks/use-confirm-delete-agent.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/hooks/use-confirm-delete-agent.tsxnew file mode 100644index 000000000..521c9dca4--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/hooks/use-confirm-delete-agent.tsx@@ -0,0 +1,26 @@+import { getLocationManagerStore } from '@renderer/features/locations/stores/location-selectors';+import { useShowModal } from '@renderer/lib/modal/modal-provider';++export function useConfirmDeleteAgent() {+ const showConfirmDeleteLocation = useShowModal('confirmActionModal');++ return async ({+ locationId,+ locationLabel,+ onDeleted,+ }: {+ locationId: string;+ locationLabel: string;+ onDeleted?: () => void;+ }) => {+ showConfirmDeleteLocation({+ title: 'Remove agent',+ description: `"${locationLabel}" will be removed from switchdash. The folder stays on the filesystem.`,+ confirmLabel: 'Remove',+ onSuccess: () => {+ void getLocationManagerStore().removeLocation(locationId);+ onDeleted?.();+ },+ });+ };+}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/agent-onboarding-types.ts b/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/agent-onboarding-types.tsnew file mode 100644index 000000000..c6bd5167a--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/agent-onboarding-types.ts@@ -0,0 +1,33 @@+import type { Result } from '@switchdash/shared';+import type { OnboardAgentError } from '@shared/core/agents/onboarding';+import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';++interface BaseModeData {+ name: string;+ /** Local working directory. Omitted for a remote agent (see `remote`). */+ path?: string;+}++export interface PickModeData extends BaseModeData {+ mode: 'pick';+ /** The registered Switch server the user chose for this agent. */+ serverId: string;+ /** The agent type (CLI provider) the user picked when onboarding. */+ providerId: AgentProviderId;+ /** When set, the agent runs at a remote location on this SSH host + dir. */+ remote?: { sshHost: string; dir: string };+}++export type ModeData = PickModeData;++export type AgentOnboardingError = OnboardAgentError;++export type AgentOnboardingCompletion = Result<void, AgentOnboardingError>;++export type StartAgentOnboardingResult =+ | { kind: 'existing'; locationId: string }+ | { kind: 'creating'; locationId: string; completion: Promise<AgentOnboardingCompletion> };++export interface StartAgentOnboardingOptions {+ id?: string;+}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/agents-store.ts b/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/agents-store.tsnew file mode 100644index 000000000..6e1ea478a--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/agents-store.ts@@ -0,0 +1,64 @@+import { makeAutoObservable, runInAction } from 'mobx';+import { rpc } from '@renderer/lib/ipc';+import type { Agent } from '@shared/core/agents/agents';++/**+ * Renderer cache of every agent across all locations, used to resolve which+ * Switch server a location belongs to. The sidebar scopes its tree to the active+ * server (see {@link switchServersStore.activeServerId}), so it needs a reactive+ * location→serverId lookup that does not depend on each row's own react-query.+ *+ * A location holds one parent agent plus any subagents, which all share the same+ * server; {@link serverIdForLocation} returns the first non-null serverId among a+ * location's agents.+ */+export class AgentsStore {+ /** All agents grouped by their location id. */+ readonly byLocation = new Map<string, Agent[]>();+ /**+ * Server id a just-created location's agent will belong to, recorded by the+ * add-agent modal before {@link load} has re-fetched the new agent. Used as a+ * fallback in {@link serverIdForLocation} so a freshly-created location does not+ * flicker out of the sidebar's server-scoped view during the gap between the+ * location mounting and the agent list refreshing.+ */+ readonly optimisticServerByLocation = new Map<string, string>();+ loaded = false;++ constructor() {+ makeAutoObservable(this);+ }++ async load(): Promise<void> {+ const agents = await rpc.agents.getAgents();+ runInAction(() => {+ this.byLocation.clear();+ for (const agent of agents) {+ const list = this.byLocation.get(agent.locationId);+ if (list) list.push(agent);+ else this.byLocation.set(agent.locationId, [agent]);+ }+ // Drop optimistic notes now superseded by a real agent record.+ for (const locationId of this.byLocation.keys()) {+ this.optimisticServerByLocation.delete(locationId);+ }+ this.loaded = true;+ });+ }++ /** Record the server a location's agent will bind to, ahead of {@link load}. */+ noteLocationServer(locationId: string, serverId: string): void {+ runInAction(() => {+ this.optimisticServerByLocation.set(locationId, serverId);+ });+ }++ /** The Switch server a location's agents belong to, or null if unlinked. */+ serverIdForLocation(locationId: string): string | null {+ const agents = this.byLocation.get(locationId);+ const resolved = agents?.find((a) => a.serverId !== null)?.serverId ?? null;+ return resolved ?? this.optimisticServerByLocation.get(locationId) ?? null;+ }+}++export const agentsStore = new AgentsStore();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.tsnew file mode 100644index 000000000..d18e93643--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/location-manager.test.ts@@ -0,0 +1,177 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { Agent } from '@shared/core/agents/agents';+import type { Location } from '@shared/core/locations/locations';+import { isUnregisteredLocation } from './location';+import { LocationManagerStore } from './location-manager';++const mocks = vi.hoisted(() => ({+ onboardAgent: vi.fn(),+ getLocations: vi.fn(async () => [] as Location[]),+ inspectLocationPath: vi.fn(),+ openLocation: vi.fn(),+ eventOn: vi.fn(),+}));++vi.mock('@renderer/lib/ipc', () => ({+ events: {+ on: mocks.eventOn,+ },+ rpc: {+ agents: {+ onboardAgent: mocks.onboardAgent,+ getAgents: vi.fn(async () => [] as Agent[]),+ },+ locations: {+ getLocations: mocks.getLocations,+ inspectLocationPath: mocks.inspectLocationPath,+ openLocation: mocks.openLocation,+ },+ },+}));++vi.mock('@renderer/lib/stores/app-state', () => ({+ appState: {+ navigation: {+ currentViewId: 'home',+ revalidate: vi.fn(),+ viewParamsStore: {},+ },+ },+}));++vi.mock('@renderer/lib/stores/view-state-cache', () => ({+ viewStateCache: {+ get: vi.fn(async () => undefined),+ },+}));++function location(overrides: Partial<Location> = {}): Location {+ return {+ id: 'location-id',+ name: 'Location',+ sshHost: null,+ dir: '/location',+ createdAt: '2026-05-28T00:00:00.000Z',+ updatedAt: '2026-05-28T00:00:00.000Z',+ ...overrides,+ };+}++function agent(overrides: Partial<Agent> = {}): Agent {+ return {+ id: 'agent-id',+ locationId: 'location-id',+ name: 'Agent',+ providerId: 'claude',+ switchAgentId: 'sw-1',+ apiEndpoint: 'https://switch.example.com',+ serverId: 'server-1',+ status: null,+ createdAt: '2026-05-28T00:00:00.000Z',+ updatedAt: '2026-05-28T00:00:00.000Z',+ ...overrides,+ };+}++describe('LocationManagerStore agent onboarding', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.inspectLocationPath.mockResolvedValue({ isDirectory: true });+ mocks.onboardAgent.mockResolvedValue({ success: true, data: agent() });+ mocks.getLocations.mockResolvedValue([location()]);+ mocks.openLocation.mockReturnValue(new Promise(() => {}));+ });++ it('returns an existing location without starting onboarding', async () => {+ mocks.inspectLocationPath.mockResolvedValueOnce({+ isDirectory: true,+ existingLocation: location({ id: 'existing-location' }),+ });+ const store = new LocationManagerStore();++ const result = await store.startAgentOnboarding(+ {+ mode: 'pick',+ name: 'Location',+ path: '/location',+ serverId: 'server-1',+ providerId: 'claude',+ },+ { id: 'optimistic-location' }+ );++ expect(result).toEqual({ kind: 'existing', locationId: 'existing-location' });+ expect(mocks.onboardAgent).not.toHaveBeenCalled();+ expect(store.locations.has('optimistic-location')).toBe(false);+ expect(store.pendingCreationIds.has('optimistic-location')).toBe(false);+ });++ it('creates unregistered location state before returning creating', async () => {+ let resolveOnboard: (a: Agent) => void = () => {};+ mocks.onboardAgent.mockReturnValueOnce(+ new Promise((resolve) => {+ resolveOnboard = (a) => resolve({ success: true, data: a });+ })+ );+ const store = new LocationManagerStore();++ const result = await store.startAgentOnboarding(+ {+ mode: 'pick',+ name: 'Location',+ path: '/location',+ serverId: 'server-1',+ providerId: 'claude',+ },+ { id: 'optimistic-location' }+ );++ expect(result.kind).toBe('creating');+ const pending = store.locations.get('optimistic-location');+ expect(pending && isUnregisteredLocation(pending)).toBe(true);+ expect(pending?.phase).toBe('registering');+ expect(store.pendingCreationIds.has('optimistic-location')).toBe(true);+ expect(mocks.inspectLocationPath).toHaveBeenCalledTimes(1);++ resolveOnboard(agent());+ if (result.kind === 'creating') await result.completion;++ expect(store.pendingCreationIds.has('optimistic-location')).toBe(false);+ });++ it('marks onboarding as failed when the RPC returns a typed error', async () => {+ mocks.onboardAgent.mockResolvedValueOnce({+ success: false,+ error: {+ type: 'switch-server-unauthenticated',+ dir: '/location',+ serverId: 'server-1',+ serverName: 'Pilot',+ },+ });+ const store = new LocationManagerStore();++ const result = await store.startAgentOnboarding(+ {+ mode: 'pick',+ name: 'Location',+ path: '/location',+ serverId: 'server-1',+ providerId: 'claude',+ },+ { id: 'optimistic-location' }+ );++ expect(result.kind).toBe('creating');+ if (result.kind === 'creating') {+ await expect(result.completion).resolves.toMatchObject({ success: false });+ }++ const loc = store.locations.get('optimistic-location');+ expect(loc && isUnregisteredLocation(loc)).toBe(true);+ if (loc && isUnregisteredLocation(loc)) {+ expect(loc.phase).toBe('error');+ expect(loc.error).toBe('Sign in to Pilot before adding this agent.');+ }+ });+});diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/location-manager.ts b/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/location-manager.tsnew file mode 100644index 000000000..c266beff1--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/location-manager.ts@@ -0,0 +1,300 @@+import { err, ok } from '@switchdash/shared';+import { makeObservable, observable, runInAction } from 'mobx';+import { rpc } from '@renderer/lib/ipc';+import { appState } from '@renderer/lib/stores/app-state';+import { viewStateCache } from '@renderer/lib/stores/view-state-cache';+import { type Location } from '@shared/core/locations/locations';+import type { LocationViewSnapshot } from '@shared/view-state';+import type {+ AgentOnboardingCompletion,+ AgentOnboardingError,+ ModeData,+ StartAgentOnboardingOptions,+ StartAgentOnboardingResult,+} from './agent-onboarding-types';+import {+ createUnmountedLocation,+ createUnregisteredLocation,+ isUnmountedLocation,+ isUnregisteredLocation,+ type LocationStore,+} from './location';++export class LocationManagerStore {+ locations = observable.map<string, LocationStore>();+ pendingCreationIds = observable.set<string>();+ private _locationMountPromises = new Map<string, Promise<void>>();+ private _loadPromise: Promise<void> | null = null;++ constructor() {+ makeObservable(this, { locations: observable, pendingCreationIds: observable });+ }++ load(): Promise<void> {+ if (!this._loadPromise) {+ this._loadPromise = this._doLoad();+ }+ return this._loadPromise;+ }++ private async _doLoad(): Promise<void> {+ // Only surface locations that still have at least one agent — a location+ // with no agents lingers in the DB (kept for reuse) but has no sidebar row.+ const [rawLocations, agents] = await Promise.all([+ rpc.locations.getLocations(),+ rpc.agents.getAgents(),+ ]);+ const locationIdsWithAgents = new Set(agents.map((a) => a.locationId));+ const toMount: string[] = [];+ runInAction(() => {+ for (const loc of rawLocations) {+ if (!locationIdsWithAgents.has(loc.id)) continue;+ if (this.locations.has(loc.id)) continue;+ this.locations.set(loc.id, createUnmountedLocation(loc, 'idle'));+ toMount.push(loc.id);+ }+ });+ await Promise.allSettled(toMount.map((id) => this.mountLocation(id)));+ }++ async createAgent(data: ModeData, id?: string): Promise<string | undefined> {+ const result = await this.startAgentOnboarding(data, { id });+ if (result.kind === 'existing') return result.locationId;++ const completion = await result.completion;+ return completion.success ? result.locationId : undefined;+ }++ async startAgentOnboarding(+ data: ModeData,+ options: StartAgentOnboardingOptions = {}+ ): Promise<StartAgentOnboardingResult> {+ const placeholderId = options.id ?? crypto.randomUUID();+ const dir = data.remote ? data.remote.dir : data.path;+ // Local onboarding can dedup against an existing location for the same dir.+ if (!data.remote && dir !== undefined) {+ const inspection = await rpc.locations.inspectLocationPath({ path: dir });+ if (inspection.existingLocation) {+ return { kind: 'existing', locationId: inspection.existingLocation.id };+ }+ }++ runInAction(() => {+ this.pendingCreationIds.add(placeholderId);+ this.locations.set(+ placeholderId,+ createUnregisteredLocation(placeholderId, data.name, 'registering', 'pick')+ );+ });++ const completion = this._doOnboardAgent(data, placeholderId).finally(() => {+ runInAction(() => this.pendingCreationIds.delete(placeholderId));+ });++ return { kind: 'creating', locationId: placeholderId, completion };+ }++ private async _doOnboardAgent(+ data: ModeData,+ placeholderId: string+ ): Promise<AgentOnboardingCompletion> {+ const dir = data.remote ? data.remote.dir : data.path;+ if (dir === undefined) {+ const error: AgentOnboardingError = {+ type: 'invalid-directory',+ dir: '',+ message: 'A directory is required',+ };+ this._markCreationError(placeholderId, error);+ return err(error);+ }++ let result: AgentOnboardingCompletion;+ try {+ const onboarded = await rpc.agents.onboardAgent({+ name: data.name,+ serverId: data.serverId,+ providerId: data.providerId,+ dir,+ sshHost: data.remote?.sshHost,+ });+ if (!onboarded.success) {+ result = err(onboarded.error);+ } else {+ const location = (await rpc.locations.getLocations()).find(+ (l) => l.id === onboarded.data.locationId+ );+ if (!location)+ throw new Error(`Onboarded agent's location ${onboarded.data.locationId} not found`);+ // Drop the optimistic placeholder; key the store by the real location id.+ runInAction(() => this.locations.delete(placeholderId));+ this._setAndOpenLocation(location.id, location);+ result = ok();+ }+ } catch (error) {+ this._markUnexpectedCreationError(placeholderId, error);+ throw error;+ }++ if (!result.success) this._markCreationError(placeholderId, result.error);+ return result;+ }++ mountLocation(locationId: string): Promise<void> {+ const inFlight = this._locationMountPromises.get(locationId);+ if (inFlight) return inFlight;++ const location = this.locations.get(locationId);+ if (!location || !isUnmountedLocation(location)) return Promise.resolve();++ runInAction(() => {+ location.phase = 'opening';+ location.error = undefined;+ location.errorCode = undefined;+ });++ const promise = Promise.all([+ rpc.locations.openLocation(locationId),+ viewStateCache.get(`location:${locationId}`),+ ])+ .then(async ([openResult, savedSnapshot]) => {+ if (!openResult.success) {+ runInAction(() => {+ const current = this.locations.get(locationId);+ if (current && isUnmountedLocation(current)) {+ current.phase = 'error';+ if (openResult.error.type === 'path-not-found') {+ current.error = openResult.error.path;+ current.errorCode = 'path-not-found';+ } else if (openResult.error.type === 'error') {+ current.error = openResult.error.message;+ current.errorCode = undefined;+ } else {+ current.error = undefined;+ current.errorCode = undefined;+ }+ }+ });+ return;+ }+ runInAction(() => {+ const current = this.locations.get(locationId);+ if (current && isUnmountedLocation(current)) {+ current.transitionToMounted(+ current.data,+ savedSnapshot as LocationViewSnapshot | undefined+ );+ }+ });+ // Load the session list before provisioning so the sessions map is populated.+ const sessionManager = this.locations.get(locationId)?.mountedLocation?.sessionManager;+ if (sessionManager) {+ await sessionManager.loadSessions();+ const nav = appState.navigation;+ const navParams = nav.viewParamsStore['session'] as+ | { locationId?: string; sessionId?: string }+ | undefined;+ const navSessionId =+ nav.currentViewId === 'session' && navParams?.locationId === locationId+ ? navParams.sessionId+ : undefined;+ if (navSessionId) {+ sessionManager.provisionSession(navSessionId).catch(() => {});+ }+ }+ })+ .catch((error: unknown) => {+ runInAction(() => {+ const current = this.locations.get(locationId);+ if (current && isUnmountedLocation(current)) {+ current.phase = 'error';+ current.error = error instanceof Error ? error.message : String(error);+ current.errorCode = undefined;+ }+ });+ throw error;+ })+ .finally(() => {+ this._locationMountPromises.delete(locationId);+ });++ this._locationMountPromises.set(locationId, promise);+ return promise;+ }++ /**+ * Remove every agent at a location (the sidebar's "Remove Agent" action). The+ * location row is kept in the DB for reuse; it simply drops out of the sidebar+ * once it has no agents.+ */+ async removeLocation(locationId: string): Promise<void> {+ const snapshot = this.locations.get(locationId);+ const agents = await rpc.agents.getAgents(locationId);+ runInAction(() => {+ this.locations.delete(locationId);+ });+ appState.navigation.revalidate();+ try {+ await Promise.all(agents.map((agent) => rpc.agents.deleteAgent(agent.id)));+ } catch (error) {+ runInAction(() => {+ if (snapshot) this.locations.set(locationId, snapshot);+ });+ throw error;+ }+ }++ removeUnregisteredLocation(locationId: string): void {+ runInAction(() => {+ const store = this.locations.get(locationId);+ if (store && isUnregisteredLocation(store)) {+ this.locations.delete(locationId);+ }+ });+ }++ private _setAndOpenLocation(id: string, location: Location): void {+ runInAction(() => {+ const current = this.locations.get(id);+ if (current) {+ current.transitionToUnmounted(location, 'opening');+ } else {+ this.locations.set(id, createUnmountedLocation(location, 'opening'));+ }+ });+ void this.mountLocation(id);+ }++ private _markCreationError(id: string, error: AgentOnboardingError): void {+ runInAction(() => {+ const store = this.locations.get(id);+ if (store && isUnregisteredLocation(store)) {+ store.phase = 'error';+ store.error = creationErrorMessage(error);+ }+ });+ }++ private _markUnexpectedCreationError(id: string, error: unknown): void {+ runInAction(() => {+ const store = this.locations.get(id);+ if (store && isUnregisteredLocation(store)) {+ store.phase = 'error';+ store.error = error instanceof Error ? error.message : String(error);+ }+ });+ }+}++function creationErrorMessage(error: AgentOnboardingError): string {+ switch (error.type) {+ case 'switch-agent-not-on-server':+ return `This agent isn't registered on ${error.serverName}. Pick the server it belongs to.`;+ case 'switch-server-unauthenticated':+ return `Sign in to ${error.serverName} before adding this agent.`;+ case 'invalid-directory':+ return error.message;+ default:+ return error.message;+ }+}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/location-selectors.ts b/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/location-selectors.tsnew file mode 100644index 000000000..7c1997a49--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/location-selectors.ts@@ -0,0 +1,87 @@+import { appState } from '@renderer/lib/stores/app-state';+import type { Location } from '@shared/core/locations/locations';+import {+ isUnmountedLocation,+ isUnregisteredLocation,+ type MountedLocation,+ type LocationStore,+} from './location';+import type { LocationManagerStore } from './location-manager';+import type { LocationSettingsStore } from './location-settings-store';+import type { LocationViewStore } from './location-view';++/** Returns the LocationManagerStore from appState. Call only inside `observer` components (or other MobX reactions). */+export function getLocationManagerStore(): LocationManagerStore {+ return appState.locations;+}++/** Call only inside `observer` components (or other MobX reactions). */+export function getLocationStore(locationId: string): LocationStore | undefined {+ return getLocationManagerStore().locations.get(locationId);+}++/** Summary for routing the location shell; call only inside `observer` (or other MobX reactions). */+export type LocationViewKind =+ | 'missing'+ | 'creating'+ | 'bootstrapping'+ | 'mount_error'+ | 'path_not_found'+ | 'idle_unmounted'+ | 'ready';++export function locationViewKind(store: LocationStore | undefined): LocationViewKind {+ if (!store) return 'missing';+ if (isUnregisteredLocation(store)) return 'creating';+ if (isUnmountedLocation(store)) {+ if (store.phase === 'opening') return 'bootstrapping';+ if (store.phase === 'error') {+ if (store.errorCode === 'path-not-found') return 'path_not_found';+ return 'mount_error';+ }+ return 'idle_unmounted';+ }+ return 'ready';+}++/** Returns the mounted location payload if ready, otherwise undefined. */+export function asMounted(store: LocationStore | undefined): MountedLocation | undefined {+ return store?.mountedLocation ?? undefined;+}++/** Returns the id of the first mounted location, or undefined if none are mounted. */+export function firstMountedLocationId(): string | undefined {+ for (const [id, store] of getLocationManagerStore().locations.entries()) {+ if (asMounted(store)) return id;+ }+ return undefined;+}++export function mountedLocationData(store: LocationStore | undefined): Location | null {+ return store?.mountedLocation?.data ?? null;+}++/** Returns the display name from any location store variant. */+export function locationDisplayName(store: LocationStore | undefined): string | undefined {+ return store?.name ?? undefined;+}++export function unmountedMountErrorMessage(store: LocationStore | undefined): string {+ if (store && isUnmountedLocation(store) && store.phase === 'error') {+ if (store.errorCode === 'path-not-found') {+ return `No location found at ${store.error ?? 'the configured path'}`;+ }+ return store.error ?? 'Failed to open location';+ }+ return 'Failed to open location';+}++/** Returns the LocationSettingsStore for a mounted location, or undefined if not ready. */+export function getLocationSettingsStore(locationId: string): LocationSettingsStore | undefined {+ return asMounted(getLocationStore(locationId))?.settings;+}++/** Returns the LocationViewStore for a mounted location, or undefined if not ready. */+export function getLocationViewStore(locationId: string): LocationViewStore | undefined {+ return asMounted(getLocationStore(locationId))?.view;+}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/location-settings-store.ts b/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/location-settings-store.tsnew file mode 100644index 000000000..5a293f7e8--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/location-settings-store.ts@@ -0,0 +1,121 @@+import type { Result } from '@switchdash/shared';+import { events, rpc } from '@renderer/lib/ipc';+import { Resource } from '@renderer/lib/stores/resource';+import { fsWatchEventChannel } from '@shared/core/fs/fsEvents';+import {+ LOCATION_CONFIG_FILE,+ type MigrateLocationConfigRequest,+ type MigrateLocationConfigResult,+ type LocationConfigMigration,+ type LocationSettings,+ type LocationSettingsOverrideState,+ type LocationSettingsPage,+ type LocationSettingsWriteTargetOption,+ type WriteLocationConfigRequest,+} from '@shared/core/location-settings/location-settings';+import { locationSettingsChangedChannel } from '@shared/core/locations/locationEvents';+import type { UpdateLocationSettingsError } from '@shared/core/locations/locations';++export class LocationSettingsStore {+ readonly pageData: Resource<LocationSettingsPage>;+ private readonly _unsubscribeConfigWatch: () => void;+ private readonly _unsubscribeSettingsChanged: () => void;++ constructor(private readonly locationId: string) {+ this.pageData = new Resource(async () => {+ const result = await rpc.locations.getLocationSettingsPage(locationId);+ if (!result.success) {+ throw new Error(+ result.error.type === 'location-not-found'+ ? `Location ${locationId} not found`+ : 'Failed to load location settings'+ );+ }+ return result.data;+ }, [{ kind: 'demand' }]);++ this._unsubscribeConfigWatch = events.on(fsWatchEventChannel, (data) => {+ if (data.locationId !== locationId) return;+ if (+ data.events.some(+ (event) => event.path === LOCATION_CONFIG_FILE || event.oldPath === LOCATION_CONFIG_FILE+ )+ ) {+ this.pageData.invalidate();+ }+ });++ this._unsubscribeSettingsChanged = events.on(locationSettingsChangedChannel, (data) => {+ if (data.locationId === locationId) {+ this.pageData.invalidate();+ }+ });+ }++ get settings(): LocationSettings | null {+ return this.pageData.data?.settings ?? null;+ }++ get defaults(): LocationSettingsPage['defaults'] | null {+ return this.pageData.data?.defaults ?? null;+ }++ get writeTargets(): LocationSettingsWriteTargetOption[] | null {+ return this.pageData.data?.writeTargets ?? null;+ }++ get overrideState(): LocationSettingsOverrideState | null {+ return this.pageData.data?.overrideState ?? null;+ }++ get configMigrations(): LocationConfigMigration[] | null {+ return this.pageData.data?.configMigrations ?? null;+ }++ get shouldPromptConfigMigration(): boolean {+ return this.pageData.data?.shouldPromptConfigMigration ?? false;+ }++ async load(): Promise<LocationSettingsPage | null> {+ await this.pageData.load();+ return this.pageData.data;+ }++ async save(+ settings: LocationSettings+ ): Promise<Result<LocationSettings, UpdateLocationSettingsError>> {+ const result = await rpc.locations.updateLocationSettings(this.locationId, settings);+ if (result.success) {+ const current = this.pageData.data;+ if (current) this.pageData.setValue({ ...current, settings: result.data });+ else this.pageData.invalidate();+ }+ return result;+ }++ async writeConfigToRepo(+ request: WriteLocationConfigRequest+ ): Promise<Result<LocationSettingsPage, UpdateLocationSettingsError>> {+ const result = await rpc.locations.shareLocationSettingsToConfig(this.locationId, request);+ if (result.success) {+ this.pageData.setValue(result.data);+ }+ return result;+ }++ async migrateLocationConfig(+ request: MigrateLocationConfigRequest+ ): Promise<Result<MigrateLocationConfigResult, UpdateLocationSettingsError>> {+ const result = await rpc.locations.migrateLocationConfig(this.locationId, request);+ if (result.success) {+ this.pageData.setValue(result.data.page);+ }+ return result;+ }++ dispose(): void {+ this._unsubscribeConfigWatch();+ this._unsubscribeSettingsChanged();+ this.pageData.dispose();+ }+}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/projects/stores/project-view.test.ts b/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/location-view.test.tssimilarity index 79%rename from dash/apps/switchdash-desktop/src/renderer/features/projects/stores/project-view.test.tsrename to dash/apps/switchdash-desktop/src/renderer/features/locations/stores/location-view.test.tsindex 240a33443..d2a37053b 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/projects/stores/project-view.test.ts+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/location-view.test.ts@@ -1,9 +1,9 @@import { describe, expect, it } from 'vitest';-import { ProjectViewStore } from './project-view';+import { LocationViewStore } from './location-view';describe('SessionViewStore range selection', () => {it('keeps the non-shift click as the range anchor', () => {- const store = new ProjectViewStore().sessionView;+ const store = new LocationViewStore().sessionView;const ids = ['1', '2', '3', '4', '5'];store.toggleSelect('1');diff --git a/dash/apps/switchdash-desktop/src/renderer/features/projects/stores/project-view.ts b/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/location-view.tssimilarity index 80%rename from dash/apps/switchdash-desktop/src/renderer/features/projects/stores/project-view.tsrename to dash/apps/switchdash-desktop/src/renderer/features/locations/stores/location-view.tsindex bf317014e..53aa38b59 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/projects/stores/project-view.ts+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/location-view.ts@@ -1,30 +1,30 @@import { makeAutoObservable } from 'mobx';import type { Snapshottable } from '@renderer/lib/stores/snapshottable';-import type { ProjectViewSnapshot } from '@shared/view-state';+import type { LocationViewSnapshot } from '@shared/view-state';-export type ProjectView = 'sessions' | 'subagents' | 'settings';+export type LocationView = 'sessions' | 'subagents' | 'settings';-export class ProjectViewStore implements Snapshottable<ProjectViewSnapshot> {- activeView: ProjectView = 'sessions';+export class LocationViewStore implements Snapshottable<LocationViewSnapshot> {+ activeView: LocationView = 'sessions';sessionView: SessionViewStore = new SessionViewStore();constructor() {makeAutoObservable(this);}- setProjectView(view: ProjectView) {+ setLocationView(view: LocationView) {this.activeView = view;}- get snapshot(): ProjectViewSnapshot {+ get snapshot(): LocationViewSnapshot {return {activeView: this.activeView,sessionViewTab: this.sessionView.tab,};}- restoreSnapshot(snapshot: Partial<ProjectViewSnapshot>): void {- if (snapshot.activeView) this.activeView = snapshot.activeView as ProjectView;+ restoreSnapshot(snapshot: Partial<LocationViewSnapshot>): void {+ if (snapshot.activeView) this.activeView = snapshot.activeView as LocationView;if (snapshot.sessionViewTab) this.sessionView.setTab(snapshot.sessionViewTab);}}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/location.ts b/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/location.tsnew file mode 100644index 000000000..e077566ba--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/location.ts@@ -0,0 +1,185 @@+import { makeAutoObservable, observable } from 'mobx';+import { SessionManagerStore } from '@renderer/features/sessions/stores/session-manager';+import { snapshotRegistry } from '@renderer/lib/stores/snapshot-registry';+import type { Location } from '@shared/core/locations/locations';+import type { LocationViewSnapshot } from '@shared/view-state';+import { LocationSettingsStore } from './location-settings-store';+import { LocationViewStore } from './location-view';++export type UnregisteredLocationPhase =+ | 'registering' // onboarding the agent + creating the location row+ | 'error';++export type UnmountedLocationPhase = 'opening' | 'error' | 'closing' | 'idle';++export type LocationMode = 'pick';++/**+ * Holds all mounted-only state for a location. Created atomically by+ * LocationStore.transitionToMounted and disposed on unmount or deletion.+ */+export class MountedLocation {+ readonly sessionManager: SessionManagerStore;+ readonly view: LocationViewStore;+ readonly settings: LocationSettingsStore;+ readonly data: Location;++ private _snapshotDisposer: (() => void) | null = null;++ get snapshot(): LocationViewSnapshot {+ return {+ activeView: this.view.activeView,+ sessionViewTab: this.view.sessionView.tab,+ };+ }++ constructor(data: Location, savedSnapshot?: LocationViewSnapshot) {+ this.data = data;+ this.view = new LocationViewStore();+ this.settings = new LocationSettingsStore(data.id);+ this.sessionManager = new SessionManagerStore(data.id, this.settings);++ if (savedSnapshot) this.view.restoreSnapshot(savedSnapshot);++ makeAutoObservable(this, {+ sessionManager: false,+ view: false,+ settings: false,+ });++ this._snapshotDisposer = snapshotRegistry.register(`location:${data.id}`, () => this.snapshot);+ }++ dispose(): void {+ this.settings.dispose();+ this._snapshotDisposer?.();+ this._snapshotDisposer = null;+ }+}++/**+ * Container class — holds a stable reference in the ObservableMap across all+ * lifecycle transitions. Transitioning replaces `mountedLocation` atomically+ * rather than nulling out individual fields.+ */+export class LocationStore {+ state: 'unregistered' | 'unmounted' | 'mounted';+ id: string;+ name: string | null;+ data: Location | null;+ createdAt: string;+ phase: UnregisteredLocationPhase | UnmountedLocationPhase | null;+ error: string | undefined = undefined;+ errorCode: 'path-not-found' | 'ssh-disconnected' | undefined = undefined;+ mode: LocationMode | null;+ mountedLocation: MountedLocation | null = null;++ constructor(+ state: LocationStore['state'],+ id: string,+ name: string | null,+ data: Location | null,+ phase: UnregisteredLocationPhase | UnmountedLocationPhase | null,+ mode: LocationMode | null = null+ ) {+ this.state = state;+ this.id = id;+ this.name = name;+ this.data = data;+ this.createdAt = data?.createdAt ?? new Date().toISOString();+ this.phase = phase;+ this.mode = mode;+ makeAutoObservable(this, { mountedLocation: observable.ref });+ }++ transitionToMounted(data: Location, savedSnapshot?: LocationViewSnapshot): void {+ this.mountedLocation = new MountedLocation(data, savedSnapshot);+ this.data = data;+ this.id = data.id;+ this.name = data.name;+ this.createdAt = data.createdAt;+ this.state = 'mounted';+ this.phase = null;+ this.error = undefined;+ this.errorCode = undefined;+ }++ transitionToUnmounted(data: Location, phase: UnmountedLocationPhase = 'opening'): void {+ this.mountedLocation?.dispose();+ this.mountedLocation = null;+ this.data = data;+ this.id = data.id;+ this.name = data.name;+ this.createdAt = data.createdAt;+ this.state = 'unmounted';+ this.phase = phase;+ this.error = undefined;+ this.errorCode = undefined;+ }++ transitionToUnregistered(+ id: string,+ name: string,+ phase: UnregisteredLocationPhase,+ mode: LocationMode+ ): void {+ this.mountedLocation?.dispose();+ this.mountedLocation = null;+ this.data = null;+ this.id = id;+ this.name = name;+ this.state = 'unregistered';+ this.phase = phase;+ this.mode = mode;+ this.error = undefined;+ }+}++export type UnregisteredLocation = LocationStore & {+ state: 'unregistered';+ id: string;+ name: string;+ phase: UnregisteredLocationPhase;+ mode: LocationMode;+ error: string | undefined;+};++export type UnmountedLocation = LocationStore & {+ state: 'unmounted';+ data: Location;+ phase: UnmountedLocationPhase;+ error: string | undefined;+ errorCode: 'path-not-found' | 'ssh-disconnected' | undefined;+};++export function isUnregisteredLocation(p: LocationStore): p is UnregisteredLocation {+ return p.state === 'unregistered';+}++export function isUnmountedLocation(p: LocationStore): p is UnmountedLocation {+ return p.state === 'unmounted';+}++export function isMountedLocation(p: LocationStore): p is LocationStore & {+ state: 'mounted';+ mountedLocation: MountedLocation;+ data: Location;+} {+ return p.state === 'mounted';+}++export function createUnregisteredLocation(+ id: string,+ name: string,+ phase: UnregisteredLocationPhase,+ mode: LocationMode = 'pick'+): LocationStore {+ return new LocationStore('unregistered', id, name, null, phase, mode);+}++export function createUnmountedLocation(+ data: Location,+ phase: UnmountedLocationPhase = 'opening'+): LocationStore {+ return new LocationStore('unmounted', data.id, data.name, data, phase);+}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/view.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/view.tsxnew file mode 100644index 000000000..d26a1320d--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/view.tsx@@ -0,0 +1,22 @@+import type { GuardResult, ViewDefinition } from '@renderer/app/view-registry';+import { LocationViewWrapper } from '@renderer/features/locations/components/location-view-wrapper';+import { appState } from '@renderer/lib/stores/app-state';+import { LocationTitlebar } from './components/location-titlebar';+import { LocationMainPanel } from './components/main-panel/main-panel';++export const locationView = {+ WrapView: LocationViewWrapper,+ TitlebarSlot: LocationTitlebar,+ MainPanel: LocationMainPanel,+ canActivate: (params: unknown): GuardResult => {+ const locationId =+ typeof params === 'object' && params !== null+ ? (params as { locationId?: unknown }).locationId+ : undefined;+ if (typeof locationId !== 'string') return { ok: false, redirect: 'home' };+ return appState.locations.locations.has(locationId) ||+ appState.locations.pendingCreationIds.has(locationId)+ ? { ok: true }+ : { ok: false, redirect: 'home' };+ },+} satisfies ViewDefinition<{ locationId: string; subagentName?: string }>;diff --git a/dash/apps/switchdash-desktop/src/renderer/features/projects/components/settings-view/sections/connection-settings-section.tsx b/dash/apps/switchdash-desktop/src/renderer/features/projects/components/settings-view/sections/connection-settings-section.tsxdeleted file mode 100644index d08be3ff2..000000000--- a/dash/apps/switchdash-desktop/src/renderer/features/projects/components/settings-view/sections/connection-settings-section.tsx+++ /dev/null@@ -1,219 +0,0 @@-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';-import { useEffect, useState } from 'react';-import { rpc } from '@renderer/lib/ipc';-import { Button } from '@renderer/lib/ui/button';-import { Field, FieldDescription, FieldTitle } from '@renderer/lib/ui/field';-import { Input } from '@renderer/lib/ui/input';-import { Label } from '@renderer/lib/ui/label';-import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,-} from '@renderer/lib/ui/select';-import { Switch } from '@renderer/lib/ui/switch';-import { log } from '@renderer/utils/logger';-import type { Agent } from '@shared/core/agents/agents';--/**- * Per-agent local/remote connection control (CHOO-1059). A remote agent runs- * its sessions on an SSH host (resolved from `~/.ssh/config`) so it keeps- * working and listening to its Switch rooms while switchdash is closed.- * Toggling to remote reveals the SSH host + remote working dir; both are- * required before the connection is saved. Saving remote also copies the- * agent's Switch credentials to the host (option A); "Set up host" re-runs that- * copy on demand. A connectivity/dependency preflight still runs when a remote- * session is first provisioned.- */-export function ConnectionSettingsSection({ projectId }: { projectId: string }) {- const { data: agents } = useQuery({- queryKey: ['project-agents', projectId],- queryFn: () => rpc.agents.getAgents(projectId),- });-- const list = agents ?? [];- if (list.length === 0) return null;-- return (- <Field>- <FieldTitle>Run location</FieldTitle>- <FieldDescription className="text-foreground-muted">- Run an agent on a remote SSH host instead of this machine. A remote agent keeps working and- listening to its Switch rooms even while switchdash is closed.- </FieldDescription>- <div className="flex flex-col gap-2">- {list.map((agent) => (- <ConnectionRow key={agent.id} projectId={projectId} agent={agent} />- ))}- </div>- </Field>- );-}--function ConnectionRow({ projectId, agent }: { projectId: string; agent: Agent }) {- const queryClient = useQueryClient();- const isRemote = agent.connection === 'remote';-- // Onboarded remote hosts drive the host picker so an agent is pointed at a- // managed host (Settings → Remote hosts) rather than an arbitrary alias.- const { data: remoteHosts } = useQuery({- queryKey: ['remote-hosts'],- queryFn: () => rpc.remoteHosts.listHosts(),- });- const onboardedHosts = remoteHosts ?? [];-- const [showRemote, setShowRemote] = useState(isRemote);- const [sshHost, setSshHost] = useState(agent.remoteConfig?.sshHost ?? '');- const [remoteRepoDir, setRemoteRepoDir] = useState(agent.remoteConfig?.remoteRepoDir ?? '');-- // Re-sync local form state when the agent record changes (e.g. after a save- // invalidates the agents query and a fresh row arrives).- useEffect(() => {- setShowRemote(agent.connection === 'remote');- setSshHost(agent.remoteConfig?.sshHost ?? '');- setRemoteRepoDir(agent.remoteConfig?.remoteRepoDir ?? '');- }, [agent.connection, agent.remoteConfig?.sshHost, agent.remoteConfig?.remoteRepoDir]);-- // Copies the agent's Switch creds to the host (CHOO-1059, option A). Runs- // automatically right after the connection is saved remote, and can be re-run- // manually (e.g. once the host is reachable, or after rotating creds).- const setupMutation = useMutation({- mutationFn: () => rpc.agents.setupRemoteAgent({ agentId: agent.id }),- onError: (error) => {- log.error('Failed to set up remote agent host', { agentId: agent.id, error });- },- });-- const mutation = useMutation({- mutationFn: (params: Parameters<typeof rpc.agents.setAgentConnection>[0]) =>- rpc.agents.setAgentConnection(params),- onError: (error) => {- log.error('Failed to update agent connection', { agentId: agent.id, error });- },- onSuccess: (_data, variables) => {- if (variables.connection === 'remote') setupMutation.mutate();- },- onSettled: () => {- void queryClient.invalidateQueries({ queryKey: ['project-agents', projectId] });- },- });-- const onToggle = (checked: boolean) => {- setShowRemote(checked);- // Switching off persists immediately; switching on waits for a valid host +- // dir (saved via the Save button) so we never write a half-formed config.- if (!checked && isRemote) {- mutation.mutate({ agentId: agent.id, connection: 'local' });- }- };-- const trimmedHost = sshHost.trim();- const trimmedDir = remoteRepoDir.trim();- const dirty =- trimmedHost !== (agent.remoteConfig?.sshHost ?? '') ||- trimmedDir !== (agent.remoteConfig?.remoteRepoDir ?? '');- const canSave = trimmedHost.length > 0 && trimmedDir.length > 0 && dirty;-- const onSave = () => {- mutation.mutate({- agentId: agent.id,- connection: 'remote',- remoteConfig: { sshHost: trimmedHost, remoteRepoDir: trimmedDir },- });- };-- return (- <div className="flex flex-col gap-2 rounded-md border border-border px-2 py-1.5">- <div className="flex items-center justify-between gap-3">- <span className="truncate text-sm">{agent.name}</span>- <div className="flex items-center gap-2">- <span className="text-xs text-foreground-muted">{showRemote ? 'Remote' : 'Local'}</span>- <Switch checked={showRemote} disabled={mutation.isPending} onCheckedChange={onToggle} />- </div>- </div>-- {showRemote && (- <div className="flex flex-col gap-2 pt-1">- <div className="flex flex-col gap-1">- <Label htmlFor={`ssh-host-${agent.id}`} className="text-xs">- SSH host- </Label>- <FieldDescription className="text-foreground-muted">- {onboardedHosts.length > 0- ? 'An onboarded remote host (manage them in Settings → Remote hosts).'- : "A Host alias from your ~/.ssh/config — the same name you'd pass to ssh."}- </FieldDescription>- {onboardedHosts.length > 0 ? (- <Select- value={sshHost}- onValueChange={(v) => setSshHost(v ?? '')}- disabled={mutation.isPending}- >- <SelectTrigger id={`ssh-host-${agent.id}`}>- <SelectValue placeholder="Select a host" />- </SelectTrigger>- <SelectContent>- {onboardedHosts.map((host) => (- <SelectItem key={host.sshHost} value={host.sshHost}>- {host.name} ({host.sshHost})- </SelectItem>- ))}- </SelectContent>- </Select>- ) : (- <Input- id={`ssh-host-${agent.id}`}- value={sshHost}- placeholder="dev-vm"- disabled={mutation.isPending}- onChange={(e) => setSshHost(e.target.value)}- />- )}- </div>- <div className="flex flex-col gap-1">- <Label htmlFor={`remote-dir-${agent.id}`} className="text-xs">- Remote working directory- </Label>- <Input- id={`remote-dir-${agent.id}`}- value={remoteRepoDir}- placeholder="/home/agent/repo"- disabled={mutation.isPending}- onChange={(e) => setRemoteRepoDir(e.target.value)}- />- </div>- <div className="flex items-center justify-end gap-2">- {isRemote && !dirty && (- <Button- size="sm"- variant="outline"- disabled={setupMutation.isPending || mutation.isPending}- onClick={() => setupMutation.mutate()}- >- {setupMutation.isPending ? 'Setting up…' : 'Set up host'}- </Button>- )}- <Button- size="sm"- disabled={!canSave || mutation.isPending || setupMutation.isPending}- onClick={onSave}- >- {isRemote ? 'Update' : 'Save'}- </Button>- </div>- {setupMutation.isError && (- <p className="text-destructive text-xs">- Host setup failed: {(setupMutation.error as Error).message}- </p>- )}- {setupMutation.isSuccess && !setupMutation.isPending && (- <p className="text-xs text-foreground-muted">- Host set up — credentials copied to the remote working directory.- </p>- )}- </div>- )}- </div>- );-}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/projects/components/settings-view/settings-panel.tsx b/dash/apps/switchdash-desktop/src/renderer/features/projects/components/settings-view/settings-panel.tsxdeleted file mode 100644index 4f594195f..000000000--- a/dash/apps/switchdash-desktop/src/renderer/features/projects/components/settings-view/settings-panel.tsx+++ /dev/null@@ -1,35 +0,0 @@-import { observer } from 'mobx-react-lite';-import { AutoSessionSettingsSection } from '@renderer/features/projects/components/settings-view/sections/auto-session-settings-section';-import { ConnectionSettingsSection } from '@renderer/features/projects/components/settings-view/sections/connection-settings-section';-import { SubagentAutoSessionSettingsSection } from '@renderer/features/projects/components/settings-view/sections/subagent-auto-session-settings-section';-import { asMounted, getProjectStore } from '@renderer/features/projects/stores/project-selectors';-import { useParams } from '@renderer/lib/layout/navigation-provider';-import { Spinner } from '@renderer/lib/ui/spinner';--export const SettingsPanel = observer(function SettingsPanel() {- const {- params: { projectId, subagentName },- } = useParams('project');- const mounted = asMounted(getProjectStore(projectId));-- if (!mounted) {- return (- <div className="flex items-center justify-center py-10">- <Spinner />- </div>- );- }-- return (- <div className="flex flex-col gap-6">- {subagentName ? (- <SubagentAutoSessionSettingsSection projectId={projectId} subagentName={subagentName} />- ) : (- <>- <AutoSessionSettingsSection projectId={projectId} />- <ConnectionSettingsSection projectId={projectId} />- </>- )}- </div>- );-});diff --git a/dash/apps/switchdash-desktop/src/renderer/features/projects/hooks/use-confirm-delete-project.tsx b/dash/apps/switchdash-desktop/src/renderer/features/projects/hooks/use-confirm-delete-project.tsxdeleted file mode 100644index 175f54fc9..000000000--- a/dash/apps/switchdash-desktop/src/renderer/features/projects/hooks/use-confirm-delete-project.tsx+++ /dev/null@@ -1,26 +0,0 @@-import { getProjectManagerStore } from '@renderer/features/projects/stores/project-selectors';-import { useShowModal } from '@renderer/lib/modal/modal-provider';--export function useConfirmDeleteProject() {- const showConfirmDeleteProject = useShowModal('confirmActionModal');-- return async ({- projectId,- projectLabel,- onDeleted,- }: {- projectId: string;- projectLabel: string;- onDeleted?: () => void;- }) => {- showConfirmDeleteProject({- title: 'Remove agent',- description: `"${projectLabel}" will be removed from switchdash. The folder stays on the filesystem.`,- confirmLabel: 'Remove',- onSuccess: () => {- void getProjectManagerStore().deleteProject(projectId);- onDeleted?.();- },- });- };-}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/projects/stores/agents-store.ts b/dash/apps/switchdash-desktop/src/renderer/features/projects/stores/agents-store.tsdeleted file mode 100644index a608f7c12..000000000--- a/dash/apps/switchdash-desktop/src/renderer/features/projects/stores/agents-store.ts+++ /dev/null@@ -1,64 +0,0 @@-import { makeAutoObservable, runInAction } from 'mobx';-import { rpc } from '@renderer/lib/ipc';-import type { Agent } from '@shared/core/agents/agents';--/**- * Renderer cache of every agent across all projects, used to resolve which- * Switch server a project belongs to. The sidebar scopes its tree to the active- * server (see {@link switchServersStore.activeServerId}), so it needs a reactive- * project→serverId lookup that does not depend on each row's own react-query.- *- * A project holds one parent agent plus any subagents, which all share the same- * server; {@link serverIdForProject} returns the first non-null serverId among a- * project's agents.- */-export class AgentsStore {- /** All agents grouped by their project id. */- readonly byProject = new Map<string, Agent[]>();- /**- * Server id a just-created project's agent will belong to, recorded by the- * add-agent modal before {@link load} has re-fetched the new agent. Used as a- * fallback in {@link serverIdForProject} so a freshly-created project does not- * flicker out of the sidebar's server-scoped view during the gap between the- * project mounting and the agent list refreshing.- */- readonly optimisticServerByProject = new Map<string, string>();- loaded = false;-- constructor() {- makeAutoObservable(this);- }-- async load(): Promise<void> {- const agents = await rpc.agents.getAgents();- runInAction(() => {- this.byProject.clear();- for (const agent of agents) {- const list = this.byProject.get(agent.projectId);- if (list) list.push(agent);- else this.byProject.set(agent.projectId, [agent]);- }- // Drop optimistic notes now superseded by a real agent record.- for (const projectId of this.byProject.keys()) {- this.optimisticServerByProject.delete(projectId);- }- this.loaded = true;- });- }-- /** Record the server a project's agent will bind to, ahead of {@link load}. */- noteProjectServer(projectId: string, serverId: string): void {- runInAction(() => {- this.optimisticServerByProject.set(projectId, serverId);- });- }-- /** The Switch server a project's agents belong to, or null if unlinked. */- serverIdForProject(projectId: string): string | null {- const agents = this.byProject.get(projectId);- const resolved = agents?.find((a) => a.serverId !== null)?.serverId ?? null;- return resolved ?? this.optimisticServerByProject.get(projectId) ?? null;- }-}--export const agentsStore = new AgentsStore();diff --git a/dash/apps/switchdash-desktop/src/renderer/features/projects/stores/project-creation-types.ts b/dash/apps/switchdash-desktop/src/renderer/features/projects/stores/project-creation-types.tsdeleted file mode 100644index aa9b7b7ba..000000000--- a/dash/apps/switchdash-desktop/src/renderer/features/projects/stores/project-creation-types.ts+++ /dev/null@@ -1,36 +0,0 @@-import type { Result } from '@switchdash/shared';-import type { AgentRemoteConfig } from '@shared/core/agents/agent-connection';-import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';-import type { CreateProjectError } from '@shared/projects';--interface BaseModeData {- name: string;- /** Local working directory. Omitted for a remote agent (see `remoteConfig`). */- path?: string;-}--export interface PickModeData extends BaseModeData {- mode: 'pick';- /** The registered Switch server the user chose for this agent. */- serverId: string;- /** The agent type (CLI provider) the user picked when onboarding. */- providerId: AgentProviderId;- /** When set, the agent runs remotely on this host instead of locally. */- remoteConfig?: AgentRemoteConfig;-}--export type ModeData = PickModeData;--export type ProjectType = { type: 'local' };--export type ProjectCreationError = CreateProjectError;--export type ProjectCreationCompletion = Result<void, ProjectCreationError>;--export type StartProjectCreationResult =- | { kind: 'existing'; projectId: string }- | { kind: 'creating'; projectId: string; completion: Promise<ProjectCreationCompletion> };--export interface StartProjectCreationOptions {- id?: string;-}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/projects/stores/project-manager.test.ts b/dash/apps/switchdash-desktop/src/renderer/features/projects/stores/project-manager.test.tsdeleted file mode 100644index 612b917bb..000000000--- a/dash/apps/switchdash-desktop/src/renderer/features/projects/stores/project-manager.test.ts+++ /dev/null@@ -1,169 +0,0 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';-import type { LocalProject } from '@shared/projects';-import { isUnregisteredProject } from './project';-import { ProjectManagerStore } from './project-manager';--const mocks = vi.hoisted(() => ({- createProject: vi.fn(),- inspectProjectPath: vi.fn(),- openProject: vi.fn(),- eventOn: vi.fn(),-}));--vi.mock('@renderer/lib/ipc', () => ({- events: {- on: mocks.eventOn,- },- rpc: {- projects: {- createProject: mocks.createProject,- getProjects: vi.fn(async () => []),- inspectProjectPath: mocks.inspectProjectPath,- openProject: mocks.openProject,- },- },-}));--vi.mock('@renderer/lib/stores/app-state', () => ({- appState: {- navigation: {- currentViewId: 'home',- revalidate: vi.fn(),- viewParamsStore: {},- },- },-}));--vi.mock('@renderer/lib/stores/view-state-cache', () => ({- viewStateCache: {- get: vi.fn(async () => undefined),- },-}));--function localProject(overrides: Partial<LocalProject> = {}): LocalProject {- return {- type: 'local',- id: 'project-id',- name: 'Project',- path: '/project',- repositoryWorkspaceId: null,- createdAt: '2026-05-28T00:00:00.000Z',- updatedAt: '2026-05-28T00:00:00.000Z',- ...overrides,- };-}--function okProject(project: LocalProject) {- return { success: true as const, data: project };-}--describe('ProjectManagerStore project creation', () => {- beforeEach(() => {- vi.clearAllMocks();- mocks.inspectProjectPath.mockResolvedValue({ isDirectory: true, isGitRepo: true });- mocks.createProject.mockResolvedValue(okProject(localProject()));- mocks.openProject.mockReturnValue(new Promise(() => {}));- });-- it('returns an existing project without starting creation', async () => {- const existingProject = localProject({ id: 'existing-project' });- mocks.inspectProjectPath.mockResolvedValueOnce({- isDirectory: true,- isGitRepo: true,- existingProject,- });- const store = new ProjectManagerStore();-- const result = await store.startProjectCreation(- { type: 'local' },- {- mode: 'pick',- name: 'Project',- path: '/project',- serverId: 'server-1',- providerId: 'claude',- },- { id: 'optimistic-project' }- );-- expect(result).toEqual({ kind: 'existing', projectId: 'existing-project' });- expect(mocks.createProject).not.toHaveBeenCalled();- expect(store.projects.has('optimistic-project')).toBe(false);- expect(store.pendingCreationIds.has('optimistic-project')).toBe(false);- });-- it('creates unregistered project state before returning creating', async () => {- let resolveCreateProject: (project: LocalProject) => void = () => {};- mocks.createProject.mockReturnValueOnce(- new Promise<ReturnType<typeof okProject>>((resolve) => {- resolveCreateProject = (project) => resolve(okProject(project));- })- );- const store = new ProjectManagerStore();-- const result = await store.startProjectCreation(- { type: 'local' },- {- mode: 'pick',- name: 'Project',- path: '/project',- serverId: 'server-1',- providerId: 'claude',- },- { id: 'optimistic-project' }- );-- expect(result.kind).toBe('creating');- const pendingProject = store.projects.get('optimistic-project');- expect(pendingProject && isUnregisteredProject(pendingProject)).toBe(true);- expect(pendingProject?.phase).toBe('registering');- expect(store.pendingCreationIds.has('optimistic-project')).toBe(true);- expect(mocks.inspectProjectPath).toHaveBeenCalledTimes(1);-- resolveCreateProject(localProject({ id: 'optimistic-project' }));- if (result.kind === 'creating') await result.completion;-- expect(mocks.inspectProjectPath).toHaveBeenCalledTimes(1);- expect(store.pendingCreationIds.has('optimistic-project')).toBe(false);- });-- it('marks project creation as failed when the project RPC returns a typed error', async () => {- mocks.createProject.mockResolvedValueOnce({- success: false,- error: {- type: 'not-repository',- path: '/project',- },- });- const store = new ProjectManagerStore();-- const result = await store.startProjectCreation(- { type: 'local' },- {- mode: 'pick',- name: 'Project',- path: '/project',- serverId: 'server-1',- providerId: 'claude',- },- { id: 'optimistic-project' }- );-- expect(result.kind).toBe('creating');- if (result.kind === 'creating') {- await expect(result.completion).resolves.toEqual({- success: false,- error: { type: 'not-repository', path: '/project' },- });- }-- const project = store.projects.get('optimistic-project');- expect(project && isUnregisteredProject(project)).toBe(true);- if (project && isUnregisteredProject(project)) {- expect(project.phase).toBe('error');- expect(project.error).toBe(- 'Directory is not a git repository. Enable "Initialize git repository" to continue.'- );- }- });-});diff --git a/dash/apps/switchdash-desktop/src/renderer/features/projects/stores/project-manager.ts b/dash/apps/switchdash-desktop/src/renderer/features/projects/stores/project-manager.tsdeleted file mode 100644index a24f3792d..000000000--- a/dash/apps/switchdash-desktop/src/renderer/features/projects/stores/project-manager.ts+++ /dev/null@@ -1,298 +0,0 @@-import { err, ok } from '@switchdash/shared';-import { makeObservable, observable, runInAction } from 'mobx';-import { rpc } from '@renderer/lib/ipc';-import { appState } from '@renderer/lib/stores/app-state';-import { viewStateCache } from '@renderer/lib/stores/view-state-cache';-import { type LocalProject } from '@shared/projects';-import type { ProjectViewSnapshot } from '@shared/view-state';-import {- createUnmountedProject,- createUnregisteredProject,- isUnmountedProject,- isUnregisteredProject,- type ProjectStore,- type UnregisteredProjectPhase,-} from './project';-import type {- ModeData,- ProjectCreationCompletion,- ProjectCreationError,- ProjectType,- StartProjectCreationOptions,- StartProjectCreationResult,-} from './project-creation-types';--export class ProjectManagerStore {- projects = observable.map<string, ProjectStore>();- pendingCreationIds = observable.set<string>();- private _projectMountPromises = new Map<string, Promise<void>>();- private _loadPromise: Promise<void> | null = null;-- constructor() {- makeObservable(this, { projects: observable, pendingCreationIds: observable });- }-- load(): Promise<void> {- if (!this._loadPromise) {- this._loadPromise = this._doLoad();- }- return this._loadPromise;- }-- private async _doLoad(): Promise<void> {- const rawProjects = await rpc.projects.getProjects();- const toMount: string[] = [];- runInAction(() => {- for (const p of rawProjects) {- if (this.projects.has(p.id)) continue;- this.projects.set(p.id, createUnmountedProject(p, 'idle'));- toMount.push(p.id);- }- });- await Promise.allSettled(toMount.map((id) => this.mountProject(id)));- }-- async createProject(- projectType: ProjectType,- data: ModeData,- id?: string- ): Promise<string | undefined> {- const result = await this.startProjectCreation(projectType, data, { id });- if (result.kind === 'existing') return result.projectId;-- const completion = await result.completion;- return completion.success ? result.projectId : undefined;- }-- async startProjectCreation(- projectType: ProjectType,- data: ModeData,- options: StartProjectCreationOptions = {}- ): Promise<StartProjectCreationResult> {- const projectId = options.id ?? crypto.randomUUID();- // Remote agents have no local directory: skip the local path inspection /- // existing-project dedup and create straight away (create-local-project- // detects + validates the agent in the remote dir over SSH).- const targetPath = data.remoteConfig- ? undefined- : data.mode === 'pick'- ? data.path- : `${data.path}/${data.name}`;- if (targetPath !== undefined) {- const inspection = await rpc.projects.inspectProjectPath({ type: 'local', path: targetPath });- if (inspection.existingProject) {- return { kind: 'existing', projectId: inspection.existingProject.id };- }- }-- runInAction(() => {- this.pendingCreationIds.add(projectId);- this.projects.set(- projectId,- createUnregisteredProject(projectId, data.name, initialCreationPhase(data.mode), data.mode)- );- });-- const completion = this._doCreateProject(projectType, data, projectId, targetPath).finally(- () => {- runInAction(() => this.pendingCreationIds.delete(projectId));- }- );-- return { kind: 'creating', projectId, completion };- }-- private async _doCreateProject(- _projectType: ProjectType,- data: ModeData,- projectId: string,- targetPath: string | undefined- ): Promise<ProjectCreationCompletion> {- let result: ProjectCreationCompletion;- try {- const projectResult = await rpc.projects.createProject({- type: 'local',- id: projectId,- path: targetPath,- name: data.name,- serverId: data.serverId,- providerId: data.providerId,- remoteConfig: data.remoteConfig,- });- if (!projectResult.success) {- result = err(projectResult.error);- } else {- this._setAndOpenProject(projectId, projectResult.data);- result = ok();- }- } catch (error) {- this._markUnexpectedCreationError(projectId, error);- throw error;- }-- if (!result.success) this._markCreationError(projectId, result.error);- return result;- }-- mountProject(projectId: string): Promise<void> {- const inFlight = this._projectMountPromises.get(projectId);- if (inFlight) return inFlight;-- const project = this.projects.get(projectId);- if (!project || !isUnmountedProject(project)) return Promise.resolve();-- runInAction(() => {- project.phase = 'opening';- project.error = undefined;- project.errorCode = undefined;- });-- const promise = Promise.all([- rpc.projects.openProject(projectId),- viewStateCache.get(`project:${projectId}`),- ])- .then(async ([openResult, savedSnapshot]) => {- if (!openResult.success) {- runInAction(() => {- const current = this.projects.get(projectId);- if (current && isUnmountedProject(current)) {- current.phase = 'error';- if (openResult.error.type === 'path-not-found') {- current.error = openResult.error.path;- current.errorCode = 'path-not-found';- } else if (openResult.error.type === 'error') {- current.error = openResult.error.message;- current.errorCode = undefined;- } else {- current.error = undefined;- current.errorCode = undefined;- }- }- });- return;- }- runInAction(() => {- const current = this.projects.get(projectId);- if (current && isUnmountedProject(current)) {- // Patch repositoryWorkspaceId from the main process response so the- // mounted project data is up-to-date (fixes stale null after creation).- const projectData = current.data;- if (openResult.data.repositoryWorkspaceId && projectData) {- projectData.repositoryWorkspaceId = openResult.data.repositoryWorkspaceId;- }- current.transitionToMounted(- projectData,- savedSnapshot as ProjectViewSnapshot | undefined- );- }- });- // Load the session list before provisioning so the sessions map is populated.- const sessionManager = this.projects.get(projectId)?.mountedProject?.sessionManager;- if (sessionManager) {- await sessionManager.loadSessions();- const nav = appState.navigation;- const navParams = nav.viewParamsStore['session'] as- | { projectId?: string; sessionId?: string }- | undefined;- const navSessionId =- nav.currentViewId === 'session' && navParams?.projectId === projectId- ? navParams.sessionId- : undefined;- if (navSessionId) {- sessionManager.provisionSession(navSessionId).catch(() => {});- }- }- })- .catch((err: unknown) => {- runInAction(() => {- const current = this.projects.get(projectId);- if (current && isUnmountedProject(current)) {- current.phase = 'error';- current.error = err instanceof Error ? err.message : String(err);- current.errorCode = undefined;- }- });- throw err;- })- .finally(() => {- this._projectMountPromises.delete(projectId);- });-- this._projectMountPromises.set(projectId, promise);- return promise;- }-- async deleteProject(projectId: string): Promise<void> {- const snapshot = this.projects.get(projectId);- runInAction(() => {- this.projects.delete(projectId);- });- appState.navigation.revalidate();- try {- await rpc.projects.deleteProject(projectId);- } catch (err) {- runInAction(() => {- if (snapshot) this.projects.set(projectId, snapshot);- });- throw err;- }- }-- removeUnregisteredProject(projectId: string): void {- runInAction(() => {- const store = this.projects.get(projectId);- if (store && isUnregisteredProject(store)) {- this.projects.delete(projectId);- }- });- }-- private _setAndOpenProject(id: string, project: LocalProject): void {- runInAction(() => {- const current = this.projects.get(id);- if (current) {- current.transitionToUnmounted(project, 'opening');- } else {- this.projects.set(id, createUnmountedProject(project, 'opening'));- }- });- void this.mountProject(id);- }-- private _markCreationError(id: string, error: ProjectCreationError): void {- runInAction(() => {- const store = this.projects.get(id);- if (store && isUnregisteredProject(store)) {- store.phase = 'error';- store.error = creationErrorMessage(error);- }- });- }-- private _markUnexpectedCreationError(id: string, error: unknown): void {- runInAction(() => {- const store = this.projects.get(id);- if (store && isUnregisteredProject(store)) {- store.phase = 'error';- store.error = error instanceof Error ? error.message : String(error);- }- });- }-}--function creationErrorMessage(error: ProjectCreationError): string {- switch (error.type) {- case 'not-repository':- return 'Directory is not a git repository. Enable "Initialize git repository" to continue.';- case 'switch-agent-not-on-server':- return `This agent isn't registered on ${error.serverName}. Pick the server it belongs to.`;- case 'switch-server-unauthenticated':- return `Sign in to ${error.serverName} before adding this agent.`;- default:- return error.message;- }-}--function initialCreationPhase(_mode: ModeData['mode']): UnregisteredProjectPhase {- return 'registering';-}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/projects/stores/project-selectors.ts b/dash/apps/switchdash-desktop/src/renderer/features/projects/stores/project-selectors.tsdeleted file mode 100644index 8e09669f8..000000000--- a/dash/apps/switchdash-desktop/src/renderer/features/projects/stores/project-selectors.ts+++ /dev/null@@ -1,87 +0,0 @@-import { appState } from '@renderer/lib/stores/app-state';-import type { LocalProject } from '@shared/projects';-import {- isUnmountedProject,- isUnregisteredProject,- type MountedProject,- type ProjectStore,-} from './project';-import type { ProjectManagerStore } from './project-manager';-import type { ProjectSettingsStore } from './project-settings-store';-import type { ProjectViewStore } from './project-view';--/** Returns the ProjectManagerStore from appState. Call only inside `observer` components (or other MobX reactions). */-export function getProjectManagerStore(): ProjectManagerStore {- return appState.projects;-}--/** Call only inside `observer` components (or other MobX reactions). */-export function getProjectStore(projectId: string): ProjectStore | undefined {- return getProjectManagerStore().projects.get(projectId);-}--/** Summary for routing the project shell; call only inside `observer` (or other MobX reactions). */-export type ProjectViewKind =- | 'missing'- | 'creating'- | 'bootstrapping'- | 'mount_error'- | 'path_not_found'- | 'idle_unmounted'- | 'ready';--export function projectViewKind(store: ProjectStore | undefined): ProjectViewKind {- if (!store) return 'missing';- if (isUnregisteredProject(store)) return 'creating';- if (isUnmountedProject(store)) {- if (store.phase === 'opening') return 'bootstrapping';- if (store.phase === 'error') {- if (store.errorCode === 'path-not-found') return 'path_not_found';- return 'mount_error';- }- return 'idle_unmounted';- }- return 'ready';-}--/** Returns the mounted project payload if ready, otherwise undefined. */-export function asMounted(store: ProjectStore | undefined): MountedProject | undefined {- return store?.mountedProject ?? undefined;-}--/** Returns the id of the first mounted project, or undefined if none are mounted. */-export function firstMountedProjectId(): string | undefined {- for (const [id, store] of getProjectManagerStore().projects.entries()) {- if (asMounted(store)) return id;- }- return undefined;-}--export function mountedProjectData(store: ProjectStore | undefined): LocalProject | null {- return store?.mountedProject?.data ?? null;-}--/** Returns the display name from any project store variant. */-export function projectDisplayName(store: ProjectStore | undefined): string | undefined {- return store?.name ?? undefined;-}--export function unmountedMountErrorMessage(store: ProjectStore | undefined): string {- if (store && isUnmountedProject(store) && store.phase === 'error') {- if (store.errorCode === 'path-not-found') {- return `No project found at ${store.error ?? 'the configured path'}`;- }- return store.error ?? 'Failed to open project';- }- return 'Failed to open project';-}--/** Returns the ProjectSettingsStore for a mounted project, or undefined if not ready. */-export function getProjectSettingsStore(projectId: string): ProjectSettingsStore | undefined {- return asMounted(getProjectStore(projectId))?.settings;-}--/** Returns the ProjectViewStore for a mounted project, or undefined if not ready. */-export function getProjectViewStore(projectId: string): ProjectViewStore | undefined {- return asMounted(getProjectStore(projectId))?.view;-}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/projects/stores/project-settings-store.ts b/dash/apps/switchdash-desktop/src/renderer/features/projects/stores/project-settings-store.tsdeleted file mode 100644index 2b9856479..000000000--- a/dash/apps/switchdash-desktop/src/renderer/features/projects/stores/project-settings-store.ts+++ /dev/null@@ -1,121 +0,0 @@-import type { Result } from '@switchdash/shared';-import { events, rpc } from '@renderer/lib/ipc';-import { Resource } from '@renderer/lib/stores/resource';-import { fsWatchEventChannel } from '@shared/core/fs/fsEvents';-import {- PROJECT_CONFIG_FILE,- type MigrateProjectConfigRequest,- type MigrateProjectConfigResult,- type ProjectConfigMigration,- type ProjectSettings,- type ProjectSettingsOverrideState,- type ProjectSettingsPage,- type ProjectSettingsWriteTargetOption,- type WriteProjectConfigRequest,-} from '@shared/core/project-settings/project-settings';-import { projectSettingsChangedChannel } from '@shared/core/projects/projectEvents';-import type { UpdateProjectSettingsError } from '@shared/projects';--export class ProjectSettingsStore {- readonly pageData: Resource<ProjectSettingsPage>;- private readonly _unsubscribeConfigWatch: () => void;- private readonly _unsubscribeSettingsChanged: () => void;-- constructor(private readonly projectId: string) {- this.pageData = new Resource(async () => {- const result = await rpc.projects.getProjectSettingsPage(projectId);- if (!result.success) {- throw new Error(- result.error.type === 'project-not-found'- ? `Project ${projectId} not found`- : 'Failed to load project settings'- );- }- return result.data;- }, [{ kind: 'demand' }]);-- this._unsubscribeConfigWatch = events.on(fsWatchEventChannel, (data) => {- if (data.projectId !== projectId) return;- if (- data.events.some(- (event) => event.path === PROJECT_CONFIG_FILE || event.oldPath === PROJECT_CONFIG_FILE- )- ) {- this.pageData.invalidate();- }- });-- this._unsubscribeSettingsChanged = events.on(projectSettingsChangedChannel, (data) => {- if (data.projectId === projectId) {- this.pageData.invalidate();- }- });- }-- get settings(): ProjectSettings | null {- return this.pageData.data?.settings ?? null;- }-- get defaults(): ProjectSettingsPage['defaults'] | null {- return this.pageData.data?.defaults ?? null;- }-- get writeTargets(): ProjectSettingsWriteTargetOption[] | null {- return this.pageData.data?.writeTargets ?? null;- }-- get overrideState(): ProjectSettingsOverrideState | null {- return this.pageData.data?.overrideState ?? null;- }-- get configMigrations(): ProjectConfigMigration[] | null {- return this.pageData.data?.configMigrations ?? null;- }-- get shouldPromptConfigMigration(): boolean {- return this.pageData.data?.shouldPromptConfigMigration ?? false;- }-- async load(): Promise<ProjectSettingsPage | null> {- await this.pageData.load();- return this.pageData.data;- }-- async save(- settings: ProjectSettings- ): Promise<Result<ProjectSettings, UpdateProjectSettingsError>> {- const result = await rpc.projects.updateProjectSettings(this.projectId, settings);- if (result.success) {- const current = this.pageData.data;- if (current) this.pageData.setValue({ ...current, settings: result.data });- else this.pageData.invalidate();- }- return result;- }-- async writeConfigToRepo(- request: WriteProjectConfigRequest- ): Promise<Result<ProjectSettingsPage, UpdateProjectSettingsError>> {- const result = await rpc.projects.shareProjectSettingsToConfig(this.projectId, request);- if (result.success) {- this.pageData.setValue(result.data);- }- return result;- }-- async migrateProjectConfig(- request: MigrateProjectConfigRequest- ): Promise<Result<MigrateProjectConfigResult, UpdateProjectSettingsError>> {- const result = await rpc.projects.migrateProjectConfig(this.projectId, request);- if (result.success) {- this.pageData.setValue(result.data.page);- }- return result;- }-- dispose(): void {- this._unsubscribeConfigWatch();- this._unsubscribeSettingsChanged();- this.pageData.dispose();- }-}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/projects/stores/project.ts b/dash/apps/switchdash-desktop/src/renderer/features/projects/stores/project.tsdeleted file mode 100644index 6064197c6..000000000--- a/dash/apps/switchdash-desktop/src/renderer/features/projects/stores/project.ts+++ /dev/null@@ -1,187 +0,0 @@-import { makeAutoObservable, observable } from 'mobx';-import { SessionManagerStore } from '@renderer/features/sessions/stores/session-manager';-import { snapshotRegistry } from '@renderer/lib/stores/snapshot-registry';-import type { LocalProject } from '@shared/projects';-import type { ProjectViewSnapshot } from '@shared/view-state';-import { ProjectSettingsStore } from './project-settings-store';-import { ProjectViewStore } from './project-view';--export type UnregisteredProjectPhase =- | 'creating-repo' // gh api — new mode only- | 'cloning' // git clone- | 'registering' // db insert- | 'error';--export type UnmountedProjectPhase = 'opening' | 'error' | 'closing' | 'idle';--export type ProjectMode = 'pick' | 'clone' | 'new';--/**- * Holds all mounted-only state for a project. Created atomically by- * ProjectStore.transitionToMounted and disposed on unmount or deletion.- */-export class MountedProject {- readonly sessionManager: SessionManagerStore;- readonly view: ProjectViewStore;- readonly settings: ProjectSettingsStore;- readonly data: LocalProject;-- private _snapshotDisposer: (() => void) | null = null;-- get snapshot(): ProjectViewSnapshot {- return {- activeView: this.view.activeView,- sessionViewTab: this.view.sessionView.tab,- };- }-- constructor(data: LocalProject, savedSnapshot?: ProjectViewSnapshot) {- this.data = data;- this.view = new ProjectViewStore();- this.settings = new ProjectSettingsStore(data.id);- this.sessionManager = new SessionManagerStore(data.id, this.settings);-- if (savedSnapshot) this.view.restoreSnapshot(savedSnapshot);-- makeAutoObservable(this, {- sessionManager: false,- view: false,- settings: false,- });-- this._snapshotDisposer = snapshotRegistry.register(`project:${data.id}`, () => this.snapshot);- }-- dispose(): void {- this.settings.dispose();- this._snapshotDisposer?.();- this._snapshotDisposer = null;- }-}--/**- * Container class — holds a stable reference in the ObservableMap across all- * lifecycle transitions. Transitioning replaces `mountedProject` atomically- * rather than nulling out individual fields.- */-export class ProjectStore {- state: 'unregistered' | 'unmounted' | 'mounted';- id: string;- name: string | null;- data: LocalProject | null;- createdAt: string;- phase: UnregisteredProjectPhase | UnmountedProjectPhase | null;- error: string | undefined = undefined;- errorCode: 'path-not-found' | 'ssh-disconnected' | undefined = undefined;- mode: ProjectMode | null;- mountedProject: MountedProject | null = null;-- constructor(- state: ProjectStore['state'],- id: string,- name: string | null,- data: LocalProject | null,- phase: UnregisteredProjectPhase | UnmountedProjectPhase | null,- mode: ProjectMode | null = null- ) {- this.state = state;- this.id = id;- this.name = name;- this.data = data;- this.createdAt = data?.createdAt ?? new Date().toISOString();- this.phase = phase;- this.mode = mode;- makeAutoObservable(this, { mountedProject: observable.ref });- }-- transitionToMounted(data: LocalProject, savedSnapshot?: ProjectViewSnapshot): void {- this.mountedProject = new MountedProject(data, savedSnapshot);- this.data = data;- this.id = data.id;- this.name = data.name;- this.createdAt = data.createdAt;- this.state = 'mounted';- this.phase = null;- this.error = undefined;- this.errorCode = undefined;- }-- transitionToUnmounted(data: LocalProject, phase: UnmountedProjectPhase = 'opening'): void {- this.mountedProject?.dispose();- this.mountedProject = null;- this.data = data;- this.id = data.id;- this.name = data.name;- this.createdAt = data.createdAt;- this.state = 'unmounted';- this.phase = phase;- this.error = undefined;- this.errorCode = undefined;- }-- transitionToUnregistered(- id: string,- name: string,- phase: UnregisteredProjectPhase,- mode: ProjectMode- ): void {- this.mountedProject?.dispose();- this.mountedProject = null;- this.data = null;- this.id = id;- this.name = name;- this.state = 'unregistered';- this.phase = phase;- this.mode = mode;- this.error = undefined;- }-}--export type UnregisteredProject = ProjectStore & {- state: 'unregistered';- id: string;- name: string;- phase: UnregisteredProjectPhase;- mode: ProjectMode;- error: string | undefined;-};--export type UnmountedProject = ProjectStore & {- state: 'unmounted';- data: LocalProject;- phase: UnmountedProjectPhase;- error: string | undefined;- errorCode: 'path-not-found' | 'ssh-disconnected' | undefined;-};--export function isUnregisteredProject(p: ProjectStore): p is UnregisteredProject {- return p.state === 'unregistered';-}--export function isUnmountedProject(p: ProjectStore): p is UnmountedProject {- return p.state === 'unmounted';-}--export function isMountedProject(p: ProjectStore): p is ProjectStore & {- state: 'mounted';- mountedProject: MountedProject;- data: LocalProject;-} {- return p.state === 'mounted';-}--export function createUnregisteredProject(- id: string,- name: string,- phase: UnregisteredProjectPhase,- mode: ProjectMode = 'pick'-): ProjectStore {- return new ProjectStore('unregistered', id, name, null, phase, mode);-}--export function createUnmountedProject(- data: LocalProject,- phase: UnmountedProjectPhase = 'opening'-): ProjectStore {- return new ProjectStore('unmounted', data.id, data.name, data, phase);-}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/projects/view.tsx b/dash/apps/switchdash-desktop/src/renderer/features/projects/view.tsxdeleted file mode 100644index 81557bbc2..000000000--- a/dash/apps/switchdash-desktop/src/renderer/features/projects/view.tsx+++ /dev/null@@ -1,22 +0,0 @@-import type { GuardResult } from '@renderer/app/view-registry';-import { ProjectViewWrapper } from '@renderer/features/projects/components/project-view-wrapper';-import { appState } from '@renderer/lib/stores/app-state';-import { ProjectMainPanel } from './components/main-panel/main-panel';-import { ProjectTitlebar } from './components/project-titlebar';--export const projectView = {- WrapView: ProjectViewWrapper,- TitlebarSlot: ProjectTitlebar,- MainPanel: ProjectMainPanel,- canActivate: (params: unknown): GuardResult => {- const projectId =- typeof params === 'object' && params !== null- ? (params as { projectId?: unknown }).projectId- : undefined;- if (typeof projectId !== 'string') return { ok: false, redirect: 'home' };- return appState.projects.projects.has(projectId) ||- appState.projects.pendingCreationIds.has(projectId)- ? { ok: true }- : { ok: false, redirect: 'home' };- },-};diff --git a/dash/apps/switchdash-desktop/src/renderer/features/remote-hosts/gh-auth-panel.tsx b/dash/apps/switchdash-desktop/src/renderer/features/remote-hosts/gh-auth-panel.tsxindex cc4e17af2..98f8e7bc9 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/remote-hosts/gh-auth-panel.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/remote-hosts/gh-auth-panel.tsx@@ -119,7 +119,7 @@ export function GhAuthPanel({ sshHost, onDone }: Props) {ref={paneRef}sessionId={sessionId}pty={pty}- workspaceId=""+ locationId=""className="h-full w-full"/></div>diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/commands.test.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/commands.test.tsindex 80d0b66c1..82f190bd4 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/commands.test.ts+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/commands.test.ts@@ -7,8 +7,8 @@ const mocks = vi.hoisted(() => ({navigate: vi.fn(),setPinned: vi.fn(),visibleSessionEntries: [- { projectId: 'project-1', sessionId: 'session-1' },- { projectId: 'project-1', sessionId: 'session-2' },+ { locationId: 'location-1', sessionId: 'session-1' },+ { locationId: 'location-1', sessionId: 'session-2' },],}));@@ -42,19 +42,19 @@ describe('createSessionCommandProvider', () => {isPinned: false,});mocks.visibleSessionEntries = [- { projectId: 'project-1', sessionId: 'session-1' },- { projectId: 'project-1', sessionId: 'session-2' },+ { locationId: 'location-1', sessionId: 'session-1' },+ { locationId: 'location-1', sessionId: 'session-2' },];});it('returns no commands when the session is not provisioned', () => {mocks.getSessionStore.mockReturnValue({ state: 'unprovisioned' });- const provider = createSessionCommandProvider('project-1', 'session-1');+ const provider = createSessionCommandProvider('location-1', 'session-1');expect(provider.getCommands()).toEqual([]);});it('exposes a pin command that toggles the pinned state', () => {- const provider = createSessionCommandProvider('project-1', 'session-1');+ const provider = createSessionCommandProvider('location-1', 'session-1');const command = provider.getCommands().find((candidate) => candidate.id === 'session.pin');@@ -63,12 +63,12 @@ describe('createSessionCommandProvider', () => {expect(mocks.setPinned).toHaveBeenCalledWith(true);});- it('navigates to the next visible session across project boundaries', () => {+ it('navigates to the next visible session across location boundaries', () => {mocks.visibleSessionEntries = [- { projectId: 'project-1', sessionId: 'session-1' },- { projectId: 'project-2', sessionId: 'session-2' },+ { locationId: 'location-1', sessionId: 'session-1' },+ { locationId: 'location-2', sessionId: 'session-2' },];- const provider = createSessionCommandProvider('project-1', 'session-1');+ const provider = createSessionCommandProvider('location-1', 'session-1');const command = provider.getCommands()@@ -78,17 +78,17 @@ describe('createSessionCommandProvider', () => {command?.execute();expect(mocks.navigate).toHaveBeenCalledWith('session', {- projectId: 'project-2',+ locationId: 'location-2',sessionId: 'session-2',});});- it('navigates to the previous visible session across project boundaries', () => {+ it('navigates to the previous visible session across location boundaries', () => {mocks.visibleSessionEntries = [- { projectId: 'project-1', sessionId: 'session-1' },- { projectId: 'project-2', sessionId: 'session-2' },+ { locationId: 'location-1', sessionId: 'session-1' },+ { locationId: 'location-2', sessionId: 'session-2' },];- const provider = createSessionCommandProvider('project-2', 'session-2');+ const provider = createSessionCommandProvider('location-2', 'session-2');const command = provider.getCommands()@@ -98,7 +98,7 @@ describe('createSessionCommandProvider', () => {command?.execute();expect(mocks.navigate).toHaveBeenCalledWith('session', {- projectId: 'project-1',+ locationId: 'location-1',sessionId: 'session-1',});});diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/commands.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/commands.tsindex a5fed5573..7673f8ada 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/commands.ts+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/commands.ts@@ -16,20 +16,20 @@ function sessionDef(id: SessionCommandId): CommandDef {* sidebar panels, terminal drawer) are gone — only pin and prev/next remain.*/export function createSessionCommandProvider(- projectId: string,+ locationId: string,sessionId: string): CommandProvider {return {scopeId: 'session',getCommands() {- const sessionStore = getSessionStore(projectId, sessionId);+ const sessionStore = getSessionStore(locationId, sessionId);if (sessionStore?.state !== 'provisioned') return [];- const sessionData = getRegisteredSessionData(projectId, sessionId);+ const sessionData = getRegisteredSessionData(locationId, sessionId);const visibleSessionEntries = sidebarStore.visibleSessionEntries;const currentIdx = visibleSessionEntries.findIndex(- (entry) => entry.projectId === projectId && entry.sessionId === sessionId+ (entry) => entry.locationId === locationId && entry.sessionId === sessionId);const pinDef = sessionDef('session.pin');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 f5fdfdd8b..466394c59 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@@ -2,7 +2,7 @@ import { useQuery } from '@tanstack/react-query';import { ChevronDown } from 'lucide-react';import { observer } from 'mobx-react-lite';import { useEffect, useMemo, useState } from 'react';-import { getProjectManagerStore } from '@renderer/features/projects/stores/project-selectors';+import { getLocationManagerStore } from '@renderer/features/locations/stores/location-selectors';import { useAgentAutoApproveDefaults } from '@renderer/features/sessions/hooks/useAgentAutoApproveDefaults';import { getSessionManagerStore } from '@renderer/features/sessions/stores/session-selectors';import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';@@ -43,26 +43,26 @@ import { buildConnectPrompt } from './build-connect-prompt';// In switchdash a "session" is a *session*: a `claude` process spawned in the agent's// own directory. The directory is fixed (the agent), the provider is fixed (claude),-// and there is no git worktree — sessions run in the agent's project root. So the+// and there is no git worktree — sessions run in the agent's location root. So the// spawn dialog only asks for an optional name, an optional initial prompt, and an// optional Switch room (and role in it) to connect to on start.const SESSION_PROVIDER = 'claude' as const;const NO_ROLE = '__none__';-function useDefaultProjectId(propProjectId?: string): string | undefined {+function useDefaultLocationId(propLocationId?: string): string | undefined {return useMemo(() => {- if (propProjectId) return propProjectId;+ if (propLocationId) return propLocationId;const nav = appState.navigation;- const navProjectId =+ const navLocationId =nav.currentViewId === 'session'- ? (nav.viewParamsStore['session'] as { projectId?: string } | undefined)?.projectId- : nav.currentViewId === 'project'- ? (nav.viewParamsStore['project'] as { projectId?: string } | undefined)?.projectId+ ? (nav.viewParamsStore['session'] as { locationId?: string } | undefined)?.locationId+ : nav.currentViewId === 'location'+ ? (nav.viewParamsStore['location'] as { locationId?: string } | undefined)?.locationId: undefined;return (- navProjectId ??- Array.from(getProjectManagerStore().projects.values())+ navLocationId ??+ Array.from(getLocationManagerStore().locations.values()).reverse().find((p) => p.state === 'mounted')?.data?.id);@@ -71,18 +71,18 @@ function useDefaultProjectId(propProjectId?: string): string | undefined {}export const CreateSessionModal = observer(function CreateSessionModal({- projectId,+ locationId,subagentName,onClose,}: BaseModalProps & {- projectId?: string;+ locationId?: string;/** When set, start the session as this Claude Code subagent of the agent. */subagentName?: string;// Accepted for source compatibility with switchdash callers; ignored in switchdash v0.strategy?: string;initialPR?: unknown;}) {- const selectedProjectId = useDefaultProjectId(projectId);+ const selectedLocationId = useDefaultLocationId(locationId);const autoApproveDefaults = useAgentAutoApproveDefaults();const { navigate } = useNavigate();@@ -91,15 +91,15 @@ export const CreateSessionModal = observer(function CreateSessionModal({const [room, setRoom] = useState<RemoteAgentRoom | null>(null);const [roleName, setRoleName] = useState<string>(NO_ROLE);- // A session belongs to an agent; resolve the project's agent up front so we+ // A session belongs to an agent; resolve the location's agent up front so we// can offer the rooms it belongs to.const agentQuery = useQuery({- queryKey: ['projectAgent', selectedProjectId],+ queryKey: ['locationAgent', selectedLocationId],queryFn: async () => {- const agents = await rpc.agents.getAgents(selectedProjectId);+ const agents = await rpc.agents.getAgents(selectedLocationId);return agents[0] ?? null;},- enabled: !!selectedProjectId,+ enabled: !!selectedLocationId,});const agent = agentQuery.data ?? null;@@ -144,11 +144,11 @@ export const CreateSessionModal = observer(function CreateSessionModal({});const roles = rolesQuery.data ?? [];- const canCreate = !!selectedProjectId;+ const canCreate = !!selectedLocationId;const handleSpawn = () => {- if (!selectedProjectId) return;- const sessionManager = getSessionManagerStore(selectedProjectId);+ if (!selectedLocationId) return;+ const sessionManager = getSessionManagerStore(selectedLocationId);if (!sessionManager) return;const id = crypto.randomUUID();@@ -157,9 +157,9 @@ export const CreateSessionModal = observer(function CreateSessionModal({const initialPrompt = buildConnectPrompt(room?.roomName ?? null, chosenRole, prompt);void (async () => {- const resolvedAgent = agent ?? (await rpc.agents.getAgents(selectedProjectId))[0];+ const resolvedAgent = agent ?? (await rpc.agents.getAgents(selectedLocationId))[0];if (!resolvedAgent) {- log.error('spawn session failed: project has no agents', selectedProjectId);+ log.error('spawn session failed: location has no agents', selectedLocationId);return;}// createSession registers the session synchronously (before its first@@ -173,7 +173,7 @@ export const CreateSessionModal = observer(function CreateSessionModal({initialPrompt,subagentName: subagentName || undefined,});- navigate('session', { projectId: selectedProjectId, sessionId: id });+ navigate('session', { locationId: selectedLocationId, sessionId: id });onClose();await created;})().catch((e) => log.error('spawn session failed', e));diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/delete-session-modal.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sessions/delete-session-modal.tsxindex 22a577420..6cfcf1267 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/delete-session-modal.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/delete-session-modal.tsx@@ -9,7 +9,7 @@ import {} from '@renderer/lib/ui/dialog';export type DeleteSessionModalArgs = {- projectId: string;+ locationId: string;sessions: Array<{ sessionId: string; sessionName: string }>;};diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/main-panel.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sessions/main-panel.tsxindex 4d1e2331c..e4fa3f32f 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/main-panel.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/main-panel.tsx@@ -9,9 +9,9 @@ import {import { SessionTerminal } from './session-terminal';export const SessionMainPanel = observer(function SessionMainPanel() {- const { projectId, sessionId } = useSessionViewContext();- const sessionStore = getSessionStore(projectId, sessionId);- const kind = sessionViewKind(sessionStore, projectId);+ const { locationId, sessionId } = useSessionViewContext();+ const sessionStore = getSessionStore(locationId, sessionId);+ const kind = sessionViewKind(sessionStore, locationId);if (kind === 'creating') {return (@@ -37,8 +37,8 @@ export const SessionMainPanel = observer(function SessionMainPanel() {);}- if (kind === 'project-mounting' || kind === 'provisioning') {- const progressMessage = sessionStore?.provisionProgressMessage ?? 'Setting up workspace…';+ if (kind === 'location-mounting' || kind === 'provisioning') {+ const progressMessage = sessionStore?.provisionProgressMessage ?? 'Setting up session…';return (<div className="flex h-full w-full flex-col items-center justify-center gap-3"><Loader2 className="h-5 w-5 animate-spin text-foreground-muted" />@@ -47,12 +47,12 @@ export const SessionMainPanel = observer(function SessionMainPanel() {);}- if (kind === 'provision-error' || kind === 'project-error') {+ if (kind === 'provision-error' || kind === 'location-error') {return (<div className="flex h-full w-full flex-col items-center justify-center p-8"><div className="flex max-w-xs flex-col items-center gap-2 text-center"><p className="font-mono text-sm font-medium text-foreground-destructive">- Failed to set up workspace+ Failed to set up session</p><p className="font-mono text-xs text-foreground-muted">{sessionErrorMessage(sessionStore)}@@ -63,7 +63,7 @@ export const SessionMainPanel = observer(function SessionMainPanel() {}if (kind === 'idle' || kind === 'teardown') {- const progressMessage = sessionStore?.provisionProgressMessage ?? 'Setting up workspace…';+ const progressMessage = sessionStore?.provisionProgressMessage ?? 'Setting up session…';return (<div className="flex h-full w-full flex-col items-center justify-center gap-3"><Loader2 className="h-5 w-5 animate-spin text-foreground-muted" />@@ -77,7 +77,7 @@ export const SessionMainPanel = observer(function SessionMainPanel() {<div className="flex h-full w-full flex-col items-center justify-center p-8"><div className="flex max-w-xs flex-col items-center gap-2 text-center"><p className="font-mono text-sm font-medium text-foreground-destructive">- Failed to tear down workspace+ Failed to tear down session</p><p className="font-mono text-xs text-foreground-muted">{sessionErrorMessage(sessionStore)}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/rename-session-modal.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sessions/rename-session-modal.tsxindex 86269a195..5a80b12e6 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/rename-session-modal.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/rename-session-modal.tsx@@ -21,7 +21,7 @@ import {} from '@renderer/utils/sessionNames';type RenameSessionModalArgs = {- projectId: string;+ locationId: string;sessionId: string;currentName: string;};@@ -29,7 +29,7 @@ type RenameSessionModalArgs = {type Props = BaseModalProps<void> & RenameSessionModalArgs;export const RenameSessionModal = observer(function RenameSessionModal({- projectId,+ locationId,sessionId,currentName,onSuccess,@@ -40,7 +40,7 @@ export const RenameSessionModal = observer(function RenameSessionModal({const [error, setError] = useState<string | null>(null);const { preserveNameCapitalization } = useSessionSettings();- const sessionManager = getSessionManagerStore(projectId);+ const sessionManager = getSessionManagerStore(locationId);const siblingNames = new Set(Array.from(sessionManager?.sessions.values() ?? []).filter((t) => t.state !== 'unregistered' && t.data.id !== sessionId)@@ -56,7 +56,7 @@ export const RenameSessionModal = observer(function RenameSessionModal({const isValid = !isEmpty && !isDuplicate && !isUnchanged;const validationMessage = isDuplicate- ? 'A session with this name already exists in this project.'+ ? 'A session with this name already exists in this location.': isEmpty? 'Session name cannot be empty.': undefined;diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/session-terminal.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sessions/session-terminal.tsxindex 0fd3fe35f..7f8e3ea8f 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/session-terminal.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/session-terminal.tsx@@ -5,8 +5,8 @@ import { useIsActiveSession } from '@renderer/features/sessions/hooks/use-is-actimport {useSessionAgent,useSessionViewContext,- useWorkspaceId,- useWorkspaceViewModel,+ useSessionLocationId,+ useSessionViewModel,} from '@renderer/features/sessions/session-view-context';import { PaneSizingProvider } from '@renderer/lib/pty/pane-sizing-context';import { PtyPane } from '@renderer/lib/pty/pty-pane';@@ -20,9 +20,9 @@ import { useTerminalSearch } from '@renderer/lib/pty/use-terminal-search';*/export const SessionTerminal = observer(function SessionTerminal() {const { sessionId } = useSessionViewContext();- const sessionView = useWorkspaceViewModel();+ const sessionView = useSessionViewModel();const agentStore = useSessionAgent();- const workspaceId = useWorkspaceId();+ const locationId = useSessionLocationId();const isActive = useIsActiveSession(sessionId);const autoFocus = isActive && sessionView.focusedRegion === 'main';@@ -104,7 +104,7 @@ export const SessionTerminal = observer(function SessionTerminal() {className="h-full w-full"onInterruptPress={onInterruptPress}mapShiftEnterToCtrlJ- workspaceId={workspaceId}+ locationId={locationId}/></div>) : (diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/session-titlebar.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sessions/session-titlebar.tsxindex 697ea5c7f..05fb20ec5 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/session-titlebar.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/session-titlebar.tsx@@ -1,9 +1,9 @@import { Pin } from 'lucide-react';import { observer } from 'mobx-react-lite';import {- getProjectStore,- projectDisplayName,-} from '@renderer/features/projects/stores/project-selectors';+ getLocationStore,+ locationDisplayName,+} from '@renderer/features/locations/stores/location-selectors';import { useSessionViewContext } from '@renderer/features/sessions/session-view-context';import {getRegisteredSessionData,@@ -17,10 +17,10 @@ import { cn } from '@renderer/utils/utils';// switchdash titlebar: agent / session breadcrumb plus a pin toggle. The switchdash// git, issue, diff, preview, terminal-drawer and sidebar chrome is gone.export const SessionTitlebar = observer(function SessionTitlebar() {- const { projectId, sessionId } = useSessionViewContext();- const sessionStore = getSessionStore(projectId, sessionId);- const sessionPayload = getRegisteredSessionData(projectId, sessionId);- const projectName = projectDisplayName(getProjectStore(projectId));+ const { locationId, sessionId } = useSessionViewContext();+ const sessionStore = getSessionStore(locationId, sessionId);+ const sessionPayload = getRegisteredSessionData(locationId, sessionId);+ const locationName = locationDisplayName(getLocationStore(locationId));const { navigate } = useNavigate();return (@@ -30,9 +30,9 @@ export const SessionTitlebar = observer(function SessionTitlebar() {<buttontype="button"className="text-sm text-foreground-passive hover:text-foreground"- onClick={() => navigate('project', { projectId })}+ onClick={() => navigate('location', { locationId })}>- {projectName}+ {locationName}</button><span className="text-sm text-foreground-passive">/</span><span className="max-w-56 truncate">{sessionDisplayName(sessionStore)}</span>diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/session-view-context.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sessions/session-view-context.tsxindex 768b2f91e..4721db36c 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/session-view-context.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/session-view-context.tsx@@ -1,42 +1,39 @@import { observer } from 'mobx-react-lite';import { createContext, useContext, type ReactNode } from 'react';-import { ProjectViewWrapper } from '@renderer/features/projects/components/project-view-wrapper';+import { LocationViewWrapper } from '@renderer/features/locations/components/location-view-wrapper';import type { SessionAgentStore } from '@renderer/features/sessions/stores/session-agent-store';+import type { SessionRuntimeStore } from '@renderer/features/sessions/stores/session-runtime-store';import {getSessionAgent,getSessionStore,- getWorkspaceForSession,+ getSessionRuntime,sessionViewKind,type SessionViewKind,} from '@renderer/features/sessions/stores/session-selectors';-import type { WorkspaceStore } from '@renderer/features/sessions/stores/workspace';-import type { WorkspaceViewModel } from '@renderer/features/sessions/stores/workspace-view-model';+import type { SessionViewModel } from '@renderer/features/sessions/stores/session-view-model';interface SessionViewContext {- projectId: string;+ locationId: string;sessionId: string;- /** The workspace ID for this session, or null when not yet registered. */- workspaceId: string | null;}const SessionViewContext = createContext<SessionViewContext | null>(null);export const SessionViewWrapper = observer(function SessionViewWrapper({children,- projectId,+ locationId,sessionId,}: {children: ReactNode;- projectId: string;+ locationId: string;sessionId: string;}) {- const workspaceId = getSessionStore(projectId, sessionId)?.workspaceId ?? null;return (- <ProjectViewWrapper projectId={projectId}>- <SessionViewContext.Provider value={{ projectId, sessionId, workspaceId }}>+ <LocationViewWrapper locationId={locationId}>+ <SessionViewContext.Provider value={{ locationId, sessionId }}>{children}</SessionViewContext.Provider>- </ProjectViewWrapper>+ </LocationViewWrapper>);});@@ -49,33 +46,32 @@ export function useSessionViewContext(): SessionViewContext {}export function useSessionViewKind(): SessionViewKind {- const { projectId, sessionId } = useSessionViewContext();- return sessionViewKind(getSessionStore(projectId, sessionId), projectId);+ const { locationId, sessionId } = useSessionViewContext();+ return sessionViewKind(getSessionStore(locationId, sessionId), locationId);}-/** Returns the active WorkspaceStore. Throws if the session is not provisioned. */-export function useWorkspace(): WorkspaceStore {- const { projectId, sessionId } = useSessionViewContext();- const workspace = getWorkspaceForSession(projectId, sessionId);- if (!workspace) {- throw new Error('useWorkspace: session is not provisioned (no workspace)');+/** Returns the active SessionRuntimeStore. Throws if the session is not provisioned. */+export function useSessionRuntime(): SessionRuntimeStore {+ const { locationId, sessionId } = useSessionViewContext();+ const runtime = getSessionRuntime(locationId, sessionId);+ if (!runtime) {+ throw new Error('useSessionRuntime: session is not provisioned (no runtime)');}- return workspace;+ return runtime;}-/** Returns the workspace ID. Throws if the session has no workspace yet. */-export function useWorkspaceId(): string {- const { workspaceId } = useSessionViewContext();- if (!workspaceId) throw new Error('useWorkspaceId: session has no workspace');- return workspaceId;+/** Returns the location id for the active session. */+export function useSessionLocationId(): string {+ const { locationId } = useSessionViewContext();+ return locationId;}-/** Returns the WorkspaceViewModel. Throws if the session is not registered. */-export function useWorkspaceViewModel(): WorkspaceViewModel {- const { projectId, sessionId } = useSessionViewContext();- const viewModel = getSessionStore(projectId, sessionId)?.viewModel;+/** Returns the SessionViewModel. Throws if the session is not registered. */+export function useSessionViewModel(): SessionViewModel {+ const { locationId, sessionId } = useSessionViewContext();+ const viewModel = getSessionStore(locationId, sessionId)?.viewModel;if (!viewModel) {- throw new Error('useWorkspaceViewModel: session is not registered (no view model)');+ throw new Error('useSessionViewModel: session is not registered (no view model)');}return viewModel;}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/file-link-handlers.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/file-link-handlers.tsindex 8c0afa9fd..daa2762dc 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/file-link-handlers.ts+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/file-link-handlers.ts@@ -7,7 +7,7 @@ import { confirmOpenExternalLink } from '@renderer/lib/open-external-link';* `open-file-in-file-editor` handlers.)*/export function makeFileLinkHandlers(- _projectId: string,+ _locationId: string,_sessionId: string): { onOpenFile: (filePath: string) => void; onOpenExternal: (filePath: string) => void } {return {diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/lifecycle-scripts.test.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/lifecycle-scripts.test.tsindex db26ec176..e874941a3 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/lifecycle-scripts.test.ts+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/lifecycle-scripts.test.ts@@ -1,6 +1,6 @@import { beforeEach, describe, expect, it, vi } from 'vitest';import { fsWatchEventChannel } from '@shared/core/fs/fsEvents';-import { projectSettingsChangedChannel } from '@shared/core/projects/projectEvents';+import { locationSettingsChangedChannel } from '@shared/core/locations/locationEvents';import { lifecycleScriptStatusChannel } from '@shared/core/sessions/sessionEvents';import { createLifecycleScriptTerminalId } from '@shared/core/terminals/terminals';import { LifecycleScriptsStore, LifecycleScriptStore } from './lifecycle-scripts';@@ -19,11 +19,11 @@ vi.mock('@renderer/lib/ipc', () => ({}),},rpc: {- projectSettings: {+ locationRuntimeSettings: {getSettings,},- workspace: {- fs: {+ fs: {+ watch: {watchSetPaths,watchStop,},@@ -56,16 +56,14 @@ describe('LifecycleScriptStore', () => {it('tracks script running state from lifecycle status events', () => {const store = new LifecycleScriptStore({ id: 'script-id', type: 'run', label: 'Run', command: 'pnpm dev' },- 'project-1',- 'branch:feature'+ 'loc-1');expect(store.isRunning).toBe(false);eventHandlers.get(`${lifecycleScriptStatusChannel.name}.`)?.({- projectId: 'project-1',+ locationId: 'loc-1',sessionId: 'session-1',- workspaceId: 'branch:feature',type: 'run',origin: 'manual',status: 'running',@@ -75,9 +73,8 @@ describe('LifecycleScriptStore', () => {expect(store.status).toBe('running');eventHandlers.get(`${lifecycleScriptStatusChannel.name}.`)?.({- projectId: 'project-1',+ locationId: 'loc-1',sessionId: 'session-1',- workspaceId: 'branch:feature',type: 'run',origin: 'manual',status: 'succeeded',@@ -91,8 +88,7 @@ describe('LifecycleScriptStore', () => {it('unsubscribes from lifecycle status events on dispose', () => {const store = new LifecycleScriptStore({ id: 'script-id', type: 'run', label: 'Run', command: 'pnpm dev' },- 'project-1',- 'branch:feature'+ 'loc-1');store.dispose();@@ -114,23 +110,17 @@ describe('LifecycleScriptsStore', () => {getSettings.mockResolvedValueOnce({ scripts: { run: 'pnpm dev' } }).mockResolvedValueOnce({ scripts: { run: 'pnpm start' } });- const store = new LifecycleScriptsStore('project-1', 'workspace-1');+ const store = new LifecycleScriptsStore('loc-1');await (store as unknown as { load(): Promise<void> }).load();- expect(watchSetPaths).toHaveBeenCalledWith(- 'project-1',- 'workspace-1',- [''],- 'lifecycle-scripts'- );+ expect(watchSetPaths).toHaveBeenCalledWith('loc-1', [''], 'lifecycle-scripts');expect(store.tabs).toHaveLength(1);expect(store.tabs[0].data.id).toBe(createLifecycleScriptTerminalId('run'));expect(store.tabs[0].data.command).toBe('pnpm dev');eventHandlers.get(`${fsWatchEventChannel.name}.`)?.({- projectId: 'project-1',- workspaceId: 'workspace-1',+ locationId: 'loc-1',events: [{ type: 'modify', entryType: 'file', path: '.switchdash.json' }],});@@ -138,18 +128,18 @@ describe('LifecycleScriptsStore', () => {expect(store.tabs[0].data.id).toBe(createLifecycleScriptTerminalId('run'));store.dispose();- expect(watchStop).toHaveBeenCalledWith('project-1', 'workspace-1', 'lifecycle-scripts');+ expect(watchStop).toHaveBeenCalledWith('loc-1', 'lifecycle-scripts');});- it('reloads lifecycle scripts when project settings change', async () => {+ it('reloads lifecycle scripts when location settings change', async () => {getSettings.mockResolvedValueOnce({ scripts: { setup: 'pnpm install' } }).mockResolvedValueOnce({ scripts: { setup: 'corepack install', run: 'pnpm dev' } });- const store = new LifecycleScriptsStore('project-1', 'workspace-1');+ const store = new LifecycleScriptsStore('loc-1');await (store as unknown as { load(): Promise<void> }).load();- eventHandlers.get(`${projectSettingsChangedChannel.name}.`)?.({ projectId: 'project-1' });+ eventHandlers.get(`${locationSettingsChangedChannel.name}.`)?.({ locationId: 'loc-1' });await expect.poll(() => store.tabs.map((tab) => tab.data.command))@@ -163,7 +153,7 @@ describe('LifecycleScriptsStore', () => {resolveSettings = resolve;}));- const store = new LifecycleScriptsStore('project-1', 'workspace-1');+ const store = new LifecycleScriptsStore('loc-1');const loadPromise = (store as unknown as { load(): Promise<void> }).load();store.dispose();@@ -171,6 +161,6 @@ describe('LifecycleScriptsStore', () => {await loadPromise;expect(store.tabs).toEqual([]);- expect(watchStop).toHaveBeenCalledWith('project-1', 'workspace-1', 'lifecycle-scripts');+ expect(watchStop).toHaveBeenCalledWith('loc-1', 'lifecycle-scripts');});});diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/lifecycle-scripts.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/lifecycle-scripts.tsindex 1a6976446..3dcbbc0bb 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/lifecycle-scripts.ts+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/lifecycle-scripts.ts@@ -10,8 +10,8 @@ import {setTabActiveIndex,} from '@renderer/lib/stores/tab-utils';import { fsWatchEventChannel } from '@shared/core/fs/fsEvents';-import { PROJECT_CONFIG_FILE } from '@shared/core/project-settings/project-settings';-import { projectSettingsChangedChannel } from '@shared/core/projects/projectEvents';+import { LOCATION_CONFIG_FILE } from '@shared/core/location-settings/location-settings';+import { locationSettingsChangedChannel } from '@shared/core/locations/locationEvents';import { makePtySessionId } from '@shared/core/pty/ptySessionId';import {lifecycleScriptStatusChannel,@@ -36,20 +36,16 @@ export class LifecycleScriptStore {status: LifecycleScriptStatus = 'idle';private offStatus: (() => void) | null = null;- constructor(data: LifecycleScriptData, projectId: string, workspaceId: string) {+ constructor(data: LifecycleScriptData, locationId: string) {this.data = data;this.session = new PtySession(- makePtySessionId(projectId, workspaceId, data.id),+ makePtySessionId(locationId, locationId, data.id),undefined,undefined,undefined);this.offStatus = events.on(lifecycleScriptStatusChannel, (event) => {- if (- event.projectId !== projectId ||- event.workspaceId !== workspaceId ||- event.type !== this.data.type- ) {+ if (event.locationId !== locationId || event.type !== this.data.type) {return;}this.setStatus(event.status);@@ -79,8 +75,7 @@ export class LifecycleScriptStore {}export class LifecycleScriptsStore implements TabViewProvider<LifecycleScriptStore, never> {- private readonly projectId: string;- private readonly workspaceId: string;+ private readonly locationId: string;private _loaded = false;private _disposed = false;private _watchingConfig = false;@@ -90,9 +85,8 @@ export class LifecycleScriptsStore implements TabViewProvider<LifecycleScriptStotabOrder: string[] = [];activeTabId: string | undefined = undefined;- constructor(projectId: string, workspaceId: string) {- this.projectId = projectId;- this.workspaceId = workspaceId;+ constructor(locationId: string) {+ this.locationId = locationId;makeObservable(this, {scripts: observable,tabOrder: observable,@@ -110,17 +104,17 @@ export class LifecycleScriptsStore implements TabViewProvider<LifecycleScriptSto});this._unsubscribes.push(events.on(fsWatchEventChannel, (data) => {- if (data.projectId !== this.projectId || data.workspaceId !== this.workspaceId) return;+ if (data.locationId !== this.locationId) return;if (data.events.some(- (event) => event.path === PROJECT_CONFIG_FILE || event.oldPath === PROJECT_CONFIG_FILE+ (event) => event.path === LOCATION_CONFIG_FILE || event.oldPath === LOCATION_CONFIG_FILE)) {this.reloadIfLoaded();}}),- events.on(projectSettingsChangedChannel, ({ projectId }) => {- if (projectId === this.projectId) this.reloadIfLoaded();+ events.on(locationSettingsChangedChannel, ({ locationId }) => {+ if (locationId === this.locationId) this.reloadIfLoaded();}));}@@ -183,14 +177,9 @@ export class LifecycleScriptsStore implements TabViewProvider<LifecycleScriptStoprivate async watchConfig(): Promise<void> {if (this._watchingConfig || this._disposed) return;try {- await rpc.workspace.fs.watchSetPaths(- this.projectId,- this.workspaceId,- [''],- 'lifecycle-scripts'- );+ await rpc.fs.watch.watchSetPaths(this.locationId, [''], 'lifecycle-scripts');if (this._disposed) {- void rpc.workspace.fs.watchStop(this.projectId, this.workspaceId, 'lifecycle-scripts');+ void rpc.fs.watch.watchStop(this.locationId, 'lifecycle-scripts');return;}this._watchingConfig = true;@@ -202,7 +191,7 @@ export class LifecycleScriptsStore implements TabViewProvider<LifecycleScriptStoprivate async reload(): Promise<void> {if (this._disposed) return;const refreshSeq = ++this._refreshSeq;- const settings = await rpc.projectSettings.getSettings(this.workspaceId);+ const settings = await rpc.locationRuntimeSettings.getSettings(this.locationId);if (this._disposed) return;const entries: { type: ScriptType; command: string; label: string }[] = [];@@ -239,7 +228,7 @@ export class LifecycleScriptsStore implements TabViewProvider<LifecycleScriptStoif (existing) {Object.assign(existing.data, data);} else {- const store = new LifecycleScriptStore(data, this.projectId, this.workspaceId);+ const store = new LifecycleScriptStore(data, this.locationId);this.scripts.set(entry.id, store);addTabId(this, entry.id);}@@ -260,7 +249,7 @@ export class LifecycleScriptsStore implements TabViewProvider<LifecycleScriptStothis._refreshSeq++;for (const unsubscribe of this._unsubscribes) unsubscribe();if (this._watchingConfig) {- void rpc.workspace.fs.watchStop(this.projectId, this.workspaceId, 'lifecycle-scripts');+ void rpc.fs.watch.watchStop(this.locationId, 'lifecycle-scripts');}for (const script of this.scripts.values()) {script.dispose();diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-agent-registry.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-agent-registry.tsindex f5805c2f4..236dc5669 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-agent-registry.ts+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-agent-registry.ts@@ -4,10 +4,10 @@ import type { Session } from '@shared/core/sessions/sessions';export class SessionAgentRegistry {private readonly entries = new Map<string, SessionAgentStore>();- acquire(sessionId: string, projectId: string, preloaded?: Session[]): SessionAgentStore {+ acquire(sessionId: string, locationId: string, preloaded?: Session[]): SessionAgentStore {const existing = this.entries.get(sessionId);if (existing) return existing;- const store = new SessionAgentStore(projectId, sessionId, preloaded);+ const store = new SessionAgentStore(locationId, sessionId, preloaded);this.entries.set(sessionId, store);return store;}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-agent-store.test.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-agent-store.test.tsindex 63c6e1c9e..09901659f 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-agent-store.test.ts+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-agent-store.test.ts@@ -62,7 +62,7 @@ describe('SessionAgentStore hydration', () => {};it('does not hydrate the session from the PTY session connect path', async () => {- const store = new SessionAgentStore('project-1', 'session-1', [sessionRecord]);+ const store = new SessionAgentStore('location-1', 'session-1', [sessionRecord]);const session = store.pty;expect(session).toBeDefined();@@ -76,7 +76,7 @@ describe('SessionAgentStore hydration', () => {});it('hydrates when desired and dehydrates when released', async () => {- const store = new SessionAgentStore('project-1', 'session-1', [sessionRecord]);+ const store = new SessionAgentStore('location-1', 'session-1', [sessionRecord]);store.setHydrationDesired(true);await vi.waitFor(() => expect(hydrateSession).toHaveBeenCalledTimes(1));@@ -95,7 +95,7 @@ describe('SessionAgentStore hydration', () => {resolveHydrate = resolve;}));- const store = new SessionAgentStore('project-1', 'session-1', [sessionRecord]);+ const store = new SessionAgentStore('location-1', 'session-1', [sessionRecord]);store.setHydrationDesired(true);await vi.waitFor(() => expect(hydrateSession).toHaveBeenCalledTimes(1));diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-agent-store.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-agent-store.tsindex e6e5a8b59..4948b23ff 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-agent-store.ts+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-agent-store.ts@@ -49,7 +49,7 @@ export class SessionAgentStore implements IDisposable {private hydrationDisposed = false;constructor(- private readonly projectId: string,+ private readonly locationId: string,private readonly sessionId: string,preloaded?: Session[]) {@@ -97,9 +97,9 @@ export class SessionAgentStore implements IDisposable {this.agent = new AgentStatusStore(session);}if (!this.pty) {- const handlers = makeFileLinkHandlers(this.projectId, this.sessionId);+ const handlers = makeFileLinkHandlers(this.locationId, this.sessionId);this.pty = new PtySession(- makeAgentPtySessionId(this.projectId, this.sessionId),+ makeAgentPtySessionId(this.locationId, this.sessionId),undefined,handlers.onOpenFile,handlers.onOpenExternal,@@ -159,7 +159,7 @@ export class SessionAgentStore implements IDisposable {runInAction(() => {if (!this.agent) {log.warn(`SessionAgentStore: session ${this.sessionId} not found after load`, {- projectId: this.projectId,+ locationId: this.locationId,});return;}@@ -190,7 +190,7 @@ export class SessionAgentStore implements IDisposable {private async hydrate(): Promise<void> {this.hydrationState = 'starting';try {- await rpc.sessions.hydrateSession(this.projectId, this.sessionId);+ await rpc.sessions.hydrateSession(this.sessionId);} catch (error) {this.hydrationState = 'stopped';log.warn('SessionAgentStore: failed to hydrate session', {@@ -210,7 +210,7 @@ export class SessionAgentStore implements IDisposable {this.hydrationState = 'stopping';this.pty?.dispose();try {- await rpc.sessions.dehydrateSession(this.projectId, this.sessionId);+ await rpc.sessions.dehydrateSession(this.sessionId);} catch (error) {this.hydrationState = 'running';log.warn(diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-manager.test.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-manager.test.tsindex 81651e49e..d6f27093f 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-manager.test.ts+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-manager.test.ts@@ -14,18 +14,17 @@ const mocks = vi.hoisted(() => ({archiveSession: vi.fn(),agentAcquire: vi.fn(),agentRelease: vi.fn(),- getProjectManagerStore: vi.fn(),+ getLocationManagerStore: vi.fn(),getSessionGitWorktreeStore: vi.fn(),getSessions: vi.fn(),- mountProject: vi.fn(),- provisionWorkspace: vi.fn(),+ mountLocation: vi.fn(),+ provisionSession: vi.fn(),teardownSession: vi.fn(),viewModels: [] as MockViewModel[],viewStateGet: vi.fn(),- workspaceActivate: vi.fn(),- workspaceAcquire: vi.fn(),- workspaceRelease: vi.fn(),- workspaceSetBootstrapState: vi.fn(),+ runtimeActivate: vi.fn(),+ runtimeAcquire: vi.fn(),+ runtimeRelease: vi.fn(),}));vi.mock('@renderer/lib/ipc', () => ({@@ -39,14 +38,14 @@ vi.mock('@renderer/lib/ipc', () => ({sessions: {archiveSession: mocks.archiveSession,getSessions: mocks.getSessions,- provisionWorkspace: mocks.provisionWorkspace,+ provisionSession: mocks.provisionSession,teardownSession: mocks.teardownSession,},},}));-vi.mock('@renderer/features/projects/stores/project-selectors', () => ({- getProjectManagerStore: mocks.getProjectManagerStore,+vi.mock('@renderer/features/locations/stores/location-selectors', () => ({+ getLocationManagerStore: mocks.getLocationManagerStore,}));vi.mock('@renderer/features/sessions/stores/session-selectors', () => ({@@ -65,8 +64,8 @@ vi.mock('sonner', () => ({},}));-vi.mock('./workspace-view-model', () => ({- WorkspaceViewModel: class {+vi.mock('./session-view-model', () => ({+ SessionViewModel: class {initialize = vi.fn();suspend = vi.fn();dispose = vi.fn();@@ -78,12 +77,11 @@ vi.mock('./workspace-view-model', () => ({},}));-vi.mock('./workspace-registry', () => ({- workspaceRegistry: {- activate: mocks.workspaceActivate,- acquire: mocks.workspaceAcquire,- release: mocks.workspaceRelease,- setBootstrapState: mocks.workspaceSetBootstrapState,+vi.mock('./session-runtime-registry', () => ({+ sessionRuntimeRegistry: {+ activate: mocks.runtimeActivate,+ acquire: mocks.runtimeAcquire,+ release: mocks.runtimeRelease,},}));@@ -114,7 +112,7 @@ function makeSession(overrides: Partial<Session> = {}): Session {}function makeSessionManager(): SessionManagerStore {- return new SessionManagerStore('project-1', { pageData: { invalidate: vi.fn() } } as never);+ return new SessionManagerStore('location-1', { pageData: { invalidate: vi.fn() } } as never);}describe('SessionManagerStore archive lifecycle', () => {@@ -122,14 +120,14 @@ describe('SessionManagerStore archive lifecycle', () => {vi.clearAllMocks();mocks.viewModels.length = 0;mocks.archiveSession.mockResolvedValue(undefined);- mocks.getProjectManagerStore.mockReturnValue({ mountProject: mocks.mountProject });+ mocks.getLocationManagerStore.mockReturnValue({ mountLocation: mocks.mountLocation });mocks.getSessions.mockResolvedValue([]);- mocks.mountProject.mockResolvedValue(undefined);- mocks.provisionWorkspace.mockResolvedValue({+ mocks.mountLocation.mockResolvedValue(undefined);+ mocks.provisionSession.mockResolvedValue({success: true,data: {- path: '/tmp/workspace-1',- workspaceId: 'workspace-1',+ path: '/tmp/location-1',+ locationId: 'location-1',},});mocks.viewStateGet.mockResolvedValue(undefined);@@ -138,20 +136,19 @@ describe('SessionManagerStore archive lifecycle', () => {it('archives by disposing frontend runtime instead of soft-tearing down the session', async () => {const manager = makeSessionManager();const session = makeSession();- const store = createUnprovisionedSession('project-1', session);- store.transitionToProvisioned(session, '/tmp/workspace-1', 'workspace-1');+ const store = createUnprovisionedSession('location-1', session);+ store.transitionToProvisioned(session, '/tmp/loc-1');const viewModel = mocks.viewModels[0];manager.sessions.set(session.id, store);await manager.archiveSession(session.id);- expect(mocks.archiveSession).toHaveBeenCalledWith('project-1', 'session-1');+ expect(mocks.archiveSession).toHaveBeenCalledWith('session-1');expect(mocks.teardownSession).not.toHaveBeenCalled();expect(mocks.agentRelease).toHaveBeenCalledWith('session-1');expect(viewModel.dispose).toHaveBeenCalledOnce();expect(store.state).toBe('unprovisioned');expect(store.phase).toBe('idle');- expect(store.workspaceId).toBeNull();expect(store.viewModel).toBeNull();expect((store.data as Session).archivedAt).toBeDefined();@@ -161,13 +158,13 @@ describe('SessionManagerStore archive lifecycle', () => {it('reacquires frontend managers before provisioning a dry restored session', async () => {const manager = makeSessionManager();const session = makeSession({ archivedAt: undefined });- const store = createUnprovisionedSession('project-1', session);+ const store = createUnprovisionedSession('location-1', session);store.transitionToDryUnprovisioned(session);manager.sessions.set(session.id, store);await manager.provisionSession(session.id);- expect(mocks.agentAcquire).toHaveBeenCalledWith('session-1', 'project-1');+ expect(mocks.agentAcquire).toHaveBeenCalledWith('session-1', 'location-1');expect(store.state).toBe('provisioned');expect(store.viewModel).toBe(mocks.viewModels[1]);expect(mocks.viewModels[1].initialize).toHaveBeenCalledOnce();diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-manager.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-manager.tsindex a7a8074f9..6e10d10e5 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-manager.ts+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-manager.ts@@ -1,7 +1,7 @@import { makeObservable, observable, runInAction, toJS } from 'mobx';import { toast } from 'sonner';-import { getProjectManagerStore } from '@renderer/features/projects/stores/project-selectors';-import type { ProjectSettingsStore } from '@renderer/features/projects/stores/project-settings-store';+import { getLocationManagerStore } from '@renderer/features/locations/stores/location-selectors';+import type { LocationSettingsStore } from '@renderer/features/locations/stores/location-settings-store';import { events, rpc } from '@renderer/lib/ipc';import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';import {@@ -28,7 +28,6 @@ import {isUnregistered,type SessionStore,} from './session-store';-import { workspaceRegistry } from './workspace-registry';function formatCreateSessionError(error: CreateSessionError): string {switch (error.type) {@@ -42,15 +41,15 @@ function formatCreateSessionError(error: CreateSessionError): string {}export class SessionManagerStore {- private readonly projectId: string;- private readonly _settingsStore: ProjectSettingsStore;+ private readonly locationId: string;+ private readonly _settingsStore: LocationSettingsStore;private _loadPromise: Promise<void> | null = null;private _teardownPromises = new Map<string, Promise<void>>();private _provisionPromises = new Map<string, Promise<void>>();/** session:provisioned events that arrived before their session:created* (main-process automation emits both back-to-back; the created handler is* async, so provisioned can win the race). Applied once the session lands. */- private _pendingProvisioned = new Map<string, { path: string; workspaceId: string }>();+ private _pendingProvisioned = new Map<string, { path: string }>();private _unsubSessionCreated: (() => void) | null = null;private _unsubSessionDeleted: (() => void) | null = null;@@ -61,28 +60,28 @@ export class SessionManagerStore {sessions = observable.map<string, SessionStore>();- constructor(projectId: string, settingsStore: ProjectSettingsStore) {- this.projectId = projectId;+ constructor(locationId: string, settingsStore: LocationSettingsStore) {+ this.locationId = locationId;this._settingsStore = settingsStore;makeObservable(this, { sessions: observable });this._unsubSessionCreated = events.on(sessionCreatedChannel, ({ session }) => {if (this.sessions.has(session.id)) return;void rpc.agents.getAgentById(session.agentId).then((agent) => {- if (!agent || agent.projectId !== this.projectId || this.sessions.has(session.id)) return;+ if (!agent || agent.locationId !== this.locationId || this.sessions.has(session.id)) return;runInAction(() => {- this.sessions.set(session.id, createUnprovisionedSession(this.projectId, session));+ this.sessions.set(session.id, createUnprovisionedSession(this.locationId, session));// This session was created elsewhere (the auto-session watcher /// another window), so there is no record to seed — omit the preloaded// list so the store demand-fetches the real session record.- sessionAgentRegistry.acquire(session.id, this.projectId);+ sessionAgentRegistry.acquire(session.id, this.locationId);// A provisioned event for this session may have arrived first (the// automation path emits created→provisioned back-to-back). Apply it// now so the session reaches 'ready' without waiting for a restart.const pending = this._pendingProvisioned.get(session.id);if (pending) {this._pendingProvisioned.delete(session.id);- this._applyProvisioned(session.id, pending.path, pending.workspaceId);+ this._applyProvisioned(session.id, pending.path);}});});@@ -92,39 +91,30 @@ export class SessionManagerStore {// terminated a shared session, or the reconciler pruned a vanished VM// session). This window did not initiate the delete, so remove the row here// — otherwise it lingers as a ghost until restart.- this._unsubSessionDeleted = events.on(- sessionDeletedChannel,- ({ sessionId, projectId: evtProjectId }) => {- if (evtProjectId !== this.projectId) return;- const store = this.sessions.get(sessionId);- if (!store) return;- console.info('SessionManager: removing session (remote-driven delete)', {- sessionId,- projectId: this.projectId,- });- runInAction(() => this.sessions.delete(sessionId));- this._releaseSessionRegistries(sessionId);- store.dispose();- }- );+ this._unsubSessionDeleted = events.on(sessionDeletedChannel, ({ sessionId }) => {+ const store = this.sessions.get(sessionId);+ if (!store) return;+ console.info('SessionManager: removing session (remote-driven delete)', {+ sessionId,+ locationId: this.locationId,+ });+ runInAction(() => this.sessions.delete(sessionId));+ this._releaseSessionRegistries(sessionId);+ store.dispose();+ });- this._unsubStatusUpdated = events.on(- sessionStatusUpdatedChannel,- ({ sessionId, projectId: evtProjectId, status }) => {- if (evtProjectId !== this.projectId) return;- const store = this.sessions.get(sessionId);- if (store && isProvisioned(store)) {- runInAction(() => {- store.data.status = status as SessionLifecycleStatus;- });- }+ this._unsubStatusUpdated = events.on(sessionStatusUpdatedChannel, ({ sessionId, status }) => {+ const store = this.sessions.get(sessionId);+ if (store && isProvisioned(store)) {+ runInAction(() => {+ store.data.status = status as SessionLifecycleStatus;+ });}- );+ });this._unsubProvisionProgress = events.on(sessionProvisionProgressChannel,- ({ sessionId, projectId: evtProjectId, message }) => {- if (evtProjectId !== this.projectId) return;+ ({ sessionId, message }) => {const store = this.sessions.get(sessionId);if (store?.isBootstrapping) {runInAction(() => {@@ -136,7 +126,7 @@ export class SessionManagerStore {this._unsubLifecycleScriptStatus = events.on(lifecycleScriptStatusChannel, (statusEvent) => {if (- statusEvent.projectId !== this.projectId ||+ statusEvent.locationId !== this.locationId ||statusEvent.status !== 'failed' ||!statusEvent.surfaceFailure) {@@ -153,13 +143,9 @@ export class SessionManagerStore {// Handles sessions provisioned by the automation path (or any main-process caller)// without renderer-initiated RPCs. The `isUnprovisioned` guard prevents a// double-transition if the renderer-driven RPC already completed first.- this._unsubProvisioned = events.on(- sessionProvisionedChannel,- ({ sessionId, projectId: evtProjectId, path, workspaceId }) => {- if (evtProjectId !== this.projectId) return;- void this._doHandleProvisioned(sessionId, path, workspaceId);- }- );+ this._unsubProvisioned = events.on(sessionProvisionedChannel, ({ sessionId, path }) => {+ void this._doHandleProvisioned(sessionId, path);+ });}private _releaseSessionRegistries(sessionId: string): void {@@ -169,14 +155,14 @@ export class SessionManagerStore {loadSessions(): Promise<void> {if (!this._loadPromise) {this._loadPromise = rpc.sessions- .getSessions(this.projectId)+ .getSessions(this.locationId).then((sessions) => {runInAction(() => {for (const t of sessions) {- this.sessions.set(t.id, createUnprovisionedSession(this.projectId, t));+ this.sessions.set(t.id, createUnprovisionedSession(this.locationId, t));// Seed the agent store with the session record so sidebar badges// are available immediately.- sessionAgentRegistry.acquire(t.id, this.projectId, [t]);+ sessionAgentRegistry.acquire(t.id, this.locationId, [t]);}});})@@ -194,7 +180,7 @@ export class SessionManagerStore {runInAction(() => {this.sessions.set(params.id,- createUnregisteredSession(this.projectId, {+ createUnregisteredSession(this.locationId, {id: params.id,lastInteractedAt: new Date().toISOString(),createdAt: new Date().toISOString(),@@ -216,7 +202,7 @@ export class SessionManagerStore {const clearOptimisticInitialWorking = () => {if (!params.initialPrompt?.trim()) return;- sessionAgentRegistry.acquire(params.id, this.projectId).agent?.clearWorking();+ sessionAgentRegistry.acquire(params.id, this.locationId).agent?.clearWorking();};runInAction(() => {@@ -238,7 +224,7 @@ export class SessionManagerStore {createdAt: now,updatedAt: now,};- const agentStore = sessionAgentRegistry.acquire(params.id, this.projectId, [optimistic]);+ const agentStore = sessionAgentRegistry.acquire(params.id, this.locationId, [optimistic]);if (params.initialPrompt?.trim()) {void agentStore.markWorking();}@@ -286,7 +272,7 @@ export class SessionManagerStore {}async provisionSession(sessionId: string): Promise<void> {- await getProjectManagerStore().mountProject(this.projectId);+ await getLocationManagerStore().mountLocation(this.locationId);await this.loadSessions();const inFlight = this._provisionPromises.get(sessionId);@@ -311,8 +297,8 @@ export class SessionManagerStore {const session = this.sessions.get(sessionId);if (!session || !isUnprovisioned(session)) return;- // Single-phase provision: workspace bootstrap + session provider construction + registration.- const result = await rpc.sessions.provisionWorkspace(sessionId);+ // Single-phase provision: session bootstrap + session provider construction + registration.+ const result = await rpc.sessions.provisionSession(sessionId);if (!result.success) {const message = result.error.message;runInAction(() => {@@ -325,52 +311,44 @@ export class SessionManagerStore {return;}- workspaceRegistry.setBootstrapState(this.projectId, result.data.workspaceId, { kind: 'ready' });-runInAction(() => {const current = this.sessions.get(sessionId);if (current && isUnprovisioned(current)) {- sessionAgentRegistry.acquire(sessionId, this.projectId);+ sessionAgentRegistry.acquire(sessionId, this.locationId);current.ensureRegisteredStores();current.transitionToProvisioned({ ...current.data, lastInteractedAt: new Date().toISOString() },- result.data.path,- result.data.workspaceId+ result.data.path);current.activate();}});}- private async _doHandleProvisioned(- sessionId: string,- path: string,- workspaceId: string- ): Promise<void> {+ private async _doHandleProvisioned(sessionId: string, path: string): Promise<void> {runInAction(() => {const current = this.sessions.get(sessionId);// The session:created handler is async, so a main-process automation// path that emits created→provisioned can deliver provisioned first.// Buffer it; the created handler applies it when the session lands.if (!current) {- this._pendingProvisioned.set(sessionId, { path, workspaceId });+ this._pendingProvisioned.set(sessionId, { path });return;}- this._applyProvisioned(sessionId, path, workspaceId);+ this._applyProvisioned(sessionId, path);});}/** Transition an already-registered unprovisioned session to provisioned.* Must run inside a `runInAction`. */- private _applyProvisioned(sessionId: string, path: string, workspaceId: string): void {+ private _applyProvisioned(sessionId: string, path: string): void {const current = this.sessions.get(sessionId);if (current && isUnprovisioned(current)) {- sessionAgentRegistry.acquire(sessionId, this.projectId);+ sessionAgentRegistry.acquire(sessionId, this.locationId);current.ensureRegisteredStores();current.transitionToProvisioned({ ...current.data, lastInteractedAt: new Date().toISOString() },- path,- workspaceId+ path);current.activate();}@@ -394,7 +372,7 @@ export class SessionManagerStore {});const promise = rpc.sessions- .teardownSession(this.projectId, sessionId)+ .teardownSession(sessionId).then(() => {runInAction(() => {const current = this.sessions.get(sessionId);@@ -438,7 +416,7 @@ export class SessionManagerStore {session.data.archivedAt = new Date().toISOString();}});- await rpc.sessions.archiveSession(this.projectId, sessionId);+ await rpc.sessions.archiveSession(sessionId);} catch (e) {runInAction(() => {const session = this.sessions.get(sessionId);@@ -505,7 +483,7 @@ export class SessionManagerStore {this._releaseSessionRegistries(id);t.dispose();});- await rpc.sessions.deleteSessions(this.projectId, sessionIds);+ await rpc.sessions.deleteSessions(sessionIds);} catch (e) {runInAction(() => {removed.forEach((t, id) => this.sessions.set(id, t));diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-runtime-registry.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-runtime-registry.tsnew file mode 100644index 000000000..3f066c1e2--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-runtime-registry.ts@@ -0,0 +1,56 @@+import { SessionRuntimeStore } from './session-runtime-store';++type SessionRuntimeRegistryEntry = {+ store: SessionRuntimeStore;+ refCount: number;+ activated: boolean;+};++/**+ * Ref-counted renderer-side cache of per-location session runtimes, keyed by+ * location id. Every session at a location shares one runtime.+ */+export class SessionRuntimeRegistryStore {+ private readonly entries = new Map<string, SessionRuntimeRegistryEntry>();++ acquire(locationId: string, path: string): SessionRuntimeStore {+ const existing = this.entries.get(locationId);+ if (existing) {+ existing.refCount += 1;+ return existing.store;+ }++ const store = new SessionRuntimeStore(locationId, path);+ this.entries.set(locationId, { store, refCount: 1, activated: false });+ return store;+ }++ get(locationId: string): SessionRuntimeStore | undefined {+ return this.entries.get(locationId)?.store;+ }++ activate(locationId: string): void {+ const entry = this.entries.get(locationId);+ if (!entry || entry.activated) {+ return;+ }+ entry.activated = true;+ entry.store.activate();+ }++ release(locationId: string): void {+ const entry = this.entries.get(locationId);+ if (!entry) {+ return;+ }++ entry.refCount -= 1;++ if (entry.refCount <= 0) {+ entry.store.dispose();+ this.entries.delete(locationId);+ }+ }+}++export const sessionRuntimeRegistry = new SessionRuntimeRegistryStore();diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/workspace.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-runtime-store.tssimilarity index 63%rename from dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/workspace.tsrename to dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-runtime-store.tsindex dcf816874..a2e9fd2a4 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/workspace.ts+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-runtime-store.ts@@ -1,13 +1,13 @@import type { ILifecycle } from '@switchdash/shared';import { LifecycleScriptsStore } from './lifecycle-scripts';-export class WorkspaceStore implements ILifecycle {+export class SessionRuntimeStore implements ILifecycle {readonly path: string;readonly lifecycleScripts: LifecycleScriptsStore;- constructor(projectId: string, workspaceId: string, path: string) {+ constructor(locationId: string, path: string) {this.path = path;- this.lifecycleScripts = new LifecycleScriptsStore(projectId, workspaceId);+ this.lifecycleScripts = new LifecycleScriptsStore(locationId);}activate(): void {}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-selectors.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-selectors.tsindex e966cd488..f2fe46514 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-selectors.ts+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-selectors.ts@@ -1,9 +1,10 @@-import { isUnmountedProject } from '@renderer/features/projects/stores/project';-import { getProjectManagerStore } from '@renderer/features/projects/stores/project-selectors';+import { isUnmountedLocation } from '@renderer/features/locations/stores/location';+import { getLocationManagerStore } from '@renderer/features/locations/stores/location-selectors';import type { AgentStatus } from '@shared/core/providers/agentEvents';import type { Session } from '@shared/core/sessions/sessions';import { sessionAgentRegistry } from './session-agent-registry';import type { SessionManagerStore } from './session-manager';+import { sessionRuntimeRegistry } from './session-runtime-registry';import {isProvisioned,isUnprovisioned,@@ -11,36 +12,35 @@ import {registeredSessionData,type SessionStore,} from './session-store';-import { workspaceRegistry } from './workspace-registry';-import type { WorkspaceViewModel } from './workspace-view-model';+import type { SessionViewModel } from './session-view-model';/** Call only inside `observer` components (or other MobX reactions). */-export function getSessionManagerStore(projectId: string): SessionManagerStore | undefined {- const p = getProjectManagerStore().projects.get(projectId);- return p?.mountedProject?.sessionManager;+export function getSessionManagerStore(locationId: string): SessionManagerStore | undefined {+ const p = getLocationManagerStore().locations.get(locationId);+ return p?.mountedLocation?.sessionManager;}/** Call only inside `observer` components (or other MobX reactions). */-export function getSessionStore(projectId: string, sessionId: string): SessionStore | undefined {- return getSessionManagerStore(projectId)?.sessions.get(sessionId);+export function getSessionStore(locationId: string, sessionId: string): SessionStore | undefined {+ return getSessionManagerStore(locationId)?.sessions.get(sessionId);}/** Registered session payload (`Session`) when the row exists and is not unregistered; otherwise undefined. */export function getRegisteredSessionData(- projectId: string,+ locationId: string,sessionId: string): Session | undefined {- const store = getSessionStore(projectId, sessionId);+ const store = getSessionStore(locationId, sessionId);if (!store) return undefined;return registeredSessionData(store);}/** Call only inside `observer` components (or other MobX reactions). */export function getSessionView(- projectId: string,+ locationId: string,sessionId: string-): WorkspaceViewModel | undefined {- return getSessionStore(projectId, sessionId)?.viewModel ?? undefined;+): SessionViewModel | undefined {+ return getSessionStore(locationId, sessionId)?.viewModel ?? undefined;}export function sessionAgentStatus(store: SessionStore): AgentStatus | null {@@ -50,8 +50,8 @@ export function sessionAgentStatus(store: SessionStore): AgentStatus | null {export type SessionViewKind =| 'missing'- | 'project-mounting' // project is still opening — session data not yet available- | 'project-error' // project failed to open+ | 'location-mounting' // location is still opening — session data not yet available+ | 'location-error' // location failed to open| 'creating'| 'create-error'| 'provisioning'@@ -62,26 +62,26 @@ export type SessionViewKind =| 'ready';/**- * Derives the session view kind from the project + session store state.+ * Derives the session view kind from the location + session store state.*- * Pass `projectId` so that "project still opening" can be distinguished from+ * Pass `locationId` so that "location still opening" can be distinguished from* "session genuinely missing". Call only inside `observer` components.*/export function sessionViewKind(store: SessionStore | undefined,- projectId: string+ locationId: string): SessionViewKind {- const projectStore = getProjectManagerStore().projects.get(projectId);+ const locationStore = getLocationManagerStore().locations.get(locationId);- if (!projectStore) return 'missing';+ if (!locationStore) return 'missing';- if (isUnmountedProject(projectStore)) {- if (projectStore.phase === 'opening') return 'project-mounting';- if (projectStore.phase === 'error') return 'project-error';- return 'project-mounting';+ if (isUnmountedLocation(locationStore)) {+ if (locationStore.phase === 'opening') return 'location-mounting';+ if (locationStore.phase === 'error') return 'location-error';+ return 'location-mounting';}- if (projectStore.state === 'unregistered') return 'missing';+ if (locationStore.state === 'unregistered') return 'missing';if (!store) return 'missing';@@ -104,7 +104,7 @@ export function sessionViewKind(/** Returns the narrowed provisioned session store if the session is provisioned, otherwise undefined. */export function asProvisioned(store: SessionStore | undefined-): (SessionStore & { state: 'provisioned'; workspaceId: string }) | undefined {+): (SessionStore & { state: 'provisioned'; locationId: string }) | undefined {return store && isProvisioned(store) ? store : undefined;}@@ -112,16 +112,16 @@ export function asProvisioned(// New focused selectors (Phase 4)// ----------------------------------------------------------------------------export function getWorkspaceForSession(projectId: string, sessionId: string) {- const wsId = getSessionStore(projectId, sessionId)?.workspaceId;- return wsId ? (workspaceRegistry.get(projectId, wsId) ?? undefined) : undefined;+export function getSessionRuntime(locationId: string, sessionId: string) {+ const store = getSessionStore(locationId, sessionId);+ return store ? (sessionRuntimeRegistry.get(locationId) ?? undefined) : undefined;}-export function getWorkspaceViewModel(- projectId: string,+export function getSessionViewModel(+ locationId: string,sessionId: string-): WorkspaceViewModel | undefined {- return getSessionStore(projectId, sessionId)?.viewModel ?? undefined;+): SessionViewModel | undefined {+ return getSessionStore(locationId, sessionId)?.viewModel ?? undefined;}export function getSessionAgent(sessionId: string) {@@ -142,7 +142,7 @@ export function sessionErrorMessage(store: SessionStore | undefined): string | u}if (isUnprovisioned(store)) {if (store.phase === 'provision-error') {- return store.errorMessage ?? 'Failed to set up workspace';+ return store.errorMessage ?? 'Failed to set up session';}if (store.phase === 'teardown-error') {return store.errorMessage ?? 'Failed to tear down session';@@ -151,11 +151,11 @@ export function sessionErrorMessage(store: SessionStore | undefined): string | ureturn undefined;}-/** Returns the mount error message for the project. */-export function projectMountErrorMessage(projectId: string): string {- const store = getProjectManagerStore().projects.get(projectId);- if (store && isUnmountedProject(store) && store.phase === 'error') {- return store.error ?? 'Failed to open project';+/** Returns the mount error message for the location. */+export function locationMountErrorMessage(locationId: string): string {+ const store = getLocationManagerStore().locations.get(locationId);+ if (store && isUnmountedLocation(store) && store.phase === 'error') {+ return store.error ?? 'Failed to open location';}- return 'Failed to open project';+ return 'Failed to open location';}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-store.test.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-store.test.tsindex 2480dd83a..50e92c46b 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-store.test.ts+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-store.test.ts@@ -11,12 +11,12 @@ type MockViewModel = {const mocks = vi.hoisted(() => ({viewModels: [] as MockViewModel[],- workspaceAcquire: vi.fn(),- workspaceRelease: vi.fn(),+ runtimeAcquire: vi.fn(),+ runtimeRelease: vi.fn(),}));-vi.mock('./workspace-view-model', () => ({- WorkspaceViewModel: class {+vi.mock('./session-view-model', () => ({+ SessionViewModel: class {initialize = vi.fn();suspend = vi.fn();dispose = vi.fn();@@ -28,10 +28,10 @@ vi.mock('./workspace-view-model', () => ({},}));-vi.mock('./workspace-registry', () => ({- workspaceRegistry: {- acquire: mocks.workspaceAcquire,- release: mocks.workspaceRelease,+vi.mock('./session-runtime-registry', () => ({+ sessionRuntimeRegistry: {+ acquire: mocks.runtimeAcquire,+ release: mocks.runtimeRelease,},}));@@ -69,37 +69,36 @@ function makeSession(overrides: Partial<Session> = {}): Session {describe('SessionStore frontend runtime lifecycle', () => {beforeEach(() => {mocks.viewModels.length = 0;- mocks.workspaceAcquire.mockReset();- mocks.workspaceRelease.mockReset();+ mocks.runtimeAcquire.mockReset();+ mocks.runtimeRelease.mockReset();});it('can transition a provisioned session back to a dry unprovisioned state', () => {const session = makeSession();- const store = createUnprovisionedSession('project-1', session);+ const store = createUnprovisionedSession('location-1', session);- store.transitionToProvisioned(session, '/tmp/workspace-1', 'workspace-1');+ store.transitionToProvisioned(session, '/tmp/loc-1');const viewModel = mocks.viewModels[0];store.transitionToDryUnprovisioned({ ...session, archivedAt: '2026-01-02T00:00:00.000Z' });expect(viewModel.dispose).toHaveBeenCalledOnce();- expect(mocks.workspaceRelease).toHaveBeenCalledWith('project-1', 'workspace-1');+ expect(mocks.runtimeRelease).toHaveBeenCalledWith('location-1');expect(store.state).toBe('unprovisioned');expect(store.phase).toBe('idle');- expect(store.workspaceId).toBeNull();expect(store.viewModel).toBeNull();expect((store.data as Session).archivedAt).toBe('2026-01-02T00:00:00.000Z');});it('recreates registered stores before reprovisioning a dry session', () => {const session = makeSession();- const store = createUnprovisionedSession('project-1', session);+ const store = createUnprovisionedSession('location-1', session);const firstViewModel = mocks.viewModels[0];store.transitionToDryUnprovisioned(session);expect(store.viewModel).toBeNull();- store.transitionToProvisioned(session, '/tmp/workspace-1', 'workspace-1');+ store.transitionToProvisioned(session, '/tmp/loc-1');expect(mocks.viewModels).toHaveLength(2);expect(store.viewModel).toBe(mocks.viewModels[1]);diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-store.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-store.tsindex a6fad30c2..9c6661317 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-store.ts+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-store.ts@@ -8,8 +8,8 @@ import type {Session,SessionLifecycleStatus,} from '@shared/core/sessions/sessions';-import { workspaceRegistry } from './workspace-registry';-import { WorkspaceViewModel } from './workspace-view-model';+import { sessionRuntimeRegistry } from './session-runtime-registry';+import { SessionViewModel } from './session-view-model';export type UnregisteredSessionPhase = 'creating' | 'create-error';@@ -33,21 +33,21 @@ export type UnregisteredSessionData = {};export class SessionStore {- /** The project this session belongs to (session → agent → project). */- readonly projectId: string;+ /** The location this session runs at (session → agent → location). */+ readonly locationId: string;state: 'unregistered' | 'unprovisioned' | 'provisioned';data: UnregisteredSessionData | Session;phase: UnregisteredSessionPhase | UnprovisionedSessionPhase | null;errorMessage: string | undefined = undefined;provisionProgressMessage: string | null = null;- /** The workspace ID for this session session — null when unprovisioned. */- workspaceId: string | null = null;+ /** Whether this session currently holds an acquired location runtime. */+ private _acquired = false;/*** Stable view model — created when session first becomes registered, persists* across provision/unprovision cycles. Null only while session is unregistered.*/- viewModel: WorkspaceViewModel | null = null;+ viewModel: SessionViewModel | null = null;get displayName(): string {return this.data.title;@@ -62,17 +62,16 @@ export class SessionStore {}constructor(- projectId: string,+ locationId: string,data: UnregisteredSessionData | Session,state: SessionStore['state'],phase: UnregisteredSessionPhase | UnprovisionedSessionPhase | null = null) {- this.projectId = projectId;+ this.locationId = locationId;this.state = state;this.data = data;this.phase = phase;makeAutoObservable(this, {- workspaceId: observable,viewModel: observable.ref,/** Deep observable so nested fields (e.g. `status`) notify observers (e.g. sidebar). */data: observable,@@ -87,15 +86,15 @@ export class SessionStore {ensureRegisteredStores(): void {if (this.state === 'unregistered') return;if (!this.viewModel) {- this.viewModel = new WorkspaceViewModel(this);+ this.viewModel = new SessionViewModel(this);}}- transitionToProvisioned(data: Session, path: string, workspaceId: string): void {+ transitionToProvisioned(data: Session, path: string): void {this.data = data;this.ensureRegisteredStores();- workspaceRegistry.acquire(this.projectId, workspaceId, path);- this.workspaceId = workspaceId;+ sessionRuntimeRegistry.acquire(this.locationId, path);+ this._acquired = true;this.state = 'provisioned';this.phase = null;this.errorMessage = undefined;@@ -105,9 +104,9 @@ export class SessionStore {transitionToUnprovisioned(data: Session, phase: UnprovisionedSessionPhase = 'idle'): void {this.viewModel?.suspend();- if (this.workspaceId) {- workspaceRegistry.release(this.projectId, this.workspaceId);- this.workspaceId = null;+ if (this._acquired) {+ sessionRuntimeRegistry.release(this.locationId);+ this._acquired = false;}this.data = data;this.state = 'unprovisioned';@@ -130,9 +129,9 @@ export class SessionStore {transitionToUnregistered(data: UnregisteredSessionData): void {this.viewModel?.suspend();- if (this.workspaceId) {- workspaceRegistry.release(this.projectId, this.workspaceId);- this.workspaceId = null;+ if (this._acquired) {+ sessionRuntimeRegistry.release(this.locationId);+ this._acquired = false;}this.data = data;this.state = 'unregistered';@@ -141,17 +140,17 @@ export class SessionStore {}activate(): void {- if (this.workspaceId) {- workspaceRegistry.activate(this.projectId, this.workspaceId);+ if (this._acquired) {+ sessionRuntimeRegistry.activate(this.locationId);}}dispose(): void {this.viewModel?.dispose();this.viewModel = null;- if (this.workspaceId) {- workspaceRegistry.release(this.projectId, this.workspaceId);- this.workspaceId = null;+ if (this._acquired) {+ sessionRuntimeRegistry.release(this.locationId);+ this._acquired = false;}}@@ -165,7 +164,7 @@ export class SessionStore {const session = registeredSessionData(this);if (!session) return err({ type: 'session-not-found', sessionId: this.data.id });try {- const result = await rpc.sessions.renameSession(this.projectId, session.id, name);+ const result = await rpc.sessions.renameSession(session.id, name);if (!result.success) {return result;}@@ -252,7 +251,7 @@ export function isUnprovisioned(t: SessionStore): t is UnprovisionedSession {export function isProvisioned(t: SessionStore-): t is SessionStore & { state: 'provisioned'; data: Session; workspaceId: string } {+): t is SessionStore & { state: 'provisioned'; data: Session; locationId: string } {return t.state === 'provisioned';}@@ -266,12 +265,12 @@ export function unregisteredSessionData(store: SessionStore): UnregisteredSessio}export function createUnregisteredSession(- projectId: string,+ locationId: string,data: UnregisteredSessionData): SessionStore {- return new SessionStore(projectId, data, 'unregistered', 'creating');+ return new SessionStore(locationId, data, 'unregistered', 'creating');}-export function createUnprovisionedSession(projectId: string, data: Session): SessionStore {- return new SessionStore(projectId, data, 'unprovisioned', 'idle');+export function createUnprovisionedSession(locationId: string, data: Session): SessionStore {+ return new SessionStore(locationId, data, 'unprovisioned', 'idle');}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/workspace-view-model.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-view-model.tsxsimilarity index 96%rename from dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/workspace-view-model.tsxrename to dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-view-model.tsxindex 46e88b5dc..7ac1bf026 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/workspace-view-model.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-view-model.tsx@@ -11,7 +11,7 @@ import type { SessionStore } from './session-store';* session is provisioned, which is what connects its PTY. The terminal itself* is rendered by `SessionTerminal`.*/-export class WorkspaceViewModel implements ILifecycle {+export class SessionViewModel implements ILifecycle {/** Which region of the session view has focus. Kept for the terminal pane. */focusedRegion: 'main' | 'bottom' = 'main';diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-view.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-view.tsxdeleted file mode 100644index 144d11ac9..000000000--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-view.tsx+++ /dev/null@@ -1,5 +0,0 @@-/**- * @deprecated Import from workspace-view-model directly.- * This shim exists for backwards compatibility during the renderer store refactor.- */-export { WorkspaceViewModel as SessionViewStore } from './workspace-view-model';diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/workspace-registry.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/workspace-registry.tsdeleted file mode 100644index 0022b15ea..000000000--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/workspace-registry.ts+++ /dev/null@@ -1,82 +0,0 @@-import { observable } from 'mobx';-import type { WorkspaceResolution } from '@shared/core/workspaces/workspaces';-import { WorkspaceStore } from './workspace';--export type WorkspaceBootstrapState =- | { kind: 'pending' }- | { kind: 'resolving' }- | { kind: 'needs-resolution'; resolution: WorkspaceResolution }- | { kind: 'ready' }- | { kind: 'error'; message: string };--type WorkspaceRegistryEntry = {- store: WorkspaceStore;- refCount: number;- activated: boolean;-};--function makeKey(projectId: string, workspaceId: string): string {- return `${projectId}::${workspaceId}`;-}--export class WorkspaceRegistryStore {- private readonly entries = new Map<string, WorkspaceRegistryEntry>();- /** Observable map of workspace bootstrap states, keyed by projectId::workspaceId. */- private readonly bootstrapStates = observable.map<string, WorkspaceBootstrapState>();-- acquire(projectId: string, workspaceId: string, path: string): WorkspaceStore {- const key = makeKey(projectId, workspaceId);- const existing = this.entries.get(key);- if (existing) {- existing.refCount += 1;- return existing.store;- }-- const store = new WorkspaceStore(projectId, workspaceId, path);- this.entries.set(key, { store, refCount: 1, activated: false });- return store;- }-- get(projectId: string, workspaceId: string): WorkspaceStore | undefined {- return this.entries.get(makeKey(projectId, workspaceId))?.store;- }-- activate(projectId: string, workspaceId: string): void {- const entry = this.entries.get(makeKey(projectId, workspaceId));- if (!entry || entry.activated) {- return;- }- entry.activated = true;- entry.store.activate();- }-- release(projectId: string, workspaceId: string): void {- const key = makeKey(projectId, workspaceId);- const entry = this.entries.get(key);- if (!entry) {- return;- }-- entry.refCount -= 1;-- if (entry.refCount <= 0) {- entry.store.dispose();- this.entries.delete(key);- this.bootstrapStates.delete(key);- }- }-- // -------------------------------------------------------------------------- // Bootstrap state- // --------------------------------------------------------------------------- setBootstrapState(projectId: string, workspaceId: string, state: WorkspaceBootstrapState): void {- this.bootstrapStates.set(makeKey(projectId, workspaceId), state);- }-- bootstrapStateFor(projectId: string, workspaceId: string): WorkspaceBootstrapState | undefined {- return this.bootstrapStates.get(makeKey(projectId, workspaceId));- }-}--export const workspaceRegistry = new WorkspaceRegistryStore();diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/view.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sessions/view.tsxindex 94c94b916..67c25be97 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/view.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/view.tsx@@ -14,15 +14,15 @@ import { SessionTitlebar } from './session-titlebar';const SessionViewWrapperWithProviders = observer(function SessionViewWrapperWithProviders({children,- projectId,+ locationId,sessionId,}: {children: ReactNode;- projectId: string;+ locationId: string;sessionId: string;}) {- const sessionStore = getSessionStore(projectId, sessionId);- const kind = sessionViewKind(sessionStore, projectId);+ const sessionStore = getSessionStore(locationId, sessionId);+ const kind = sessionViewKind(sessionStore, locationId);// Auto-provision when the session view is rendered with an idle session — covers// session restore where the session wasn't in openSessionIds, direct navigation,@@ -31,21 +31,21 @@ const SessionViewWrapperWithProviders = observer(function SessionViewWrapperWithif (kind !== 'idle') return;if (sessionStore && 'archivedAt' in sessionStore.data && sessionStore.data.archivedAt) return;- getSessionManagerStore(projectId)+ getSessionManagerStore(locationId)?.provisionSession(sessionId).catch(() => {});- }, [kind, projectId, sessionId, sessionStore]);+ }, [kind, locationId, sessionId, sessionStore]);if (kind !== 'ready') {return (- <SessionViewWrapper projectId={projectId} sessionId={sessionId}>+ <SessionViewWrapper locationId={locationId} sessionId={sessionId}>{children}</SessionViewWrapper>);}return (- <SessionViewWrapper projectId={projectId} sessionId={sessionId}>+ <SessionViewWrapper locationId={locationId} sessionId={sessionId}>{children}</SessionViewWrapper>);@@ -55,30 +55,30 @@ export const sessionView = {WrapView: SessionViewWrapperWithProviders,TitlebarSlot: SessionTitlebar,MainPanel: SessionMainPanel,- commandProvider: ({ projectId, sessionId }: { projectId: string; sessionId: string }) =>- createSessionCommandProvider(projectId, sessionId),+ commandProvider: ({ locationId, sessionId }: { locationId: string; sessionId: string }) =>+ createSessionCommandProvider(locationId, sessionId),canActivate: (params: unknown): GuardResult => {- const projectId =+ const locationId =typeof params === 'object' && params !== null- ? (params as { projectId?: unknown }).projectId+ ? (params as { locationId?: unknown }).locationId: undefined;const sessionId =typeof params === 'object' && params !== null? (params as { sessionId?: unknown }).sessionId: undefined;- if (typeof projectId !== 'string' || typeof sessionId !== 'string') {+ if (typeof locationId !== 'string' || typeof sessionId !== 'string') {return { ok: false, redirect: 'home' };}if (- !appState.projects.projects.has(projectId) &&- !appState.projects.pendingCreationIds.has(projectId)+ !appState.locations.locations.has(locationId) &&+ !appState.locations.pendingCreationIds.has(locationId)) {return { ok: false, redirect: 'home' };}- const sessionManager = getSessionManagerStore(projectId);+ const sessionManager = getSessionManagerStore(locationId);if (sessionManager && !sessionManager.sessions.has(sessionId)) {- return { ok: false, redirect: 'project', params: { projectId } };+ return { ok: false, redirect: 'location', params: { locationId } };}return { ok: true };},-} satisfies ViewDefinition<{ projectId: string; sessionId: string }>;+} satisfies ViewDefinition<{ locationId: string; sessionId: string }>;diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/workspace-resolution-view.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sessions/workspace-resolution-view.tsxdeleted file mode 100644index 4162c0b6f..000000000--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/workspace-resolution-view.tsx+++ /dev/null@@ -1,4 +0,0 @@-// Workspace resolution is now handled automatically in the main process.-// Branch-already-checked-out and stale-directory errors are recovered by-// WorkspaceBootstrapService.ensureWorkspaceSetup before the session session is started.-export const WorkspaceResolutionView = null;diff --git a/dash/apps/switchdash-desktop/src/renderer/features/settings/components/SessionSettingsRows.tsx b/dash/apps/switchdash-desktop/src/renderer/features/settings/components/SessionSettingsRows.tsxindex 0dbf0578c..83501e95f 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/settings/components/SessionSettingsRows.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/settings/components/SessionSettingsRows.tsx@@ -168,15 +168,15 @@ export const IncludeIssueContextByDefaultRow: React.FC = () => {export const EnableTmuxRow: React.FC = () => {const {- value: projects,+ value: locations,update,isLoading: loading,isSaving: saving,isFieldOverridden,resetField,- } = useAppSettingsKey('project');+ } = useAppSettingsKey('location');- const tmuxByDefault = projects?.tmuxByDefault ?? false;+ const tmuxByDefault = locations?.tmuxByDefault ?? false;return (<SettingRowdiff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/left-sidebar.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/left-sidebar.tsxindex 494acbb56..03a3a5998 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/left-sidebar.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/left-sidebar.tsx@@ -9,8 +9,8 @@ import {import { BoundShortcut } from '@renderer/lib/ui/shortcut';import { cn } from '@renderer/utils/utils';import { ServersSidebarSection } from '../switch-servers/ServersSidebarSection';+import { LocationsGroupLabel } from './locations-group-label';import { SidebarPinnedSessionList } from './pinned-session-list';-import { ProjectsGroupLabel } from './projects-group-label';import { SidebarGroupedList } from './sidebar-grouped-list';import {SidebarContainer,@@ -55,7 +55,7 @@ export const LeftSidebar: React.FC = observer(function LeftSidebar() {<SidebarPinnedSessionList /><ServersSidebarSection /><SidebarGroup className="mb-0 flex min-h-0 flex-1 flex-col">- <ProjectsGroupLabel />+ <LocationsGroupLabel /><SidebarGroupContent className="flex min-h-0 flex-1 flex-col"><SidebarMenu className="flex min-h-0 flex-1 flex-col"><SidebarGroupedList />diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/project-item.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/location-item.tsxsimilarity index 69%rename from dash/apps/switchdash-desktop/src/renderer/features/sidebar/project-item.tsxrename to dash/apps/switchdash-desktop/src/renderer/features/sidebar/location-item.tsxindex 635686a0b..cb98d2042 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/project-item.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/location-item.tsx@@ -11,15 +11,15 @@ import {} from 'lucide-react';import { observer } from 'mobx-react-lite';import React from 'react';-import { useConfirmDeleteProject } from '@renderer/features/projects/hooks/use-confirm-delete-project';+import { useConfirmDeleteAgent } from '@renderer/features/locations/hooks/use-confirm-delete-agent';import {- isUnregisteredProject,- type UnregisteredProject,-} from '@renderer/features/projects/stores/project';+ isUnregisteredLocation,+ type UnregisteredLocation,+} from '@renderer/features/locations/stores/location';import {- getProjectStore,- projectViewKind,-} from '@renderer/features/projects/stores/project-selectors';+ getLocationStore,+ locationViewKind,+} from '@renderer/features/locations/stores/location-selectors';import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';import { AgentIcon } from '@renderer/lib/components/agent-icon';import { rpc } from '@renderer/lib/ipc';@@ -47,75 +47,73 @@ import {} from './sidebar-primitives';import { depthIndent } from './sidebar-store';-const UNREGISTERED_PHASE_LABEL: Record<UnregisteredProject['phase'], string> = {- 'creating-repo': 'Creating repository…',- cloning: 'Cloning…',+const UNREGISTERED_PHASE_LABEL: Record<UnregisteredLocation['phase'], string> = {registering: 'Registering…',error: 'Failed',};-export const SidebarProjectItem = observer(function SidebarProjectItem({- projectId,+export const SidebarLocationItem = observer(function SidebarLocationItem({+ locationId,depth = 0,}: {- projectId: string;+ locationId: string;depth?: number;}) {const { navigate } = useNavigate();const { currentView } = useWorkspaceSlots();- const { params: projectParams } = useParams('project');+ const { params: locationParams } = useParams('location');const { params: sessionParams } = useParams('session');const showCreateSessionModal = useShowModal('sessionModal');const showAssignServerModal = useShowModal('assignServerModal');- const confirmDeleteProject = useConfirmDeleteProject();+ const confirmDeleteAgent = useConfirmDeleteAgent();// Resolve the agent's Switch identity so the "go to" button can open its// detail page in the gateway web app (parallel to a room's "go to" button).const agentQuery = useQuery({- queryKey: ['projectAgent', projectId],- queryFn: async () => (await rpc.agents.getAgents(projectId))[0] ?? null,- enabled: !!projectId,+ queryKey: ['locationAgent', locationId],+ queryFn: async () => (await rpc.agents.getAgents(locationId))[0] ?? null,+ enabled: !!locationId,});- const project = getProjectStore(projectId);+ const location = getLocationStore(locationId);- const currentProjectId =+ const currentLocationId =currentView === 'session'- ? sessionParams.projectId- : currentView === 'project'- ? projectParams.projectId+ ? sessionParams.locationId+ : currentView === 'location'+ ? locationParams.locationId: null;const currentSessionId = currentView === 'session' ? sessionParams.sessionId : null;- // A subagent of this project is scoped by subagentName on the project view;+ // A subagent of this location is scoped by subagentName on the location view;// the parent row is active only when no subagent is selected.- const currentSubagentName = currentView === 'project' ? projectParams.subagentName : undefined;+ const currentSubagentName = currentView === 'location' ? locationParams.subagentName : undefined;- const isProjectActive =- currentProjectId === projectId && !currentSessionId && !currentSubagentName;+ const isLocationActive =+ currentLocationId === locationId && !currentSessionId && !currentSubagentName;- const isExpanded = sidebarStore.expandedProjectIds.has(projectId);+ const isExpanded = sidebarStore.expandedLocationIds.has(locationId);- if (!project) return null;+ if (!location) return null;const iconClass ='absolute h-4 w-4 opacity-100 transition-opacity duration-150 group-hover/row:opacity-0';- const projectLabel = project.name ?? 'agent';- const toggleExpanded = () => sidebarStore.toggleProjectExpanded(projectId);+ const locationLabel = location.name ?? 'agent';+ const toggleExpanded = () => sidebarStore.toggleLocationExpanded(locationId);// Clicking the row opens the agent's page (Sessions / Subagents / Settings),// mirroring subagent rows; the chevron button below toggles expansion. An// unregistered agent has no page yet, so there we just expand.- const openProject = () => {- if (isUnregisteredProject(project)) {+ const openLocation = () => {+ if (isUnregisteredLocation(location)) {toggleExpanded();return;}- sidebarStore.ensureProjectExpanded(projectId);- navigate('project', { projectId });+ sidebarStore.ensureLocationExpanded(locationId);+ navigate('location', { locationId });};const agent = agentQuery.data ?? null;- // The project's agent type drives its icon; fall back to a generic icon until+ // The location's agent type drives its icon; fall back to a generic icon until// the agent (and its providerId) is available.const providerId = agent?.providerId ?? null;const gatewayUrl =@@ -127,8 +125,8 @@ export const SidebarProjectItem = observer(function SidebarProjectItem({};const renderSpinnerWithTooltip = () => {- if (!isUnregisteredProject(project)) return null;- const label = UNREGISTERED_PHASE_LABEL[project.phase] ?? 'Loading…';+ if (!isUnregisteredLocation(location)) return null;+ const label = UNREGISTERED_PHASE_LABEL[location.phase] ?? 'Loading…';return (<Tooltip><TooltipTrigger>@@ -147,22 +145,22 @@ export const SidebarProjectItem = observer(function SidebarProjectItem({<SidebarMenuRowclassName={cn('group/row h-8 justify-between flex px-1')}style={depthIndent(depth)}- data-active={isProjectActive || undefined}- isActive={isProjectActive}+ data-active={isLocationActive || undefined}+ isActive={isLocationActive}onMouseDown={(e) => e.preventDefault()}- onClick={openProject}+ onClick={openLocation}><div className="flex min-w-0 flex-1 items-center gap-1">- {project.state === 'unregistered' ? (+ {location.state === 'unregistered' ? (renderSpinnerWithTooltip()) : (<SidebarItemMiniButtontype="button"- aria-label={`${isExpanded ? 'Collapse' : 'Expand'} ${projectLabel}`}+ aria-label={`${isExpanded ? 'Collapse' : 'Expand'} ${locationLabel}`}className="relative"onClick={(e) => {e.stopPropagation();- sidebarStore.toggleProjectExpanded(projectId);+ sidebarStore.toggleLocationExpanded(locationId);}}>{providerId ? (@@ -179,27 +177,24 @@ export const SidebarProjectItem = observer(function SidebarProjectItem({</SidebarItemMiniButton>)}<SidebarMenuAction- aria-label={`Open agent ${projectLabel}`}+ aria-label={`Open agent ${locationLabel}`}className={cn('truncate transition-colors select-none',- projectViewKind(getProjectStore(projectId)) === 'bootstrapping' &&+ locationViewKind(getLocationStore(locationId)) === 'bootstrapping' &&'text-foreground-tertiary-passive')}><span className="flex min-w-0 items-center gap-1.5">- <span className="truncate">{project.name}</span>- {agent?.connection === 'remote' && (+ <span className="truncate">{location.name}</span>+ {location.data?.sshHost != null && (<Tooltip><TooltipTrigger><Server className="h-3.5 w-3.5 shrink-0 text-foreground-muted" /></TooltipTrigger>- <TooltipContent>- Runs remotely- {agent.remoteConfig?.sshHost ? ` on ${agent.remoteConfig.sshHost}` : ''}- </TooltipContent>+ <TooltipContent>Runs remotely on {location.data.sshHost}</TooltipContent></Tooltip>)}- {projectViewKind(project) === 'path_not_found' && (+ {locationViewKind(location) === 'path_not_found' && (<Tooltip><TooltipTrigger><TriangleAlert className="h-3.5 w-3.5 shrink-0 text-foreground-destructive" />@@ -216,7 +211,7 @@ export const SidebarProjectItem = observer(function SidebarProjectItem({render={<SidebarItemMiniButtontype="button"- aria-label={`Open ${projectLabel} in gateway`}+ aria-label={`Open ${locationLabel} in gateway`}className="opacity-0 transition-opacity duration-150 group-hover/row:opacity-100"onClick={(e) => {e.stopPropagation();@@ -236,15 +231,15 @@ export const SidebarProjectItem = observer(function SidebarProjectItem({render={<SidebarItemMiniButtontype="button"- aria-label={`New session for ${projectLabel}`}+ aria-label={`New session for ${locationLabel}`}className={'opacity-0 transition-opacity duration-150 group-hover/row:opacity-100'}onClick={(e) => {e.stopPropagation();- showCreateSessionModal({ projectId });+ showCreateSessionModal({ locationId });}}- disabled={project.state === 'unregistered'}+ disabled={location.state === 'unregistered'}><Plus className="h-4 w-4" /></SidebarItemMiniButton>@@ -258,18 +253,18 @@ export const SidebarProjectItem = observer(function SidebarProjectItem({</SidebarMenuRow></ContextMenuTrigger><ContextMenuContent>- <ContextMenuItem onClick={() => showAssignServerModal({ projectId })}>+ <ContextMenuItem onClick={() => showAssignServerModal({ locationId })}><Server className="size-4" />Assign server</ContextMenuItem><ContextMenuItemvariant="destructive"onClick={() => {- void confirmDeleteProject({- projectId,- projectLabel: project.name ?? 'this agent',+ void confirmDeleteAgent({+ locationId,+ locationLabel: location.name ?? 'this agent',onDeleted: () => {- if (isProjectActive) navigate('home');+ if (isLocationActive) navigate('home');},});}}@@ -282,11 +277,11 @@ export const SidebarProjectItem = observer(function SidebarProjectItem({);});-interface BaseProjectItemProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {+interface BaseLocationItemProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {isActive: boolean;}-export function BaseProjectItem({ isActive, className, ...props }: BaseProjectItemProps) {+export function BaseLocationItem({ isActive, className, ...props }: BaseLocationItemProps) {return (<SidebarMenuButtonclassName={cn('justify-between flex item px-1 py-1', className)}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/projects-group-label.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/locations-group-label.tsxsimilarity index 97%rename from dash/apps/switchdash-desktop/src/renderer/features/sidebar/projects-group-label.tsxrename to dash/apps/switchdash-desktop/src/renderer/features/sidebar/locations-group-label.tsxindex 3ac359f29..bc00f6751 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/projects-group-label.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/locations-group-label.tsx@@ -205,8 +205,8 @@ const FilterDropdown = observer(function FilterDropdown() {);});-export const ProjectsGroupLabel = observer(function ProjectsGroupLabel() {- const showAddProjectModal = useShowModal('addProjectModal');+export const LocationsGroupLabel = observer(function LocationsGroupLabel() {+ const showAddLocationModal = useShowModal('addAgentModal');return (<div className="flex h-[40px] items-center justify-between pr-2.5 pl-5">@@ -263,7 +263,7 @@ export const ProjectsGroupLabel = observer(function ProjectsGroupLabel() {render={<buttontype="button"- onClick={() => showAddProjectModal({})}+ onClick={() => showAddLocationModal({})}aria-label="Add Agent"className={buttonVariants({size: 'icon-xs',@@ -277,7 +277,7 @@ export const ProjectsGroupLabel = observer(function ProjectsGroupLabel() {/><TooltipContent>Add Agent- <BoundShortcut settingsKey="newProject" variant="badge" />+ <BoundShortcut settingsKey="newLocation" variant="badge" /></TooltipContent></Tooltip></div>diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/pinned-session-list.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/pinned-session-list.tsxindex a4a11c09d..b1164733f 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/pinned-session-list.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/pinned-session-list.tsx@@ -14,10 +14,10 @@ export const SidebarPinnedSessionList = observer(function SidebarPinnedSessionLi<MicroLabel className="text-foreground-tertiary-passive">Pinned</MicroLabel></div><SidebarMenu className="px-3 pb-2">- {entries.map(({ projectId, sessionId }) => (+ {entries.map(({ locationId, sessionId }) => (<SidebarSessionItem- key={`${projectId}:${sessionId}`}- projectId={projectId}+ key={`${locationId}:${sessionId}`}+ locationId={locationId}sessionId={sessionId}rowVariant="pinned"/>diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/session-item.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/session-item.tsxindex 396977a42..729cb4c0b 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/session-item.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/session-item.tsx@@ -19,9 +19,9 @@ import { depthIndent } from './sidebar-store';interface SidebarSessionItemProps {sessionId: string;- projectId: string;- /** Pinned strip uses tighter padding than sessions nested under a project. */- rowVariant?: 'underProject' | 'pinned';+ locationId: string;+ /** Pinned strip uses tighter padding than sessions nested under a location. */+ rowVariant?: 'underLocation' | 'pinned';/** Tree depth of this row (ignored for the pinned strip). Drives the row's* left indent so a session aligns with the other entities at its depth. */depth?: number;@@ -29,8 +29,8 @@ interface SidebarSessionItemProps {export const SidebarSessionItem = observer(function SidebarSessionItem({sessionId,- projectId,- rowVariant = 'underProject',+ locationId,+ rowVariant = 'underLocation',depth = 0,}: SidebarSessionItemProps) {const { navigate } = useNavigate();@@ -41,10 +41,10 @@ export const SidebarSessionItem = observer(function SidebarSessionItem({const { params } = useParams('session');const { value: interfaceSettings } = useAppSettingsKey('interface');const isActive =- currentView === 'session' && params.sessionId === sessionId && params.projectId === projectId;+ currentView === 'session' && params.sessionId === sessionId && params.locationId === locationId;- const session = getSessionStore(projectId, sessionId)!;- const sessionManager = getSessionManagerStore(projectId);+ const session = getSessionStore(locationId, sessionId)!;+ const sessionManager = getSessionManagerStore(locationId);const sessionName = session.data.title;@@ -55,23 +55,23 @@ export const SidebarSessionItem = observer(function SidebarSessionItem({const openSession = () => {handleProvision();- navigate('session', { projectId, sessionId });+ navigate('session', { locationId, sessionId });};const handleArchive = () => {- if (isActive) navigate('project', { projectId });+ if (isActive) navigate('location', { locationId });void sessionManager?.archiveSession(sessionId);};- const handleRename = () => showRename({ projectId, sessionId, currentName: sessionName });+ const handleRename = () => showRename({ locationId, sessionId, currentName: sessionName });const handleDelete = () =>showDeleteSession({- projectId,+ locationId,sessions: [{ sessionId, sessionName }],onSuccess: () => {void sessionManager?.deleteSessions([sessionId]);- if (isActive) navigate('project', { projectId });+ if (isActive) navigate('location', { locationId });},});diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/session-sidebar-agent-status.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/session-sidebar-agent-status.tsxindex addfa8194..c812c4dd8 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/session-sidebar-agent-status.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/session-sidebar-agent-status.tsx@@ -38,7 +38,7 @@ export const SessionSidebarTrailingSlot = observer(function SessionSidebarTraili<CLISpinner variant="2" /></span></TooltipTrigger>- <TooltipContent>Creating session workspace...</TooltipContent>+ <TooltipContent>Creating session…</TooltipContent></Tooltip></Slot>);diff --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 f3d220432..ef9cfc4d8 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@@ -2,13 +2,13 @@ import { DndContext } from '@dnd-kit/core';import { SortableContext, verticalListSortingStrategy } from '@dnd-kit/sortable';import { observer } from 'mobx-react-lite';import { Fragment, useEffect } from 'react';-import { agentsStore } from '@renderer/features/projects/stores/agents-store';+import { agentsStore } from '@renderer/features/locations/stores/agents-store';import type { SessionStore } from '@renderer/features/sessions/stores/session-store';import { switchRoomsStore as roomConnectionsStore } from '@renderer/features/switch-rooms/switch-rooms-store';import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';import { sidebarStore } from '@renderer/lib/stores/app-state';-import { SidebarProjectItem } from './project-item';+import { SidebarLocationItem } from './location-item';import { SidebarSessionItem } from './session-item';import { makeDndId, SortableBranch, SortableLeaf, useSidebarDnd } from './sidebar-dnd';import {@@ -26,11 +26,11 @@ import { SidebarSubagentList } from './sidebar-subagent-list';const AGENTS_CONTAINER = 'agents';const ROOMS_CONTAINER = 'rooms';/** Sessions of one agent's room group (agent-focused view). */-const agentSessionsContainer = (projectId: string, roomKey: string): string =>- `as:${projectId}|${roomKey}`;+const agentSessionsContainer = (locationId: string, roomKey: string): string =>+ `as:${locationId}|${roomKey}`;/** Sessions of one agent within a room (room-focused view). */-const roomSessionsContainer = (roomKey: string, projectId: string): string =>- `rs:${roomKey}|${projectId}`;+const roomSessionsContainer = (roomKey: string, locationId: string): string =>+ `rs:${roomKey}|${locationId}`;export const SidebarGroupedList = observer(function SidebarGroupedList() {// Live session→room connections + room names live on the server; pull them@@ -48,7 +48,7 @@ export const SidebarGroupedList = observer(function SidebarGroupedList() {}, []);const showFilterEmptyState =- sidebarStore.hasActiveFilters && sidebarStore.filteredProjects.length === 0;+ sidebarStore.hasActiveFilters && sidebarStore.filteredLocations.length === 0;return (<div className="min-h-0 flex-1 overflow-y-auto px-3 pt-1 pb-3">@@ -64,19 +64,19 @@ export const SidebarGroupedList = observer(function SidebarGroupedList() {});const AgentFocusedTree = observer(function AgentFocusedTree() {- const projects = sidebarStore.filteredProjects;+ const locations = sidebarStore.filteredLocations;// Populated during render (each rendered group registers its ordered ids) so// the drag handler can resolve a container's siblings on drop.const containers: Record<string, string[]> = {- [AGENTS_CONTAINER]: projects.map((project) => project.id),+ [AGENTS_CONTAINER]: locations.map((location) => location.id),};const dnd = useSidebarDnd(containers, (containerId, orderedIds) => {- if (containerId === AGENTS_CONTAINER) sidebarStore.setProjectOrder(orderedIds);+ if (containerId === AGENTS_CONTAINER) sidebarStore.setLocationOrder(orderedIds);else sidebarStore.setGroupOrder(containerId, orderedIds);});- function renderSessionGroup(projectId: string, roomKey: string, roomSessions: SessionStore[]) {- const container = agentSessionsContainer(projectId, roomKey);+ function renderSessionGroup(locationId: string, roomKey: string, roomSessions: SessionStore[]) {+ const container = agentSessionsContainer(locationId, roomKey);const ordered = sidebarStore.orderGroupItems(container,roomSessions,@@ -92,7 +92,7 @@ const AgentFocusedTree = observer(function AgentFocusedTree() {>{ordered.map((session) => (<SortableLeaf key={session.data.id} id={makeDndId(container, session.data.id)}>- <SidebarSessionItem projectId={projectId} sessionId={session.data.id} depth={depth} />+ <SidebarSessionItem locationId={locationId} sessionId={session.data.id} depth={depth} /></SortableLeaf>))}</SortableContext>@@ -102,21 +102,21 @@ const AgentFocusedTree = observer(function AgentFocusedTree() {return (<DndContext {...dnd}><SortableContext- items={projects.map((project) => makeDndId(AGENTS_CONTAINER, project.id))}+ items={locations.map((location) => makeDndId(AGENTS_CONTAINER, location.id))}strategy={verticalListSortingStrategy}>- {projects.map((project) => {- const projectId = project.id;- const expanded = sidebarStore.expandedProjectIds.has(projectId);- const allSessions = expanded ? sidebarStore.visibleSessionsForProject(projectId) : [];+ {locations.map((location) => {+ const locationId = location.id;+ const expanded = sidebarStore.expandedLocationIds.has(locationId);+ const allSessions = expanded ? sidebarStore.visibleSessionsForLocation(locationId) : [];// Subagent sessions nest under their subagent row; the rest group by room.const subagentSessions = allSessions.filter(isSubagentSession);const grouped = groupByRoom(allSessions.filter((s) => !isSubagentSession(s)));return (<SortableBranch- key={projectId}- id={makeDndId(AGENTS_CONTAINER, projectId)}- header={<SidebarProjectItem projectId={projectId} depth={0} />}+ key={locationId}+ id={makeDndId(AGENTS_CONTAINER, locationId)}+ header={<SidebarLocationItem locationId={locationId} depth={0} />}>{/* The agent's own rooms/sessions come first, then its subagents. */}{expanded &&@@ -127,11 +127,11 @@ const AgentFocusedTree = observer(function AgentFocusedTree() {if (roomKey === UNASSIGNED_ROOM_KEY) {return (<Fragment key={roomKey}>- {renderSessionGroup(projectId, roomKey, roomSessions)}+ {renderSessionGroup(locationId, roomKey, roomSessions)}</Fragment>);}- const groupKey = agentRoomGroupKey(projectId, roomKey);+ const groupKey = agentRoomGroupKey(locationId, roomKey);const roomExpanded = sidebarStore.isGroupExpanded(groupKey);return (<div key={roomKey}>@@ -149,12 +149,16 @@ const AgentFocusedTree = observer(function AgentFocusedTree() {: null}/>- {roomExpanded && renderSessionGroup(projectId, roomKey, roomSessions)}+ {roomExpanded && renderSessionGroup(locationId, roomKey, roomSessions)}</div>);})}{expanded && (- <SidebarSubagentList projectId={projectId} sessions={subagentSessions} depth={1} />+ <SidebarSubagentList+ locationId={locationId}+ sessions={subagentSessions}+ depth={1}+ />)}</SortableBranch>);@@ -166,10 +170,10 @@ const AgentFocusedTree = observer(function AgentFocusedTree() {const RoomFocusedTree = observer(function RoomFocusedTree() {// Collect every visible session across mounted agents, tagged with its agent.- const tagged: { projectId: string; session: SessionStore }[] = [];- for (const project of sidebarStore.filteredProjects) {- for (const session of sidebarStore.visibleSessionsForProject(project.id)) {- tagged.push({ projectId: project.id, session });+ const tagged: { locationId: string; session: SessionStore }[] = [];+ for (const location of sidebarStore.filteredLocations) {+ for (const session of sidebarStore.visibleSessionsForLocation(location.id)) {+ tagged.push({ locationId: location.id, session });}}@@ -195,11 +199,11 @@ const RoomFocusedTree = observer(function RoomFocusedTree() {const roomViewKey = roomViewGroupKey(roomKey);const expanded = sidebarStore.isGroupExpanded(roomViewKey);const sessionIds = new Set(roomSessions.map((s) => s.data.id));- const byProject = sidebarStore.filteredProjects- .map((project) => ({- projectId: project.id,+ const byLocation = sidebarStore.filteredLocations+ .map((location) => ({+ locationId: location.id,sessions: tagged- .filter((t) => t.projectId === project.id && sessionIds.has(t.session.data.id))+ .filter((t) => t.locationId === location.id && sessionIds.has(t.session.data.id)).map((t) => t.session),})).filter((entry) => entry.sessions.length > 0);@@ -226,17 +230,17 @@ const RoomFocusedTree = observer(function RoomFocusedTree() {}>{expanded &&- byProject.map((entry) => {+ byLocation.map((entry) => {// Reuse the agent row so it matches the agent-focused view// (icon, hover-chevron, sizing). Its expand state is the global- // project expand, shared across the rooms an agent appears in.- const agentExpanded = sidebarStore.expandedProjectIds.has(entry.projectId);+ // location expand, shared across the rooms an agent appears in.+ const agentExpanded = sidebarStore.expandedLocationIds.has(entry.locationId);// The agent's own sessions in this room render under it; the// subagents that have a session here render as sibling rows at// the same depth as the agent (not nested inside it).const parentSessions = entry.sessions.filter((s) => !isSubagentSession(s));const subagentSessions = entry.sessions.filter(isSubagentSession);- const container = roomSessionsContainer(roomKey, entry.projectId);+ const container = roomSessionsContainer(roomKey, entry.locationId);const orderedParent = sidebarStore.orderGroupItems(container,parentSessions,@@ -245,8 +249,8 @@ const RoomFocusedTree = observer(function RoomFocusedTree() {);containers[container] = orderedParent.map((session) => session.data.id);return (- <Fragment key={entry.projectId}>- <SidebarProjectItem projectId={entry.projectId} depth={1} />+ <Fragment key={entry.locationId}>+ <SidebarLocationItem locationId={entry.locationId} depth={1} />{agentExpanded && (<SortableContextitems={orderedParent.map((session) =>@@ -260,7 +264,7 @@ const RoomFocusedTree = observer(function RoomFocusedTree() {id={makeDndId(container, session.data.id)}><SidebarSessionItem- projectId={entry.projectId}+ locationId={entry.locationId}sessionId={session.data.id}depth={2}/>@@ -270,7 +274,7 @@ const RoomFocusedTree = observer(function RoomFocusedTree() {)}{subagentSessions.length > 0 && (<SidebarSubagentList- projectId={entry.projectId}+ locationId={entry.locationId}depth={1}sessions={subagentSessions}onlyWithSessionsdiff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-search-trigger.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-search-trigger.tsxindex fb2d56250..6f9ff19b2 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-search-trigger.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-search-trigger.tsx@@ -1,6 +1,5 @@import { Search } from 'lucide-react';import { observer } from 'mobx-react-lite';-import { getSessionStore } from '@renderer/features/sessions/stores/session-selectors';import { useParams, useWorkspaceSlots } from '@renderer/lib/layout/navigation-provider';import { useShowModal } from '@renderer/lib/modal/modal-provider';import { BoundShortcut } from '@renderer/lib/ui/shortcut';@@ -10,29 +9,23 @@ export const SidebarSearchTrigger = observer(function SidebarSearchTrigger() {const showCommandPalette = useShowModal('commandPaletteModal');const { currentView } = useWorkspaceSlots();const { params: sessionParams } = useParams('session');- const { params: projectParams } = useParams('project');+ const { params: locationParams } = useParams('location');- const currentProjectId =+ const currentLocationId =currentView === 'session'- ? sessionParams.projectId- : currentView === 'project'- ? projectParams.projectId+ ? sessionParams.locationId+ : currentView === 'location'+ ? locationParams.locationId: undefined;const currentSessionId = currentView === 'session' ? sessionParams.sessionId : undefined;- const currentWorkspaceId =- currentProjectId && currentSessionId- ? (getSessionStore(currentProjectId, currentSessionId)?.workspaceId ?? undefined)- : undefined;-return (<SidebarMenuButtonisActive={false}onClick={() =>showCommandPalette({- projectId: currentProjectId,+ locationId: currentLocationId,sessionId: currentSessionId,- workspaceId: currentWorkspaceId,})}aria-label="Search"diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-store.test.ts b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-store.test.tsindex ee75607a4..516b909f4 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-store.test.ts+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-store.test.ts@@ -1,6 +1,7 @@import { afterEach, describe, expect, it, vi } from 'vitest';-import { agentsStore } from '@renderer/features/projects/stores/agents-store';+import { agentsStore } from '@renderer/features/locations/stores/agents-store';import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';+import type { AgentConnectionKind } from '@shared/core/agents/agent-connection';import type { Agent } from '@shared/core/agents/agents';import {agentRoomGroupKey,@@ -9,7 +10,7 @@ import {SidebarStore,} from './sidebar-store';-type SidebarProjectManager = ConstructorParameters<typeof SidebarStore>[0];+type SidebarLocationManager = ConstructorParameters<typeof SidebarStore>[0];vi.mock('@renderer/lib/ipc', () => ({events: {@@ -22,10 +23,10 @@ vi.mock('@renderer/lib/stores/app-state', () => ({appState: {},}));-function projectManager(projects: { id: string; createdAt: string }[]): SidebarProjectManager {+function locationManager(locations: { id: string; createdAt: string }[]): SidebarLocationManager {return {- projects: new Map(projects.map((p) => [p.id, { ...p, mountedProject: null }])),- } as unknown as SidebarProjectManager;+ locations: new Map(locations.map((p) => [p.id, { ...p, mountedLocation: null }])),+ } as unknown as SidebarLocationManager;}function session(id: string, createdAt: string) {@@ -41,20 +42,20 @@ function session(id: string, createdAt: string) {};}-function projectManagerWithSessions(- projects: { id: string; createdAt: string; sessionIds: string[] }[]-): SidebarProjectManager {+function locationManagerWithSessions(+ locations: { id: string; createdAt: string; sessionIds: string[] }[]+): SidebarLocationManager {return {- projects: new Map(- projects.map((project) => [- project.id,+ locations: new Map(+ locations.map((location) => [+ location.id,{- id: project.id,- createdAt: project.createdAt,- mountedProject: {+ id: location.id,+ createdAt: location.createdAt,+ mountedLocation: {sessionManager: {sessions: new Map(- project.sessionIds.map((sessionId, index) => [+ location.sessionIds.map((sessionId, index) => [sessionId,session(sessionId, `2026-01-01T00:00:0${index}.000Z`),])@@ -64,72 +65,72 @@ function projectManagerWithSessions(},])),- } as unknown as SidebarProjectManager;+ } as unknown as SidebarLocationManager;}-describe('SidebarStore project ordering', () => {- it('sorts projects newest first by default', () => {+describe('SidebarStore location ordering', () => {+ it('sorts locations newest first by default', () => {const store = new SidebarStore(- projectManager([+ locationManager([{ id: 'old', createdAt: '2026-01-01T00:00:00.000Z' },{ id: 'new', createdAt: '2026-01-02T00:00:00.000Z' },]));- expect(store.orderedProjects.map((project) => project.id)).toEqual(['new', 'old']);+ expect(store.orderedLocations.map((location) => location.id)).toEqual(['new', 'old']);});- it('places projects missing from a saved manual order first', () => {+ it('places locations missing from a saved manual order first', () => {const store = new SidebarStore(- projectManager([+ locationManager([{ id: 'old', createdAt: '2026-01-01T00:00:00.000Z' },{ id: 'manual', createdAt: '2026-01-02T00:00:00.000Z' },{ id: 'new', createdAt: '2026-01-03T00:00:00.000Z' },]));- store.setProjectOrder(['manual', 'old']);+ store.setLocationOrder(['manual', 'old']);- expect(store.orderedProjects.map((project) => project.id)).toEqual(['new', 'manual', 'old']);+ expect(store.orderedLocations.map((location) => location.id)).toEqual(['new', 'manual', 'old']);});- it('returns visible session entries in rendered project-tree order', () => {+ it('returns visible session entries in rendered location-tree order', () => {const store = new SidebarStore(- projectManagerWithSessions([+ locationManagerWithSessions([{- id: 'project-1',+ id: 'location-1',createdAt: '2026-01-01T00:00:00.000Z',sessionIds: ['session-1a', 'session-1b'],},{- id: 'project-2',+ id: 'location-2',createdAt: '2026-01-02T00:00:00.000Z',sessionIds: ['session-2a'],},]));- store.setProjectOrder(['project-1', 'project-2']);- store.ensureProjectExpanded('project-1');- store.ensureProjectExpanded('project-2');- store.setSessionOrder('project-1', ['session-1a', 'session-1b']);+ store.setLocationOrder(['location-1', 'location-2']);+ store.ensureLocationExpanded('location-1');+ store.ensureLocationExpanded('location-2');+ store.setSessionOrder('location-1', ['session-1a', 'session-1b']);expect(store.visibleSessionEntries).toEqual([- { projectId: 'project-1', sessionId: 'session-1a' },- { projectId: 'project-1', sessionId: 'session-1b' },- { projectId: 'project-2', sessionId: 'session-2a' },+ { locationId: 'location-1', sessionId: 'session-1a' },+ { locationId: 'location-1', sessionId: 'session-1b' },+ { locationId: 'location-2', sessionId: 'session-2a' },]);});});describe('SidebarStore grouping', () => {it('defaults to agent grouping', () => {- const store = new SidebarStore(projectManager([]));+ const store = new SidebarStore(locationManager([]));expect(store.grouping).toBe('agent');});it('round-trips grouping and expanded room keys through the snapshot', () => {- const store = new SidebarStore(projectManager([]));+ const store = new SidebarStore(locationManager([]));store.setGrouping('room');store.ensureRoomExpanded('room-1');store.toggleRoomExpanded('room-2');@@ -138,7 +139,7 @@ describe('SidebarStore grouping', () => {expect(snapshot.grouping).toBe('room');expect(snapshot.expandedRoomKeys?.sort()).toEqual(['room-1', 'room-2']);- const restored = new SidebarStore(projectManager([]));+ const restored = new SidebarStore(locationManager([]));restored.restoreSnapshot(snapshot);expect(restored.grouping).toBe('room');expect(restored.expandedRoomKeys.has('room-1')).toBe(true);@@ -146,25 +147,25 @@ describe('SidebarStore grouping', () => {});it('reveals a session in its room across both layouts', () => {- const store = new SidebarStore(projectManager([]));+ const store = new SidebarStore(locationManager([]));// Simulate the user having collapsed the room group in each layout.- store.toggleGroupExpanded(agentRoomGroupKey('project-1', 'room-1'));+ store.toggleGroupExpanded(agentRoomGroupKey('location-1', 'room-1'));store.toggleGroupExpanded(roomViewGroupKey('room-1'));- expect(store.isGroupExpanded(agentRoomGroupKey('project-1', 'room-1'))).toBe(false);+ expect(store.isGroupExpanded(agentRoomGroupKey('location-1', 'room-1'))).toBe(false);expect(store.isGroupExpanded(roomViewGroupKey('room-1'))).toBe(false);- store.revealSessionInRoom('project-1', 'room-1');+ store.revealSessionInRoom('location-1', 'room-1');- expect(store.expandedProjectIds.has('project-1')).toBe(true);- expect(store.isGroupExpanded(agentRoomGroupKey('project-1', 'room-1'))).toBe(true);+ expect(store.expandedLocationIds.has('location-1')).toBe(true);+ expect(store.isGroupExpanded(agentRoomGroupKey('location-1', 'room-1'))).toBe(true);expect(store.isGroupExpanded(roomViewGroupKey('room-1'))).toBe(true);});- it("returns a project's visible sessions for grouped views", () => {+ it("returns a location's visible sessions for grouped views", () => {const store = new SidebarStore(- projectManagerWithSessions([+ locationManagerWithSessions([{- id: 'project-1',+ id: 'location-1',createdAt: '2026-01-01T00:00:00.000Z',sessionIds: ['session-1a', 'session-1b'],},@@ -173,27 +174,27 @@ describe('SidebarStore grouping', () => {expect(store- .visibleSessionsForProject('project-1')+ .visibleSessionsForLocation('location-1').map((s) => s.data.id).sort()).toEqual(['session-1a', 'session-1b']);- expect(store.visibleSessionsForProject('missing')).toEqual([]);+ expect(store.visibleSessionsForLocation('missing')).toEqual([]);});});describe('SidebarStore active-server scoping', () => {- function linkAgent(projectId: string, serverId: string | null) {- agentsStore.byProject.set(projectId, [{ projectId, serverId } as Agent]);+ function linkAgent(locationId: string, serverId: string | null) {+ agentsStore.byLocation.set(locationId, [{ locationId, serverId } as Agent]);}afterEach(() => {switchServersStore.activeServerId = null;- agentsStore.byProject.clear();+ agentsStore.byLocation.clear();});- it("shows only the active server's projects", () => {+ it("shows only the active server's locations", () => {const store = new SidebarStore(- projectManager([+ locationManager([{ id: 'a', createdAt: '2026-01-01T00:00:00.000Z' },{ id: 'b', createdAt: '2026-01-02T00:00:00.000Z' },])@@ -202,13 +203,13 @@ describe('SidebarStore active-server scoping', () => {linkAgent('b', 'server-2');switchServersStore.activeServerId = 'server-1';- expect(store.orderedProjects.map((p) => p.id)).toEqual(['a']);+ expect(store.orderedLocations.map((p) => p.id)).toEqual(['a']);expect(store.isEmpty).toBe(false);});- it('shows all projects when no server is active', () => {+ it('shows all locations when no server is active', () => {const store = new SidebarStore(- projectManager([+ locationManager([{ id: 'a', createdAt: '2026-01-01T00:00:00.000Z' },{ id: 'b', createdAt: '2026-01-02T00:00:00.000Z' },])@@ -216,17 +217,17 @@ describe('SidebarStore active-server scoping', () => {linkAgent('a', 'server-1');linkAgent('b', 'server-2');- expect(store.orderedProjects.map((p) => p.id).sort()).toEqual(['a', 'b']);+ expect(store.orderedLocations.map((p) => p.id).sort()).toEqual(['a', 'b']);});- it('hides unlinked projects when a server is active', () => {+ it('hides unlinked locations when a server is active', () => {const store = new SidebarStore(- projectManager([{ id: 'a', createdAt: '2026-01-01T00:00:00.000Z' }])+ locationManager([{ id: 'a', createdAt: '2026-01-01T00:00:00.000Z' }]));linkAgent('a', null);switchServersStore.activeServerId = 'server-1';- expect(store.orderedProjects).toEqual([]);+ expect(store.orderedLocations).toEqual([]);expect(store.isEmpty).toBe(true);});});@@ -234,22 +235,35 @@ describe('SidebarStore active-server scoping', () => {describe('SidebarStore filters', () => {type SessionState = 'provisioned' | 'unprovisioned' | 'unregistered';- function filterProjectManager(- projects: { id: string; createdAt: string; sessionStates?: SessionState[] }[]- ): SidebarProjectManager {+ function filterLocationManager(+ locations: {+ id: string;+ createdAt: string;+ sessionStates?: SessionState[];+ sshHost?: string | null;+ }[]+ ): SidebarLocationManager {return {- projects: new Map(- projects.map((project) => [- project.id,+ locations: new Map(+ locations.map((location) => [+ location.id,{- id: project.id,- createdAt: project.createdAt,- mountedProject: project.sessionStates+ id: location.id,+ createdAt: location.createdAt,+ data: {+ id: location.id,+ name: location.id,+ sshHost: location.sshHost ?? null,+ dir: `/repo/${location.id}`,+ createdAt: location.createdAt,+ updatedAt: location.createdAt,+ },+ mountedLocation: location.sessionStates? {sessionManager: {sessions: new Map(- project.sessionStates.map((state, index) => {- const id = `${project.id}-s${index}`;+ location.sessionStates.map((state, index) => {+ const id = `${location.id}-s${index}`;return [id,{@@ -257,8 +271,8 @@ describe('SidebarStore filters', () => {data: {id,isPinned: false,- createdAt: project.createdAt,- updatedAt: project.createdAt,+ createdAt: location.createdAt,+ updatedAt: location.createdAt,},},];@@ -270,49 +284,44 @@ describe('SidebarStore filters', () => {},])),- } as unknown as SidebarProjectManager;+ } as unknown as SidebarLocationManager;}- function linkAgent(- projectId: string,- fields: { connection?: Agent['connection']; providerId?: Agent['providerId'] }- ) {- agentsStore.byProject.set(projectId, [{ projectId, serverId: null, ...fields } as Agent]);+ function linkAgent(locationId: string, fields: { providerId?: Agent['providerId'] }) {+ agentsStore.byLocation.set(locationId, [{ locationId, serverId: null, ...fields } as Agent]);}afterEach(() => {- agentsStore.byProject.clear();+ agentsStore.byLocation.clear();switchServersStore.activeServerId = null;});- it('returns all projects unfiltered when no filter is active', () => {+ it('returns all locations unfiltered when no filter is active', () => {const store = new SidebarStore(- filterProjectManager([+ filterLocationManager([{ id: 'a', createdAt: '2026-01-01T00:00:00.000Z' },{ id: 'b', createdAt: '2026-01-02T00:00:00.000Z' },]));expect(store.hasActiveFilters).toBe(false);- expect(store.filteredProjects).toEqual(store.orderedProjects);+ expect(store.filteredLocations).toEqual(store.orderedLocations);});it('filters by run location', () => {const store = new SidebarStore(- filterProjectManager([- { id: 'local-agent', createdAt: '2026-01-01T00:00:00.000Z' },- { id: 'remote-agent', createdAt: '2026-01-02T00:00:00.000Z' },+ filterLocationManager([+ { id: 'local-agent', createdAt: '2026-01-01T00:00:00.000Z', sshHost: null },+ { id: 'remote-agent', createdAt: '2026-01-02T00:00:00.000Z', sshHost: 'vm' },]));- linkAgent('local-agent', { connection: 'local' });- linkAgent('remote-agent', { connection: 'remote' });store.toggleFilterConnection('remote');- expect(store.filteredProjects.map((p) => p.id)).toEqual(['remote-agent']);+ expect(store.filteredLocations.map((p) => p.id)).toEqual(['remote-agent']);});it('filters by agent type, OR-ing selections within the dimension', () => {const store = new SidebarStore(- filterProjectManager([+ filterLocationManager([{ id: 'claude-agent', createdAt: '2026-01-01T00:00:00.000Z' },{ id: 'opencode-agent', createdAt: '2026-01-02T00:00:00.000Z' },{ id: 'codex-agent', createdAt: '2026-01-03T00:00:00.000Z' },@@ -324,7 +333,7 @@ describe('SidebarStore filters', () => {store.toggleFilterProviderId('claude');store.toggleFilterProviderId('opencode');- expect(store.filteredProjects.map((p) => p.id).sort()).toEqual([+ expect(store.filteredLocations.map((p) => p.id).sort()).toEqual(['claude-agent','opencode-agent',]);@@ -332,7 +341,7 @@ describe('SidebarStore filters', () => {it('filters by presence of a running (provisioned) session', () => {const store = new SidebarStore(- filterProjectManager([+ filterLocationManager([{ id: 'running', createdAt: '2026-01-01T00:00:00.000Z', sessionStates: ['provisioned'] },{ id: 'idle', createdAt: '2026-01-02T00:00:00.000Z', sessionStates: ['unprovisioned'] },{ id: 'none', createdAt: '2026-01-03T00:00:00.000Z' },@@ -340,54 +349,54 @@ describe('SidebarStore filters', () => {);store.setFilterHasLiveSession(true);- expect(store.filteredProjects.map((p) => p.id)).toEqual(['running']);+ expect(store.filteredLocations.map((p) => p.id)).toEqual(['running']);});- it('composes dimensions with AND across, keeping only projects that match all', () => {+ it('composes dimensions with AND across, keeping only locations that match all', () => {const store = new SidebarStore(- filterProjectManager([+ filterLocationManager([{id: 'remote-running',createdAt: '2026-01-01T00:00:00.000Z',sessionStates: ['provisioned'],+ sshHost: 'vm',},{id: 'remote-idle',createdAt: '2026-01-02T00:00:00.000Z',sessionStates: ['unprovisioned'],+ sshHost: 'vm',},{id: 'local-running',createdAt: '2026-01-03T00:00:00.000Z',sessionStates: ['provisioned'],+ sshHost: null,},]));- linkAgent('remote-running', { connection: 'remote' });- linkAgent('remote-idle', { connection: 'remote' });- linkAgent('local-running', { connection: 'local' });store.toggleFilterConnection('remote');store.setFilterHasLiveSession(true);- expect(store.filteredProjects.map((p) => p.id)).toEqual(['remote-running']);+ expect(store.filteredLocations.map((p) => p.id)).toEqual(['remote-running']);});it('offers only filter values present among in-scope agents', () => {const store = new SidebarStore(- filterProjectManager([+ filterLocationManager([{ id: 'a', createdAt: '2026-01-01T00:00:00.000Z' },{ id: 'b', createdAt: '2026-01-02T00:00:00.000Z' },]));- linkAgent('a', { connection: 'local', providerId: 'claude' });- linkAgent('b', { connection: 'local', providerId: 'opencode' });+ linkAgent('a', { providerId: 'claude' });+ linkAgent('b', { providerId: 'opencode' });expect(store.availableFilterConnections).toEqual(['local']);expect(store.availableFilterProviderIds).toEqual(['claude', 'opencode']);});it('clears every filter dimension', () => {- const store = new SidebarStore(filterProjectManager([]));+ const store = new SidebarStore(filterLocationManager([]));store.toggleFilterConnection('remote');store.toggleFilterProviderId('claude');store.setFilterHasLiveSession(true);@@ -401,7 +410,7 @@ describe('SidebarStore filters', () => {});it('round-trips filters through the snapshot, dropping invalid values', () => {- const store = new SidebarStore(filterProjectManager([]));+ const store = new SidebarStore(filterLocationManager([]));store.toggleFilterConnection('remote');store.toggleFilterProviderId('claude');store.setFilterHasLiveSession(true);@@ -411,10 +420,10 @@ describe('SidebarStore filters', () => {expect(snapshot.filterProviderIds).toEqual(['claude']);expect(snapshot.filterHasLiveSession).toBe(true);- const restored = new SidebarStore(filterProjectManager([]));+ const restored = new SidebarStore(filterLocationManager([]));restored.restoreSnapshot({...snapshot,- filterConnections: [...(snapshot.filterConnections ?? []), 'bogus' as Agent['connection']],+ filterConnections: [...(snapshot.filterConnections ?? []), 'bogus' as AgentConnectionKind],filterProviderIds: [...(snapshot.filterProviderIds ?? []), 'nope' as Agent['providerId']],});expect([...restored.filterConnections]).toEqual(['remote']);@@ -450,7 +459,7 @@ describe('applyManualOrder', () => {describe('SidebarStore grouped-view ordering', () => {it('orders top-level room keys by the saved manual room order', () => {- const store = new SidebarStore(projectManager([]));+ const store = new SidebarStore(locationManager([]));store.setRoomOrder(['room-c', 'room-a']);// Saved rooms come first in saved order; unknown rooms append.expect(store.orderRoomKeys(['room-a', 'room-b', 'room-c'])).toEqual([@@ -461,7 +470,7 @@ describe('SidebarStore grouped-view ordering', () => {});it('orders a sub-group by its saved order, surfacing new sessions first', () => {- const store = new SidebarStore(projectManager([]));+ const store = new SidebarStore(locationManager([]));const sessions = [{ id: 's1' }, { id: 's2' }, { id: 's3' }];store.setGroupOrder('as:p1|room-1', ['s2', 's1']);expect(store.orderGroupItems('as:p1|room-1', sessions, (s) => s.id, true)).toEqual([@@ -472,7 +481,7 @@ describe('SidebarStore grouped-view ordering', () => {});it('round-trips room and group order through the snapshot', () => {- const store = new SidebarStore(projectManager([]));+ const store = new SidebarStore(locationManager([]));store.setRoomOrder(['room-2', 'room-1']);store.setGroupOrder('as:p1|room-1', ['s2', 's1']);@@ -480,7 +489,7 @@ describe('SidebarStore grouped-view ordering', () => {expect(snapshot.roomOrder).toEqual(['room-2', 'room-1']);expect(snapshot.groupOrder).toEqual({ 'as:p1|room-1': ['s2', 's1'] });- const restored = new SidebarStore(projectManager([]));+ const restored = new SidebarStore(locationManager([]));restored.restoreSnapshot(snapshot);expect(restored.roomOrder).toEqual(['room-2', 'room-1']);expect(restored.groupOrder).toEqual({ 'as:p1|room-1': ['s2', 's1'] });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 fa8331539..011099cbc 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@@ -1,7 +1,7 @@import { computed, makeAutoObservable, observable, reaction, runInAction } from 'mobx';-import { agentsStore } from '@renderer/features/projects/stores/agents-store';-import { type ProjectStore } from '@renderer/features/projects/stores/project';-import type { ProjectManagerStore } from '@renderer/features/projects/stores/project-manager';+import { agentsStore } from '@renderer/features/locations/stores/agents-store';+import { type LocationStore } from '@renderer/features/locations/stores/location';+import type { LocationManagerStore } from '@renderer/features/locations/stores/location-manager';import {isProvisioned,registeredSessionData,@@ -41,8 +41,8 @@ export function depthIndent(depth: number): { paddingLeft: number } {}/** `collapsedGroupKeys` key for a room nested under an agent (agent-focused view). */-export function agentRoomGroupKey(projectId: string, roomKey: string): string {- return `ar:${projectId}|${roomKey}`;+export function agentRoomGroupKey(locationId: string, roomKey: string): string {+ return `ar:${locationId}|${roomKey}`;}/** `collapsedGroupKeys` key for a room header in the room-focused view. */@@ -79,8 +79,8 @@ export function getSortInstant(session: SessionStore, kind: SessionSortKind): st}export type SidebarRow =- | { kind: 'project'; projectId: string }- | { kind: 'session'; projectId: string; sessionId: string };+ | { kind: 'location'; locationId: string }+ | { kind: 'session'; locationId: string; sessionId: string };/*** Reorder `items` to honour a saved manual order. Items present in `stored`@@ -110,13 +110,13 @@ export function applyManualOrder<T>(}export class SidebarStore implements Snapshottable<SidebarSnapshot> {- projectOrder: string[] = [];- sessionOrderByProject: Record<string, string[]> = {};+ locationOrder: string[] = [];+ sessionOrderByLocation: Record<string, string[]> = {};/** Manual order of top-level rooms (room-focused grouping). */roomOrder: string[] = [];/** Manual order of items within a grouped-view sub-group, keyed by container id. */groupOrder: Record<string, string[]> = {};- expandedProjectIds = observable.set<string>();+ expandedLocationIds = observable.set<string>();sessionSortBy: SidebarSessionSortBy = 'created-at';grouping: SidebarGrouping = 'agent';expandedRoomKeys = observable.set<string>();@@ -132,26 +132,26 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {filterProviderIds = observable.set<AgentProviderId>();filterHasLiveSession = false;- constructor(private readonly projectManager: ProjectManagerStore) {+ constructor(private readonly locationManager: LocationManagerStore) {makeAutoObservable(this, {- expandedProjectIds: false,+ expandedLocationIds: false,expandedRoomKeys: false,collapsedGroupKeys: false,filterConnections: false,filterProviderIds: false,sidebarRows: computed,pinnedSidebarEntries: computed,- filteredProjects: computed,+ filteredLocations: computed,});- // Auto-expand a project when its session count goes from 0 to >0.+ // Auto-expand a location when its session count goes from 0 to >0.const prevSessionCounts = new Map<string, number>();reaction(() => {const counts: [string, number][] = [];- for (const [id, project] of this.projectManager.projects) {- if (project.mountedProject) {- counts.push([id, project.mountedProject.sessionManager.sessions.size]);+ for (const [id, location] of this.locationManager.locations) {+ if (location.mountedLocation) {+ counts.push([id, location.mountedLocation.sessionManager.sessions.size]);}}return counts;@@ -161,7 +161,7 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {for (const [id, count] of counts) {const prev = prevSessionCounts.get(id) ?? 0;if (prev === 0 && count > 0) {- this.ensureProjectExpanded(id);+ this.ensureLocationExpanded(id);}prevSessionCounts.set(id, count);}@@ -171,55 +171,57 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {}/**- * Whether a project belongs to the active server. The whole sidebar tree is- * scoped to one server at a time: a project shows only when its agents are- * linked to {@link switchServersStore.activeServerId}. Unregistered projects+ * Whether a location belongs to the active server. The whole sidebar tree is+ * scoped to one server at a time: a location shows only when its agents are+ * linked to {@link switchServersStore.activeServerId}. Unregistered locations* (mid-onboarding, no agent row yet) always show so the user sees progress.* When no server is active, nothing is hidden.*/- isProjectInActiveScope(projectId: string): boolean {+ isLocationInActiveScope(locationId: string): boolean {const activeServerId = switchServersStore.activeServerId;if (!activeServerId) return true;- const project = this.projectManager.projects.get(projectId);- if (project && project.state === 'unregistered') return true;- return agentsStore.serverIdForProject(projectId) === activeServerId;+ const location = this.locationManager.locations.get(locationId);+ if (location && location.state === 'unregistered') return true;+ return agentsStore.serverIdForLocation(locationId) === activeServerId;}- get orderedProjects(): ProjectStore[] {- const all = Array.from(this.projectManager.projects.values()).filter((project) =>- this.isProjectInActiveScope(project.id)+ get orderedLocations(): LocationStore[] {+ const all = Array.from(this.locationManager.locations.values()).filter((location) =>+ this.isLocationInActiveScope(location.id));return [...all].sort((a, b) => {- const ai = this.projectOrder.indexOf(a.id);- const bi = this.projectOrder.indexOf(b.id);- if (ai === -1 && bi === -1) return this.compareSidebarProjects(a, b);+ const ai = this.locationOrder.indexOf(a.id);+ const bi = this.locationOrder.indexOf(b.id);+ if (ai === -1 && bi === -1) return this.compareSidebarLocations(a, b);if (ai === -1) return -1;if (bi === -1) return 1;return ai - bi;});}- /** The parent agent of a project (the agent shown on its sidebar row). */- private parentAgent(projectId: string) {- return agentsStore.byProject.get(projectId)?.[0];+ /** The parent agent of a location (the agent shown on its sidebar row). */+ private parentAgent(locationId: string) {+ return agentsStore.byLocation.get(locationId)?.[0];}- /** Where a project's agent runs, or null when its agent is not yet known. */- projectConnection(projectId: string): AgentConnectionKind | null {- return this.parentAgent(projectId)?.connection ?? null;+ /** Where a location runs — `remote` when it has an SSH host, else `local`. */+ locationConnection(locationId: string): AgentConnectionKind | null {+ const location = this.locationManager.locations.get(locationId)?.data;+ if (!location) return null;+ return location.sshHost !== null ? 'remote' : 'local';}- /** A project's agent-type provider, or null when its agent is not yet known. */- projectProviderId(projectId: string): AgentProviderId | null {- return this.parentAgent(projectId)?.providerId ?? null;+ /** A location's agent-type provider, or null when its agent is not yet known. */+ locationProviderId(locationId: string): AgentProviderId | null {+ return this.parentAgent(locationId)?.providerId ?? null;}- /** Whether a project has at least one running (provisioned) session. */- projectHasLiveSession(projectId: string): boolean {- const project = this.projectManager.projects.get(projectId);- if (!project?.mountedProject) return false;- for (const session of project.mountedProject.sessionManager.sessions.values()) {+ /** Whether a location has at least one running (provisioned) session. */+ locationHasLiveSession(locationId: string): boolean {+ const location = this.locationManager.locations.get(locationId);+ if (!location?.mountedLocation) return false;+ for (const session of location.mountedLocation.sessionManager.sessions.values()) {if (isProvisioned(session)) return true;}return false;@@ -234,48 +236,48 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {);}- /** A project passes when it satisfies every active filter dimension. */- private projectMatchesFilters(projectId: string): boolean {+ /** A location passes when it satisfies every active filter dimension. */+ private locationMatchesFilters(locationId: string): boolean {if (this.filterConnections.size > 0) {- const connection = this.projectConnection(projectId);+ const connection = this.locationConnection(locationId);if (!connection || !this.filterConnections.has(connection)) return false;}if (this.filterProviderIds.size > 0) {- const providerId = this.projectProviderId(projectId);+ const providerId = this.locationProviderId(locationId);if (!providerId || !this.filterProviderIds.has(providerId)) return false;}- if (this.filterHasLiveSession && !this.projectHasLiveSession(projectId)) return false;+ if (this.filterHasLiveSession && !this.locationHasLiveSession(locationId)) return false;return true;}/**- * Server-scoped, ordered projects with the active sidebar filters applied. The+ * Server-scoped, ordered locations with the active sidebar filters applied. The* grouped sidebar trees render from this; when no filter is active it equals- * {@link orderedProjects}.+ * {@link orderedLocations}.*/- get filteredProjects(): ProjectStore[] {- if (!this.hasActiveFilters) return this.orderedProjects;- return this.orderedProjects.filter((project) => this.projectMatchesFilters(project.id));+ get filteredLocations(): LocationStore[] {+ if (!this.hasActiveFilters) return this.orderedLocations;+ return this.orderedLocations.filter((location) => this.locationMatchesFilters(location.id));}/**- * Run-location values present among the in-scope projects' agents, so the+ * Run-location values present among the in-scope locations' agents, so the* filter menu only offers dimensions that actually match something.*/get availableFilterConnections(): AgentConnectionKind[] {const present = new Set<AgentConnectionKind>();- for (const project of this.orderedProjects) {- const connection = this.projectConnection(project.id);+ for (const location of this.orderedLocations) {+ const connection = this.locationConnection(location.id);if (connection) present.add(connection);}return AGENT_CONNECTION_KINDS.filter((kind) => present.has(kind));}- /** Agent-type providers present among the in-scope projects' agents. */+ /** Agent-type providers present among the in-scope locations' agents. */get availableFilterProviderIds(): AgentProviderId[] {const present = new Set<AgentProviderId>();- for (const project of this.orderedProjects) {- const providerId = this.projectProviderId(project.id);+ for (const location of this.orderedLocations) {+ const providerId = this.locationProviderId(location.id);if (providerId) present.add(providerId);}return AGENT_PROVIDER_IDS.filter((id) => present.has(id));@@ -283,81 +285,83 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {get sidebarRows(): SidebarRow[] {const rows: SidebarRow[] = [];- for (const project of this.orderedProjects) {- const projectId = project.id;- rows.push({ kind: 'project', projectId });- if (this.expandedProjectIds.has(projectId) && project.mountedProject) {- const sessions = Array.from(project.mountedProject.sessionManager.sessions.values()).filter(+ for (const location of this.orderedLocations) {+ const locationId = location.id;+ rows.push({ kind: 'location', locationId });+ if (this.expandedLocationIds.has(locationId) && location.mountedLocation) {+ const sessions = Array.from(+ location.mountedLocation.sessionManager.sessions.values()+ ).filter((t) => t.state === 'unregistered' || !('archivedAt' in t.data && t.data.archivedAt));- const manualOrder = this.sessionOrderByProject[projectId];+ const manualOrder = this.sessionOrderByLocation[locationId];const ordered = manualOrder?.length- ? this.mergeSessionOrder(projectId, sessions)+ ? this.mergeSessionOrder(locationId, sessions): this.sortSessionsForSidebar(sessions);for (const session of ordered) {if (session.data.isPinned) continue;- rows.push({ kind: 'session', projectId, sessionId: session.data.id });+ rows.push({ kind: 'session', locationId, sessionId: session.data.id });}}}return rows;}- /** Visible unpinned sessions in the same order they are rendered in the project tree. */- get visibleSessionEntries(): { projectId: string; sessionId: string }[] {+ /** Visible unpinned sessions in the same order they are rendered in the location tree. */+ get visibleSessionEntries(): { locationId: string; sessionId: string }[] {return this.sidebarRows.filter((row): row is Extract<SidebarRow, { kind: 'session' }> => row.kind === 'session')- .map(({ projectId, sessionId }) => ({ projectId, sessionId }));+ .map(({ locationId, sessionId }) => ({ locationId, sessionId }));}- /** Flat list of pinned sessions (all mounted projects), same sort rules as project tree sessions. */- get pinnedSidebarEntries(): { projectId: string; sessionId: string }[] {- const pairs: { projectId: string; session: SessionStore }[] = [];- for (const project of this.projectManager.projects.values()) {- if (!project.mountedProject) continue;- if (!this.isProjectInActiveScope(project.id)) continue;- const projectId = project.id;- for (const session of project.mountedProject.sessionManager.sessions.values()) {+ /** Flat list of pinned sessions (all mounted locations), same sort rules as location tree sessions. */+ get pinnedSidebarEntries(): { locationId: string; sessionId: string }[] {+ const pairs: { locationId: string; session: SessionStore }[] = [];+ for (const location of this.locationManager.locations.values()) {+ if (!location.mountedLocation) continue;+ if (!this.isLocationInActiveScope(location.id)) continue;+ const locationId = location.id;+ for (const session of location.mountedLocation.sessionManager.sessions.values()) {const visible =session.state === 'unregistered' ||!('archivedAt' in session.data && session.data.archivedAt);if (!visible || !session.data.isPinned) continue;- pairs.push({ projectId, session });+ pairs.push({ locationId, session });}}pairs.sort((a, b) => this.compareSidebarSessions(a.session, b.session));- return pairs.map(({ projectId, session }) => ({ projectId, sessionId: session.data.id }));+ return pairs.map(({ locationId, session }) => ({ locationId, sessionId: session.data.id }));}/**- * Visible unpinned session IDs for a project in sidebar order. Archived sessions are+ * Visible unpinned session IDs for a location in sidebar order. Archived sessions are* and automation sessions are excluded. Independent of expand state so Next/Previous- * Session navigation works even when the project is collapsed.+ * Session navigation works even when the location is collapsed.*/- visibleSessionIdsForProject(projectId: string): string[] {- const project = this.projectManager.projects.get(projectId);- if (!project?.mountedProject) return [];- const sessions = Array.from(project.mountedProject.sessionManager.sessions.values()).filter(+ visibleSessionIdsForLocation(locationId: string): string[] {+ const location = this.locationManager.locations.get(locationId);+ if (!location?.mountedLocation) return [];+ const sessions = Array.from(location.mountedLocation.sessionManager.sessions.values()).filter((t) =>!t.data.isPinned &&(t.state === 'unregistered' || !('archivedAt' in t.data && t.data.archivedAt)));- const manualOrder = this.sessionOrderByProject[projectId];+ const manualOrder = this.sessionOrderByLocation[locationId];const ordered = manualOrder?.length- ? this.mergeSessionOrder(projectId, sessions)+ ? this.mergeSessionOrder(locationId, sessions): this.sortSessionsForSidebar(sessions);return ordered.map((t) => t.data.id);}/**- * Visible (non-archived, non-pinned) sessions for a project, sorted by the+ * Visible (non-archived, non-pinned) sessions for a location, sorted by the* current sidebar sort. Used by the grouped (agent/room) sidebar views, which* sort by recency rather than honouring manual drag order.*/- visibleSessionsForProject(projectId: string): SessionStore[] {- const project = this.projectManager.projects.get(projectId);- if (!project?.mountedProject) return [];- const sessions = Array.from(project.mountedProject.sessionManager.sessions.values()).filter(+ visibleSessionsForLocation(locationId: string): SessionStore[] {+ const location = this.locationManager.locations.get(locationId);+ if (!location?.mountedLocation) return [];+ const sessions = Array.from(location.mountedLocation.sessionManager.sessions.values()).filter((t) =>!t.data.isPinned &&(t.state === 'unregistered' || !('archivedAt' in t.data && t.data.archivedAt))@@ -366,14 +370,14 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {}get isEmpty(): boolean {- return this.orderedProjects.length === 0;+ return this.orderedLocations.length === 0;}get snapshot(): SidebarSnapshot {return {- expandedProjectIds: [...this.expandedProjectIds],- projectOrder: [...this.projectOrder],- sessionOrderByProject: { ...this.sessionOrderByProject },+ expandedLocationIds: [...this.expandedLocationIds],+ locationOrder: [...this.locationOrder],+ sessionOrderByLocation: { ...this.sessionOrderByLocation },sessionSortBy: this.sessionSortBy,grouping: this.grouping,expandedRoomKeys: [...this.expandedRoomKeys],@@ -387,14 +391,14 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {}restoreSnapshot(snapshot: Partial<SidebarSnapshot>): void {- if (snapshot.expandedProjectIds !== undefined) {- this.expandedProjectIds.replace(snapshot.expandedProjectIds);+ if (snapshot.expandedLocationIds !== undefined) {+ this.expandedLocationIds.replace(snapshot.expandedLocationIds);}- if (snapshot.projectOrder !== undefined) {- this.projectOrder = [...snapshot.projectOrder];+ if (snapshot.locationOrder !== undefined) {+ this.locationOrder = [...snapshot.locationOrder];}- if (snapshot.sessionOrderByProject !== undefined) {- this.sessionOrderByProject = { ...snapshot.sessionOrderByProject };+ if (snapshot.sessionOrderByLocation !== undefined) {+ this.sessionOrderByLocation = { ...snapshot.sessionOrderByLocation };}if (snapshot.sessionSortBy !== undefined) {const v = parseSidebarSessionSortBy(snapshot.sessionSortBy);@@ -425,23 +429,23 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {}}- /** Called on first load when no snapshot exists — expand all known projects. */- expandAllProjects(): void {- for (const project of this.orderedProjects) {- this.expandedProjectIds.add(project.id);+ /** Called on first load when no snapshot exists — expand all known locations. */+ expandAllLocations(): void {+ for (const location of this.orderedLocations) {+ this.expandedLocationIds.add(location.id);}}- toggleProjectExpanded(projectId: string): void {- if (this.expandedProjectIds.has(projectId)) {- this.expandedProjectIds.delete(projectId);+ toggleLocationExpanded(locationId: string): void {+ if (this.expandedLocationIds.has(locationId)) {+ this.expandedLocationIds.delete(locationId);} else {- this.expandedProjectIds.add(projectId);+ this.expandedLocationIds.add(locationId);}}- ensureProjectExpanded(projectId: string): void {- this.expandedProjectIds.add(projectId);+ ensureLocationExpanded(locationId: string): void {+ this.expandedLocationIds.add(locationId);}setSessionSortBy(sortBy: SidebarSessionSortBy): void {@@ -507,20 +511,20 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {* agent-focused and room-focused layouts. Used by the deeplink handler so the* targeted session is visible (and thus highlighted) wherever it lives.*/- revealSessionInRoom(projectId: string, roomId: string): void {- this.ensureProjectExpanded(projectId);- this.ensureGroupExpanded(agentRoomGroupKey(projectId, roomId));+ revealSessionInRoom(locationId: string, roomId: string): void {+ this.ensureLocationExpanded(locationId);+ this.ensureGroupExpanded(agentRoomGroupKey(locationId, roomId));this.ensureGroupExpanded(roomViewGroupKey(roomId));}/** Set the sort key and clear all manual session orders so the list fully re-sorts. */applySort(sortBy: SidebarSessionSortBy): void {this.sessionSortBy = sortBy;- this.sessionOrderByProject = {};+ this.sessionOrderByLocation = {};}- setProjectOrder(ids: string[]): void {- this.projectOrder = ids;+ setLocationOrder(ids: string[]): void {+ this.locationOrder = ids;}setRoomOrder(ids: string[]): void {@@ -549,8 +553,8 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {return applyManualOrder(items, getId, this.groupOrder[containerId], newFirst);}- mergeSessionOrder(projectId: string, sessions: SessionStore[]): SessionStore[] {- const stored = this.sessionOrderByProject[projectId] ?? [];+ mergeSessionOrder(locationId: string, sessions: SessionStore[]): SessionStore[] {+ const stored = this.sessionOrderByLocation[locationId] ?? [];const byId = new Map(sessions.map((t) => [t.data.id, t] as const));const seen = new Set<string>();const result: SessionStore[] = [];@@ -569,8 +573,8 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {return [...newSessions, ...result];}- setSessionOrder(projectId: string, orderedIds: string[]): void {- this.sessionOrderByProject = { ...this.sessionOrderByProject, [projectId]: orderedIds };+ setSessionOrder(locationId: string, orderedIds: string[]): void {+ this.sessionOrderByLocation = { ...this.sessionOrderByLocation, [locationId]: orderedIds };}private compareSidebarSessions(a: SessionStore, b: SessionStore): number {@@ -582,7 +586,7 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {return a.data.id.localeCompare(b.data.id);}- private compareSidebarProjects(a: ProjectStore, b: ProjectStore): number {+ private compareSidebarLocations(a: LocationStore, b: LocationStore): number {const d = b.createdAt.localeCompare(a.createdAt);if (d !== 0) return d;return a.id.localeCompare(b.id);diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-subagent-list.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-subagent-list.tsxindex 105235704..a905225d3 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-subagent-list.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-subagent-list.tsx@@ -32,35 +32,35 @@ function subagentNameOf(session: SessionStore): string | undefined {}/** Expand-state key for a subagent row (its sessions live underneath). */-function subagentKey(projectId: string, name: string): string {- return `sa:${projectId}|${name}`;+function subagentKey(locationId: string, name: string): string {+ return `sa:${locationId}|${name}`;}/** Expand-state key for a room nested under a subagent. */-function subagentRoomKey(projectId: string, name: string, roomKey: string): string {- return `sar:${projectId}|${name}|${roomKey}`;+function subagentRoomKey(locationId: string, name: string, roomKey: string): string {+ return `sar:${locationId}|${name}|${roomKey}`;}/**- * The Claude Code subagents of a project's agent, rendered as first-class agent+ * The Claude Code subagents of a location's agent, rendered as first-class agent* rows (same size/icon/affordances as the parent) nested under it. Each row* starts a session that runs as that subagent and, when expanded, lists the* sessions launched as it — grouped by room exactly like the parent agent. A* subagent discovered locally but not registered on the gateway is flagged* "local" so the drift is visible.*- * `sessions` is the project's subagent-launched sessions; pass them in the+ * `sessions` is the location's subagent-launched sessions; pass them in the* agent-focused view so they nest here. Omit them (room-focused view) to render* only the launcher rows.*/export const SidebarSubagentList = observer(function SidebarSubagentList({- projectId,+ locationId,sessions = [],depth = 1,onlyWithSessions = false,groupSessionsByRoom = true,}: {- projectId: string;+ locationId: string;sessions?: SessionStore[];/** Tree depth of the subagent rows; their rooms/sessions nest below it. */depth?: number;@@ -75,16 +75,16 @@ export const SidebarSubagentList = observer(function SidebarSubagentList({const showCreateSessionModal = useShowModal('sessionModal');const { navigate } = useNavigate();const { currentView } = useWorkspaceSlots();- const { params: projectParams } = useParams('project');+ const { params: locationParams } = useParams('location');const activeSubagent =- currentView === 'project' && projectParams.projectId === projectId- ? projectParams.subagentName+ currentView === 'location' && locationParams.locationId === locationId+ ? locationParams.subagentName: undefined;const agentQuery = useQuery({- queryKey: ['projectAgent', projectId],- queryFn: async () => (await rpc.agents.getAgents(projectId))[0] ?? null,- enabled: !!projectId,+ queryKey: ['locationAgent', locationId],+ queryFn: async () => (await rpc.agents.getAgents(locationId))[0] ?? null,+ enabled: !!locationId,});const agent = agentQuery.data ?? null;@@ -99,7 +99,7 @@ export const SidebarSubagentList = observer(function SidebarSubagentList({});const discovered = subagentsQuery.data?.subagents ?? [];- // Group the project's subagent sessions by the subagent they ran as.+ // Group the location's subagent sessions by the subagent they ran as.const sessionsByName = new Map<string, SessionStore[]>();for (const session of sessions) {const name = subagentNameOf(session);@@ -128,10 +128,10 @@ export const SidebarSubagentList = observer(function SidebarSubagentList({{names.map((name) => {const subagent = discoveredByName.get(name) ?? null;const subSessions = sessionsByName.get(name) ?? [];- const expanded = sidebarStore.isGroupExpanded(subagentKey(projectId, name));- const toggle = () => sidebarStore.toggleGroupExpanded(subagentKey(projectId, name));+ const expanded = sidebarStore.isGroupExpanded(subagentKey(locationId, name));+ const toggle = () => sidebarStore.toggleGroupExpanded(subagentKey(locationId, name));const isActive = activeSubagent === name;- const open = () => navigate('project', { projectId, subagentName: name });+ const open = () => navigate('location', { locationId, subagentName: name });return (<div key={name}><SidebarMenuRow@@ -201,7 +201,7 @@ export const SidebarSubagentList = observer(function SidebarSubagentList({className="opacity-0 transition-opacity duration-150 group-hover/row:opacity-100"onClick={(e) => {e.stopPropagation();- showCreateSessionModal({ projectId, subagentName: name });+ showCreateSessionModal({ locationId, subagentName: name });}}><Plus className="h-4 w-4" />@@ -216,7 +216,7 @@ export const SidebarSubagentList = observer(function SidebarSubagentList({subSessions.map((session) => (<SidebarSessionItemkey={session.data.id}- projectId={projectId}+ locationId={locationId}sessionId={session.data.id}depth={depth + 1}/>@@ -231,13 +231,13 @@ export const SidebarSubagentList = observer(function SidebarSubagentList({return roomSessions.map((session) => (<SidebarSessionItemkey={session.data.id}- projectId={projectId}+ locationId={locationId}sessionId={session.data.id}depth={depth + 1}/>));}- const groupKey = subagentRoomKey(projectId, name, roomKey);+ const groupKey = subagentRoomKey(locationId, name, roomKey);const roomExpanded = sidebarStore.isGroupExpanded(groupKey);return (<div key={roomKey}>@@ -259,7 +259,7 @@ export const SidebarSubagentList = observer(function SidebarSubagentList({roomSessions.map((session) => (<SidebarSessionItemkey={session.data.id}- projectId={projectId}+ locationId={locationId}sessionId={session.data.id}depth={depth + 2}/>diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/use-sidebar-drop.ts b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/use-sidebar-drop.tsindex 24ec1a453..be71bfd5b 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/use-sidebar-drop.ts+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/use-sidebar-drop.ts@@ -1,5 +1,5 @@import { useCallback, useRef, useState } from 'react';-import { getProjectManagerStore } from '@renderer/features/projects/stores/project-selectors';+import { getLocationManagerStore } from '@renderer/features/locations/stores/location-selectors';import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';import { getDraggedFilePaths, hasDraggedFiles } from '@renderer/lib/drag-files';import { useToast } from '@renderer/lib/hooks/use-toast';@@ -46,15 +46,12 @@ export function useSidebarDrop() {const filePaths = getDraggedFilePaths(e.dataTransfer);if (filePaths.length === 0) return;- const projectManager = getProjectManagerStore();+ const locationManager = getLocationManagerStore();void Promise.allSettled(filePaths.map(async (filePath) => {try {- const status = await rpc.projects.inspectProjectPath({- type: 'local',- path: filePath,- });+ const status = await rpc.locations.inspectLocationPath({ path: filePath });if (!status.isDirectory) {toast({title: 'Cannot add agent',@@ -86,42 +83,39 @@ export function useSidebarDrop() {}const name = basenameFromAnyPath(filePath);- return await projectManager.createProject(- { type: 'local' },- {- mode: 'pick',- name,- path: filePath,- serverId,- // Quick-add has no agent-type picker; a dropped Switch agent is- // detected from its .claude config, so it is a Claude Code agent.- providerId: 'claude',- }- );+ return await locationManager.createAgent({+ mode: 'pick',+ name,+ path: filePath,+ serverId,+ // Quick-add has no agent-type picker; a dropped Switch agent is+ // detected from its .claude config, so it is a Claude Code agent.+ providerId: 'claude',+ });} catch (err) {- log.error('Failed to add dropped project:', err);+ log.error('Failed to add dropped location:', err);toast({- title: 'Cannot add project',- description: `Failed to add ${basenameFromAnyPath(filePath)} as a project.`,+ title: 'Cannot add location',+ description: `Failed to add ${basenameFromAnyPath(filePath)} as a location.`,variant: 'destructive',});return null;}})).then((results) => {- const projectIds = results.flatMap((r) =>+ const locationIds = results.flatMap((r) =>r.status === 'fulfilled' && r.value != null ? [r.value] : []);- const firstProjectId = projectIds[0];+ const firstLocationId = locationIds[0];- if (firstProjectId) {- navigate('project', { projectId: firstProjectId });+ if (firstLocationId) {+ navigate('location', { locationId: firstLocationId });}- if (projectIds.length > 1) {+ if (locationIds.length > 1) {toast({- title: 'Projects added',- description: `${projectIds.length} projects added.`,+ title: 'Locations added',+ description: `${locationIds.length} locations added.`,});}});diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/session-deeplink-listener.tsx b/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/session-deeplink-listener.tsxindex ae71e980c..5b7cdc5bf 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/session-deeplink-listener.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/session-deeplink-listener.tsx@@ -1,6 +1,6 @@import { useEffect } from 'react';-import { agentsStore } from '@renderer/features/projects/stores/agents-store';-import { getProjectManagerStore } from '@renderer/features/projects/stores/project-selectors';+import { agentsStore } from '@renderer/features/locations/stores/agents-store';+import { getLocationManagerStore } from '@renderer/features/locations/stores/location-selectors';import { getSessionManagerStore } from '@renderer/features/sessions/stores/session-selectors';import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';import { events } from '@renderer/lib/ipc';@@ -14,13 +14,13 @@ import { switchRoomsStore as roomConnectionsStore } from './switch-rooms-store';* normally has a single local session, so room id alone disambiguates;* `agentId` / `server` from the deeplink are advisory.*/-function findSessionForRoom(roomId: string): { projectId: string; sessionId: string } | null {- for (const projectId of getProjectManagerStore().projects.keys()) {- const manager = getSessionManagerStore(projectId);+function findSessionForRoom(roomId: string): { locationId: string; sessionId: string } | null {+ for (const locationId of getLocationManagerStore().locations.keys()) {+ const manager = getSessionManagerStore(locationId);if (!manager) continue;for (const session of manager.sessions.values()) {if (roomConnectionsStore.roomForSession(session.data.id) === roomId) {- return { projectId, sessionId: session.data.id };+ return { locationId, sessionId: session.data.id };}}}@@ -33,11 +33,11 @@ function findSessionForRoom(roomId: string): { projectId: string; sessionId: str* that has an active relay for the session. This is what makes the deeplink open* the right session on a different switchdash client that merely adopted it.*/-function findSessionById(sessionId: string): { projectId: string; sessionId: string } | null {- for (const projectId of getProjectManagerStore().projects.keys()) {- const manager = getSessionManagerStore(projectId);+function findSessionById(sessionId: string): { locationId: string; sessionId: string } | null {+ for (const locationId of getLocationManagerStore().locations.keys()) {+ const manager = getSessionManagerStore(locationId);if (manager?.sessions.has(sessionId)) {- return { projectId, sessionId: sessionId };+ return { locationId, sessionId: sessionId };}}return null;@@ -70,13 +70,13 @@ export function SessionDeeplinkListener(): null {});return;}- // Scope the sidebar to the session's server first; otherwise its project+ // Scope the sidebar to the session's server first; otherwise its location// is filtered out of the server-scoped tree and the reveal has nothing// to expand.if (!agentsStore.loaded) await agentsStore.load();- const serverId = agentsStore.serverIdForProject(match.projectId);+ const serverId = agentsStore.serverIdForLocation(match.locationId);if (serverId) await switchServersStore.setActive(serverId);- sidebarStore.revealSessionInRoom(match.projectId, roomId);+ sidebarStore.revealSessionInRoom(match.locationId, roomId);appState.navigation.navigate('session', match);})();});diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/assign-server-modal.tsx b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/assign-server-modal.tsxindex c4c2f3632..b9ddeb1e1 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/assign-server-modal.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/assign-server-modal.tsx@@ -19,7 +19,7 @@ import { Field, FieldLabel } from '@renderer/lib/ui/field';import { log } from '@renderer/utils/logger';export type AssignServerModalProps = BaseModalProps & {- projectId: string;+ locationId: string;};/**@@ -29,7 +29,7 @@ export type AssignServerModalProps = BaseModalProps & {* verified before it is persisted.*/export const AssignServerModal = observer(function AssignServerModal({- projectId,+ locationId,onClose,}: AssignServerModalProps) {const [serverId, setServerId] = useState<string | null>(null);@@ -37,9 +37,9 @@ export const AssignServerModal = observer(function AssignServerModal({const [submitState, setSubmitState] = useState<'idle' | 'saving'>('idle');const agentQuery = useQuery({- queryKey: ['projectAgent', projectId],+ queryKey: ['locationAgent', locationId],queryFn: async () => {- const agents = await rpc.agents.getAgents(projectId);+ const agents = await rpc.agents.getAgents(locationId);return agents[0] ?? null;},});diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-servers-store.ts b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-servers-store.tsindex 315900d83..0a9180129 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-servers-store.ts+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-servers-store.ts@@ -13,7 +13,7 @@ import type {* server is active. Managing a server's agents/rooms happens in the gateway web* app for now, so this store deliberately does not fetch those — only what the* sidebar + the minimal server view need. Modeled on the singleton-store +- * observable-state pattern (see workspace-registry).+ * observable-state pattern used across the renderer stores.*/export class SwitchServersStore {servers: SwitchServer[] = [];diff --git a/dash/apps/switchdash-desktop/src/renderer/lib/commands/app-commands.ts b/dash/apps/switchdash-desktop/src/renderer/lib/commands/app-commands.tsindex d52a311c4..773e6ca15 100644--- a/dash/apps/switchdash-desktop/src/renderer/lib/commands/app-commands.ts+++ b/dash/apps/switchdash-desktop/src/renderer/lib/commands/app-commands.ts@@ -20,7 +20,7 @@ function createAppCommandProvider(): CommandProvider {// Reads MobX observables — reactions automatically invalidate activeCommands// when navigation changes.const settingsDef = appDef('app.settings');- const newProjectDef = appDef('app.newProject');+ const newLocationDef = appDef('app.newLocation');const giveFeedbackDef = appDef('app.giveFeedback');const toggleThemeDef = appDef('app.toggleTheme');const navigateBackDef = appDef('app.navigateBack');@@ -42,13 +42,13 @@ function createAppCommandProvider(): CommandProvider {},},{- id: newProjectDef.id,- label: newProjectDef.label,- description: newProjectDef.description,- shortcutKey: newProjectDef.shortcutKey,- group: newProjectDef.group,+ id: newLocationDef.id,+ label: newLocationDef.label,+ description: newLocationDef.description,+ shortcutKey: newLocationDef.shortcutKey,+ group: newLocationDef.group,execute() {- showModal('addProjectModal', {});+ showModal('addAgentModal', {});},},];diff --git a/dash/apps/switchdash-desktop/src/renderer/lib/commands/types.ts b/dash/apps/switchdash-desktop/src/renderer/lib/commands/types.tsindex a51db947c..3a290e2ac 100644--- a/dash/apps/switchdash-desktop/src/renderer/lib/commands/types.ts+++ b/dash/apps/switchdash-desktop/src/renderer/lib/commands/types.ts@@ -39,7 +39,7 @@ export interface CommandProvider {*/export const SCOPE_LEVELS = {app: 0,- project: 1,+ location: 1,session: 2,} as const;diff --git a/dash/apps/switchdash-desktop/src/renderer/lib/components/app-keyboard-shortcuts.tsx b/dash/apps/switchdash-desktop/src/renderer/lib/components/app-keyboard-shortcuts.tsxindex 1a423820a..eed0b354f 100644--- a/dash/apps/switchdash-desktop/src/renderer/lib/components/app-keyboard-shortcuts.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/lib/components/app-keyboard-shortcuts.tsx@@ -25,13 +25,13 @@ export function AppKeyboardShortcuts() {const { currentView, lastNonSettingsView } = useWorkspaceSlots();const { params: sessionParams } = useParams('session');- const { params: projectParams } = useParams('project');+ const { params: locationParams } = useParams('location');- const currentProjectId =+ const currentLocationId =currentView === 'session'- ? sessionParams.projectId- : currentView === 'project'- ? projectParams.projectId+ ? sessionParams.locationId+ : currentView === 'location'+ ? locationParams.locationId: undefined;const currentSessionId = currentView === 'session' ? sessionParams.sessionId : undefined;@@ -39,7 +39,7 @@ export function AppKeyboardShortcuts() {getHotkeyRegistration('commandPalette', keyboard),() =>showCommandPalette({- projectId: currentProjectId,+ locationId: currentLocationId,sessionId: currentSessionId,}),{ enabled: commandPaletteHotkey !== null }diff --git a/dash/apps/switchdash-desktop/src/renderer/lib/drag-files.ts b/dash/apps/switchdash-desktop/src/renderer/lib/drag-files.tsindex 983d6828d..35a20ec68 100644--- a/dash/apps/switchdash-desktop/src/renderer/lib/drag-files.ts+++ b/dash/apps/switchdash-desktop/src/renderer/lib/drag-files.ts@@ -9,24 +9,24 @@ export function getDraggedFilePaths(dataTransfer: DataTransfer): string[] {}/**- * In-app drags of workspace files (e.g. from the editor file tree) are tagged+ * In-app drags of location files (e.g. from the editor file tree) are tagged* with this MIME type. Custom types must be lowercase; browsers lowercase* `DataTransfer.types`.*/-export const WORKSPACE_FILE_DRAG_TYPE = 'application/x-switchdash-workspace-file';+export const LOCATION_FILE_DRAG_TYPE = 'application/x-switchdash-location-file';-export type DraggedWorkspaceFile = {- workspaceId: string;+export type DraggedLocationFile = {+ locationId: string;relPath: string;- /** Absolute path in the workspace environment where the target agent runs. */+ /** Absolute path in the location environment where the target agent runs. */targetPath: string;- /** Remote workspaces are Linux targets even when the renderer runs elsewhere. */+ /** Remote locations are Linux targets even when the renderer runs elsewhere. */targetPlatform?: NodeJS.Platform;};-type DraggedWorkspaceFileInput = {- workspaceId: string;- workspaceRootPath: string;+type DraggedLocationFileInput = {+ locationId: string;+ locationRootPath: string;relPath: string;targetPlatform?: NodeJS.Platform;};@@ -36,40 +36,40 @@ type DraggedWorkspaceFileInput = {// drag source and same-window drop targets share the renderer. Consumers still// require the DataTransfer marker so stale state from a previous drag cannot be// accepted by an unrelated drop.-let draggedWorkspaceFile: DraggedWorkspaceFile | null = null;+let draggedLocationFile: DraggedLocationFile | null = null;-export function resolveWorkspaceFileTargetPath(rootPath: string, relPath: string): string {+export function resolveLocationFileTargetPath(rootPath: string, relPath: string): string {const separator = rootPath.includes('\\') ? '\\' : '/';const normalizedRoot = rootPath.replace(/[\\/]+$/, '');const normalizedPath = relPath.replace(/^[\\/]+/, '').replace(/[\\/]+/g, separator);return `${normalizedRoot}${separator}${normalizedPath}`;}-export function setDraggedWorkspaceFile(+export function setDraggedLocationFile(dataTransfer: DataTransfer,- input: DraggedWorkspaceFileInput+ input: DraggedLocationFileInput): void {- const payload: DraggedWorkspaceFile = {- workspaceId: input.workspaceId,+ const payload: DraggedLocationFile = {+ locationId: input.locationId,relPath: input.relPath,- targetPath: resolveWorkspaceFileTargetPath(input.workspaceRootPath, input.relPath),+ targetPath: resolveLocationFileTargetPath(input.locationRootPath, input.relPath),targetPlatform: input.targetPlatform,};- draggedWorkspaceFile = payload;- dataTransfer.setData(WORKSPACE_FILE_DRAG_TYPE, JSON.stringify(payload));+ draggedLocationFile = payload;+ dataTransfer.setData(LOCATION_FILE_DRAG_TYPE, JSON.stringify(payload));dataTransfer.setData('text/plain', payload.targetPath);dataTransfer.effectAllowed = 'copy';}/** Call on dragend; drop fires on the target before dragend on the source. */-export function clearDraggedWorkspaceFile(): void {- draggedWorkspaceFile = null;+export function clearDraggedLocationFile(): void {+ draggedLocationFile = null;}-/** True when this transfer is tagged as an in-app workspace-file drag. */-export function hasDraggedWorkspaceFile(dataTransfer: DataTransfer): boolean {- return dataTransfer.types.includes(WORKSPACE_FILE_DRAG_TYPE);+/** True when this transfer is tagged as an in-app location-file drag. */+export function hasDraggedLocationFile(dataTransfer: DataTransfer): boolean {+ return dataTransfer.types.includes(LOCATION_FILE_DRAG_TYPE);}const NODE_PLATFORMS = new Set<NodeJS.Platform>([@@ -90,24 +90,24 @@ function isNodePlatform(value: unknown): value is NodeJS.Platform {return typeof value === 'string' && NODE_PLATFORMS.has(value as NodeJS.Platform);}-function isDraggedWorkspaceFile(value: unknown): value is DraggedWorkspaceFile {+function isDraggedLocationFile(value: unknown): value is DraggedLocationFile {if (!value || typeof value !== 'object') return false;- const candidate = value as Partial<DraggedWorkspaceFile>;+ const candidate = value as Partial<DraggedLocationFile>;return (- typeof candidate.workspaceId === 'string' &&+ typeof candidate.locationId === 'string' &&typeof candidate.relPath === 'string' &&typeof candidate.targetPath === 'string' &&(candidate.targetPlatform === undefined || isNodePlatform(candidate.targetPlatform)));}-export function getDraggedWorkspaceFile(dataTransfer: DataTransfer): DraggedWorkspaceFile | null {- if (!hasDraggedWorkspaceFile(dataTransfer)) return null;- if (draggedWorkspaceFile) return draggedWorkspaceFile;+export function getDraggedLocationFile(dataTransfer: DataTransfer): DraggedLocationFile | null {+ if (!hasDraggedLocationFile(dataTransfer)) return null;+ if (draggedLocationFile) return draggedLocationFile;try {- const parsed: unknown = JSON.parse(dataTransfer.getData(WORKSPACE_FILE_DRAG_TYPE));- return isDraggedWorkspaceFile(parsed) ? parsed : null;+ const parsed: unknown = JSON.parse(dataTransfer.getData(LOCATION_FILE_DRAG_TYPE));+ return isDraggedLocationFile(parsed) ? parsed : null;} catch {return null;}diff --git a/dash/apps/switchdash-desktop/src/renderer/lib/hooks/use-terminal-shell-availability.ts b/dash/apps/switchdash-desktop/src/renderer/lib/hooks/use-terminal-shell-availability.tsindex 06847feb0..ea9ecac5c 100644--- a/dash/apps/switchdash-desktop/src/renderer/lib/hooks/use-terminal-shell-availability.ts+++ b/dash/apps/switchdash-desktop/src/renderer/lib/hooks/use-terminal-shell-availability.ts@@ -4,7 +4,7 @@ import type { TerminalShellAvailability } from '@shared/core/terminals/terminal-export const DEFAULT_TERMINAL_SHELL_AVAILABILITY: TerminalShellAvailability[] = [];// Shell-availability detection has no RPC surface in switchdash — every session-// runs in the project dir with the system shell. Return the empty default so the+// runs in the location dir with the system shell. Return the empty default so the// settings UI degrades gracefully (only the system shell is selectable).export function useTerminalShellAvailability(options: { enabled?: boolean } = {}) {return useQuery<TerminalShellAvailability[]>({diff --git a/dash/apps/switchdash-desktop/src/renderer/lib/pty/pty-pane.tsx b/dash/apps/switchdash-desktop/src/renderer/lib/pty/pty-pane.tsxindex 63493b161..0398827d0 100644--- a/dash/apps/switchdash-desktop/src/renderer/lib/pty/pty-pane.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/lib/pty/pty-pane.tsx@@ -1,5 +1,5 @@import React, { forwardRef, useCallback, useImperativeHandle, useRef } from 'react';-import { getDraggedWorkspaceFile } from '@renderer/lib/drag-files';+import { getDraggedLocationFile } from '@renderer/lib/drag-files';import { rpc } from '@renderer/lib/ipc';import { log } from '@renderer/utils/logger';import { cn } from '@renderer/utils/utils';@@ -16,7 +16,7 @@ import { type PasteFromClipboardHandler, usePty } from './use-pty';type Props = {/**- * Deterministic PTY session ID: `makePtySessionId(projectId, scopeId, leafId)`.+ * Deterministic PTY session ID: `makePtySessionId(locationId, scopeId, leafId)`.*/sessionId: string;/** Pre-connected FrontendPty owned by the entity's PtySession store. */@@ -26,7 +26,7 @@ type Props = {mapShiftEnterToCtrlJ?: boolean;/** SSH connection ID — used for remote file drag-and-drop and image paste. */remoteConnectionId?: string;- workspaceId: string;+ locationId: string;themeOverride?: SessionTheme['override'];onActivity?: () => void;onExit?: (info: { exitCode: number | undefined; signal?: number }) => void;@@ -124,7 +124,7 @@ const PtyPaneComponent = forwardRef<{ focus: () => void }, Props>(contentFilter,mapShiftEnterToCtrlJ,remoteConnectionId,- workspaceId,+ locationId,themeOverride,onActivity,onExit,@@ -260,21 +260,21 @@ const PtyPaneComponent = forwardRef<{ focus: () => void }, Props>(if (!dt) return;// In-app drag from the editor file tree. The drag payload already- // carries the path in the workspace environment where this agent runs.- const draggedWorkspaceFile = getDraggedWorkspaceFile(dt);- if (draggedWorkspaceFile) {- if (draggedWorkspaceFile.workspaceId !== workspaceId) return;+ // carries the path in the location environment where this agent runs.+ const draggedLocationFile = getDraggedLocationFile(dt);+ if (draggedLocationFile) {+ if (draggedLocationFile.locationId !== locationId) return;void (async () => {try {const platform =- draggedWorkspaceFile.targetPlatform ??+ draggedLocationFile.targetPlatform ??((await rpc.app.getPlatform()) as NodeJS.Platform);// Plain text, not bracketed paste: Claude Code swallows externally// injected paste markers, and the escaped single-line path needs// no paste protection in shells or other agent TUIs.sendInput(- `${formatTerminalImagePaths([draggedWorkspaceFile.targetPath], platform)} `,+ `${formatTerminalImagePaths([draggedLocationFile.targetPath], platform)} `,{track: false,}diff --git a/dash/apps/switchdash-desktop/src/renderer/lib/pty/use-pty.ts b/dash/apps/switchdash-desktop/src/renderer/lib/pty/use-pty.tsindex 19dff45f4..50ba9134e 100644--- a/dash/apps/switchdash-desktop/src/renderer/lib/pty/use-pty.ts+++ b/dash/apps/switchdash-desktop/src/renderer/lib/pty/use-pty.ts@@ -74,7 +74,7 @@ function getRecentSelection(selection: { text: string; capturedAt: number } | nu}export interface UsePtyOptions {- /** Deterministic PTY session ID: makePtySessionId(projectId, scopeId, leafId). */+ /** Deterministic PTY session ID: makePtySessionId(locationId, scopeId, leafId). */sessionId: string;/** Pre-connected FrontendPty instance owned by the entity's PtySession store. */pty: FrontendPty;diff --git a/dash/apps/switchdash-desktop/src/renderer/lib/stores/app-state.ts b/dash/apps/switchdash-desktop/src/renderer/lib/stores/app-state.tsindex f2f8d0cf8..7c03d15f0 100644--- a/dash/apps/switchdash-desktop/src/renderer/lib/stores/app-state.ts+++ b/dash/apps/switchdash-desktop/src/renderer/lib/stores/app-state.ts@@ -1,4 +1,4 @@-import { ProjectManagerStore } from '@renderer/features/projects/stores/project-manager';+import { LocationManagerStore } from '@renderer/features/locations/stores/location-manager';import { SidebarStore } from '@renderer/features/sidebar/sidebar-store';import { NavigationHistoryStore } from './navigation-history-store';import { NavigationStore } from './navigation-store';@@ -8,7 +8,7 @@ import { UpdateStore } from './update-store';class AppState {readonly update: UpdateStore;- readonly projects: ProjectManagerStore;+ readonly locations: LocationManagerStore;readonly sidebar: SidebarStore;readonly snapshots: SnapshotRegistry;readonly history: NavigationHistoryStore;@@ -18,8 +18,8 @@ class AppState {constructor() {this.snapshots = snapshotRegistry;this.update = new UpdateStore();- this.projects = new ProjectManagerStore();- this.sidebar = new SidebarStore(this.projects);+ this.locations = new LocationManagerStore();+ this.sidebar = new SidebarStore(this.locations);this.history = new NavigationHistoryStore();this.navigation = new NavigationStore();this.resourceMonitor = new ResourceMonitorStore();diff --git a/dash/apps/switchdash-desktop/src/renderer/lib/stores/navigation-history-store.ts b/dash/apps/switchdash-desktop/src/renderer/lib/stores/navigation-history-store.tsindex cd9ad9e44..4840c6f02 100644--- a/dash/apps/switchdash-desktop/src/renderer/lib/stores/navigation-history-store.ts+++ b/dash/apps/switchdash-desktop/src/renderer/lib/stores/navigation-history-store.ts@@ -5,7 +5,7 @@ const MAX_STACK_SIZE = 50;export type HistoryEntry =| { kind: 'view'; viewId: ViewId; params: WrapParams<ViewId> }- | { kind: 'tab'; projectId: string; taskId: string; tabId: string };+ | { kind: 'tab'; locationId: string; taskId: string; tabId: string };function entriesEqual(a: HistoryEntry, b: HistoryEntry): boolean {if (a.kind !== b.kind) return false;diff --git a/dash/apps/switchdash-desktop/src/renderer/lib/stores/navigation-store.test.ts b/dash/apps/switchdash-desktop/src/renderer/lib/stores/navigation-store.test.tsindex eef6a8e1e..05360f3e9 100644--- a/dash/apps/switchdash-desktop/src/renderer/lib/stores/navigation-store.test.ts+++ b/dash/apps/switchdash-desktop/src/renderer/lib/stores/navigation-store.test.ts@@ -15,7 +15,7 @@ const { NavigationStore } = await import('./navigation-store');function buildStore() {const store = new NavigationStore();store.registerView('home');- store.registerView('project');+ store.registerView('location');store.registerView('session');store.registerView('settings');return store;@@ -29,19 +29,19 @@ describe('NavigationStore.restoreSnapshot', () => {it('restores a snapshot whose view is registered', () => {const store = buildStore();store.restoreSnapshot({- currentViewId: 'project',- viewParams: { project: { projectId: 'p1' } },+ currentViewId: 'location',+ viewParams: { location: { locationId: 'p1' } },});- expect(store.currentViewId).toBe('project');- expect(store.viewParamsStore.project).toEqual({ projectId: 'p1' });- expect(store.lastNonSettingsView).toBe('project');+ expect(store.currentViewId).toBe('location');+ expect(store.viewParamsStore.location).toEqual({ locationId: 'p1' });+ expect(store.lastNonSettingsView).toBe('location');});it('falls back to home when the persisted view is not in the registry', () => {const store = buildStore();store.restoreSnapshot({currentViewId: 'phantom-view-from-old-build',- viewParams: { project: { projectId: 'p1' } },+ viewParams: { location: { locationId: 'p1' } },});expect(store.currentViewId).toBe('home');expect(store.lastNonSettingsView).toBe('home');@@ -52,11 +52,11 @@ describe('NavigationStore.restoreSnapshot', () => {store.restoreSnapshot({currentViewId: 'home',viewParams: {- project: { projectId: 'p1' },+ location: { locationId: 'p1' },ghostView: { stale: true },},});- expect(store.viewParamsStore.project).toEqual({ projectId: 'p1' });+ expect(store.viewParamsStore.location).toEqual({ locationId: 'p1' });expect((store.viewParamsStore as Record<string, unknown>).ghostView).toBeUndefined();});@@ -69,10 +69,10 @@ describe('NavigationStore.restoreSnapshot', () => {it('honors a guard redirect after a valid view is restored', () => {const store = buildStore();- store.registerGuard('project', () => ({ ok: false, redirect: 'home' }));+ store.registerGuard('location', () => ({ ok: false, redirect: 'home' }));store.restoreSnapshot({- currentViewId: 'project',- viewParams: { project: { projectId: 'gone' } },+ currentViewId: 'location',+ viewParams: { location: { locationId: 'gone' } },});expect(store.currentViewId).toBe('home');});diff --git a/dash/apps/switchdash-desktop/src/renderer/lib/stores/view-state-cache.ts b/dash/apps/switchdash-desktop/src/renderer/lib/stores/view-state-cache.tsindex c201613dd..da59ca480 100644--- a/dash/apps/switchdash-desktop/src/renderer/lib/stores/view-state-cache.ts+++ b/dash/apps/switchdash-desktop/src/renderer/lib/stores/view-state-cache.ts@@ -6,7 +6,7 @@ import { rpc } from '@renderer/lib/ipc';* After the bulk `getAll()` load at bootstrap, every subsequent `get` call is* a synchronous Map lookup (returned as a resolved Promise). Writes update the* cache immediately and then fire the async IPC save. Eviction happens when a- * SnapshotRegistry disposer is called (task or project teardown/deletion).+ * SnapshotRegistry disposer is called (task or location teardown/deletion).*/class ViewStateCache {private readonly map = new Map<string, unknown>();diff --git a/dash/apps/switchdash-desktop/src/renderer/lib/ui/markdown-renderer.tsx b/dash/apps/switchdash-desktop/src/renderer/lib/ui/markdown-renderer.tsxindex 2c4a925d3..191703282 100644--- a/dash/apps/switchdash-desktop/src/renderer/lib/ui/markdown-renderer.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/lib/ui/markdown-renderer.tsx@@ -25,7 +25,7 @@ interface MarkdownRendererProps {allowHtml?: boolean;/*** Optional callback for resolving non-external image src values (e.g. relative- * paths inside a workspace). Should return a `data:` URI string, or `null` to+ * paths inside a location). Should return a `data:` URI string, or `null` to* render a "not found" placeholder. When omitted, local images are not resolved.*/resolveImage?: (src: string) => Promise<string | null>;diff --git a/dash/apps/switchdash-desktop/src/renderer/main.tsx b/dash/apps/switchdash-desktop/src/renderer/main.tsxindex af327b55f..8f77faa1d 100644--- a/dash/apps/switchdash-desktop/src/renderer/main.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/main.tsx@@ -26,7 +26,7 @@ async function bootstrap() {rpc.viewState.get('navigation') as Promise<NavigationSnapshot> | null,rpc.viewState.get('sidebar'),rpc.viewState.getAll(),- appState.projects.load(),+ appState.locations.load(),prefetchAppSettingsKey('interface'),]);@@ -39,7 +39,7 @@ async function bootstrap() {if (sidebarResult) {appState.sidebar.restoreSnapshot(sidebarResult as Partial<SidebarSnapshot>);} else {- appState.sidebar.expandAllProjects();+ appState.sidebar.expandAllLocations();}// Avoid double-mount in dev which can duplicate PTY sessionsdiff --git a/dash/apps/switchdash-desktop/src/renderer/tests/drag-files.test.ts b/dash/apps/switchdash-desktop/src/renderer/tests/drag-files.test.tsindex 48c0503d7..748c9a73d 100644--- a/dash/apps/switchdash-desktop/src/renderer/tests/drag-files.test.ts+++ b/dash/apps/switchdash-desktop/src/renderer/tests/drag-files.test.ts@@ -1,10 +1,10 @@import { describe, expect, it } from 'vitest';import {- clearDraggedWorkspaceFile,- getDraggedWorkspaceFile,- hasDraggedWorkspaceFile,- resolveWorkspaceFileTargetPath,- setDraggedWorkspaceFile,+ clearDraggedLocationFile,+ getDraggedLocationFile,+ hasDraggedLocationFile,+ resolveLocationFileTargetPath,+ setDraggedLocationFile,} from '@renderer/lib/drag-files';function makeDataTransfer(): DataTransfer {@@ -25,28 +25,28 @@ function makeDataTransfer(): DataTransfer {}describe('drag-files', () => {- it('resolves workspace-relative paths into the workspace target path', () => {- expect(resolveWorkspaceFileTargetPath('/tmp/repo/', 'src/file name.ts')).toBe(+ it('resolves location-relative paths into the location target path', () => {+ expect(resolveLocationFileTargetPath('/tmp/repo/', 'src/file name.ts')).toBe('/tmp/repo/src/file name.ts');- expect(resolveWorkspaceFileTargetPath('C:\\repo\\', 'src/file name.ts')).toBe(+ expect(resolveLocationFileTargetPath('C:\\repo\\', 'src/file name.ts')).toBe('C:\\repo\\src\\file name.ts');});- it('carries workspace file payloads for same-window drops', () => {+ it('carries location file payloads for same-window drops', () => {const dataTransfer = makeDataTransfer();- setDraggedWorkspaceFile(dataTransfer, {- workspaceId: 'workspace-1',- workspaceRootPath: '/remote/repo',+ setDraggedLocationFile(dataTransfer, {+ locationId: 'location-1',+ locationRootPath: '/remote/repo',relPath: 'src/index.ts',targetPlatform: 'linux',});- expect(hasDraggedWorkspaceFile(dataTransfer)).toBe(true);- expect(getDraggedWorkspaceFile(dataTransfer)).toEqual({- workspaceId: 'workspace-1',+ expect(hasDraggedLocationFile(dataTransfer)).toBe(true);+ expect(getDraggedLocationFile(dataTransfer)).toEqual({+ locationId: 'location-1',relPath: 'src/index.ts',targetPath: '/remote/repo/src/index.ts',targetPlatform: 'linux',@@ -54,32 +54,32 @@ describe('drag-files', () => {expect(dataTransfer.getData('text/plain')).toBe('/remote/repo/src/index.ts');});- it('does not accept stale workspace state without a matching transfer marker', () => {+ it('does not accept stale location state without a matching transfer marker', () => {const sourceTransfer = makeDataTransfer();- setDraggedWorkspaceFile(sourceTransfer, {- workspaceId: 'workspace-1',- workspaceRootPath: '/repo',+ setDraggedLocationFile(sourceTransfer, {+ locationId: 'location-1',+ locationRootPath: '/repo',relPath: 'src/index.ts',});const unrelatedTransfer = makeDataTransfer();- expect(hasDraggedWorkspaceFile(unrelatedTransfer)).toBe(false);- expect(getDraggedWorkspaceFile(unrelatedTransfer)).toBeNull();- clearDraggedWorkspaceFile();+ expect(hasDraggedLocationFile(unrelatedTransfer)).toBe(false);+ expect(getDraggedLocationFile(unrelatedTransfer)).toBeNull();+ clearDraggedLocationFile();});it('falls back to the serialized transfer payload after dragend clears same-window state', () => {const dataTransfer = makeDataTransfer();- setDraggedWorkspaceFile(dataTransfer, {- workspaceId: 'workspace-1',- workspaceRootPath: '/repo',+ setDraggedLocationFile(dataTransfer, {+ locationId: 'location-1',+ locationRootPath: '/repo',relPath: 'src/index.ts',});- clearDraggedWorkspaceFile();+ clearDraggedLocationFile();- expect(getDraggedWorkspaceFile(dataTransfer)).toEqual({- workspaceId: 'workspace-1',+ expect(getDraggedLocationFile(dataTransfer)).toEqual({+ locationId: 'location-1',relPath: 'src/index.ts',targetPath: '/repo/src/index.ts',});diff --git a/dash/apps/switchdash-desktop/src/shared/browser.test.ts b/dash/apps/switchdash-desktop/src/shared/browser.test.tsindex 1d080a8d3..5c6a9a293 100644--- a/dash/apps/switchdash-desktop/src/shared/browser.test.ts+++ b/dash/apps/switchdash-desktop/src/shared/browser.test.ts@@ -104,8 +104,7 @@ describe('browser session identity', () => {it('assigns the default persistent profile partition to new sessions', () => {const identity = makeBrowserSessionIdentity({browserId: 'Browser One',- projectId: 'Project/One',- workspaceId: 'Workspace.One',+ locationId: 'Location/One',sessionId: 'Session One',});@@ -118,13 +117,12 @@ describe('browser session identity', () => {it('can assign an isolated persistent session partition', () => {const identity = makeBrowserSessionIdentity({browserId: 'Browser One',- projectId: 'Project/One',- workspaceId: 'Workspace.One',+ locationId: 'Location/One',sessionId: 'Session One',});expect(makeIsolatedBrowserPartition(identity)).toBe(- 'persist:switchdash-browser-isolated-Project_One-Workspace_One-Session_One'+ 'persist:switchdash-browser-isolated-Location_One-Session_One');expect(createBrowserSessionSnapshot({@@ -134,15 +132,14 @@ describe('browser session identity', () => {})).toMatchObject({profileId: BROWSER_ISOLATED_PROFILE_ID,- partition: 'persist:switchdash-browser-isolated-Project_One-Workspace_One-Session_One',+ partition: 'persist:switchdash-browser-isolated-Location_One-Session_One',});});it('creates safe snapshots with normalized URLs', () => {const identity = makeBrowserSessionIdentity({browserId: 'browser-1',- projectId: 'project-1',- workspaceId: 'workspace-1',+ locationId: 'location-1',sessionId: 'session-1',});@@ -163,8 +160,7 @@ describe('browser session identity', () => {it('preserves bare host URLs in snapshots', () => {const identity = makeBrowserSessionIdentity({browserId: 'browser-1',- projectId: 'project-1',- workspaceId: 'workspace-1',+ locationId: 'location-1',sessionId: 'session-1',});diff --git a/dash/apps/switchdash-desktop/src/shared/browser.ts b/dash/apps/switchdash-desktop/src/shared/browser.tsindex 0c2ff3be8..b8c230a9f 100644--- a/dash/apps/switchdash-desktop/src/shared/browser.ts+++ b/dash/apps/switchdash-desktop/src/shared/browser.ts@@ -35,8 +35,7 @@ export type BrowserUrlNormalizeOptions = {export type BrowserSessionIdentity = {browserId: string;- projectId: string;- workspaceId: string;+ locationId: string;sessionId: string;};@@ -180,15 +179,13 @@ export function normalizeBrowserUrl(}export function makeBrowserSessionIdentity(input: {- projectId: string;- workspaceId: string;+ locationId: string;sessionId: string;browserId?: string;}): BrowserSessionIdentity {return {browserId: input.browserId ?? crypto.randomUUID(),- projectId: input.projectId,- workspaceId: input.workspaceId,+ locationId: input.locationId,sessionId: input.sessionId,};}@@ -202,8 +199,7 @@ export function makeIsolatedBrowserPartition(identity: BrowserSessionIdentity):return [BROWSER_PARTITION_PREFIX,'isolated',- partitionComponent(identity.projectId),- partitionComponent(identity.workspaceId),+ partitionComponent(identity.locationId),partitionComponent(identity.sessionId),].join('-');}diff --git a/dash/apps/switchdash-desktop/src/shared/commands.ts b/dash/apps/switchdash-desktop/src/shared/commands.tsindex 168d7e7a4..8008d649e 100644--- a/dash/apps/switchdash-desktop/src/shared/commands.ts+++ b/dash/apps/switchdash-desktop/src/shared/commands.ts@@ -5,7 +5,7 @@ export interface CommandDef {label: string;description?: string;group?: string;- scope: 'app' | 'project' | 'session' | 'session-sub';+ scope: 'app' | 'location' | 'session' | 'session-sub';shortcutKey?: ShortcutSettingsKey;/** Token resolved to a LucideIcon by the renderer's COMMAND_ICONS map. */iconKey?: string;@@ -39,11 +39,11 @@ export const APP_COMMAND_DEFS = defineCommandDefs([iconKey: 'library',},{- id: 'app.newProject',+ id: 'app.newLocation',label: 'Add Switch Agent',description: 'Onboard a local directory as a Switch agent — configuring one if needed',scope: 'app',- shortcutKey: 'newProject',+ shortcutKey: 'newLocation',group: 'App',iconKey: 'plus',},diff --git a/dash/apps/switchdash-desktop/src/shared/core/agents/agent-connection.ts b/dash/apps/switchdash-desktop/src/shared/core/agents/agent-connection.tsindex a402db819..07eff7f25 100644--- a/dash/apps/switchdash-desktop/src/shared/core/agents/agent-connection.ts+++ b/dash/apps/switchdash-desktop/src/shared/core/agents/agent-connection.ts@@ -3,7 +3,7 @@ import { defineVersionedSchema } from '@shared/lib/versioned-schema/versioned-sc/*** Where an agent's sessions run. `local` (the default) runs every session in- * the project directory on this machine, exactly as switchdash always has.+ * the location directory on this machine, exactly as switchdash always has.* `remote` runs them on an SSH-reachable host, so the agent keeps working and* listening to its Switch rooms while switchdash is closed (CHOO-1059).*/diff --git a/dash/apps/switchdash-desktop/src/shared/core/agents/agents.ts b/dash/apps/switchdash-desktop/src/shared/core/agents/agents.tsindex 3b28d1095..21143c7e9 100644--- a/dash/apps/switchdash-desktop/src/shared/core/agents/agents.ts+++ b/dash/apps/switchdash-desktop/src/shared/core/agents/agents.ts@@ -1,34 +1,30 @@-import type { AgentConnectionKind, AgentRemoteConfig } from '@shared/core/agents/agent-connection';import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';/**- * A Switch agent: an agent identity bound to a single provider, living in a- * project directory. Many agents may share a directory. `switchAgentId` /- * `apiEndpoint` carry the Switch identity detected from the directory's- * `.claude/settings.local.json`. `serverId` is the registered Switch server the- * agent belongs to (resolved from `apiEndpoint`); null means unlinked — the- * server it points at is not registered in this app.+ * A Switch agent: an agent identity bound to a single provider, living at a+ * location (a working directory on this machine or an SSH host). Many agents+ * may share a location. `switchAgentId` / `apiEndpoint` carry the Switch+ * identity detected from the location dir's `.claude/settings.local.json`.+ * `serverId` is the registered Switch server the agent belongs to (resolved+ * from `apiEndpoint`); null means unlinked — the server it points at is not+ * registered in this app.*/export type Agent = {id: string;- projectId: string;+ locationId: string;name: string;providerId: AgentProviderId;switchAgentId: string | null;apiEndpoint: string | null;serverId: string | null;status: string | null;- /** Where this agent's sessions run. New agents default to `local`. */- connection: AgentConnectionKind;- /** SSH host + remote working dir; null unless `connection === 'remote'`. */- remoteConfig: AgentRemoteConfig | null;createdAt: string;updatedAt: string;};export type CreateAgentParams = {id: string;- projectId: string;+ locationId: string;name: string;providerId: AgentProviderId;switchAgentId: string | null;diff --git a/dash/apps/switchdash-desktop/src/shared/core/agents/onboarding.ts b/dash/apps/switchdash-desktop/src/shared/core/agents/onboarding.tsnew file mode 100644index 000000000..a7abfb5e3--- /dev/null+++ b/dash/apps/switchdash-desktop/src/shared/core/agents/onboarding.ts@@ -0,0 +1,46 @@+import type { Result } from '@switchdash/shared';+import type { Agent } from '@shared/core/agents/agents';+import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';++/**+ * Onboarding creates an agent at a location, creating the location row first+ * if no location exists yet for (sshHost, dir). The directory must already be+ * configured as a Switch agent (its `.claude/settings.local.json` resolves an+ * identity) — minting a new identity happens before this call, via+ * `switchServers.provisionAgent` / `provisionRemoteAgent`.+ */+export type OnboardAgentParams = {+ id?: string;+ name: string;+ /** The registered Switch server the user chose for this agent. The agent must+ * exist on it — verified server-side at onboard time. */+ serverId: string;+ /** The agent type (CLI provider) the user picked when onboarding. */+ providerId: AgentProviderId;+ /** Where the agent runs: `~/.ssh/config` Host alias (omit for this machine)+ * plus the absolute working directory on that host. */+ sshHost?: string;+ dir: string;+};++export type OnboardAgentError =+ | { type: 'invalid-directory'; dir: string; message: string }+ /** The chosen Switch server does not have this agent — the user picked the+ * wrong server, or the directory's `SWITCH_AGENT_ID` isn't registered there. */+ | {+ type: 'switch-agent-not-on-server';+ dir: string;+ serverId: string;+ serverName: string;+ agentId: string;+ }+ /** The chosen Switch server is registered but this app is not signed in to it. */+ | {+ type: 'switch-server-unauthenticated';+ dir: string;+ serverId: string;+ serverName: string;+ }+ | { type: 'error'; message: string };++export type OnboardAgentResult = Result<Agent, OnboardAgentError>;diff --git a/dash/apps/switchdash-desktop/src/shared/core/app-settings.ts b/dash/apps/switchdash-desktop/src/shared/core/app-settings.tsindex ccb4d975f..27c270d07 100644--- a/dash/apps/switchdash-desktop/src/shared/core/app-settings.ts+++ b/dash/apps/switchdash-desktop/src/shared/core/app-settings.ts@@ -5,17 +5,17 @@ import {type browserSettingsSchema,type changesViewModeSchema,type interfaceSettingsSchema,- type localProjectSettingsSchema,+ type localLocationSettingsSchema,type notificationSettingsSchema,- type projectSettingsSchema,+ type locationSettingsSchema,type providerCustomConfigEntrySchema,type sessionSettingsSchema,type terminalSettingsSchema,type themeSchema,} from '@main/core/settings/schema';-export type LocalProjectSettings = z.infer<typeof localProjectSettingsSchema>;-export type ProjectSettings = z.infer<typeof projectSettingsSchema>;+export type LocalLocationSettings = z.infer<typeof localLocationSettingsSchema>;+export type LocationSettings = z.infer<typeof locationSettingsSchema>;export type NotificationSettings = z.infer<typeof notificationSettingsSchema>;export type SessionSettings = z.infer<typeof sessionSettingsSchema>;export type AgentAutoApproveDefaults = z.infer<typeof agentAutoApproveDefaultsSchema>;diff --git a/dash/apps/switchdash-desktop/src/shared/core/fs/fsEvents.ts b/dash/apps/switchdash-desktop/src/shared/core/fs/fsEvents.tsindex 66e2831d9..504e3baad 100644--- a/dash/apps/switchdash-desktop/src/shared/core/fs/fsEvents.ts+++ b/dash/apps/switchdash-desktop/src/shared/core/fs/fsEvents.ts@@ -2,7 +2,6 @@ import type { FileWatchEvent } from '@shared/core/fs/fs';import { defineEvent } from '@shared/lib/ipc/events';export const fsWatchEventChannel = defineEvent<{- projectId: string;- workspaceId: string;+ locationId: string;events: FileWatchEvent[];}>('fs:watch-event');diff --git a/dash/apps/switchdash-desktop/src/shared/core/project-settings/project-settings-fields.test.ts b/dash/apps/switchdash-desktop/src/shared/core/location-settings/location-settings-fields.test.tssimilarity index 63%rename from dash/apps/switchdash-desktop/src/shared/core/project-settings/project-settings-fields.test.tsrename to dash/apps/switchdash-desktop/src/shared/core/location-settings/location-settings-fields.test.tsindex 3386190e2..805c8a397 100644--- a/dash/apps/switchdash-desktop/src/shared/core/project-settings/project-settings-fields.test.ts+++ b/dash/apps/switchdash-desktop/src/shared/core/location-settings/location-settings-fields.test.ts@@ -1,11 +1,11 @@import { describe, expect, it } from 'vitest';-import { DEFAULT_PRESERVE_PATTERNS, type ProjectSettings } from './project-settings';-import { hasConfiguredShareableProjectSettings } from './project-settings-fields';+import { DEFAULT_PRESERVE_PATTERNS, type LocationSettings } from './location-settings';+import { hasConfiguredShareableLocationSettings } from './location-settings-fields';-describe('hasConfiguredShareableProjectSettings', () => {+describe('hasConfiguredShareableLocationSettings', () => {it('does not treat seeded default preserve patterns as configured settings', () => {expect(- hasConfiguredShareableProjectSettings({+ hasConfiguredShareableLocationSettings({preservePatterns: [...DEFAULT_PRESERVE_PATTERNS],})).toBe(false);@@ -13,7 +13,7 @@ describe('hasConfiguredShareableProjectSettings', () => {it('does not treat reordered default preserve patterns as configured settings', () => {expect(- hasConfiguredShareableProjectSettings({+ hasConfiguredShareableLocationSettings({preservePatterns: [...DEFAULT_PRESERVE_PATTERNS].reverse(),})).toBe(false);@@ -21,14 +21,14 @@ describe('hasConfiguredShareableProjectSettings', () => {it('treats non-default preserve patterns as configured settings', () => {expect(- hasConfiguredShareableProjectSettings({+ hasConfiguredShareableLocationSettings({preservePatterns: ['.env*'],})).toBe(true);});it('treats scripts and shell setup as configured settings', () => {- const settings: ProjectSettings = {+ const settings: LocationSettings = {preservePatterns: [...DEFAULT_PRESERVE_PATTERNS],shellSetup: 'nvm use',scripts: {@@ -36,6 +36,6 @@ describe('hasConfiguredShareableProjectSettings', () => {},};- expect(hasConfiguredShareableProjectSettings(settings)).toBe(true);+ expect(hasConfiguredShareableLocationSettings(settings)).toBe(true);});});diff --git a/dash/apps/switchdash-desktop/src/shared/core/project-settings/project-settings-fields.ts b/dash/apps/switchdash-desktop/src/shared/core/location-settings/location-settings-fields.tssimilarity index 73%rename from dash/apps/switchdash-desktop/src/shared/core/project-settings/project-settings-fields.tsrename to dash/apps/switchdash-desktop/src/shared/core/location-settings/location-settings-fields.tsindex e01c6a60d..adaf8c0d7 100644--- a/dash/apps/switchdash-desktop/src/shared/core/project-settings/project-settings-fields.ts+++ b/dash/apps/switchdash-desktop/src/shared/core/location-settings/location-settings-fields.ts@@ -1,22 +1,22 @@import {DEFAULT_PRESERVE_PATTERNS,- SHAREABLE_PROJECT_SETTINGS_WRITE_FIELDS,- type ProjectSettings,- type ShareableProjectSettings,- type ShareableProjectSettingsWriteField,-} from './project-settings';+ SHAREABLE_LOCATION_SETTINGS_WRITE_FIELDS,+ type LocationSettings,+ type ShareableLocationSettings,+ type ShareableLocationSettingsWriteField,+} from './location-settings';type ShareableFieldAccessor = {path: string[];- get(settings: ShareableProjectSettings): unknown;- set(settings: ShareableProjectSettings, value: unknown): void;- clear(settings: ShareableProjectSettings): void;- displayValue(settings: ShareableProjectSettings): string | null;+ get(settings: ShareableLocationSettings): unknown;+ set(settings: ShareableLocationSettings, value: unknown): void;+ clear(settings: ShareableLocationSettings): void;+ displayValue(settings: ShareableLocationSettings): string | null;};function ensureScripts(- settings: ShareableProjectSettings-): NonNullable<ShareableProjectSettings['scripts']> {+ settings: ShareableLocationSettings+): NonNullable<ShareableLocationSettings['scripts']> {settings.scripts ??= {};return settings.scripts;}@@ -25,7 +25,7 @@ function displayText(value: string | undefined): string | null {return value?.trim() ? value : null;}-function compactScripts(settings: ShareableProjectSettings): void {+function compactScripts(settings: ShareableLocationSettings): void {if (settings.scripts && Object.values(settings.scripts).every((value) => value === undefined)) {delete settings.scripts;}@@ -35,15 +35,15 @@ function normalizePatterns(patterns: string[] | undefined): string[] {return patterns?.map((pattern) => pattern.trim()).filter(Boolean) ?? [];}-export function hasDefaultPreservePatterns(settings: ShareableProjectSettings): boolean {+export function hasDefaultPreservePatterns(settings: ShareableLocationSettings): boolean {const patterns = normalizePatterns(settings.preservePatterns);if (patterns.length !== DEFAULT_PRESERVE_PATTERNS.length) return false;const patternSet = new Set(patterns);return DEFAULT_PRESERVE_PATTERNS.every((pattern) => patternSet.has(pattern));}-export function hasConfiguredShareableProjectSettings(settings: ProjectSettings): boolean {- return SHAREABLE_PROJECT_SETTINGS_WRITE_FIELDS.some((field) => {+export function hasConfiguredShareableLocationSettings(settings: LocationSettings): boolean {+ return SHAREABLE_LOCATION_SETTINGS_WRITE_FIELDS.some((field) => {if (field === 'preservePatterns') {const patterns = normalizePatterns(settings.preservePatterns);return patterns.length > 0 && !hasDefaultPreservePatterns(settings);@@ -114,13 +114,13 @@ export const SHAREABLE_FIELD_ACCESSORS = {},displayValue: (settings) => displayText(settings.scripts?.teardown),},-} satisfies Record<ShareableProjectSettingsWriteField, ShareableFieldAccessor>;+} satisfies Record<ShareableLocationSettingsWriteField, ShareableFieldAccessor>;-export function clearShareableProjectSettingsFields<T extends ProjectSettings>(+export function clearShareableLocationSettingsFields<T extends LocationSettings>(settings: T,- fields: ShareableProjectSettingsWriteField[]+ fields: ShareableLocationSettingsWriteField[]): T {- const next: ProjectSettings = {+ const next: LocationSettings = {...settings,preservePatterns: settings.preservePatterns ? [...settings.preservePatterns] : undefined,scripts: settings.scripts ? { ...settings.scripts } : undefined,@@ -133,13 +133,13 @@ export function clearShareableProjectSettingsFields<T extends ProjectSettings>(return next as T;}-export function mergeShareableProjectSettings(- ...sources: ShareableProjectSettings[]-): ShareableProjectSettings {- const next: ShareableProjectSettings = {};+export function mergeShareableLocationSettings(+ ...sources: ShareableLocationSettings[]+): ShareableLocationSettings {+ const next: ShareableLocationSettings = {};for (const source of sources) {- for (const field of SHAREABLE_PROJECT_SETTINGS_WRITE_FIELDS) {+ for (const field of SHAREABLE_LOCATION_SETTINGS_WRITE_FIELDS) {const value = SHAREABLE_FIELD_ACCESSORS[field].get(source);if (value !== undefined) {SHAREABLE_FIELD_ACCESSORS[field].set(next, value);diff --git a/dash/apps/switchdash-desktop/src/shared/core/location-settings/location-settings.ts b/dash/apps/switchdash-desktop/src/shared/core/location-settings/location-settings.tsnew file mode 100644index 000000000..783053c35--- /dev/null+++ b/dash/apps/switchdash-desktop/src/shared/core/location-settings/location-settings.ts@@ -0,0 +1,158 @@+import z from 'zod';++export const LOCATION_CONFIG_FILE = '.switchdash.json';++export const DEFAULT_PRESERVE_PATTERNS = [+ '.env',+ '.env.keys',+ '.env.local',+ '.env.*.local',+ '.envrc',+ 'docker-compose.override.yml',+] as const;++const preservePatternsSchema = z+ .array(z.string())+ .transform((patterns) => patterns.filter((pattern) => pattern !== LOCATION_CONFIG_FILE));++export const shareableLocationScriptsSettingsSchema = z.object({+ setup: z.string().optional(),+ run: z.string().optional(),+ teardown: z.string().optional(),+});++export const shareableLocationSettingsSchema = z.object({+ preservePatterns: preservePatternsSchema.optional(),+ shellSetup: z.string().optional(),+ scripts: shareableLocationScriptsSettingsSchema.optional(),+});++export const shareableLocationSettingsWithDefaultsSchema = shareableLocationSettingsSchema.extend({+ preservePatterns: preservePatternsSchema.default([...DEFAULT_PRESERVE_PATTERNS]),+});++export type ShareableLocationSettings = z.infer<typeof shareableLocationSettingsSchema>;++export const baseLocationSettingsSchema = z.object({+ worktreeDirectory: z.string().trim().optional(),+ githubAccountId: z.string().trim().min(1).nullable().optional(),+ tmux: z.boolean().optional(),+ autoRunSetupScriptOnSessionCreation: z.boolean().optional(),+ autoRunRunScriptOnSessionCreation: z.boolean().optional(),+ locationProvider: z+ .object({+ type: z.literal('script'),+ provisionCommand: z.string().min(1),+ terminateCommand: z.string().min(1),+ })+ .optional(),+});++export type BaseLocationSettings = z.infer<typeof baseLocationSettingsSchema>;++export const legacyBaseLocationSettingsSchema = baseLocationSettingsSchema.extend({+ remote: z.string().optional(),+});++export const locationSettingsSchema = baseLocationSettingsSchema.merge(+ shareableLocationSettingsSchema+);++export const legacyLocationConfigSchema = legacyBaseLocationSettingsSchema.merge(+ shareableLocationSettingsSchema+);++export function defaultShareableLocationSettings(): ShareableLocationSettings {+ return shareableLocationSettingsWithDefaultsSchema.parse({});+}++export type LocationSettings = z.infer<typeof locationSettingsSchema>;++export type LocationSettingsPatch = {+ clearShareableFields?: ShareableLocationSettingsWriteField[];+ githubAccountId?: string | null;+};++export type LocationSettingsPage = {+ settings: LocationSettings;+ defaults: {+ worktreeDirectory: string;+ };+ writeTargets: LocationSettingsWriteTargetOption[];+ overrideState: LocationSettingsOverrideState;+ configMigrations: LocationConfigMigration[];+ shouldPromptConfigMigration: boolean;+};++export type LocationSettingsWriteTarget =+ | { type: 'location' }+ | { type: 'session'; sessionId: string }+ | { type: 'location-runtime'; locationId: string };++export type LocationSettingsWriteTargetOption = LocationSettingsWriteTarget & {+ label: string;+ path: string;+};++export type ShareableLocationSettingsWriteField =+ | 'preservePatterns'+ | 'shellSetup'+ | 'scripts.setup'+ | 'scripts.run'+ | 'scripts.teardown';++export const SHAREABLE_LOCATION_SETTINGS_WRITE_FIELDS = [+ 'preservePatterns',+ 'shellSetup',+ 'scripts.setup',+ 'scripts.run',+ 'scripts.teardown',+] as const satisfies ShareableLocationSettingsWriteField[];++export type WriteLocationConfigRequest = {+ target: LocationSettingsWriteTarget;+ fields: ShareableLocationSettingsWriteField[];+};++export type LocationSettingsOverrideSource = {+ label: string;+ path: string;+ value: string;+};++export type LocationSettingsOverrideState = Record<+ ShareableLocationSettingsWriteField,+ LocationSettingsOverrideSource[]+>;++export type LocationConfigMigrationProvider = 'conductor' | 'superset' | 'paseo' | 'codex';++export type LocationConfigMigration = {+ provider: LocationConfigMigrationProvider;+ label: string;+ files: string[];+ fields: ShareableLocationSettingsWriteField[];+ unsupportedFields: string[];+};++export type LocationConfigMigrationDestination = 'local' | 'shared';++export type MigrateLocationConfigRequest = {+ provider: LocationConfigMigrationProvider;+ destination: LocationConfigMigrationDestination;+};++export type MigrateLocationConfigResult = {+ page: LocationSettingsPage;+ migration: LocationConfigMigration;+};++export function emptyLocationSettingsOverrideState(): LocationSettingsOverrideState {+ return {+ preservePatterns: [],+ shellSetup: [],+ 'scripts.setup': [],+ 'scripts.run': [],+ 'scripts.teardown': [],+ };+}diff --git a/dash/apps/switchdash-desktop/src/shared/core/locations/locationEvents.ts b/dash/apps/switchdash-desktop/src/shared/core/locations/locationEvents.tsnew file mode 100644index 000000000..b140ace0d--- /dev/null+++ b/dash/apps/switchdash-desktop/src/shared/core/locations/locationEvents.ts@@ -0,0 +1,5 @@+import { defineEvent } from '@shared/lib/ipc/events';++export const locationSettingsChangedChannel = defineEvent<{+ locationId: string;+}>('location:settings-changed');diff --git a/dash/apps/switchdash-desktop/src/shared/core/locations/locations.ts b/dash/apps/switchdash-desktop/src/shared/core/locations/locations.tsnew file mode 100644index 000000000..64487b265--- /dev/null+++ b/dash/apps/switchdash-desktop/src/shared/core/locations/locations.ts@@ -0,0 +1,59 @@+import type { SwitchAgentConfig } from '@shared/switch-agents';++/**+ * A Location: where agents' sessions run — a working directory on a host.+ * Local locations live on this machine (`sshHost` null); remote ones on an+ * SSH host identified by its `~/.ssh/config` alias, with auth resolved from+ * the user's SSH config/agent (switchdash stores no credentials). Multiple+ * agents may share one location.+ */+export type Location = {+ id: string;+ name: string;+ /** `~/.ssh/config` Host alias; null when the location is on this machine. */+ sshHost: string | null;+ /** Absolute path to the working directory on the location's host. */+ dir: string;+ createdAt: string;+ updatedAt: string;+};++export type LocationKind = 'local' | 'ssh';++export function locationKind(location: Pick<Location, 'sshHost'>): LocationKind {+ return location.sshHost === null ? 'local' : 'ssh';+}++export type LocationPathStatus = {+ isDirectory: boolean;+};++export type InspectLocationPathParams = {+ path: string;+};++export type LocationPathInspection = LocationPathStatus & {+ existingLocation?: Location;+ /**+ * The Switch agent configured in this directory, if any (read from the dir's+ * `.claude/settings.local.json`). switchdash only allows onboarding+ * directories that resolve a Switch agent.+ */+ switchAgent?: SwitchAgentConfig | null;+};++export type OpenLocationError =+ | { type: 'path-not-found'; path: string }+ | { type: 'error'; message: string };++export type UpdateLocationSettingsError =+ | { type: 'location-not-found' }+ | { type: 'invalid-settings' }+ | { type: 'invalid-worktree-directory' }+ | { type: 'write-config-failed'; message: string }+ | { type: 'error' };++export type LocationRemoteState = {+ hasRemote: boolean;+ selectedRemoteUrl: string | null;+};diff --git a/dash/apps/switchdash-desktop/src/shared/core/mcp/catalog.ts b/dash/apps/switchdash-desktop/src/shared/core/mcp/catalog.tsindex 09594d19e..124641e04 100644--- a/dash/apps/switchdash-desktop/src/shared/core/mcp/catalog.ts+++ b/dash/apps/switchdash-desktop/src/shared/core/mcp/catalog.ts@@ -53,7 +53,7 @@ export const catalogData: Record<string, CatalogEntryDef> = {url: 'https://mcp.vercel.com',},name: 'Vercel',- description: 'Analyze, debug, and manage projects and deployments',+ description: 'Analyze, debug, and manage locations and deployments',docsUrl: 'https://vercel.com/docs/agent-resources/vercel-mcp',credentialKeys: [],},@@ -93,7 +93,7 @@ export const catalogData: Record<string, CatalogEntryDef> = {url: 'https://mcp.linear.app/mcp',},name: 'Linear',- description: 'Manage issues, projects & team workflows in Linear',+ description: 'Manage issues, locations & team workflows in Linear',docsUrl: 'https://linear.app/docs/mcp',credentialKeys: [],},@@ -329,7 +329,7 @@ export const catalogData: Record<string, CatalogEntryDef> = {url: 'https://mcp.asana.com/v2/mcp',},name: 'Asana',- description: 'Connect to Asana to coordinate sessions, projects, and goals',+ description: 'Connect to Asana to coordinate sessions, locations, and goals',docsUrl: 'https://developers.asana.com/docs/mcp-server',credentialKeys: [],},@@ -339,7 +339,7 @@ export const catalogData: Record<string, CatalogEntryDef> = {url: 'https://mcp.clickup.com/mcp',},name: 'ClickUp',- description: 'Project management & collaboration for teams & agents',+ description: 'Location management & collaboration for teams & agents',docsUrl: 'https://help.clickup.com/hc/en-us/articles/33335772678423-What-is-ClickUp-MCP',credentialKeys: [],},diff --git a/dash/apps/switchdash-desktop/src/shared/core/project-settings/project-settings.ts b/dash/apps/switchdash-desktop/src/shared/core/project-settings/project-settings.tsdeleted file mode 100644index c5f2354bd..000000000--- a/dash/apps/switchdash-desktop/src/shared/core/project-settings/project-settings.ts+++ /dev/null@@ -1,158 +0,0 @@-import z from 'zod';--export const PROJECT_CONFIG_FILE = '.switchdash.json';--export const DEFAULT_PRESERVE_PATTERNS = [- '.env',- '.env.keys',- '.env.local',- '.env.*.local',- '.envrc',- 'docker-compose.override.yml',-] as const;--const preservePatternsSchema = z- .array(z.string())- .transform((patterns) => patterns.filter((pattern) => pattern !== PROJECT_CONFIG_FILE));--export const shareableProjectScriptsSettingsSchema = z.object({- setup: z.string().optional(),- run: z.string().optional(),- teardown: z.string().optional(),-});--export const shareableProjectSettingsSchema = z.object({- preservePatterns: preservePatternsSchema.optional(),- shellSetup: z.string().optional(),- scripts: shareableProjectScriptsSettingsSchema.optional(),-});--export const shareableProjectSettingsWithDefaultsSchema = shareableProjectSettingsSchema.extend({- preservePatterns: preservePatternsSchema.default([...DEFAULT_PRESERVE_PATTERNS]),-});--export type ShareableProjectSettings = z.infer<typeof shareableProjectSettingsSchema>;--export const baseProjectSettingsSchema = z.object({- worktreeDirectory: z.string().trim().optional(),- githubAccountId: z.string().trim().min(1).nullable().optional(),- tmux: z.boolean().optional(),- autoRunSetupScriptOnSessionCreation: z.boolean().optional(),- autoRunRunScriptOnSessionCreation: z.boolean().optional(),- workspaceProvider: z- .object({- type: z.literal('script'),- provisionCommand: z.string().min(1),- terminateCommand: z.string().min(1),- })- .optional(),-});--export type BaseProjectSettings = z.infer<typeof baseProjectSettingsSchema>;--export const legacyBaseProjectSettingsSchema = baseProjectSettingsSchema.extend({- remote: z.string().optional(),-});--export const projectSettingsSchema = baseProjectSettingsSchema.merge(- shareableProjectSettingsSchema-);--export const legacyProjectConfigSchema = legacyBaseProjectSettingsSchema.merge(- shareableProjectSettingsSchema-);--export function defaultShareableProjectSettings(): ShareableProjectSettings {- return shareableProjectSettingsWithDefaultsSchema.parse({});-}--export type ProjectSettings = z.infer<typeof projectSettingsSchema>;--export type ProjectSettingsPatch = {- clearShareableFields?: ShareableProjectSettingsWriteField[];- githubAccountId?: string | null;-};--export type ProjectSettingsPage = {- settings: ProjectSettings;- defaults: {- worktreeDirectory: string;- };- writeTargets: ProjectSettingsWriteTargetOption[];- overrideState: ProjectSettingsOverrideState;- configMigrations: ProjectConfigMigration[];- shouldPromptConfigMigration: boolean;-};--export type ProjectSettingsWriteTarget =- | { type: 'project' }- | { type: 'session'; sessionId: string }- | { type: 'workspace'; workspaceId: string };--export type ProjectSettingsWriteTargetOption = ProjectSettingsWriteTarget & {- label: string;- path: string;-};--export type ShareableProjectSettingsWriteField =- | 'preservePatterns'- | 'shellSetup'- | 'scripts.setup'- | 'scripts.run'- | 'scripts.teardown';--export const SHAREABLE_PROJECT_SETTINGS_WRITE_FIELDS = [- 'preservePatterns',- 'shellSetup',- 'scripts.setup',- 'scripts.run',- 'scripts.teardown',-] as const satisfies ShareableProjectSettingsWriteField[];--export type WriteProjectConfigRequest = {- target: ProjectSettingsWriteTarget;- fields: ShareableProjectSettingsWriteField[];-};--export type ProjectSettingsOverrideSource = {- label: string;- path: string;- value: string;-};--export type ProjectSettingsOverrideState = Record<- ShareableProjectSettingsWriteField,- ProjectSettingsOverrideSource[]->;--export type ProjectConfigMigrationProvider = 'conductor' | 'superset' | 'paseo' | 'codex';--export type ProjectConfigMigration = {- provider: ProjectConfigMigrationProvider;- label: string;- files: string[];- fields: ShareableProjectSettingsWriteField[];- unsupportedFields: string[];-};--export type ProjectConfigMigrationDestination = 'local' | 'shared';--export type MigrateProjectConfigRequest = {- provider: ProjectConfigMigrationProvider;- destination: ProjectConfigMigrationDestination;-};--export type MigrateProjectConfigResult = {- page: ProjectSettingsPage;- migration: ProjectConfigMigration;-};--export function emptyProjectSettingsOverrideState(): ProjectSettingsOverrideState {- return {- preservePatterns: [],- shellSetup: [],- 'scripts.setup': [],- 'scripts.run': [],- 'scripts.teardown': [],- };-}diff --git a/dash/apps/switchdash-desktop/src/shared/core/projects/projectEvents.ts b/dash/apps/switchdash-desktop/src/shared/core/projects/projectEvents.tsdeleted file mode 100644index 72d40aba6..000000000--- a/dash/apps/switchdash-desktop/src/shared/core/projects/projectEvents.ts+++ /dev/null@@ -1,5 +0,0 @@-import { defineEvent } from '@shared/lib/ipc/events';--export const projectSettingsChangedChannel = defineEvent<{- projectId: string;-}>('project:settings-changed');diff --git a/dash/apps/switchdash-desktop/src/shared/core/providers/agent-provider-registry.ts b/dash/apps/switchdash-desktop/src/shared/core/providers/agent-provider-registry.tsindex ef5886f30..75d22d0a0 100644--- a/dash/apps/switchdash-desktop/src/shared/core/providers/agent-provider-registry.ts+++ b/dash/apps/switchdash-desktop/src/shared/core/providers/agent-provider-registry.ts@@ -99,7 +99,7 @@ export const AGENT_PROVIDERS: AgentProviderDefinition[] = [id: 'codex',name: 'Codex',description:- 'CLI that connects to OpenAI models for project-aware code assistance and terminal workflows.',+ 'CLI that connects to OpenAI models for location-aware code assistance and terminal workflows.',docUrl: 'https://github.com/openai/codex',installCommand: 'npm install -g @openai/codex',commands: ['codex'],@@ -187,7 +187,7 @@ export const AGENT_PROVIDERS: AgentProviderDefinition[] = [id: 'cursor',name: 'Cursor',description:- "Cursor's agent CLI; provides editor-style, project-aware assistance from the shell.",+ "Cursor's agent CLI; provides editor-style, location-aware assistance from the shell.",docUrl: 'https://cursor.com/docs/cli/overview',installCommand: 'curl https://cursor.com/install -fsS | bash',commands: ['cursor-agent'],@@ -296,7 +296,7 @@ export const AGENT_PROVIDERS: AgentProviderDefinition[] = [id: 'commandcode',name: 'Command Code',description:- 'Command Code CLI for terminal-first coding sessions that learn project and personal coding taste.',+ 'Command Code CLI for terminal-first coding sessions that learn location and personal coding taste.',docUrl: 'https://commandcode.ai/docs/reference/cli',installCommand: 'npm install -g command-code@latest',commands: ['command-code'],@@ -538,7 +538,7 @@ export const AGENT_PROVIDERS: AgentProviderDefinition[] = [id: 'codebuff',name: 'Codebuff',description:- 'Codebuff is an AI coding agent for project-directory assistance and day-to-day development sessions.',+ 'Codebuff is an AI coding agent for location-directory assistance and day-to-day development sessions.',docUrl: 'https://www.codebuff.com/docs/help/quick-start',installCommand: 'npm install -g codebuff',commands: ['codebuff'],@@ -553,7 +553,7 @@ export const AGENT_PROVIDERS: AgentProviderDefinition[] = [id: 'freebuff',name: 'Freebuff',description:- 'Freebuff is a standalone Codebuff package for project-directory assistance and day-to-day development sessions.',+ 'Freebuff is a standalone Codebuff package for location-directory assistance and day-to-day development sessions.',docUrl: 'https://freebuff.com',installCommand: 'npm install -g freebuff',commands: ['freebuff'],@@ -601,7 +601,7 @@ export const AGENT_PROVIDERS: AgentProviderDefinition[] = [id: 'junie',name: 'Junie',description:- 'JetBrains agentic coding CLI for interactive terminal and headless project workflows.',+ 'JetBrains agentic coding CLI for interactive terminal and headless location workflows.',docUrl: 'https://junie.jetbrains.com/docs/junie-cli.html',installCommand: 'curl -fsSL https://junie.jetbrains.com/install.sh | bash',commands: ['junie'],diff --git a/dash/apps/switchdash-desktop/src/shared/core/providers/agentEvents.ts b/dash/apps/switchdash-desktop/src/shared/core/providers/agentEvents.tsindex fdcbea34f..efb0f0cbe 100644--- a/dash/apps/switchdash-desktop/src/shared/core/providers/agentEvents.ts+++ b/dash/apps/switchdash-desktop/src/shared/core/providers/agentEvents.ts@@ -25,7 +25,6 @@ export interface AgentEvent {source?: 'hook' | 'input';ptyId?: string;providerId?: string;- projectId: string;sessionId: string;timestamp: number;payload: {diff --git a/dash/apps/switchdash-desktop/src/shared/core/pty/ptySessionId.ts b/dash/apps/switchdash-desktop/src/shared/core/pty/ptySessionId.tsindex a9b1799e7..c6ad892b6 100644--- a/dash/apps/switchdash-desktop/src/shared/core/pty/ptySessionId.ts+++ b/dash/apps/switchdash-desktop/src/shared/core/pty/ptySessionId.ts@@ -1,25 +1,25 @@/*** Deterministic PTY session IDs.*- * Agent sessions use `<projectId>:<sessionId>` — the session IS the agent run+ * Agent sessions use `<locationId>:<sessionId>` — the session IS the agent run* (one agent PTY per session). Terminal-scoped PTYs (lifecycle scripts) use- * `<projectId>:<scopeId>:<leafId>` where scopeId is a workspace id and leafId+ * `<locationId>:<scopeId>:<leafId>` where scopeId is the location id and leafId* a terminal id.** There is at most one active PTY per leaf entity. Using a deterministic ID* means the renderer can subscribe to ptyDataChannel BEFORE the PTY spawns —* no extra round-trip is needed to learn the session ID.*/-export function makeAgentPtySessionId(projectId: string, sessionId: string): string {- return `${projectId}:${sessionId}`;+export function makeAgentPtySessionId(locationId: string, sessionId: string): string {+ return `${locationId}:${sessionId}`;}-export function makePtySessionId(projectId: string, scopeId: string, leafId: string): string {- return `${projectId}:${scopeId}:${leafId}`;+export function makePtySessionId(locationId: string, scopeId: string, leafId: string): string {+ return `${locationId}:${scopeId}:${leafId}`;}export interface ParsedPtySessionId {- projectId: string;+ locationId: string;scopeId: string;leafId: string;}@@ -28,8 +28,8 @@ export function parsePtySessionId(id: string): ParsedPtySessionId | null {const parts = id.split(':');if (parts.length === 2 && parts[0] && parts[1]) {// Agent PTY: the session id is both the scope and the leaf.- return { projectId: parts[0], scopeId: parts[1], leafId: parts[1] };+ return { locationId: parts[0], scopeId: parts[1], leafId: parts[1] };}if (parts.length !== 3 || !parts[0] || !parts[1] || !parts[2]) return null;- return { projectId: parts[0], scopeId: parts[1], leafId: parts[2] };+ return { locationId: parts[0], scopeId: parts[1], leafId: parts[2] };}diff --git a/dash/apps/switchdash-desktop/src/shared/core/search.ts b/dash/apps/switchdash-desktop/src/shared/core/search.tsindex 6cff77031..70e5ff12e 100644--- a/dash/apps/switchdash-desktop/src/shared/core/search.ts+++ b/dash/apps/switchdash-desktop/src/shared/core/search.ts@@ -1,9 +1,9 @@-export type SearchItemKind = 'session' | 'project' | 'command' | 'file';+export type SearchItemKind = 'session' | 'location' | 'command' | 'file';export interface SearchItem {kind: SearchItemKind;id: string;- projectId: string | null;+ locationId: string | null;sessionId: string | null;title: string;subtitle: string;@@ -13,8 +13,7 @@ export interface SearchItem {export interface CommandPaletteQuery {query: string;context?: {- projectId?: string;sessionId?: string;- workspaceId?: string;+ locationId?: string;};}diff --git a/dash/apps/switchdash-desktop/src/shared/core/sessions/sessionEvents.ts b/dash/apps/switchdash-desktop/src/shared/core/sessions/sessionEvents.tsindex 21b14a0da..06736cda4 100644--- a/dash/apps/switchdash-desktop/src/shared/core/sessions/sessionEvents.ts+++ b/dash/apps/switchdash-desktop/src/shared/core/sessions/sessionEvents.ts@@ -6,13 +6,11 @@ export const sessionCreatedChannel = defineEvent<{ session: Session }>('session:export const sessionChangedChannel = defineEvent<{sessionId: string;- projectId: string;changes: Partial<Pick<Session, 'lastInteractedAt' | 'title' | 'providerSessionId'>>;}>('session:changed');export const sessionAgentStatusChangedChannel = defineEvent<{sessionId: string;- projectId: string;status: AgentStatus;seen: boolean;soundEvent?: 'needs_attention' | 'session_complete';@@ -34,37 +32,31 @@ export const sessionAgentStatusChangedChannel = defineEvent<{*/export const sessionDeletedChannel = defineEvent<{sessionId: string;- projectId: string;}>('session:deleted');export const sessionStatusUpdatedChannel = defineEvent<{sessionId: string;- projectId: string;status: string;}>('session:status-updated');export type ProvisionStep =- | 'resolving-worktree'- | 'initialising-workspace'+ | 'initialising-location'| 'running-provision-script'| 'connecting'- | 'setting-up-workspace'| 'starting-sessions';export const sessionProvisionProgressChannel = defineEvent<{sessionId: string;- projectId: string;step: ProvisionStep;message: string;}>('session:provision-progress');export type LifecycleScriptType = 'setup' | 'run' | 'teardown';-export type LifecycleScriptOrigin = 'auto-setup' | 'auto-run' | 'manual' | 'workspace-destroy';+export type LifecycleScriptOrigin = 'auto-setup' | 'auto-run' | 'manual' | 'location-destroy';export type LifecycleScriptStatusEvent = {sessionId: string;- projectId: string;- workspaceId: string;+ locationId: string;type: LifecycleScriptType;origin: LifecycleScriptOrigin;} & (@@ -86,8 +78,7 @@ export const lifecycleScriptStatusChannel = defineEvent<LifecycleScriptStatusEveexport const sessionProvisionedChannel = defineEvent<{sessionId: string;- projectId: string;path: string;- workspaceId: string;+ locationId: string;sshConnectionId?: string;}>('session:provisioned');diff --git a/dash/apps/switchdash-desktop/src/shared/core/sessions/sessions.ts b/dash/apps/switchdash-desktop/src/shared/core/sessions/sessions.tsindex 1be1c832c..77302fb62 100644--- a/dash/apps/switchdash-desktop/src/shared/core/sessions/sessions.ts+++ b/dash/apps/switchdash-desktop/src/shared/core/sessions/sessions.ts@@ -20,7 +20,7 @@ export type SessionLifecycleStatus = z.infer<typeof sessionLifecycleStatuses>;/*** A session: one instantiation/run of an agent (was switchdash's "conversation").- * It belongs to an agent (which carries the project + provider), and is 1:1+ * It belongs to an agent (which carries the location + provider), and is 1:1* with the terminal it runs in (`shellId`). `providerId` is denormalised from* the owning agent for rendering.*/diff --git a/dash/apps/switchdash-desktop/src/shared/core/terminals/general-session.ts b/dash/apps/switchdash-desktop/src/shared/core/terminals/general-session.tsindex 10b62a34e..e00056caa 100644--- a/dash/apps/switchdash-desktop/src/shared/core/terminals/general-session.ts+++ b/dash/apps/switchdash-desktop/src/shared/core/terminals/general-session.ts@@ -6,7 +6,7 @@ export interface GeneralSession {export interface GeneralSessionConfig {sessionId?: string;cwd: string;- projectPath?: string;+ locationPath?: string;shellSetup?: string;tmuxSessionName?: string;command?: string;diff --git a/dash/apps/switchdash-desktop/src/shared/core/terminals/terminals.ts b/dash/apps/switchdash-desktop/src/shared/core/terminals/terminals.tsindex 6b0889785..db10191aa 100644--- a/dash/apps/switchdash-desktop/src/shared/core/terminals/terminals.ts+++ b/dash/apps/switchdash-desktop/src/shared/core/terminals/terminals.ts@@ -2,7 +2,7 @@ import type { TerminalShellId } from './terminal-settings';export type Terminal = {id: string;- projectId: string;+ locationId: string;sessionId: string;shellId: TerminalShellId;name: string;@@ -10,7 +10,7 @@ export type Terminal = {export type CreateTerminalParams = {id: string;- projectId: string;+ locationId: string;sessionId: string;name: string;shell?: TerminalShellId;diff --git a/dash/apps/switchdash-desktop/src/shared/core/workspaces/build-workspace-config.test.ts b/dash/apps/switchdash-desktop/src/shared/core/workspaces/build-workspace-config.test.tsdeleted file mode 100644index 82bfd51fe..000000000--- a/dash/apps/switchdash-desktop/src/shared/core/workspaces/build-workspace-config.test.ts+++ /dev/null@@ -1,18 +0,0 @@-import { describe, expect, it } from 'vitest';-import { buildRepoRootWorkspaceConfig } from './build-workspace-config';--describe('buildRepoRootWorkspaceConfig', () => {- it('targets the repository-instance workspace when known', () => {- expect(buildRepoRootWorkspaceConfig('ws-1')).toEqual({- version: '3',- workspace: { kind: 'repository-instance', workspaceId: 'ws-1' },- });- });-- it('falls back to a transient target before the project is mounted', () => {- expect(buildRepoRootWorkspaceConfig()).toEqual({- version: '3',- workspace: { kind: 'new-worktree' },- });- });-});diff --git a/dash/apps/switchdash-desktop/src/shared/core/workspaces/build-workspace-config.ts b/dash/apps/switchdash-desktop/src/shared/core/workspaces/build-workspace-config.tsdeleted file mode 100644index 4eabeb722..000000000--- a/dash/apps/switchdash-desktop/src/shared/core/workspaces/build-workspace-config.ts+++ /dev/null@@ -1,17 +0,0 @@-import type { WorkspaceConfig } from './workspace-config';--/**- * Builds the WorkspaceConfig for a session, which always runs in the project's- * root directory. switchdash has no worktrees: a session uses the project's- * repository-instance workspace once it is known, falling back to a transient- * placeholder before the project is mounted and its repositoryWorkspaceId exists.- */-export function buildRepoRootWorkspaceConfig(repositoryWorkspaceId?: string): WorkspaceConfig {- if (!repositoryWorkspaceId) {- return { version: '3', workspace: { kind: 'new-worktree' } };- }- return {- version: '3',- workspace: { kind: 'repository-instance', workspaceId: repositoryWorkspaceId },- };-}diff --git a/dash/apps/switchdash-desktop/src/shared/core/workspaces/project-workspace.ts b/dash/apps/switchdash-desktop/src/shared/core/workspaces/project-workspace.tsdeleted file mode 100644index 4354f8ade..000000000--- a/dash/apps/switchdash-desktop/src/shared/core/workspaces/project-workspace.ts+++ /dev/null@@ -1,20 +0,0 @@-import type { WorkspaceConfig } from './workspace-config';--/**- * A workspace belonging to a project, as returned by `getProjectWorkspaces`.- * In switchdash every workspace is the project's root directory.- */-export type ProjectWorkspace = {- id: string;- path: string | null;- config: WorkspaceConfig | null;- linesAdded: number | null;- linesDeleted: number | null;- /** The session that owns this workspace, if any. Null for the project-root workspace. */- sessionId: string | null;- sessionName: string | null;- /** Whether the workspace is currently acquired in the in-memory registry. */- isLive: boolean;- /** Number of non-archived sessions currently linked to this workspace. */- linkedSessionCount: number;-};diff --git a/dash/apps/switchdash-desktop/src/shared/core/workspaces/workspace-config.ts b/dash/apps/switchdash-desktop/src/shared/core/workspaces/workspace-config.tsdeleted file mode 100644index 0c43aaaaa..000000000--- a/dash/apps/switchdash-desktop/src/shared/core/workspaces/workspace-config.ts+++ /dev/null@@ -1,142 +0,0 @@-import z from 'zod';-import { defineVersionedSchema } from '@shared/lib/versioned-schema/versioned-schema';--// ----------------------------------------------------------------------------// Supporting schemas (Branch and its dependencies)-// -----------------------------------------------------------------------------const remoteSchema = z.object({- name: z.string(),- url: z.string(),-});--const branchSchema = z.discriminatedUnion('type', [- z.object({ type: z.literal('local'), branch: z.string(), remote: remoteSchema.optional() }),- z.object({ type: z.literal('remote'), branch: z.string(), remote: remoteSchema }),-]);--// ----------------------------------------------------------------------------// GitSetup schema — mirrors GitSetup in src/shared/sessions.ts-// -----------------------------------------------------------------------------const gitSetupSchema = z.discriminatedUnion('kind', [- z.object({ kind: z.literal('none') }),- z.object({ kind: z.literal('use-branch'), branchName: z.string() }),- z.object({- kind: z.literal('create-branch'),- branchName: z.string(),- fromBranch: branchSchema,- pushBranch: z.boolean().optional(),- }),- z.object({- kind: z.literal('pr-branch'),- prNumber: z.number(),- headBranch: z.string(),- headRepositoryUrl: z.string(),- isFork: z.boolean(),- sessionBranch: z.string().optional(),- pushBranch: z.boolean().optional(),- }),-]);--// ----------------------------------------------------------------------------// v1 schema — stored in workspaces.config rows created before v2-// -----------------------------------------------------------------------------const workspaceLocationSchema = z.discriminatedUnion('host', [- z.object({ host: z.literal('local'), path: z.string().optional() }),- z.object({ host: z.literal('project-ssh'), path: z.string().optional() }),- z.object({ host: z.literal('byoi'), remoteWorkspaceId: z.string().optional() }),-]);--const v1Schema = z.object({- version: z.literal('1'),- git: gitSetupSchema,- workspace: workspaceLocationSchema,-});--// ----------------------------------------------------------------------------// v2 schema — current version-// -----------------------------------------------------------------------------const workspaceTargetSchema = z.discriminatedUnion('kind', [- z.object({ kind: z.literal('repository-instance'), workspaceId: z.string() }),- z.object({ kind: z.literal('new-worktree') }),- z.object({ kind: z.literal('byoi'), remoteWorkspaceId: z.string().optional() }),-]);--const v2Schema = z.object({- version: z.literal('2'),- git: gitSetupSchema,- workspace: workspaceTargetSchema,-});--// ----------------------------------------------------------------------------// v3 schema — current version-//-// switchdash has no git worktrees, branches, PRs, or BYOI: every session runs-// in the project root directory. The `git` field (always `none`) is dropped and-// the workspace target narrows to the repository instance or a transient-// placeholder created before the project's repository workspace is known.-// -----------------------------------------------------------------------------const v3WorkspaceTargetSchema = z.discriminatedUnion('kind', [- z.object({ kind: z.literal('repository-instance'), workspaceId: z.string() }),- z.object({ kind: z.literal('new-worktree') }),-]);--const v3Schema = z.object({- version: z.literal('3'),- workspace: v3WorkspaceTargetSchema,-});--// ----------------------------------------------------------------------------// Versioned schema-// -----------------------------------------------------------------------------/**- * Versioned schema for workspace configuration stored in `workspaces.config`.- *- * v1 → v2 upgrade: reshapes the `workspace` discriminant from `host`-based to- * `kind`-based. Returns `null` (needs-context) when `git.kind === 'none'` and- * the workspace host is local/project-ssh, because the `repositoryWorkspaceId`- * needed to produce a `repository-instance` target is not available here.- *- * v2 → v3 upgrade: drops the obsolete `git` field and maps the removed `byoi`- * target onto the transient `new-worktree` placeholder.- */-export const workspaceConfig = defineVersionedSchema()- .initial('1', v1Schema)- .version('2', v2Schema, (v1) => {- const { git, workspace } = v1;- if (workspace.host === 'byoi') {- return {- version: '2' as const,- git,- workspace: { kind: 'byoi' as const, remoteWorkspaceId: workspace.remoteWorkspaceId },- };- }- if (git.kind === 'none') {- // Cannot determine repositoryWorkspaceId here — caller must resolve.- return null;- }- return { version: '2' as const, git, workspace: { kind: 'new-worktree' as const } };- })- .version('3', v3Schema, (v2) => ({- version: '3' as const,- workspace: v2.workspace.kind === 'byoi' ? { kind: 'new-worktree' as const } : v2.workspace,- }))- .build();--// ----------------------------------------------------------------------------// Exports-// -----------------------------------------------------------------------------/** The Zod schema for the latest (v3) workspace config. */-export const workspaceConfigSchema = workspaceConfig.schema;--/** The TypeScript type for the latest (v3) workspace config. */-export type WorkspaceConfig = typeof workspaceConfig.Type;--/** The TypeScript type for the `workspace` field of a v3 config. */-export type WorkspaceTarget = z.infer<typeof v3WorkspaceTargetSchema>;diff --git a/dash/apps/switchdash-desktop/src/shared/core/workspaces/workspace-provider-data.ts b/dash/apps/switchdash-desktop/src/shared/core/workspaces/workspace-provider-data.tsdeleted file mode 100644index 24001788a..000000000--- a/dash/apps/switchdash-desktop/src/shared/core/workspaces/workspace-provider-data.ts+++ /dev/null@@ -1,33 +0,0 @@-import z from 'zod';-import { defineVersionedSchema } from '@shared/lib/versioned-schema/versioned-schema';--// ----------------------------------------------------------------------------// v0 schema — unversioned legacy format stored in workspaces.data-// -----------------------------------------------------------------------------const v0Schema = z.object({- type: z.literal('script'),- provisionCommand: z.string(),- terminateCommand: z.string(),- remoteWorkspaceId: z.string().optional(),-});--// ----------------------------------------------------------------------------// Versioned schema-// -----------------------------------------------------------------------------/**- * Versioned schema for BYOI workspace provider data stored in `workspaces.data`.- *- * Written once after a successful BYOI provision script run. The data captures- * the connection commands and optional remote workspace ID so the session can- * be reused on subsequent launches.- */-export const workspaceProviderData = defineVersionedSchema().unversioned(v0Schema).build();--// ----------------------------------------------------------------------------// Exports-// -----------------------------------------------------------------------------/** The TypeScript type for BYOI workspace provider data. */-export type WorkspaceProviderData = typeof workspaceProviderData.Type;diff --git a/dash/apps/switchdash-desktop/src/shared/core/workspaces/workspaces.ts b/dash/apps/switchdash-desktop/src/shared/core/workspaces/workspaces.tsdeleted file mode 100644index 1ff38ad63..000000000--- a/dash/apps/switchdash-desktop/src/shared/core/workspaces/workspaces.ts+++ /dev/null@@ -1,7 +0,0 @@-export type WorkspaceType = 'local' | 'project-ssh' | 'byoi';--export type WorkspaceResolution =- | { kind: 'ready' }- | { kind: 'needs_create' }- | { kind: 'branch_elsewhere'; branchName: string; candidatePath: string; previousPath: string }- | { kind: 'path_missing'; previousPath: string; branchName: string | null };diff --git a/dash/apps/switchdash-desktop/src/shared/events/appEvents.ts b/dash/apps/switchdash-desktop/src/shared/events/appEvents.tsindex 3df55283d..5c74ad045 100644--- a/dash/apps/switchdash-desktop/src/shared/events/appEvents.ts+++ b/dash/apps/switchdash-desktop/src/shared/events/appEvents.ts@@ -25,7 +25,7 @@ export const tabNavigationShortcutChannel = defineEvent<{}>('tab-navigation:shortcut');export const notificationFocusSessionChannel = defineEvent<{- projectId: string;+ agentId: string;sessionId: string;}>('notification:focus-session');@@ -33,16 +33,6 @@ export const ptyStartedChannel = defineEvent<{id: string;}>('pty:started');-export type PlanEvent = {- type: 'write_blocked' | 'remove_blocked';- root: string;- relPath: string;- code?: string;- message?: string;-};--export const planEventChannel = defineEvent<PlanEvent>('plan:event');-export const ptyDataChannel = defineEvent<string>('pty:data');export const ptyExitChannel = defineEvent<{diff --git a/dash/apps/switchdash-desktop/src/shared/lib/ipc/rpc.test.ts b/dash/apps/switchdash-desktop/src/shared/lib/ipc/rpc.test.tsindex 9cbc8588e..95853dd56 100644--- a/dash/apps/switchdash-desktop/src/shared/lib/ipc/rpc.test.ts+++ b/dash/apps/switchdash-desktop/src/shared/lib/ipc/rpc.test.ts@@ -29,20 +29,20 @@ const gitRepositoryController = createRPCController({branches: () => Promise.resolve(['main']),});-const wsFsController = createRPCController({+const nestedFsController = createRPCController({list: (dir: string) => Promise.resolve([dir]),});-const workspaceNamespace = createRPCNamespace({+const nestedNamespace = createRPCNamespace({gitWorktree: gitWorktreeController,- fs: wsFsController,+ fs: nestedFsController,});const router = createRPCRouter({vcs: vcsController,gitRepository: gitRepositoryController,fs: fsController,- workspace: workspaceNamespace,+ nested: nestedNamespace,});type Router = typeof router;@@ -83,9 +83,9 @@ describe('createRPCClient', () => {const invoke = vi.fn().mockResolvedValue('ok');const rpc = createRPCClient<Router>(invoke);- await rpc.workspace.gitWorktree.clone('https://example.com/repo');+ await rpc.nested.gitWorktree.clone('https://example.com/repo');- expect(invoke).toHaveBeenCalledWith('workspace.gitWorktree.clone', 'https://example.com/repo');+ expect(invoke).toHaveBeenCalledWith('nested.gitWorktree.clone', 'https://example.com/repo');});it('forwards multiple arguments correctly', async () => {@@ -110,9 +110,9 @@ describe('createRPCClient', () => {const invoke = vi.fn().mockResolvedValue([]);const rpc = createRPCClient<Router>(invoke);- await rpc.workspace.fs.list('projects');+ await rpc.nested.fs.list('locations');- expect(invoke).toHaveBeenCalledWith('workspace.fs.list', 'projects');+ expect(invoke).toHaveBeenCalledWith('nested.fs.list', 'locations');});});@@ -135,9 +135,9 @@ describe('registerRPCRouter', () => {const ipc = makeIpcMainStub();registerRPCRouter(router, ipc as never);- expect(ipc.registeredChannels()).toContain('workspace.gitWorktree.clone');+ expect(ipc.registeredChannels()).toContain('nested.gitWorktree.clone');expect(ipc.registeredChannels()).toContain('gitRepository.branches');- expect(ipc.registeredChannels()).toContain('workspace.fs.list');+ expect(ipc.registeredChannels()).toContain('nested.fs.list');});it('calls through to the original handler function with args', async () => {@@ -152,7 +152,7 @@ describe('registerRPCRouter', () => {const ipc = makeIpcMainStub();registerRPCRouter(router, ipc as never);- const result = await ipc.invoke('workspace.gitWorktree.clone', 'https://example.com');+ const result = await ipc.invoke('nested.gitWorktree.clone', 'https://example.com');expect(result).toBe('cloned https://example.com');});@@ -185,11 +185,11 @@ describe('IpcClient type-safety', () => {});it('types a nested procedure as an async function with the original signature', () => {- expectTypeOf(rpc.workspace.gitWorktree.clone).toEqualTypeOf<(url: string) => Promise<string>>();+ expectTypeOf(rpc.nested.gitWorktree.clone).toEqualTypeOf<(url: string) => Promise<string>>();});it('types a nested namespace as a sub-namespace object, not a callable', () => {- expectTypeOf(rpc.workspace).toEqualTypeOf<{+ expectTypeOf(rpc.nested).toEqualTypeOf<{fs: { list: (dir: string) => Promise<string[]> };gitWorktree: { clone: (url: string) => Promise<string> };}>();diff --git a/dash/apps/switchdash-desktop/src/shared/lib/ipc/rpc.ts b/dash/apps/switchdash-desktop/src/shared/lib/ipc/rpc.tsindex f9eaf4036..b39765be2 100644--- a/dash/apps/switchdash-desktop/src/shared/lib/ipc/rpc.ts+++ b/dash/apps/switchdash-desktop/src/shared/lib/ipc/rpc.ts@@ -43,8 +43,8 @@ export function registerRPCRouter(router: RouterMap, ipcMain: IpcMain): void {}// Recursively maps every leaf function to its async client equivalent.-// Non-function values recurse, so both 2-level (rpc.gitRepository.fetch) and-// 3-level (rpc.workspace.gitWorktree.commit) shapes are handled by a single type.+// Non-function values recurse, so both 2-level (rpc.agents.getAgentById) and+// 3-level (rpc.fs.watch.watchSetPaths) shapes are handled by a single type.type IpcClient<R> = {[K in keyof R]: R[K] extends (...args: infer A) => infer Ret? (...args: A) => Promise<Awaited<Ret>>diff --git a/dash/apps/switchdash-desktop/src/shared/path-name.test.ts b/dash/apps/switchdash-desktop/src/shared/path-name.test.tsindex 1c46e85e8..664e3e9d5 100644--- a/dash/apps/switchdash-desktop/src/shared/path-name.test.ts+++ b/dash/apps/switchdash-desktop/src/shared/path-name.test.ts@@ -3,11 +3,11 @@ import { basenameFromAnyPath, safePathSegment } from './path-name';describe('path-name helpers', () => {describe('basenameFromAnyPath', () => {- it('extracts a project name from a Windows path', () => {+ it('extracts a location name from a Windows path', () => {expect(basenameFromAnyPath('E:\\my_work\\github_pro\\switchdash')).toBe('switchdash');});- it('extracts a project name from a POSIX path', () => {+ it('extracts a location name from a POSIX path', () => {expect(basenameFromAnyPath('/home/admin/github_pro/switchdash')).toBe('switchdash');});@@ -18,22 +18,22 @@ describe('path-name helpers', () => {});describe('safePathSegment', () => {- it('keeps normal project names unchanged', () => {+ it('keeps normal location names unchanged', () => {expect(safePathSegment('switchdash')).toBe('switchdash');});- it('collapses path-shaped project names to a safe single segment', () => {+ it('collapses path-shaped location names to a safe single segment', () => {expect(safePathSegment('E:\\my_work\\github_pro\\switchdash')).toBe('switchdash');expect(safePathSegment('../switchdash')).toBe('switchdash');});it('falls back when no safe segment remains', () => {- expect(safePathSegment('///', 'project-id')).toBe('project-id');+ expect(safePathSegment('///', 'location-id')).toBe('location-id');});it('falls back for Windows reserved device names', () => {- expect(safePathSegment('NUL', 'project-id')).toBe('project-id');- expect(safePathSegment('com1', 'project-id')).toBe('project-id');+ expect(safePathSegment('NUL', 'location-id')).toBe('location-id');+ expect(safePathSegment('com1', 'location-id')).toBe('location-id');});});});diff --git a/dash/apps/switchdash-desktop/src/shared/path-name.ts b/dash/apps/switchdash-desktop/src/shared/path-name.tsindex f3010d51b..0f6f96edd 100644--- a/dash/apps/switchdash-desktop/src/shared/path-name.ts+++ b/dash/apps/switchdash-desktop/src/shared/path-name.ts@@ -11,7 +11,7 @@ export function basenameFromAnyPath(input: string): string {);}-export function safePathSegment(input: string, fallback = 'project'): string {+export function safePathSegment(input: string, fallback = 'location'): string {const segment = basenameFromAnyPath(input).replace(/[<>:"/\\|?*\x00-\x1f]/g, '-').trim();diff --git a/dash/apps/switchdash-desktop/src/shared/projects.ts b/dash/apps/switchdash-desktop/src/shared/projects.tsdeleted file mode 100644index 72f7e30b6..000000000--- a/dash/apps/switchdash-desktop/src/shared/projects.ts+++ /dev/null@@ -1,105 +0,0 @@-import type { Result } from '@switchdash/shared';-import type { AgentRemoteConfig } from '@shared/core/agents/agent-connection';-import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';-import type { SwitchAgentConfig } from '@shared/switch-agents';--export type ProjectPathStatus = {- isDirectory: boolean;-};--export type LocalProject = {- type: 'local';- id: string;- name: string;- /** The local working directory. Null for remote-only agents, whose working- * directory lives on an SSH host (see the agent's `remoteConfig`). */- path: string | null;- /** The workspace ID of this project's repository-root workspace. Set on first mount. */- repositoryWorkspaceId: string | null;- createdAt: string;- updatedAt: string;-};--export type Project = LocalProject;--export type CreateLocalProjectParams = {- type: 'local';- id?: string;- /** The local working directory. Omit for a remote agent, which has no local- * directory — its working directory is `remoteConfig.remoteRepoDir` on the host. */- path?: string;- name: string;- /** The registered Switch server the user chose for this agent. The agent must- * exist on it — verified server-side at create time. */- serverId: string;- /** The agent type (CLI provider) the user picked when onboarding. Persisted on- * the project's agent row and used to render its agent-type icon. */- providerId: AgentProviderId;- /** When set, the new agent runs remotely: its connection is set to `remote`- * with this config and its Switch credentials are copied to the host. Omit for- * a local agent (the default). */- remoteConfig?: AgentRemoteConfig;-};--export type CreateProjectParams = CreateLocalProjectParams;--export type CreateProjectError =- | { type: 'invalid-directory'; path: string; message: string }- | { type: 'not-repository'; path: string }- | { type: 'init-failed'; path: string; message: string }- | { type: 'open-repository-failed'; path: string; message: string }- /** The chosen Switch server does not have this agent — the user picked the- * wrong server, or the directory's `SWITCH_AGENT_ID` isn't registered there. */- | {- type: 'switch-agent-not-on-server';- path: string;- serverId: string;- serverName: string;- agentId: string;- }- /** The chosen Switch server is registered but this app is not signed in to it. */- | {- type: 'switch-server-unauthenticated';- path: string;- serverId: string;- serverName: string;- };--export type CreateProjectResult = Result<Project, CreateProjectError>;--export type InspectLocalProjectPathParams = {- type: 'local';- path: string;-};--export type InspectProjectPathParams = InspectLocalProjectPathParams;--export type ProjectPathInspection = ProjectPathStatus & {- existingProject?: Project;- /**- * The Switch agent configured in this directory, if any (read from the dir's- * `.claude/settings.local.json`). switchdash only allows adding directories- * that resolve a Switch agent. Always `null` for SSH paths in v0.- */- switchAgent?: SwitchAgentConfig | null;-};--export type OpenProjectError =- | { type: 'path-not-found'; path: string }- | { type: 'error'; message: string };--export type OpenProjectSuccess = {- repositoryWorkspaceId: string | null;-};--export type UpdateProjectSettingsError =- | { type: 'project-not-found' }- | { type: 'invalid-settings' }- | { type: 'invalid-worktree-directory' }- | { type: 'write-config-failed'; message: string }- | { type: 'error' };--export type ProjectRemoteState = {- hasRemote: boolean;- selectedRemoteUrl: string | null;-};diff --git a/dash/apps/switchdash-desktop/src/shared/resource-monitor.ts b/dash/apps/switchdash-desktop/src/shared/resource-monitor.tsindex 3796c1b6b..d14333e6c 100644--- a/dash/apps/switchdash-desktop/src/shared/resource-monitor.ts+++ b/dash/apps/switchdash-desktop/src/shared/resource-monitor.ts@@ -8,12 +8,12 @@ import type { AgentProviderId } from '@shared/core/providers/agent-provider-regi* `providerId` is populated for agent PTYs. `title` is populated* for agent sessions and user-created shell terminals. They are sourced from* the registry at register-time so the renderer can label entries even when- * the owning project isn't mounted (in which case the renderer-side store join+ * the owning location isn't mounted (in which case the renderer-side store join* would fail and the row would fall back to a leafId hex).*/export interface ResourcePtyEntry {sessionId: string;- projectId: string;+ locationId: string;scopeId: string;leafId: string;pid: number | undefined;diff --git a/dash/apps/switchdash-desktop/src/shared/shortcuts.ts b/dash/apps/switchdash-desktop/src/shared/shortcuts.tsindex da313ca13..02ecd3ebe 100644--- a/dash/apps/switchdash-desktop/src/shared/shortcuts.ts+++ b/dash/apps/switchdash-desktop/src/shared/shortcuts.ts@@ -145,16 +145,16 @@ export const APP_SHORTCUTS = defineShortcuts({description: 'Delete the selected sessions',category: 'Navigation',},- newProject: {+ newLocation: {defaultHotkey: 'Mod+Shift+N',- label: 'New Project',- description: 'Create a new project',+ label: 'New Location',+ description: 'Create a new location',category: 'Navigation',},openInEditor: {defaultHotkey: 'Mod+O',label: 'Open in Editor',- description: 'Open the project in the default editor',+ description: 'Open the location in the default editor',category: 'Navigation',},sidebarChanges: {diff --git a/dash/apps/switchdash-desktop/src/shared/view-state.ts b/dash/apps/switchdash-desktop/src/shared/view-state.tsindex cd951a32a..1980bf7b5 100644--- a/dash/apps/switchdash-desktop/src/shared/view-state.ts+++ b/dash/apps/switchdash-desktop/src/shared/view-state.ts@@ -1,7 +1,7 @@import type { AgentConnectionKind } from '@shared/core/agents/agent-connection';import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';-export type ProjectViewSnapshot = {+export type LocationViewSnapshot = {activeView: string;sessionViewTab: 'active' | 'archived';};@@ -19,9 +19,9 @@ export type SidebarGrouping = 'agent' | 'room';/** Persisted sidebar UI state; fields may be absent in older DB blobs. */export type SidebarSnapshot = {- expandedProjectIds?: string[];- projectOrder?: string[];- sessionOrderByProject?: Record<string, string[]>;+ expandedLocationIds?: string[];+ locationOrder?: string[];+ sessionOrderByLocation?: Record<string, string[]>;sessionSortBy?: SidebarSessionSortBy;grouping?: SidebarGrouping;/** Expanded room keys in room-focused grouping (room id, or '__unassigned__'). */diff --git a/dash/apps/switchdash-desktop/src/sidecar/index.ts b/dash/apps/switchdash-desktop/src/sidecar/index.tsindex 6bf2cae30..46c8094a6 100644--- a/dash/apps/switchdash-desktop/src/sidecar/index.ts+++ b/dash/apps/switchdash-desktop/src/sidecar/index.ts@@ -59,7 +59,6 @@ async function main(): Promise<void> {const log = createSidecarLogger(process.env.SWITCHDASH_SIDECAR_LOG_LEVEL, 'sidecar');const repoDir = requireEnv('SWITCHDASH_SIDECAR_REPO_DIR');- const projectId = requireEnv('SWITCHDASH_SIDECAR_PROJECT_ID');const deeplinkScheme = process.env.SWITCHDASH_SIDECAR_DEEPLINK_SCHEME?.trim() || 'switchdash';const creds = await readSwitchAgentCredentials(repoDir, log);@@ -101,7 +100,6 @@ async function main(): Promise<void> {const runtime = new SidecarRuntime({creds,- projectId,deeplinkScheme,tmuxRun: createTmuxRun(log),isPaneLive,diff --git a/dash/apps/switchdash-desktop/src/sidecar/session-spawner.test.ts b/dash/apps/switchdash-desktop/src/sidecar/session-spawner.test.tsindex 038d4f349..dc523f07a 100644--- a/dash/apps/switchdash-desktop/src/sidecar/session-spawner.test.ts+++ b/dash/apps/switchdash-desktop/src/sidecar/session-spawner.test.ts@@ -31,7 +31,7 @@ function makeSpawner(over: Partial<InProcessSessionSpawnerDeps> = {}) {const runtime = { hasLiveRoom: vi.fn(() => false) };const spawner = new InProcessSessionSpawner({spec: SPEC,- projectId: 'proj-1',+ locationId: 'proj-1',hookPort: 4321,hookToken: 'hooktok',runtime,diff --git a/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.test.ts b/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.test.tsindex f1eff9839..3bd0ad1f2 100644--- a/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.test.ts+++ b/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.test.ts@@ -43,7 +43,7 @@ function makeRuntime() {};const runtime = new SidecarRuntime({creds: { agentId: 'agent-1', apiEndpoint: 'https://switch.test', token: 'tok' },- projectId: 'proj-1',+ locationId: 'proj-1',deeplinkScheme: 'switchdash',tmuxRun: vi.fn(),isPaneLive: () => true,@@ -147,7 +147,7 @@ describe('SidecarRuntime (multi-session)', () => {let paneLive = true;const runtime = new SidecarRuntime({creds: { agentId: 'agent-1', apiEndpoint: 'https://switch.test', token: 'tok' },- projectId: 'proj-1',+ locationId: 'proj-1',deeplinkScheme: 'switchdash',tmuxRun: vi.fn(),isPaneLive: () => paneLive,diff --git a/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.ts b/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.tsindex b2935d386..7cdb9c719 100644--- a/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.ts+++ b/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.ts@@ -33,8 +33,6 @@ export const defaultRoomConnectionFactory: RoomConnectionFactory = (deps) =>export interface SidecarRuntimeDeps {creds: SwitchCredentials;- /** switchdash project id, used to derive each session's tmux target. */- projectId: string;deeplinkScheme: string;tmuxRun: TmuxRun;/** Whether a given agent tmux target is currently live (poller-backed cache). */@@ -75,7 +73,6 @@ export class SidecarRuntime {if (!parsed) return null;return {sessionId: parsed.sessionId,- projectId: deps.projectId,providerId: parsed.providerId,ptyId,};diff --git a/dash/apps/switchdash-desktop/src/sidecar/vm-tmux.ts b/dash/apps/switchdash-desktop/src/sidecar/vm-tmux.tsindex e811cb870..f5053363e 100644--- a/dash/apps/switchdash-desktop/src/sidecar/vm-tmux.ts+++ b/dash/apps/switchdash-desktop/src/sidecar/vm-tmux.ts@@ -18,7 +18,7 @@ export function makeTmuxSessionName(sessionId: string): string {/*** Agent pane name, keyed on the shared session id alone. Mirrors switchdash's* `makeAgentTmuxSessionName` so the sidecar and every attached client converge- * on ONE pane per session (CHOO-1181). Must not fold in projectId — it is+ * on ONE pane per session (CHOO-1181). Must not fold in locationId — it is* switchdash-instance-local and would diverge per client.*/export function makeAgentTmuxSessionName(sessionId: string): string {diff --git a/dash/apps/switchdash-desktop/tooling/fixtures/baseline.db b/dash/apps/switchdash-desktop/tooling/fixtures/baseline.dbindex 4b30a6bde..8608034ac 100644Binary files a/dash/apps/switchdash-desktop/tooling/fixtures/baseline.db and b/dash/apps/switchdash-desktop/tooling/fixtures/baseline.db differdiff --git a/dash/apps/switchdash-desktop/tooling/fixtures/empty.db b/dash/apps/switchdash-desktop/tooling/fixtures/empty.dbindex fa155ad9d..2dd336c6c 100644Binary files a/dash/apps/switchdash-desktop/tooling/fixtures/empty.db and b/dash/apps/switchdash-desktop/tooling/fixtures/empty.db differdiff --git a/dash/apps/switchdash-desktop/tooling/fixtures/pre-0031.db b/dash/apps/switchdash-desktop/tooling/fixtures/pre-0031.dbnew file mode 100644index 000000000..767f5986dBinary files /dev/null and b/dash/apps/switchdash-desktop/tooling/fixtures/pre-0031.db differdiff --git a/dash/apps/switchdash-desktop/tooling/fixtures/pre-0031.db-shm b/dash/apps/switchdash-desktop/tooling/fixtures/pre-0031.db-shmnew file mode 100644index 000000000..5f4425d91Binary files /dev/null and b/dash/apps/switchdash-desktop/tooling/fixtures/pre-0031.db-shm differdiff --git a/dash/apps/switchdash-desktop/tooling/fixtures/pre-0031.db-wal b/dash/apps/switchdash-desktop/tooling/fixtures/pre-0031.db-walnew file mode 100644index 000000000..e69de29bbdiff --git a/dash/apps/switchdash-desktop/tooling/seeds/baseline.ts b/dash/apps/switchdash-desktop/tooling/seeds/baseline.tsindex 465d32c2c..066857a3e 100644--- a/dash/apps/switchdash-desktop/tooling/seeds/baseline.ts+++ b/dash/apps/switchdash-desktop/tooling/seeds/baseline.ts@@ -1,12 +1,14 @@import type { AppDb } from '@main/db/client';-import { agents, messages, projects, projectSettings, sessions } from '@main/db/schema';+import { agents, locations, locationSettings, messages, sessions } from '@main/db/schema';// Fixed UUIDs so fixture content is stable across regenerations.-const PROJECT_A_ID = '11111111-1111-1111-1111-111111111111';-const PROJECT_B_ID = '22222222-2222-2222-2222-222222222222';+const LOCATION_A_ID = '11111111-1111-1111-1111-111111111111';+const LOCATION_B_ID = '22222222-2222-2222-2222-222222222222';+const LOCATION_C_ID = '33333333-3333-3333-3333-333333333333';const AGENT_A_ID = 'a9e70001-0000-0000-0000-000000000000';const AGENT_B_ID = 'a9e70002-0000-0000-0000-000000000000';+const AGENT_C_ID = 'a9e70003-0000-0000-0000-000000000000';const TASK_A1_ID = 'aaaa0001-0000-0000-0000-000000000000';const TASK_A2_ID = 'aaaa0002-0000-0000-0000-000000000000';@@ -18,32 +20,40 @@ const MSG_A2_ID = 'dddd0002-0000-0000-0000-000000000000';/*** Realistic but fully synthetic dataset — no sensitive data.- * Represents a developer's day-to-day switchdash state: two projects, each with- * a Switch agent, four sessions across various lifecycle statuses, and a couple- * of messages.+ * Represents a developer's day-to-day switchdash state: two local locations and+ * one remote, each with a Switch agent, four sessions across various lifecycle+ * statuses, and a couple of messages.*/export async function baseline(db: AppDb): Promise<void> {- await db.insert(projects).values([+ await db.insert(locations).values([{- id: PROJECT_A_ID,+ id: LOCATION_A_ID,name: 'switchdash',- path: '/home/dev/projects/switchdash',+ sshHost: '',+ dir: '/home/dev/projects/switchdash',},{- id: PROJECT_B_ID,+ id: LOCATION_B_ID,name: 'my-api',- path: '/home/dev/projects/my-api',+ sshHost: '',+ dir: '/home/dev/projects/my-api',+ },+ {+ id: LOCATION_C_ID,+ name: 'remote-worker',+ sshHost: 'build-vm',+ dir: '/srv/agents/remote-worker',},]);await db- .insert(projectSettings)- .values([{ projectId: PROJECT_A_ID }, { projectId: PROJECT_B_ID }]);+ .insert(locationSettings)+ .values([{ locationId: LOCATION_A_ID }, { locationId: LOCATION_B_ID }]);await db.insert(agents).values([{id: AGENT_A_ID,- projectId: PROJECT_A_ID,+ locationId: LOCATION_A_ID,name: 'switchdash',providerId: 'claude',switchAgentId: 'switch-agent-a',@@ -51,12 +61,20 @@ export async function baseline(db: AppDb): Promise<void> {},{id: AGENT_B_ID,- projectId: PROJECT_B_ID,+ locationId: LOCATION_B_ID,name: 'my-api',providerId: 'claude',switchAgentId: 'switch-agent-b',apiEndpoint: 'https://switch.example.com',},+ {+ id: AGENT_C_ID,+ locationId: LOCATION_C_ID,+ name: 'remote-worker',+ providerId: 'claude',+ switchAgentId: 'switch-agent-c',+ apiEndpoint: 'https://switch.example.com',+ },]);await db.insert(sessions).values([