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 the subagent concept — flat repository-defined agents (CHOO-1440) (#64)
Louis Amaudruzd6a34b8ed54b
diff --git a/dash/apps/switchdash-desktop/drizzle/0040_massive_dreadnoughts.sql b/dash/apps/switchdash-desktop/drizzle/0040_massive_dreadnoughts.sqlnew file mode 100644index 000000000..0e9150303--- /dev/null+++ b/dash/apps/switchdash-desktop/drizzle/0040_massive_dreadnoughts.sql@@ -0,0 +1 @@+ALTER TABLE `agents` ADD `definition_name` text;\ No newline at end of filediff --git a/dash/apps/switchdash-desktop/drizzle/meta/0040_snapshot.json b/dash/apps/switchdash-desktop/drizzle/meta/0040_snapshot.jsonnew file mode 100644index 000000000..b94fbdd53--- /dev/null+++ b/dash/apps/switchdash-desktop/drizzle/meta/0040_snapshot.json@@ -0,0 +1,718 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "42cda662-cb01-492f-b667-cc190d511d8f",+ "prevId": "25b952e3-7377-460c-a144-8ea04170b171",+ "tables": {+ "agents": {+ "name": "agents",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "location_id": {+ "name": "location_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider_id": {+ "name": "provider_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "definition_name": {+ "name": "definition_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "switch_agent_id": {+ "name": "switch_agent_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "api_endpoint": {+ "name": "api_endpoint",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "server_id": {+ "name": "server_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "auto_approve": {+ "name": "auto_approve",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "idx_agents_location_id": {+ "name": "idx_agents_location_id",+ "columns": ["location_id"],+ "isUnique": false+ },+ "idx_agents_server_id": {+ "name": "idx_agents_server_id",+ "columns": ["server_id"],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "agents_location_id_locations_id_fk": {+ "name": "agents_location_id_locations_id_fk",+ "tableFrom": "agents",+ "tableTo": "locations",+ "columnsFrom": ["location_id"],+ "columnsTo": ["id"],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "agents_server_id_switch_servers_id_fk": {+ "name": "agents_server_id_switch_servers_id_fk",+ "tableFrom": "agents",+ "tableTo": "switch_servers",+ "columnsFrom": ["server_id"],+ "columnsTo": ["id"],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "app_secrets": {+ "name": "app_secrets",+ "columns": {+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "secret": {+ "name": "secret",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_app_secrets_key": {+ "name": "idx_app_secrets_key",+ "columns": ["key"],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "app_settings": {+ "name": "app_settings",+ "columns": {+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "idx_app_settings_key": {+ "name": "idx_app_settings_key",+ "columns": ["key"],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "kv": {+ "name": "kv",+ "columns": {+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "idx_kv_key": {+ "name": "idx_kv_key",+ "columns": ["key"],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "location_settings": {+ "name": "location_settings",+ "columns": {+ "location_id": {+ "name": "location_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "base_settings_json": {+ "name": "base_settings_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "shareable_settings_json": {+ "name": "shareable_settings_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "legacy_config_migrated_at": {+ "name": "legacy_config_migrated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "location_settings_location_id_locations_id_fk": {+ "name": "location_settings_location_id_locations_id_fk",+ "tableFrom": "location_settings",+ "tableTo": "locations",+ "columnsFrom": ["location_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "locations": {+ "name": "locations",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ssh_host": {+ "name": "ssh_host",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "dir": {+ "name": "dir",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "idx_locations_host_dir": {+ "name": "idx_locations_host_dir",+ "columns": ["ssh_host", "dir"],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "messages": {+ "name": "messages",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "sender": {+ "name": "sender",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "timestamp": {+ "name": "timestamp",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_messages_session_id": {+ "name": "idx_messages_session_id",+ "columns": ["session_id"],+ "isUnique": false+ },+ "idx_messages_timestamp": {+ "name": "idx_messages_timestamp",+ "columns": ["timestamp"],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "messages_session_id_sessions_id_fk": {+ "name": "messages_session_id_sessions_id_fk",+ "tableFrom": "messages",+ "tableTo": "sessions",+ "columnsFrom": ["session_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "remote_hosts": {+ "name": "remote_hosts",+ "columns": {+ "ssh_host": {+ "name": "ssh_host",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "sessions": {+ "name": "sessions",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "agent_id": {+ "name": "agent_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "config": {+ "name": "config",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "shell_id": {+ "name": "shell_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'system'"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "agent_session_id": {+ "name": "agent_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "agent_status": {+ "name": "agent_status",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "agent_status_seen": {+ "name": "agent_status_seen",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": 1+ },+ "is_initial_session": {+ "name": "is_initial_session",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "is_pinned": {+ "name": "is_pinned",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "archived_at": {+ "name": "archived_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_interacted_at": {+ "name": "last_interacted_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "status_changed_at": {+ "name": "status_changed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "idx_sessions_agent_id": {+ "name": "idx_sessions_agent_id",+ "columns": ["agent_id"],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "sessions_agent_id_agents_id_fk": {+ "name": "sessions_agent_id_agents_id_fk",+ "tableFrom": "sessions",+ "tableTo": "agents",+ "columnsFrom": ["agent_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "switch_servers": {+ "name": "switch_servers",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "gateway_url": {+ "name": "gateway_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "api_url": {+ "name": "api_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "managed": {+ "name": "managed",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "management_kind": {+ "name": "management_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "ssh_host": {+ "name": "ssh_host",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "idx_switch_servers_gateway_url": {+ "name": "idx_switch_servers_gateway_url",+ "columns": ["gateway_url"],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ }+ },+ "views": {},+ "enums": {},+ "_meta": {+ "schemas": {},+ "tables": {},+ "columns": {}+ },+ "internal": {+ "indexes": {}+ }+}diff --git a/dash/apps/switchdash-desktop/drizzle/meta/_journal.json b/dash/apps/switchdash-desktop/drizzle/meta/_journal.jsonindex 5955655af..94e6de660 100644--- a/dash/apps/switchdash-desktop/drizzle/meta/_journal.json+++ b/dash/apps/switchdash-desktop/drizzle/meta/_journal.json@@ -281,6 +281,13 @@"when": 1784829154686,"tag": "0039_new_ben_parker","breakpoints": true+ },+ {+ "idx": 40,+ "version": "6",+ "when": 1784989270502,+ "tag": "0040_massive_dreadnoughts",+ "breakpoints": true}]}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 28aea76c4..a5f6795e3 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@@ -23,24 +23,41 @@ export async function ensureAgentSidecar(params: {deeplinkScheme: string;/** The agent's bypass-permissions setting, baked into the auto-start launch spec. */autoApprove: boolean;+ /** Per-agent creds slug (definition name, else agent id) — selects the sidecar's+ * `.switch/agents/<slug>.json` identity file (CHOO-1440). */+ credsSlug: string;+ /** The agent's definition name (null if none) — so auto-started sessions launch+ * as the definition with its own identity. */+ definitionName: string | null;ctx: IExecutionContext;connectionId: string;host: SidecarHost;}): Promise<SidecarEndpoint> {- const { providerId, repoDir, deeplinkScheme, autoApprove, ctx, connectionId, host } = params;+ const {+ providerId,+ repoDir,+ deeplinkScheme,+ autoApprove,+ credsSlug,+ definitionName,+ ctx,+ connectionId,+ host,+ } = params;const launchSpec = await generateAgentLaunchSpec({providerId,remoteRepoDir: repoDir,deeplinkScheme,autoApprove,+ agentName: definitionName,ctx,connectionId,});const launcher = new RemoteSidecarLauncher({host,bundlePath: resolveSidecarBundlePath(),- sidecarTmuxName: agentSidecarTmuxName(repoDir),- config: { repoDir, deeplinkScheme, launchSpec },+ sidecarTmuxName: agentSidecarTmuxName(repoDir, credsSlug),+ config: { repoDir, deeplinkScheme, launchSpec, credsSlug },log,});return launcher.deployAndLaunch();@@ -60,24 +77,41 @@ export async function probeAgentSidecar(params: {/** The agent's bypass-permissions setting. Probe never writes the spec, so this* only shapes the (unused) config; pass the real value for consistency. */autoApprove: boolean;+ /** Per-agent creds slug (definition name, else agent id). Probe never launches,+ * so this only shapes the (unused) config; pass the real value for consistency. */+ credsSlug: string;+ /** The agent's definition name (null if none). Probe never launches; passed for+ * consistency with ensureAgentSidecar. */+ definitionName: string | null;ctx: IExecutionContext;connectionId: string;host: SidecarHost;}): Promise<SidecarEndpoint | null> {- const { providerId, repoDir, deeplinkScheme, autoApprove, ctx, connectionId, host } = params;+ const {+ providerId,+ repoDir,+ deeplinkScheme,+ autoApprove,+ credsSlug,+ definitionName,+ ctx,+ connectionId,+ host,+ } = params;const launchSpec = await generateAgentLaunchSpec({providerId,remoteRepoDir: repoDir,deeplinkScheme,autoApprove,+ agentName: definitionName,ctx,connectionId,});const launcher = new RemoteSidecarLauncher({host,bundlePath: resolveSidecarBundlePath(),- sidecarTmuxName: agentSidecarTmuxName(repoDir),- config: { repoDir, deeplinkScheme, launchSpec },+ sidecarTmuxName: agentSidecarTmuxName(repoDir, credsSlug),+ config: { repoDir, deeplinkScheme, launchSpec, credsSlug },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 15e479f69..793f80a05 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@@ -55,6 +55,10 @@ vi.mock('@main/core/switch-rooms/switch-notification-poller', () => ({},}));+vi.mock('@main/core/switch-rooms/switch-credentials', () => ({+ readAgentSwitchEnv: vi.fn(async () => ({})),+}));+vi.mock('@main/core/providers/plugin-registry', () => ({getPlugin: vi.fn((id: string) => ({metadata: { id },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 a2d576c20..0115cee82 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@@ -5,6 +5,7 @@ import { ensureHooksInstalled } from '@main/core/agent-hooks/hook-config-serviceimport { 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';+import { agentSettingsPath } from '@main/core/agents/switch-settings-paths';import { localDependencyManager } from '@main/core/dependencies/dependency-managers';import { hostDependencyStore } from '@main/core/dependencies/host-dependency-store';import type { IExecutionContext } from '@main/core/execution-context/types';@@ -19,6 +20,7 @@ import { getTerminalColorEnv } from '@main/core/pty/terminal-color-scheme';import { killTmuxSession, makeAgentTmuxSessionName } from '@main/core/pty/tmux-session-name';import { sessionHooks } from '@main/core/sessions/session-hooks';import { providerOverrideSettings } from '@main/core/settings/provider-settings-service';+import { readAgentSwitchEnv } from '@main/core/switch-rooms/switch-credentials';import { switchNotificationPoller } from '@main/core/switch-rooms/switch-notification-poller';import { switchRoomService } from '@main/core/switch-rooms/switch-room-service';import type { ResolvedShellProfile } from '@main/core/terminal-shell/types';@@ -130,7 +132,7 @@ export class LocalAgentRuntime implements AgentRuntimeProvider {const providerConfig = await providerOverrideSettings.getItem(session.providerId);const agentSession = resolveAgentSessionCommandArgs(session, isResuming);const plugin = getPlugin(session.providerId);- const subagentsBehavior = plugin.behavior.subagents;+ const repoAgents = plugin.behavior.repoAgents;const binaryName = plugin.capabilities.hostDependency.binaryNames[0] ?? session.providerId;const cachedStatePath = localDependencyManager.get(session.providerId as never)?.path;@@ -142,15 +144,14 @@ export class LocalAgentRuntime implements AgentRuntimeProvider {cachedStatePath,});- const extraArgs = [- ...parseExtraArgs(providerConfig?.extraArgs),- ...(session.subagentName && subagentsBehavior- ? subagentsBehavior.launchArgs(this.sessionPath, session.subagentName)- : []),- ];const agentCommand = plugin.behavior.prompt!.buildCommand({cli: executableCli,- extraArgs,+ extraArgs: parseExtraArgs(providerConfig?.extraArgs),+ // The provider owns how to run as the named agent (CHOO-1440).+ agentArgs:+ session.agentName && repoAgents+ ? repoAgents.launchArgs(this.sessionPath, session.agentName)+ : [],autoApprove: session.autoApprove ?? false,initialPrompt: agentSession.isResuming ? undefined : initialPrompt,sessionId: agentSession.sessionId,@@ -185,17 +186,18 @@ export class LocalAgentRuntime implements AgentRuntimeProvider {const port = agentHookService.getPort();const token = agentHookService.getToken();const colorEnv = await getTerminalColorEnv();- // A subagent session must talk to Switch as the subagent, not the parent- // whose creds live in `.claude/settings.local.json`. Real env vars outrank- // every settings file and reach the spawned MCP server, so inject them- // last (highest precedence).+ // A session talks to Switch as its own agent, not whatever identity happens+ // to sit in `.claude/settings.local.json`. Real env vars outrank every+ // settings file and reach the spawned MCP server, so inject the agent's+ // identity last (highest precedence): a subagent from its definition creds,+ // and a plain agent from its provider-neutral `.switch/agents/<id>.json`+ // (empty when absent — the session then falls back to settings.local.json,+ // which Claude reads natively). Lets agents sharing a location keep distinct+ // identities (CHOO-1440).const subagentVars =- session.subagentName && subagentsBehavior- ? await subagentsBehavior.readLaunchEnv(- createPluginFs(this.sessionPath),- session.subagentName- )- : {};+ session.agentName && repoAgents+ ? await repoAgents.readLaunchEnv(createPluginFs(this.sessionPath), session.agentName)+ : await readAgentSwitchEnv(agentSettingsPath(this.sessionPath, session.agentId), log);const pty = spawnLocalPty({id: ptySessionId,command: resolved.command,diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.test.tsindex 7730d68b4..f4192add7 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@@ -23,6 +23,7 @@ const CONFIG: SidecarLaunchConfig = {repoDir: '/home/dev/repo',deeplinkScheme: 'switchdash',launchSpec: SPEC,+ credsSlug: 'claude-code.repo.me',};const readyLine = (hash: string | undefined = 'hash-v1'): string =>@@ -126,9 +127,12 @@ describe('RemoteSidecarLauncher', () => {{ local: '/local/dist-sidecar/sidecar.mjs', remote: '.switchdash/sidecar.mjs' },]);const specWrite = calls.find((c) => c.command === 'sh' && isLaunchSpecWrite(c.args[1] ?? ''));- expect(specWrite!.args[1]).toContain('.switchdash/agent-launch-spec.json');- // Atomic: write to a per-process temp then mv into place, so agents sharing a- // repo dir can't interleave writes and leave a torn, unparseable spec file.+ // Per-agent state path (keyed by the creds slug), not the shared per-dir path.+ expect(specWrite!.args[1]).toContain(+ '.switchdash/agents/claude-code.repo.me/agent-launch-spec.json'+ );+ // Atomic: write to a per-process temp then mv into place, so nothing observes+ // a torn, unparseable spec file.expect(specWrite!.args[1]).toMatch(/> "\$tmp".*&& mv "\$tmp"/);});@@ -154,6 +158,7 @@ describe('RemoteSidecarLauncher', () => {]);const inner = launch!.args[6];expect(inner).toContain("SWITCHDASH_SIDECAR_REPO_DIR='/home/dev/repo'");+ expect(inner).toContain("SWITCHDASH_SIDECAR_AGENT_SLUG='claude-code.repo.me'");expect(inner).not.toContain('SWITCHDASH_SIDECAR_LOCATION_ID');expect(inner).not.toContain('SWITCHDASH_SIDECAR_TMUX_TARGET');expect(inner).toContain('.switchdash/sidecar.mjs');@@ -223,16 +228,18 @@ describe('RemoteSidecarLauncher', () => {});describe('agentSidecarTmuxName', () => {- it('is deterministic per repo dir and does not end in -sidecar', () => {- const a = agentSidecarTmuxName('/home/dev/repo');- expect(a).toBe(agentSidecarTmuxName('/home/dev/repo'));- expect(a).not.toBe(agentSidecarTmuxName('/home/dev/other'));+ it('is deterministic per repo dir + slug and does not end in -sidecar', () => {+ const a = agentSidecarTmuxName('/home/dev/repo', 'agent-a');+ expect(a).toBe(agentSidecarTmuxName('/home/dev/repo', 'agent-a'));+ expect(a).not.toBe(agentSidecarTmuxName('/home/dev/other', 'agent-a'));+ // Two agents sharing one repo dir get distinct sidecars (CHOO-1440).+ expect(a).not.toBe(agentSidecarTmuxName('/home/dev/repo', 'agent-b'));expect(a.endsWith('-sidecar')).toBe(false);});});describe('writeWatchEnabled', () => {- it('writes 1 / 0 to the watch-enabled flag file', async () => {+ it('writes 1 / 0 to the agent-scoped watch-enabled flag file', async () => {const calls: ExecCall[] = [];const host: SidecarHost = {exec: async (command, args) => {@@ -241,10 +248,10 @@ describe('writeWatchEnabled', () => {},putFile: async () => {},};- await writeWatchEnabled(host, true);- await writeWatchEnabled(host, false);+ await writeWatchEnabled(host, 'agent-a', true);+ await writeWatchEnabled(host, 'agent-a', false);expect(calls[0].args[1]).toContain('printf %s 1 > ');- expect(calls[0].args[1]).toContain('.switchdash/watch-enabled');+ expect(calls[0].args[1]).toContain('.switchdash/agents/agent-a/watch-enabled');expect(calls[1].args[1]).toContain('printf %s 0 > ');});});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 77253d58d..acefd9c5d 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@@ -3,6 +3,15 @@ import { readFile } from 'node:fs/promises';import { exactTmuxTarget } from '@main/core/pty/tmux-session-name';import { quoteShellArg } from '@main/utils/shellEscape';import type { AgentLaunchSpec } from '../../../../sidecar/agent-launch-spec';+import {+ SIDECAR_BUNDLE_HASH_REL_PATH,+ SIDECAR_BUNDLE_REL_PATH,+ sidecarAgentDir,+ sidecarLaunchSpecRelPath,+ sidecarLogRelPath,+ sidecarReadyRelPath,+ sidecarWatchEnabledRelPath,+} from '../../../../sidecar/sidecar-paths';/*** Deploys and launches the switchdash remote runtime sidecar on the agent's VM@@ -19,13 +28,6 @@ import type { AgentLaunchSpec } from '../../../../sidecar/agent-launch-spec';*/const SIDECAR_TMUX_SUFFIX = '-sidecar';-const SIDECAR_DIR = '.switchdash';-const BUNDLE_REL_PATH = `${SIDECAR_DIR}/sidecar.mjs`;-const BUNDLE_HASH_FILE = `${SIDECAR_DIR}/sidecar.mjs.sha256`;-const LAUNCH_SPEC_REL_PATH = `${SIDECAR_DIR}/agent-launch-spec.json`;-const WATCH_ENABLED_FILE = `${SIDECAR_DIR}/watch-enabled`;-const READY_FILE = `${SIDECAR_DIR}/sidecar.ready`;-const LOG_FILE = `${SIDECAR_DIR}/sidecar.log`;const READY_POLL_INTERVAL_MS = 250;const READY_MAX_ATTEMPTS = 80; // ~20s@@ -35,6 +37,10 @@ export interface SidecarLaunchConfig {deeplinkScheme: string;/** Provider-specific launch recipe the sidecar's watcher materialises per auto-start. */launchSpec: AgentLaunchSpec;+ /** The agent's per-agent credentials slug — its definition name, else its agent+ * id — so the sidecar reads `.switch/agents/<slug>.json` for this agent's Switch+ * identity rather than the legacy shared settings file (CHOO-1440). */+ credsSlug: string;}export interface SidecarEndpoint {@@ -63,6 +69,7 @@ function sidecarEnv(config: SidecarLaunchConfig): Record<string, string> {return {SWITCHDASH_SIDECAR_REPO_DIR: config.repoDir,SWITCHDASH_SIDECAR_DEEPLINK_SCHEME: config.deeplinkScheme,+ SWITCHDASH_SIDECAR_AGENT_SLUG: config.credsSlug,};}@@ -100,13 +107,14 @@ const defaultSleep = (ms: number): Promise<void> =>/*** Deterministic, agent-scoped tmux session name for the sidecar, derived from- * the remote repo dir so every caller (the SSH agent runtime and the- * auto-session setup path) computes the same name and reattaches to the one- * shared sidecar. Deliberately does NOT end in `-sidecar` so the legacy- * per-session `reapOrphanedSidecars` never mistakes it for an orphan.+ * the remote repo dir AND the agent's creds slug — so every caller (the SSH+ * agent runtime and the auto-session setup path) computes the same name and+ * reattaches to that agent's sidecar, while two agents sharing a directory get+ * distinct sidecars (CHOO-1440). Deliberately does NOT end in `-sidecar` so the+ * legacy per-session `reapOrphanedSidecars` never mistakes it for an orphan.*/-export function agentSidecarTmuxName(repoDir: string): string {- const hash = createHash('sha256').update(repoDir).digest('hex').slice(0, 16);+export function agentSidecarTmuxName(repoDir: string, slug: string): string {+ const hash = createHash('sha256').update(`${repoDir}\0${slug}`).digest('hex').slice(0, 16);return `switchdash-sidecar-${hash}`;}@@ -147,6 +155,20 @@ export class RemoteSidecarLauncher {this.hashBundle = opts.hashBundle ?? (() => sha256File(this.bundlePath));}+ /** Per-agent state paths, keyed by this agent's creds slug (CHOO-1440). */+ private get agentDir(): string {+ return sidecarAgentDir(this.config.credsSlug);+ }+ private get launchSpecPath(): string {+ return sidecarLaunchSpecRelPath(this.config.credsSlug);+ }+ private get readyPath(): string {+ return sidecarReadyRelPath(this.config.credsSlug);+ }+ private get logPath(): string {+ return sidecarLogRelPath(this.config.credsSlug);+ }+/*** Reconcile-or-launch. The sidecar is designed to outlive the switchdash UI,* so on relaunch a still-running sidecar (its tmux session alive and its ready@@ -175,7 +197,7 @@ export class RemoteSidecarLauncher {sidecarTmuxName: this.sidecarTmuxName,});} else {- await this.host.putFile(this.bundlePath, BUNDLE_REL_PATH);+ await this.host.putFile(this.bundlePath, SIDECAR_BUNDLE_REL_PATH);await this.writeBundleHash(localHash);}await this.killSidecar();@@ -191,9 +213,9 @@ export class RemoteSidecarLauncher {*/private async prepareDir(): Promise<string> {const script = [- `mkdir -p ${quoteShellArg(SIDECAR_DIR)}`,- `rm -f ${quoteShellArg(READY_FILE)}`,- `[ -f ${quoteShellArg(BUNDLE_REL_PATH)} ] && cat ${quoteShellArg(BUNDLE_HASH_FILE)} 2>/dev/null || true`,+ `mkdir -p ${quoteShellArg(this.agentDir)}`,+ `rm -f ${quoteShellArg(this.readyPath)}`,+ `[ -f ${quoteShellArg(SIDECAR_BUNDLE_REL_PATH)} ] && cat ${quoteShellArg(SIDECAR_BUNDLE_HASH_REL_PATH)} 2>/dev/null || true`,].join('; ');const { stdout } = await this.host.exec('sh', ['-c', script]);return stdout.trim();@@ -202,21 +224,21 @@ export class RemoteSidecarLauncher {private async writeLaunchSpec(): Promise<void> {const json = JSON.stringify(this.config.launchSpec);const b64 = Buffer.from(json, 'utf8').toString('base64');- const spec = quoteShellArg(LAUNCH_SPEC_REL_PATH);+ const spec = quoteShellArg(this.launchSpecPath);// base64 round-trip avoids fighting shell quoting on the JSON payload. Write- // to a per-process temp (`$$`) then atomically `mv` into place, so two agents- // that share a repo dir (hence this spec file) can't interleave writes and- // leave a torn, unparseable file that crashes the sidecar on startup.+ // to a per-process temp (`$$`) then atomically `mv` into place, so nothing+ // can observe a torn, half-written spec that would crash the sidecar on+ // startup.await this.host.exec('sh', ['-c',- `mkdir -p ${quoteShellArg(SIDECAR_DIR)} && tmp=${spec}.$$.tmp && printf %s ${quoteShellArg(b64)} | base64 -d > "$tmp" && mv "$tmp" ${spec}`,+ `mkdir -p ${quoteShellArg(this.agentDir)} && tmp=${spec}.$$.tmp && printf %s ${quoteShellArg(b64)} | base64 -d > "$tmp" && mv "$tmp" ${spec}`,]);}private async writeBundleHash(hash: string): Promise<void> {await this.host.exec('sh', ['-c',- `printf %s ${quoteShellArg(hash)} > ${quoteShellArg(BUNDLE_HASH_FILE)}`,+ `printf %s ${quoteShellArg(hash)} > ${quoteShellArg(SIDECAR_BUNDLE_HASH_REL_PATH)}`,]);}@@ -280,8 +302,8 @@ export class RemoteSidecarLauncher {.map(([key, value]) => `${key}=${quoteShellArg(value)}`).join(' ');const inner =- `${envPrefix} exec node ${quoteShellArg(BUNDLE_REL_PATH)} ` +- `> ${quoteShellArg(READY_FILE)} 2>> ${quoteShellArg(LOG_FILE)}`;+ `${envPrefix} exec node ${quoteShellArg(SIDECAR_BUNDLE_REL_PATH)} ` ++ `> ${quoteShellArg(this.readyPath)} 2>> ${quoteShellArg(this.logPath)}`;await this.host.exec('tmux', ['new-session','-d',@@ -304,7 +326,7 @@ export class RemoteSidecarLauncher {throw new Error(`sidecar did not report ready within ${(READY_MAX_ATTEMPTS * READY_POLL_INTERVAL_MS) / 1000- }s — see ${this.config.repoDir}/${LOG_FILE}`+ }s — see ${this.config.repoDir}/${this.logPath}`);}@@ -313,7 +335,7 @@ export class RemoteSidecarLauncher {await this.host.exec('tmux', ['has-session', '-t', exactTmuxTarget(this.sidecarTmuxName)]);} catch {const tail = await this.readLogTail();- const logRef = `${this.config.repoDir}/${LOG_FILE}`;+ const logRef = `${this.config.repoDir}/${this.logPath}`;this.log.warn('RemoteSidecarLauncher: sidecar exited during startup', {sidecarTmuxName: this.sidecarTmuxName,logRef,@@ -331,7 +353,7 @@ export class RemoteSidecarLauncher {* error (e.g. a SyntaxError from too-old node) instead of an opaque message. */private async readLogTail(): Promise<string> {try {- const { stdout } = await this.host.exec('tail', ['-n', '20', LOG_FILE]);+ const { stdout } = await this.host.exec('tail', ['-n', '20', this.logPath]);return stdout.trim();} catch {return '';@@ -340,7 +362,7 @@ export class RemoteSidecarLauncher {private async readReadyFile(): Promise<string | null> {try {- const { stdout } = await this.host.exec('cat', [READY_FILE]);+ const { stdout } = await this.host.exec('cat', [this.readyPath]);return stdout;} catch {return null; // not created yet@@ -349,14 +371,20 @@ export class RemoteSidecarLauncher {}/**- * Set the sidecar's live `watch-enabled` flag (1/0). The running sidecar reads+ * Set the agent's sidecar `watch-enabled` flag (1/0). The running sidecar reads* this file each poll, so toggling auto_session enables/disables auto-start* without restarting the sidecar — leaving its session injection undisturbed.+ * Keyed by the agent's creds `slug` so it targets that agent's sidecar and not a+ * co-located one (CHOO-1440).*/-export async function writeWatchEnabled(host: SidecarHost, enabled: boolean): Promise<void> {+export async function writeWatchEnabled(+ host: SidecarHost,+ slug: string,+ enabled: boolean+): Promise<void> {await host.exec('sh', ['-c',- `mkdir -p ${quoteShellArg(SIDECAR_DIR)} && printf %s ${enabled ? '1' : '0'} > ${quoteShellArg(WATCH_ENABLED_FILE)}`,+ `mkdir -p ${quoteShellArg(sidecarAgentDir(slug))} && printf %s ${enabled ? '1' : '0'} > ${quoteShellArg(sidecarWatchEnabledRelPath(slug))}`,]);}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 b59ebd34e..115cf82a3 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@@ -206,6 +206,8 @@ export class SshAgentRuntime implements AgentRuntimeProvider {repoDir: this.sessionPath,deeplinkScheme: DEEPLINK_SCHEME,autoApprove: agent?.autoApprove ?? false,+ credsSlug: agent?.definitionName ?? session.agentName ?? session.agentId,+ definitionName: agent?.definitionName ?? session.agentName ?? null,ctx: this.ctx,connectionId: this.connectionId,host: this.createSidecarHost(),@@ -344,6 +346,7 @@ export class SshAgentRuntime implements AgentRuntimeProvider {const providerConfig = await providerOverrideSettings.getItem(session.providerId);const agentSession = resolveAgentSessionCommandArgs(session, isResuming);const plugin = getPlugin(session.providerId);+ const repoAgents = plugin.behavior.repoAgents;const binaryName = plugin.capabilities.hostDependency.binaryNames[0] ?? session.providerId;const executableCli = await resolveAgentExecutable({@@ -357,6 +360,14 @@ export class SshAgentRuntime implements AgentRuntimeProvider {const agentCommand = plugin.behavior.prompt!.buildCommand({cli: executableCli,extraArgs: parseExtraArgs(providerConfig?.extraArgs),+ // A remote agent runs as its own definition: the provider produces the+ // run-as-name args (Claude → `--agent <name> --settings <neutral creds>`),+ // resolved on the VM (sessionPath is remote). Distinct from user extra+ // args (CHOO-1440).+ agentArgs:+ session.agentName && repoAgents+ ? repoAgents.launchArgs(this.sessionPath, session.agentName)+ : [],autoApprove: session.autoApprove ?? false,initialPrompt: agentSession.isResuming ? undefined : initialPrompt,sessionId: agentSession.sessionId,@@ -368,6 +379,15 @@ export class SshAgentRuntime implements AgentRuntimeProvider {const customEnv = providerConfig?.env ?? {};const providerEnv: Record<string, string> = { ...agentCommand.env, ...customEnv };+ // The agent's Switch identity as real env vars (highest precedence): read+ // from its neutral `.switch/agents/<name>.json` on the VM. A `--settings`+ // file's env block is not reliably propagated to the spawned MCP server, so+ // inject it directly, matching the local runtime.+ const identityVars =+ session.agentName && repoAgents+ ? await repoAgents.readLaunchEnv(createRemotePluginFs(this.fs), session.agentName)+ : {};+const tmuxSessionName = this.tmux ? makeAgentTmuxSessionName(this.sessionId) : undefined;const cfg: AgentSessionConfig = {@@ -419,7 +439,7 @@ export class SshAgentRuntime implements AgentRuntimeProvider {const sshCommand = resolveSshCommand('agent',cfg,- { ...providerEnv, ...colorEnv, ...this.sessionEnvVars, ...hookEnv },+ { ...providerEnv, ...colorEnv, ...this.sessionEnvVars, ...hookEnv, ...identityVars },profile);diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/add-agent.ts b/dash/apps/switchdash-desktop/src/main/core/agents/add-agent.tsnew file mode 100644index 000000000..d34e2bc8f--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agents/add-agent.ts@@ -0,0 +1,130 @@+import { randomUUID } from 'node:crypto';+import type { RepoAgentAttributes } from '@switchdash/core/agents/plugins';+import { locationManager } from '@main/core/locations/location-manager';+import { checkIsValidDirectory } from '@main/core/locations/path-utils';+import { ensureLocation } from '@main/core/locations/store';+import { getPlugin } from '@main/core/providers/plugin-registry';+import { getServer } from '@main/core/switch-servers/servers-store';+import { log } from '@main/lib/logger';+import type { Agent } from '@shared/core/agents/agents';+import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';+import { basenameFromAnyPath } from '@shared/path-name';+import { agentEvents } from './agent-events';+import { resolveWorkspaceFsFor } from './agent-workspace-fs';+import { createAgent } from './createAgent';+import { registerAgentIdentity } from './register-agent-identity';+import { reconcileAgentAutoSessionFromGateway } from './setAgentAutoSession';++export type AddAgentParams = {+ id?: string;+ /** Where the agent runs: an `~/.ssh/config` Host alias, or null for this machine. */+ sshHost: string | null;+ /** The working directory (local absolute path, or the repo dir on the host). */+ dir: string;+ /** Display name for the location row when it is created (defaults to the dir basename). */+ locationName?: string;+ /** The agent's name — filesystem-safe; also its provider definition stem and+ * the `--agent <name>` value. */+ name: string;+ providerId: AgentProviderId;+ /** The registered Switch server to mint the identity on. */+ serverId: string;+ description: string;+ autoSession: boolean;+ autoApprove: boolean;+ /** Provider-specific definition attributes (model, effort, tools, prompt, …),+ * keyed by the provider's attribute fields. `name`/`description` are set from+ * the params above. */+ definitionAttributes: RepoAgentAttributes;+};++export type AddAgentResult =+ | { kind: 'created'; agent: Agent }+ | { kind: 'unauthenticated' }+ | { kind: 'name-conflict' }+ | { kind: 'invalid-name'; message: string }+ | { kind: 'error'; message: string };++/**+ * Add a new agent to a location: mint its Switch identity on the gateway, write+ * its provider definition (`.claude/agents/<name>.md`) and its per-agent Switch+ * credentials (`.switch/agents/<name>.json`, keyed by name), then create the+ * agent row. Every switchdash-managed agent is a flat, repository-defined agent+ * — for a provider that supports definitions it launches as `--agent <name>`+ * with its own identity; there is no "main" agent and no parent (CHOO-1440).+ *+ * Works for local and remote (SSH) run locations. The minted API token is+ * written to disk and never returned. A recoverable gateway failure is mapped to+ * a typed result the modal can act on; a filesystem failure after registration+ * throws (leaving the gateway agent, as the pre-existing provision path did).+ */+export async function addAgent(params: AddAgentParams): Promise<AddAgentResult> {+ if (params.sshHost === null && !checkIsValidDirectory(params.dir)) {+ return { kind: 'error', message: `Invalid directory: ${params.dir}` };+ }++ const server = await getServer(params.serverId);+ if (!server) return { kind: 'error', message: `No Switch server with id ${params.serverId}` };++ const registered = await registerAgentIdentity(server, {+ name: params.name,+ description: params.description,+ repoDir: params.dir,+ autoSession: params.autoSession,+ });+ if (registered.kind !== 'created') return registered;++ const behavior = getPlugin(params.providerId).behavior.repoAgents;+ const workspace = await resolveWorkspaceFsFor(params.sshHost, params.dir);+ try {+ if (behavior) {+ await behavior.writeDefinition(workspace.fs, {+ ...params.definitionAttributes,+ name: params.name,+ description: params.description,+ });+ await behavior.writeCredentials(workspace.fs, {+ agentName: params.name,+ apiEndpoint: server.apiUrl,+ apiToken: registered.apiKey,+ agentId: registered.id,+ });+ }+ } finally {+ workspace.close();+ }++ const location = await ensureLocation({+ sshHost: params.sshHost,+ dir: params.dir,+ name: params.locationName ?? basenameFromAnyPath(params.dir) ?? params.name,+ });++ const agent = await createAgent({+ id: params.id ?? randomUUID(),+ locationId: location.id,+ name: params.name,+ providerId: params.providerId,+ // A provider with a definitions capability launches as `--agent <name>`;+ // one without has no on-disk definition, so it launches plainly.+ definitionName: behavior ? params.name : null,+ switchAgentId: registered.id,+ apiEndpoint: server.apiUrl,+ serverId: params.serverId,+ autoApprove: params.autoApprove,+ });++ // Seed the local auto_session mirror + watcher from the gateway profile so an+ // agent registered with auto_session on starts watching now, without an+ // off→on toggle. Best-effort: a gateway hiccup must not fail creation.+ await reconcileAgentAutoSessionFromGateway(agent.id).catch((error) => {+ log.warn('addAgent: failed to reconcile auto_session for new agent', {+ agentId: agent.id,+ error: String(error),+ });+ });++ await locationManager.openLocation(location);+ agentEvents._emit('agent:created', agent);+ return { kind: 'created', agent };+}diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/agent-definition.ts b/dash/apps/switchdash-desktop/src/main/core/agents/agent-definition.tsnew file mode 100644index 000000000..e2f179818--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agents/agent-definition.ts@@ -0,0 +1,62 @@+import type { RepoAgentAttributes } from '@switchdash/core/agents/plugins';+import { getPlugin } from '@main/core/providers/plugin-registry';+import { getAgentLocation } from './agent-location';+import { resolveWorkspaceFsFor } from './agent-workspace-fs';+import { getAgentById } from './getAgentById';++/**+ * Read an agent's on-disk definition attributes (model, effort, tools, system+ * prompt, …) so the Settings tab can prefill its editable Advanced section.+ * Returns null when the provider has no definition concept, the agent carries no+ * definition name, or the definition file is absent — the caller renders an+ * empty form in that case (CHOO-1440).+ */+export async function readAgentDefinition(agentId: string): Promise<RepoAgentAttributes | null> {+ const agent = await getAgentById(agentId);+ if (!agent) throw new Error(`No agent with id ${agentId}`);++ const behavior = getPlugin(agent.providerId).behavior.repoAgents;+ if (!behavior || !agent.definitionName) return null;++ const location = await getAgentLocation(agent);+ const workspace = await resolveWorkspaceFsFor(location.sshHost, location.dir);+ try {+ return await behavior.readDefinition(workspace.fs, agent.definitionName);+ } finally {+ workspace.close();+ }+}++/**+ * Rewrite an agent's on-disk definition with new Advanced attributes, preserving+ * its identity (name) and description. The name is immutable — it is the agent's+ * `--agent <name>` handle and its Switch identity — so only the provider's+ * advanced attributes change. Fails loud for a provider without definitions or an+ * agent with no definition name (there is nothing to edit).+ */+export async function updateAgentDefinition(params: {+ agentId: string;+ attributes: RepoAgentAttributes;+}): Promise<void> {+ const agent = await getAgentById(params.agentId);+ if (!agent) throw new Error(`No agent with id ${params.agentId}`);++ const behavior = getPlugin(agent.providerId).behavior.repoAgents;+ if (!behavior || !agent.definitionName) {+ throw new Error(`Agent ${params.agentId} has no editable on-disk definition.`);+ }++ const location = await getAgentLocation(agent);+ const workspace = await resolveWorkspaceFsFor(location.sshHost, location.dir);+ try {+ const current = await behavior.readDefinition(workspace.fs, agent.definitionName);+ const description = typeof current?.description === 'string' ? current.description : '';+ await behavior.writeDefinition(workspace.fs, {+ ...params.attributes,+ name: agent.definitionName,+ description,+ });+ } finally {+ workspace.close();+ }+}diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/agent-workspace-fs.ts b/dash/apps/switchdash-desktop/src/main/core/agents/agent-workspace-fs.tsnew file mode 100644index 000000000..8fd31f757--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agents/agent-workspace-fs.ts@@ -0,0 +1,52 @@+import { homedir } from 'node:os';+import type { PluginFs } from '@switchdash/core/agents/plugins';+import { SshFileSystem } from '@main/core/fs/impl/ssh-fs';+import { sshConnectionIdForHost } from '@main/core/locations/location-transport';+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';++/**+ * A {@link PluginFs} rooted at an agent's working directory (local disk or a+ * remote repo dir over SFTP), plus a `close()` that releases the SFTP channel.+ * Callers MUST invoke `close()` in a `finally` — a leaked SFTP channel+ * eventually exhausts the host's MaxSessions.+ */+export type WorkspaceFs = {+ /** FS rooted at the working dir — local disk or the remote repo dir. */+ fs: PluginFs;+ /** FS for user-scoped (`~/.claude`) definitions; empty for remote agents. */+ homeFs: PluginFs;+ close: () => void;+};++/**+ * A {@link PluginFs} that resolves nothing — the user (home) scope of a remote+ * agent, whose VM home dir is not mounted here. Location-scoped agent IO (what+ * switchdash authors) is unaffected.+ */+const EMPTY_PLUGIN_FS: PluginFs = {+ read: () => Promise.resolve(null),+ write: () => Promise.reject(new Error('home scope is read-only for remote agents')),+ delete: () => Promise.resolve(),+ exists: () => Promise.resolve(false),+ list: () => Promise.resolve([]),+};++/**+ * Open a {@link WorkspaceFs} for a working directory identified by run location+ * (ssh host + dir) rather than an existing agent row — used at create/onboard+ * time before a row exists. Local dirs resolve on disk; remote dirs open an+ * SFTP channel to the host.+ */+export async function resolveWorkspaceFsFor(+ sshHost: string | null,+ dir: string+): Promise<WorkspaceFs> {+ if (sshHost === null) {+ return { fs: createPluginFs(dir), homeFs: createPluginFs(homedir()), close: () => {} };+ }+ const proxy = await ensureSshConnected(sshConnectionIdForHost(sshHost), sshHost);+ const sshFs = new SshFileSystem(proxy, dir);+ return { fs: createRemotePluginFs(sshFs), homeFs: EMPTY_PLUGIN_FS, close: () => sshFs.close() };+}diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/controller.ts b/dash/apps/switchdash-desktop/src/main/core/agents/controller.tsindex b214bec7e..fc4c53cdc 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/controller.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/controller.ts@@ -1,13 +1,20 @@+import type { RepoAgentAttributes } from '@switchdash/core/agents/plugins';import type { CreateAgentParams, RenameAgentParams } from '@shared/core/agents/agents';import type { OnboardAgentParams } from '@shared/core/agents/onboarding';+import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';import type { AgentVerifyResult } from '@shared/core/switch-servers/switch-servers';import { createRPCController } from '@shared/lib/ipc/rpc';+import { addAgent, type AddAgentParams } from './add-agent';+import { readAgentDefinition, updateAgentDefinition } from './agent-definition';import { assignAgentServer } from './assignAgentServer';import { createAgent } from './createAgent';+import { getAgentDefinitionFields } from './definition-fields';import { deleteAgent, type DeleteAgentOptions } from './deleteAgent';+import { discoverLocationAgents } from './discover-location-agents';import { getAgentById } from './getAgentById';import { getAgents } from './getAgents';import { onboardAgent } from './onboard-agent';+import { onboardLocationAgents, type OnboardLocationParams } from './onboard-location-agents';import { renameAgent } from './renameAgent';import { resetRemoteAgent } from './reset-remote-agent';import { setAgentAutoApprove, type AgentAutoApproveParams } from './setAgentAutoApprove';@@ -20,7 +27,19 @@ import { updateAgent, type UpdateAgentParams } from './updateAgent';export const agentsController = createRPCController({createAgent: (params: CreateAgentParams) => createAgent(params),+ addAgent: (params: AddAgentParams) => addAgent(params),+ definitionFields: (params: { providerId: AgentProviderId }) =>+ Promise.resolve(getAgentDefinitionFields(params.providerId)),+ readAgentDefinition: (params: { agentId: string }) => readAgentDefinition(params.agentId),+ updateAgentDefinition: (params: { agentId: string; attributes: RepoAgentAttributes }) =>+ updateAgentDefinition(params),onboardAgent: (params: OnboardAgentParams) => onboardAgent(params),+ onboardLocationAgents: (params: OnboardLocationParams) => onboardLocationAgents(params),+ discoverLocationAgents: (params: {+ sshHost: string | null;+ dir: string;+ providerId: AgentProviderId;+ }) => discoverLocationAgents(params),getAgents: (locationId?: string) => getAgents(locationId),getAgentById: (agentId: string) => getAgentById(agentId),renameAgent: (params: RenameAgentParams) => renameAgent(params),diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/createAgent.ts b/dash/apps/switchdash-desktop/src/main/core/agents/createAgent.tsindex d80e27a6b..389fdf259 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/createAgent.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/createAgent.ts@@ -12,6 +12,7 @@ export async function createAgent(params: CreateAgentParams): Promise<Agent> {locationId: params.locationId,name: params.name,providerId: params.providerId,+ definitionName: params.definitionName ?? null,switchAgentId: params.switchAgentId,apiEndpoint: params.apiEndpoint,serverId: params.serverId,diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/definition-fields.ts b/dash/apps/switchdash-desktop/src/main/core/agents/definition-fields.tsnew file mode 100644index 000000000..4707b414b--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agents/definition-fields.ts@@ -0,0 +1,13 @@+import type { RepoAgentField } from '@switchdash/core/agents/plugins';+import { getPlugin } from '@main/core/providers/plugin-registry';+import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';++/**+ * The editable attribute fields for a provider's agent definitions (e.g. a Claude+ * Code subagent's model / effort / tools / system prompt), in display order, or+ * an empty list when the provider has no definition concept. Drives the "Advanced+ * configuration" section of the add-agent modal (CHOO-1440).+ */+export function getAgentDefinitionFields(providerId: AgentProviderId): RepoAgentField[] {+ return getPlugin(providerId).behavior.repoAgents?.attributeFields() ?? [];+}diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/deleteAgent.ts b/dash/apps/switchdash-desktop/src/main/core/agents/deleteAgent.tsindex 673e38d95..eb297185f 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/deleteAgent.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/deleteAgent.ts@@ -1,48 +1,43 @@import { eq } from 'drizzle-orm';import { getPlugin } from '@main/core/providers/plugin-registry';-import { resolveSubagentFs } from '@main/core/subagents/resolve-subagent-fs';-import {- listAutoSessionSubagents,- setAutoSessionAgent,- setAutoSessionSubagent,-} from '@main/core/switch-rooms/auto-session-store';+import { setAutoSessionAgent } from '@main/core/switch-rooms/auto-session-store';import { autoSessionWatcher } from '@main/core/switch-rooms/auto-session-watcher';-import {- deleteAgent as gatewayDeleteAgent,- fetchAgentChildren,-} from '@main/core/switch-servers/gateway-client';+import { deleteAgent as gatewayDeleteAgent } from '@main/core/switch-servers/gateway-client';import { getServer } from '@main/core/switch-servers/servers-store';import { viewStateService } from '@main/core/view-state/view-state-service';import { db } from '@main/db/client';import { agents, sessions } from '@main/db/schema';import { log } from '@main/lib/logger';import type { Agent } from '@shared/core/agents/agents';+import type { Location } from '@shared/core/locations/locations';import { sessionRuntimeManager } from '../sessions/session-runtime-manager';import { agentEvents } from './agent-events';import { getAgentLocation } from './agent-location';+import { resolveWorkspaceFsFor } from './agent-workspace-fs';import { getAgentById } from './getAgentById';import { stopRemoteWatcher } from './remote-watcher';import { removeSwitchCredentials } from './remove-switch-settings';export type DeleteAgentOptions = {/**- * Also delete the agent's identity on the Switch server (via the gateway),- * cascading to delete every subagent registered under it. When false, the- * agent is removed from switchdash only; its Switch identity (and its- * subagents') is left registered on the server.+ * Also delete the agent's identity on the Switch server (via the gateway).+ * When false, the agent is removed from switchdash only; its Switch identity is+ * left registered on the server.*/deleteInSwitch: boolean;};/**- * Delete the agent's identity on the Switch server, cascading to its subagents.+ * Delete this agent's own identity on the Switch server — and ONLY this one.*- * The gateway does NOT cascade child deletes on its own (a parent delete only- * orphans its children), so switchdash drives the cascade: enumerate the- * registered children and delete each one first, then delete the parent. Runs- * before any local teardown so a gateway failure surfaces loudly and aborts the- * delete with local state intact, rather than leaving the row gone but the Switch- * identity orphaned.+ * switchdash agents are flat: a directory is a container of independent agents+ * with no parent/child hierarchy (CHOO-1440), so deleting one never affects any+ * other agent, even a sibling in the same directory. (Legacy agents may still+ * carry a gateway parent/child link from the old subagent model; we deliberately+ * do not follow it — deleting a former "parent" simply orphans those links, it+ * must not cascade-delete the other agents.) Runs before any local teardown so a+ * gateway failure surfaces loudly and aborts the delete with local state intact,+ * rather than leaving the row gone but the Switch identity orphaned.*/async function deleteAgentInSwitch(agent: Agent): Promise<void> {if (!agent.serverId || !agent.switchAgentId) {@@ -53,38 +48,32 @@ async function deleteAgentInSwitch(agent: Agent): Promise<void> {const server = await getServer(agent.serverId);if (!server) throw new Error(`No Switch server with id ${agent.serverId}`);- const { children } = await fetchAgentChildren(server, agent.switchAgentId);- for (const child of children) {- await gatewayDeleteAgent(server, child.id);- }await gatewayDeleteAgent(server, agent.switchAgentId);}/**- * Reverse the on-disk state switchdash provisioned for the agent: its own Switch- * credentials (provider-aware — see {@link removeSwitchCredentials}) and every- * subagent's definition + credential files under its working directory. Runs- * against the agent's local dir or its remote SSH host transparently.+ * Reverse the on-disk state switchdash provisioned for this one agent: its+ * provider definition (`.claude/agents/<name>.md`) and its per-agent Switch+ * credentials. Runs against the agent's local dir or its remote SSH host+ * transparently. Only THIS agent's files are removed — sibling agents sharing the+ * directory are untouched (CHOO-1440).** Best-effort: a working directory that is gone or a host that is unreachable* should not block removing the agent from switchdash, so failures are logged* (visibly) rather than thrown — the credentials being torn down are already dead.*/-async function removeProvisionedFiles(agent: Agent): Promise<void> {- const ctx = await resolveSubagentFs(agent.id);+async function removeProvisionedFiles(agent: Agent, location: Location): Promise<void> {+ const ctx = await resolveWorkspaceFsFor(location.sshHost, location.dir);try {- const subagents = getPlugin(agent.providerId).behavior.subagents;- if (subagents) {- const local = await subagents.discoverLocal(ctx.fs, ctx.homeFs);- for (const subagent of local) {- await subagents.removeLocal(ctx.fs, subagent.name).catch((error) => {- log.warn('deleteAgent: failed to remove subagent files', {- agentId: agent.id,- subagent: subagent.name,- error: String(error),- });+ const behavior = getPlugin(agent.providerId).behavior.repoAgents;+ if (behavior && agent.definitionName) {+ await behavior.removeLocal(ctx.fs, agent.definitionName).catch((error) => {+ log.warn('deleteAgent: failed to remove agent definition files', {+ agentId: agent.id,+ definitionName: agent.definitionName,+ error: String(error),});- }+ });}await removeSwitchCredentials(agent.providerId, ctx.fs);} finally {@@ -96,7 +85,7 @@ async function removeProvisionedFiles(agent: Agent): Promise<void> {* 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 identity on the Switch server, cascading to its subagents —+ * 1. The agent's own identity on the Switch server (never any other agent) —* only when `deleteInSwitch` is set (the opt-in "also delete in Switch").* 2. The agent's running sessions (runtime + view-state), which previously* only the location-delete path handled.@@ -105,8 +94,9 @@ async function removeProvisionedFiles(agent: Agent): Promise<void> {* 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.- * 4. The Switch credentials + subagent files switchdash provisioned on disk- * (local or remote), which a bare row delete would leave orphaned.+ * 4. The Switch credentials + definition file switchdash provisioned on disk for+ * THIS agent (local or remote), which a bare row delete would leave orphaned.+ * Sibling agents' files in the same directory are untouched.** The agent's location row is intentionally kept — locations are reusable* and other agents may still live there.@@ -140,15 +130,10 @@ export async function deleteAgent(agentId: string, options: DeleteAgentOptions):autoSessionWatcher.stopForAgent(agentId);}- for (const { parentAgentId, name } of await listAutoSessionSubagents()) {- if (parentAgentId !== agentId) continue;- autoSessionWatcher.stopForSubagent(parentAgentId, name);- await setAutoSessionSubagent(parentAgentId, name, false);- }await setAutoSessionAgent(agentId, false);- if (agent) {- await removeProvisionedFiles(agent).catch((error) => {+ if (agent && location) {+ await removeProvisionedFiles(agent, location).catch((error) => {log.warn('deleteAgent: failed to remove provisioned files', {agentId,error: String(error),diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/discover-location-agents.ts b/dash/apps/switchdash-desktop/src/main/core/agents/discover-location-agents.tsnew file mode 100644index 000000000..e6d954658--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agents/discover-location-agents.ts@@ -0,0 +1,62 @@+import { getLocationByHostDir } from '@main/core/locations/store';+import { getPlugin } from '@main/core/providers/plugin-registry';+import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';+import { resolveWorkspaceFsFor } from './agent-workspace-fs';+import { getAgents } from './getAgents';++export type DiscoveredLocationAgent = {+ /** The definition/launch name (`.claude/agents/<name>.md` stem, `--agent <name>`). */+ name: string;+ description: string | null;+ /** Whether the definition already carries Switch credentials on disk. */+ registered: boolean;+ /** Whether the definition can join Switch (its tools allowlist keeps the+ * connector's MCP tools, or it inherits all tools). */+ eligible: boolean;+ /** Whether switchdash already has an agent row for this definition in this dir. */+ alreadyAgent: boolean;+};++/**+ * Read-only scan of a working directory for the provider's on-disk agent+ * definitions (`.claude/agents/*.md`) — used by the Add Agent modal to suggest+ * onboarding a directory's existing agents (CHOO-1440). It surfaces BOTH agents+ * already set up for Switch (carrying credentials) and plain provider subagents a+ * user created directly (no Switch setup yet), so either can be adopted as a+ * Switch agent. `alreadyAgent` marks definitions switchdash already has a row for,+ * so the modal never offers to re-add them. Works for local and remote (SSH)+ * directories. Returns an empty list for a provider with no definition concept.+ */+export async function discoverLocationAgents(params: {+ sshHost: string | null;+ dir: string;+ providerId: AgentProviderId;+}): Promise<DiscoveredLocationAgent[]> {+ const behavior = getPlugin(params.providerId).behavior.repoAgents;+ if (!behavior) return [];++ const location = await getLocationByHostDir(params.sshHost, params.dir);+ const existing = location+ ? new Set(+ (await getAgents(location.id))+ .map((a) => a.definitionName)+ .filter((n): n is string => n != null)+ )+ : new Set<string>();++ const workspace = await resolveWorkspaceFsFor(params.sshHost, params.dir);+ try {+ const definitions = await behavior.discoverDefinitions(workspace.fs);+ const local = await behavior.discoverLocal(workspace.fs, workspace.homeFs);+ const credentialled = new Set(local.filter((l) => l.switchAgentId !== null).map((l) => l.name));+ return definitions.map((def) => ({+ name: def.name,+ description: def.description,+ registered: def.registered || credentialled.has(def.name),+ eligible: def.eligible,+ alreadyAgent: existing.has(def.name),+ }));+ } finally {+ workspace.close();+ }+}diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/generate-agent-launch-spec.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/generate-agent-launch-spec.test.tsindex 5a4ee7f89..9e5a288b4 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/generate-agent-launch-spec.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/generate-agent-launch-spec.test.ts@@ -1,10 +1,16 @@import { beforeEach, describe, expect, it, vi } from 'vitest';const buildCommand = vi.fn(() => ({ command: 'claude', args: ['--x'], env: { E: '1' } }));+const launchArgs = vi.fn((dir: string, name: string) => [+ '--agent',+ name,+ '--settings',+ `${dir}/.switch/agents/${name}.json`,+]);vi.mock('@main/core/providers/plugin-registry', () => ({getPlugin: () => ({- behavior: { prompt: { buildCommand } },+ behavior: { prompt: { buildCommand }, repoAgents: { launchArgs } },capabilities: { hostDependency: { binaryNames: ['claude'] } },}),}));@@ -22,12 +28,16 @@ const baseParams = {providerId: 'claude',remoteRepoDir: '/home/agent/repo',deeplinkScheme: 'switchdash',+ agentName: null,ctx: {} as never,connectionId: 'conn-1',};describe('generateAgentLaunchSpec', () => {- beforeEach(() => buildCommand.mockClear());+ beforeEach(() => {+ buildCommand.mockClear();+ launchArgs.mockClear();+ });// The bug (CHOO-1664): autoApprove was hardcoded true, so the remote watcher's// auto-started sessions always bypassed permissions regardless of the setting.@@ -40,4 +50,25 @@ describe('generateAgentLaunchSpec', () => {await generateAgentLaunchSpec({ ...baseParams, autoApprove: false });expect(buildCommand).toHaveBeenCalledWith(expect.objectContaining({ autoApprove: false }));});++ it('appends the definition launch args so auto-started sessions run as the definition', async () => {+ await generateAgentLaunchSpec({ ...baseParams, autoApprove: false, agentName: 'reviewer' });+ expect(launchArgs).toHaveBeenCalledWith('/home/agent/repo', 'reviewer');+ expect(buildCommand).toHaveBeenCalledWith(+ expect.objectContaining({+ agentArgs: [+ '--agent',+ 'reviewer',+ '--settings',+ '/home/agent/repo/.switch/agents/reviewer.json',+ ],+ })+ );+ });++ it('adds no definition launch args when the agent has no definition', async () => {+ await generateAgentLaunchSpec({ ...baseParams, autoApprove: false, agentName: null });+ expect(launchArgs).not.toHaveBeenCalled();+ expect(buildCommand).toHaveBeenCalledWith(expect.objectContaining({ agentArgs: [] }));+ });});diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/generate-agent-launch-spec.ts b/dash/apps/switchdash-desktop/src/main/core/agents/generate-agent-launch-spec.tsindex d6bfb1b00..c1d8f5efd 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/generate-agent-launch-spec.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/generate-agent-launch-spec.ts@@ -32,10 +32,16 @@ export async function generateAgentLaunchSpec(params: {deeplinkScheme: string;/** The agent's bypass-permissions setting, applied to auto-started sessions. */autoApprove: boolean;+ /** The agent's definition name, so auto-started sessions launch as the+ * definition (`--agent <name> --settings <neutral creds>`) with its own model,+ * prompt, tools, and Switch identity. Null for a provider/agent with no+ * on-disk definition (CHOO-1440). */+ agentName: string | null;ctx: IExecutionContext;connectionId: string;}): Promise<AgentLaunchSpec> {- const { providerId, remoteRepoDir, deeplinkScheme, autoApprove, ctx, connectionId } = params;+ const { providerId, remoteRepoDir, deeplinkScheme, autoApprove, agentName, ctx, connectionId } =+ params;const plugin = getPlugin(providerId);if (!plugin.behavior.prompt) {throw new Error(@@ -53,9 +59,13 @@ export async function generateAgentLaunchSpec(params: {connectionId,});+ const repoAgents = plugin.behavior.repoAgents;const agentCommand = plugin.behavior.prompt.buildCommand({cli,extraArgs: parseExtraArgs(providerConfig?.extraArgs),+ // The provider owns how to run as the named agent (CHOO-1440); kept distinct+ // from user extra args.+ agentArgs: agentName && repoAgents ? repoAgents.launchArgs(remoteRepoDir, agentName) : [],autoApprove,initialPrompt: INITIAL_PROMPT_PLACEHOLDER,sessionId: SESSION_ID_PLACEHOLDER,diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/migrate-agent-storage.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/migrate-agent-storage.test.tsnew file mode 100644index 000000000..3041c0d79--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agents/migrate-agent-storage.test.ts@@ -0,0 +1,177 @@+import type { PluginFs } from '@switchdash/core/agents/plugins';+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * An in-memory {@link PluginFs} keyed by the exact relative paths the migration+ * uses, so path helpers (`agentSettingsRelativePath`, `SWITCH_SETTINGS_RELATIVE_PATH`)+ * resolve against real content.+ */+function fakeFs(seed: Record<string, string>): PluginFs {+ const files = new Map<string, string>(Object.entries(seed));+ return {+ read: (p) => Promise.resolve(files.has(p) ? (files.get(p) as string) : null),+ write: (p, c) => {+ files.set(p, c);+ return Promise.resolve();+ },+ delete: (p) => {+ files.delete(p);+ return Promise.resolve();+ },+ exists: (p) => Promise.resolve(files.has(p)),+ list: (dir) =>+ Promise.resolve(+ [...files.keys()]+ .filter((k) => k.startsWith(`${dir}/`))+ .map((k) => k.slice(dir.length + 1))+ .filter((k) => !k.includes('/'))+ ),+ };+}++function credsJson(agentId: string): string {+ return JSON.stringify({+ env: {+ SWITCH_API_ENDPOINT: 'http://switch.example',+ SWITCH_API_TOKEN: 'tok-123',+ SWITCH_AGENT_ID: agentId,+ },+ });+}++// Shared mock state + spies. Hoisted so the vi.mock factories (which are lifted+// above imports) can reference them. `agents`/`workspace` are set per test.+const h = vi.hoisted(() => {+ const state: { agents: Array<Record<string, unknown>>; workspace: PluginFs | null } = {+ agents: [],+ workspace: null,+ };+ return {+ state,+ writeCredentials: vi.fn((fs: PluginFs, creds: { agentName: string }) =>+ fs.write(+ `.switch/agents/${creds.agentName}.json`,+ JSON.stringify({+ env: { SWITCH_API_ENDPOINT: 'x', SWITCH_API_TOKEN: 'x', SWITCH_AGENT_ID: 'x' },+ })+ )+ ),+ readLaunchEnv: vi.fn(async (fs: PluginFs, name: string) => {+ const raw =+ (await fs.read(`.switch/agents/${name}.json`)) ??+ (await fs.read(`.claude/switch-subagents/${name}.settings.json`));+ return raw ? ((JSON.parse(raw).env ?? {}) as Record<string, string>) : {};+ }),+ readDefinition: vi.fn((fs: PluginFs, name: string) =>+ fs.read(`.claude/agents/${name}.md`).then((c) => (c === null ? null : { name }))+ ),+ writeDefinition: vi.fn((fs: PluginFs, attrs: { name: string }) =>+ fs.write(`.claude/agents/${attrs.name}.md`, `# ${attrs.name}`)+ ),+ discoverLocal: vi.fn(async () => []),+ updateAgent: vi.fn(async () => undefined),+ };+});++vi.mock('@main/core/providers/plugin-registry', () => ({+ getPlugin: () => ({+ behavior: {+ repoAgents: {+ writeCredentials: h.writeCredentials,+ readLaunchEnv: h.readLaunchEnv,+ readDefinition: h.readDefinition,+ writeDefinition: h.writeDefinition,+ discoverLocal: h.discoverLocal,+ },+ },+ }),+}));+vi.mock('@main/core/locations/store', () => ({+ getLocationById: vi.fn(async () => ({ id: 'loc', sshHost: null, dir: '/repo' })),+}));+vi.mock('./agent-workspace-fs', () => ({+ resolveWorkspaceFsFor: vi.fn(async () => ({+ fs: h.state.workspace,+ homeFs: h.state.workspace,+ close: () => {},+ })),+}));+vi.mock('./getAgents', () => ({ getAgents: vi.fn(async () => h.state.agents) }));+vi.mock('./updateAgent', () => ({ updateAgent: h.updateAgent }));+vi.mock('@main/core/switch-servers/gateway-client', () => ({ fetchAgentDetail: vi.fn() }));+vi.mock('@main/core/switch-servers/servers-store', () => ({ getServer: vi.fn() }));+vi.mock('@main/lib/logger', () => ({ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));++import { migrateAgentStorage } from './migrate-agent-storage';++const baseAgent = {+ id: 'agent-id-1',+ providerId: 'claude',+ locationId: 'loc',+ name: 'hoot-main',+ definitionName: 'cc-hoot-main',+ switchAgentId: 'sw-1',+ serverId: 'srv-1',+};++describe('migrateAgentStorage', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ h.state.agents = [{ ...baseAgent }];+ });++ it('recovers creds from a stale id-keyed neutral file, writes the name-keyed file, and removes the stale one', async () => {+ const ws = fakeFs({+ '.switch/agents/agent-id-1.json': credsJson('sw-1'),+ '.claude/agents/cc-hoot-main.md': '# def',+ });+ h.state.workspace = ws;++ await migrateAgentStorage();++ expect(h.writeCredentials).toHaveBeenCalledWith(+ ws,+ expect.objectContaining({ agentName: 'cc-hoot-main', apiToken: 'tok-123', agentId: 'sw-1' })+ );+ expect(await ws.exists('.switch/agents/cc-hoot-main.json')).toBe(true);+ expect(await ws.exists('.switch/agents/agent-id-1.json')).toBe(false);+ });++ it('falls back to .claude/settings.local.json when no neutral file exists', async () => {+ const ws = fakeFs({+ '.claude/settings.local.json': credsJson('sw-1'),+ '.claude/agents/cc-hoot-main.md': '# def',+ });+ h.state.workspace = ws;++ await migrateAgentStorage();++ expect(h.writeCredentials).toHaveBeenCalledWith(+ ws,+ expect.objectContaining({ agentName: 'cc-hoot-main', agentId: 'sw-1' })+ );+ });++ it('does nothing when the name-keyed file already exists and the definition is present', async () => {+ h.state.workspace = fakeFs({+ '.switch/agents/cc-hoot-main.json': credsJson('sw-1'),+ '.claude/agents/cc-hoot-main.md': '# def',+ });++ await migrateAgentStorage();++ expect(h.writeCredentials).not.toHaveBeenCalled();+ expect(h.writeDefinition).not.toHaveBeenCalled();+ expect(h.updateAgent).not.toHaveBeenCalled();+ });++ it('writes no credentials when none exist anywhere (unrecoverable token)', async () => {+ const ws = fakeFs({ '.claude/agents/cc-hoot-main.md': '# def' });+ h.state.workspace = ws;++ await migrateAgentStorage();++ expect(h.writeCredentials).not.toHaveBeenCalled();+ expect(await ws.exists('.switch/agents/cc-hoot-main.json')).toBe(false);+ });+});diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/migrate-agent-storage.ts b/dash/apps/switchdash-desktop/src/main/core/agents/migrate-agent-storage.tsnew file mode 100644index 000000000..d28911ab3--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agents/migrate-agent-storage.ts@@ -0,0 +1,173 @@+import { getLocationById } from '@main/core/locations/store';+import { getPlugin } from '@main/core/providers/plugin-registry';+import { parseSwitchAgentCredentials } from '@main/core/switch-rooms/switch-credentials';+import { fetchAgentDetail } from '@main/core/switch-servers/gateway-client';+import { getServer } from '@main/core/switch-servers/servers-store';+import { log } from '@main/lib/logger';+import type { Agent } from '@shared/core/agents/agents';+import { resolveWorkspaceFsFor } from './agent-workspace-fs';+import { getAgents } from './getAgents';+import { agentSettingsRelativePath, SWITCH_SETTINGS_RELATIVE_PATH } from './switch-settings-paths';+import { updateAgent } from './updateAgent';++/**+ * Migrate existing switchdash-managed agents to the current storage/definition+ * layout (CHOO-1440): every agent is a repository-defined agent with a per-agent+ * credentials file at `.switch/agents/<name>.json`, an on-disk definition, and a+ * populated `definitionName`. Pre-CHOO-1440 installs kept credentials in the+ * legacy `.claude/switch-subagents/<name>.settings.json` (or the shared+ * `.claude/settings.local.json`) and left `definitionName` null.+ *+ * Runs once at boot, best-effort: each agent is migrated in isolation so one bad+ * directory or unreachable host never aborts the rest, and every step is+ * idempotent (re-running does nothing once an agent is in the new layout).+ * Applies to LOCAL and REMOTE agents alike — remote reads/writes go over SFTP+ * through the same provider filesystem abstraction.+ */+export async function migrateAgentStorage(): Promise<void> {+ const agents = await getAgents();+ let migrated = 0;+ for (const agent of agents) {+ try {+ if (await migrateOne(agent)) migrated += 1;+ } catch (error) {+ log.warn('migrateAgentStorage: failed to migrate agent', {+ agentId: agent.id,+ error: String(error),+ });+ }+ }+ if (migrated > 0) {+ log.info('migrateAgentStorage: migrated agents to the neutral storage layout', { migrated });+ }+}++/** Migrate one agent (local or remote); returns whether anything changed. */+async function migrateOne(agent: Agent): Promise<boolean> {+ const behavior = getPlugin(agent.providerId).behavior.repoAgents;+ if (!behavior) return false;++ const location = await getLocationById(agent.locationId);+ if (!location) return false;++ const workspace = await resolveWorkspaceFsFor(location.sshHost, location.dir);+ try {+ // Resolve the agent's REAL name — the credentials/definition stem, NOT+ // `agent.name` (the directory-derived display name). Prefer the row's+ // definitionName; else the on-disk agent matched to this row by switchAgentId;+ // else the registered Switch name from the gateway (authoritative — the same+ // name new agents are created under). Never the directory name (CHOO-1440).+ let name = agent.definitionName;+ let description = agent.name;+ if (!name) {+ if (!agent.switchAgentId) return false;+ const discovered = await behavior.discoverLocal(workspace.fs, workspace.homeFs);+ const match = discovered.find((d) => d.switchAgentId === agent.switchAgentId);+ if (match) {+ name = match.name;+ description = match.description ?? match.name;+ } else {+ const registered = await fetchRegisteredName(agent);+ if (!registered) {+ log.info('migrateAgentStorage: could not resolve a real name for agent; skipping', {+ agentId: agent.id,+ switchAgentId: agent.switchAgentId,+ });+ return false;+ }+ name = registered.name;+ description = registered.description;+ }+ }++ let changed = false;++ // 1. Credentials: if the name-keyed neutral file is absent, adopt whatever+ // complete credentials already exist on disk, in priority order:+ // a. a stale ID-keyed neutral file `.switch/agents/<agentId>.json` — an+ // earlier layout keyed the neutral file by agent id, not name;+ // b. the legacy per-agent file (via readLaunchEnv: name-keyed neutral+ // then `.claude/switch-subagents/<name>.settings.json`);+ // c. the shared `.claude/settings.local.json` (legacy "main" agent).+ // The token is minted once and lives only on disk, so this is the only way+ // to recover it — nothing can reconstruct it from the gateway.+ const idKeyedRelPath = agentSettingsRelativePath(agent.id);+ const namedRelPath = agentSettingsRelativePath(name);+ const neutral = name === agent.id ? null : await workspace.fs.read(namedRelPath);+ if (neutral === null) {+ const creds =+ parseSwitchAgentCredentials((await workspace.fs.read(idKeyedRelPath)) ?? '', log) ??+ toCreds(await behavior.readLaunchEnv(workspace.fs, name)) ??+ parseSwitchAgentCredentials(+ (await workspace.fs.read(SWITCH_SETTINGS_RELATIVE_PATH)) ?? '',+ log+ );+ if (creds) {+ await behavior.writeCredentials(workspace.fs, {+ agentName: name,+ apiEndpoint: creds.apiEndpoint,+ apiToken: creds.token,+ agentId: creds.agentId,+ });+ changed = true;+ }+ }++ // Remove the stale ID-keyed neutral file once the name-keyed one is in place:+ // an incomplete leftover there otherwise shadows the real creds in the+ // session preflight (which scans both), and a complete one is now redundant.+ if (name !== agent.id && (await workspace.fs.read(namedRelPath)) !== null) {+ if ((await workspace.fs.read(idKeyedRelPath)) !== null) {+ await workspace.fs.delete(idKeyedRelPath);+ changed = true;+ }+ }++ // 2. Definition: ensure the provider has an on-disk definition for this agent+ // so it runs as a named repository-defined agent.+ if ((await behavior.readDefinition(workspace.fs, name)) === null) {+ await behavior.writeDefinition(workspace.fs, { name, description });+ changed = true;+ }++ // 3. Row: populate definitionName so sessions launch as this named agent.+ if (agent.definitionName === null) {+ await updateAgent({ agentId: agent.id, definitionName: name });+ changed = true;+ }++ return changed;+ } finally {+ workspace.close();+ }+}++/** The agent's registered name + description on its Switch server, or null. */+async function fetchRegisteredName(+ agent: Agent+): Promise<{ name: string; description: string } | null> {+ if (!agent.serverId || !agent.switchAgentId) return null;+ const server = await getServer(agent.serverId);+ if (!server) return null;+ try {+ const detail = await fetchAgentDetail(server, agent.switchAgentId);+ return { name: detail.name, description: detail.description || detail.name };+ } catch (error) {+ log.warn('migrateAgentStorage: failed to fetch registered agent name', {+ agentId: agent.id,+ error: String(error),+ });+ return null;+ }+}++/** Build credentials from a launch-env map, or null when any value is missing. */+function toCreds(+ env: Record<string, string>+): { apiEndpoint: string; token: string; agentId: string } | null {+ const apiEndpoint = env.SWITCH_API_ENDPOINT;+ const token = env.SWITCH_API_TOKEN;+ const agentId = env.SWITCH_AGENT_ID;+ if (apiEndpoint && token && agentId) return { apiEndpoint, token, agentId };+ return null;+}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.tsindex 9643d3f19..bccf9fb69 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/onboard-agent.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/onboard-agent.ts@@ -3,6 +3,7 @@ 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 { readSwitchAgentCredentials } from '@main/core/switch-rooms/switch-credentials';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';@@ -18,6 +19,7 @@ import { createAgent } from './createAgent';import { detectSwitchAgent } from './detect';import { detectSwitchAgentRemote } from './detect-remote';import { reconcileAgentAutoSessionFromGateway } from './setAgentAutoSession';+import { writeAgentNeutralSettings } from './write-switch-settings';/*** Gate agent creation on the chosen server actually owning the detected agent@@ -138,6 +140,30 @@ export async function onboardAgent(params: OnboardAgentParams): Promise<OnboardAautoApprove: params.autoApprove ?? sshHost !== null,});+ // Mirror the agent's credentials into its provider-neutral per-agent file+ // (`.switch/agents/<agentId>.json`), the authoritative identity switchdash+ // injects at launch so agents sharing a location don't collide on the single+ // `.claude/settings.local.json` identity (CHOO-1440). Local agents only — a+ // remote agent's dir lives on its VM. Best-effort: the launch/poller fall back+ // to `settings.local.json`, so a failure here does not break onboarding.+ if (sshHost === null) {+ const creds = await readSwitchAgentCredentials(params.dir, log);+ if (creds) {+ await writeAgentNeutralSettings({+ dir: params.dir,+ slug: agent.id,+ apiEndpoint: creds.apiEndpoint,+ apiToken: creds.token,+ agentId: creds.agentId,+ }).catch((error) => {+ log.warn('onboardAgent: failed to write neutral agent settings', {+ agentId: agent.id,+ error: String(error),+ });+ });+ }+ }+// 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 gatewaydiff --git a/dash/apps/switchdash-desktop/src/main/core/agents/onboard-location-agents.ts b/dash/apps/switchdash-desktop/src/main/core/agents/onboard-location-agents.tsnew file mode 100644index 000000000..79395dd43--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agents/onboard-location-agents.ts@@ -0,0 +1,259 @@+import { randomUUID } from 'node:crypto';+import { err, ok } from '@switchdash/shared';+import type { Result } 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 { getPlugin } from '@main/core/providers/plugin-registry';+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 { Agent } from '@shared/core/agents/agents';+import type { OnboardAgentError } from '@shared/core/agents/onboarding';+import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';+import { basenameFromAnyPath } from '@shared/path-name';+import { agentEvents } from './agent-events';+import { resolveWorkspaceFsFor, type WorkspaceFs } from './agent-workspace-fs';+import { createAgent } from './createAgent';+import { getAgents } from './getAgents';+import { registerAgentIdentity } from './register-agent-identity';+import { reconcileAgentAutoSessionFromGateway } from './setAgentAutoSession';++export type OnboardLocationParams = {+ sshHost: string | null;+ dir: string;+ locationName?: string;+ providerId: AgentProviderId;+ /** The registered Switch server the discovered agents belong to (or are+ * adopted onto, for plain provider subagents with no Switch setup yet). */+ serverId: string;+ /** Definition names to onboard. When omitted, every onboardable definition in+ * the directory is onboarded; when given, only these are (the modal's+ * multi-select). Names not currently onboardable are ignored. */+ names?: string[];+};++export type OnboardLocationResult = Result<Agent[], OnboardAgentError>;++/** The Switch identity an onboarded definition should run under. */+type ResolvedIdentity = { switchAgentId: string; apiEndpoint: string };++type RepoAgentsBehavior = NonNullable<ReturnType<typeof getPlugin>['behavior']['repoAgents']>;++/** Map a recoverable registration failure to an onboard error. */+function registrationError(+ kind: 'unauthenticated' | 'name-conflict' | 'invalid-name' | 'error',+ message: string,+ name: string,+ server: SwitchServer,+ dir: string+): OnboardAgentError {+ if (kind === 'unauthenticated') {+ return {+ type: 'switch-server-unauthenticated',+ dir,+ serverId: server.id,+ serverName: server.name,+ };+ }+ if (kind === 'name-conflict') {+ return {+ type: 'error',+ message: `An agent named "${name}" already exists on ${server.name}. Rename the definition or delete the conflicting agent.`,+ };+ }+ return { type: 'error', message };+}++/**+ * Resolve the Switch identity to onboard a definition under: reuse existing+ * credentials when their identity still exists on the server, otherwise register+ * a fresh identity and write the credentials (adopting a plain subagent).+ */+async function resolveIdentity(+ name: string,+ description: string | null,+ ctx: {+ server: SwitchServer;+ behavior: RepoAgentsBehavior;+ workspace: WorkspaceFs;+ credsByName: Map<string, { switchAgentId: string | null; apiEndpoint: string | null }>;+ dir: string;+ }+): Promise<{ ok: true; identity: ResolvedIdentity } | { ok: false; error: OnboardAgentError }> {+ const creds = ctx.credsByName.get(name);+ if (creds?.switchAgentId && creds.apiEndpoint) {+ try {+ if (await agentExistsOnServer(ctx.server, creds.switchAgentId)) {+ return {+ ok: true,+ identity: { switchAgentId: creds.switchAgentId, apiEndpoint: creds.apiEndpoint },+ };+ }+ } catch (cause) {+ if (cause instanceof GatewayError && cause.kind === 'unauthorized') {+ return {+ ok: false,+ error: {+ type: 'switch-server-unauthenticated',+ dir: ctx.dir,+ serverId: ctx.server.id,+ serverName: ctx.server.name,+ },+ };+ }+ throw cause;+ }+ }++ // No usable credentials — adopt: mint a fresh identity and write its creds,+ // keeping the existing definition file untouched.+ const registered = await registerAgentIdentity(ctx.server, {+ name,+ description: description ?? `Claude Code agent ${name}`,+ repoDir: ctx.dir,+ autoSession: true,+ });+ if (registered.kind !== 'created') {+ const message = 'message' in registered ? registered.message : '';+ return {+ ok: false,+ error: registrationError(registered.kind, message, name, ctx.server, ctx.dir),+ };+ }++ await ctx.behavior.writeCredentials(ctx.workspace.fs, {+ agentName: name,+ apiEndpoint: ctx.server.apiUrl,+ apiToken: registered.apiKey,+ agentId: registered.id,+ });+ return { ok: true, identity: { switchAgentId: registered.id, apiEndpoint: ctx.server.apiUrl } };+}++/**+ * Onboard the provider agents defined in a working directory. Every+ * `.claude/agents/<name>.md` definition that can join Switch and isn't already a+ * switchdash agent is brought in as a flat agent row (CHOO-1440):+ *+ * - A definition that already carries valid Switch credentials (registered, and+ * its identity still exists on the server) is imported under that identity.+ * - A plain provider subagent (a definition with no Switch setup — e.g. one a+ * user created directly in Claude Code) is *adopted*: switchdash mints a Switch+ * identity for it and writes its per-agent credentials, leaving the existing+ * definition file untouched.+ *+ * There is no "main" agent — the directory is a flat container of+ * repository-defined agents. Local and remote (SSH) directories are both+ * supported.+ */+export async function onboardLocationAgents(+ params: OnboardLocationParams+): Promise<OnboardLocationResult> {+ if (params.sshHost === null && !checkIsValidDirectory(params.dir)) {+ return err({ type: 'invalid-directory', dir: params.dir, message: 'Invalid directory' });+ }++ const server = await getServer(params.serverId);+ if (!server) throw new Error(`No Switch server with id ${params.serverId}`);++ const behavior = getPlugin(params.providerId).behavior.repoAgents;+ if (!behavior) {+ return err({+ type: 'invalid-directory',+ dir: params.dir,+ message: `Provider ${params.providerId} does not define repository agents.`,+ });+ }++ const location = await ensureLocation({+ sshHost: params.sshHost,+ dir: params.dir,+ name: params.locationName ?? basenameFromAnyPath(params.dir) ?? params.providerId,+ });++ const existing = new Set(+ (await getAgents(location.id))+ .map((a) => a.definitionName)+ .filter((n): n is string => n != null)+ );++ const workspace = await resolveWorkspaceFsFor(params.sshHost, params.dir);+ const created: Agent[] = [];+ try {+ const definitions = await behavior.discoverDefinitions(workspace.fs);+ const local = await behavior.discoverLocal(workspace.fs, workspace.homeFs);+ const credsByName = new Map(local.map((l) => [l.name, l]));++ // Onboardable = a definition that can join Switch and isn't already a row.+ const onboardable = definitions.filter((d) => d.eligible && !existing.has(d.name));+ if (onboardable.length === 0) {+ return err({+ type: 'invalid-directory',+ dir: params.dir,+ message: 'No Claude agents available to onboard in this directory.',+ });+ }++ // Restrict to the caller's selection (the modal's multi-select) when given;+ // otherwise onboard every onboardable definition.+ const requested = params.names;+ const selected = requested+ ? onboardable.filter((d) => requested.includes(d.name))+ : onboardable;+ if (selected.length === 0) {+ return err({+ type: 'invalid-directory',+ dir: params.dir,+ message: 'None of the selected agents are available to onboard in this directory.',+ });+ }++ for (const def of selected) {+ const resolved = await resolveIdentity(def.name, def.description, {+ server,+ behavior,+ workspace,+ credsByName,+ dir: params.dir,+ });+ if (!resolved.ok) return err(resolved.error);++ const agent = await createAgent({+ id: randomUUID(),+ locationId: location.id,+ name: def.name,+ providerId: params.providerId,+ definitionName: def.name,+ switchAgentId: resolved.identity.switchAgentId,+ apiEndpoint: resolved.identity.apiEndpoint,+ serverId: params.serverId,+ autoApprove: params.sshHost !== null,+ });+ existing.add(def.name);+ created.push(agent);++ await reconcileAgentAutoSessionFromGateway(agent.id).catch((error) => {+ log.warn('onboardLocationAgents: failed to reconcile auto_session', {+ agentId: agent.id,+ error: String(error),+ });+ });+ }+ } finally {+ workspace.close();+ }++ if (created.length === 0) {+ return err({+ type: 'invalid-directory',+ dir: params.dir,+ message: 'Every agent in this directory is already onboarded here.',+ });+ }++ await locationManager.openLocation(location);+ for (const agent of created) agentEvents._emit('agent:created', agent);+ return ok(created);+}diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/register-agent-identity.ts b/dash/apps/switchdash-desktop/src/main/core/agents/register-agent-identity.tsnew file mode 100644index 000000000..e90d8c896--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agents/register-agent-identity.ts@@ -0,0 +1,55 @@+import { GatewayError, registerKnownAgent } from '@main/core/switch-servers/gateway-client';+import type { ProvisionAgentResult } from '@shared/core/switch-servers/switch-servers';+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';++export type RegisterAgentInput = {+ name: string;+ description: string;+ repoDir: string;+ autoSession?: boolean;+};++/**+ * Register a new agent identity on `server` (owned by the signed-in user) and+ * map recoverable gateway failures to a typed {@link ProvisionAgentResult}+ * (unauthorized→unauthenticated, 409→name-conflict, 400→invalid-name, else+ * error). Every switchdash-managed agent is its own top-level Switch identity —+ * there is no parent/child linkage on the gateway; a switchdash agent is a flat+ * repository-defined agent (CHOO-1440). Shared by the local and remote create+ * flows so the option mapping stays identical.+ *+ * Channels are always enabled: switchdash keeps the agent's session live (and+ * auto-spawns one on notify), so it is session-addressable regardless of the+ * underlying model provider — there is no user-facing "how do you run Claude"+ * choice.+ */+export async function registerAgentIdentity(+ server: SwitchServer,+ input: RegisterAgentInput+): Promise<+ | { kind: 'created'; id: string; apiKey: string }+ | Exclude<ProvisionAgentResult, { kind: 'created' }>+> {+ try {+ const registered = await registerKnownAgent(server, {+ name: input.name,+ description: input.description,+ options: {+ channels_enabled: true,+ repo_dir: input.repoDir,+ ...(input.autoSession ? { auto_session: true } : {}),+ },+ });+ return { kind: 'created', id: registered.id, apiKey: registered.apiKey };+ } catch (cause) {+ if (cause instanceof GatewayError) {+ if (cause.kind === 'unauthorized') return { kind: 'unauthenticated' };+ if (cause.kind === 'http' && cause.status === 409) return { kind: 'name-conflict' };+ if (cause.kind === 'http' && cause.status === 400) {+ return { kind: 'invalid-name', message: cause.message };+ }+ return { kind: 'error', message: cause.message };+ }+ throw cause;+ }+}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 7063e284f..df2d8c801 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@@ -356,6 +356,8 @@ class RemoteSessionReconciler {repoDir: conn.remoteRepoDir,deeplinkScheme: DEEPLINK_SCHEME,autoApprove: agent.autoApprove,+ credsSlug: agent.definitionName ?? agent.id,+ definitionName: agent.definitionName ?? null,ctx: conn.ctx,connectionId: conn.connectionId,host: conn.host,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 ddeddaca0..5d64a798e 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/remote-watcher.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/remote-watcher.ts@@ -114,11 +114,13 @@ export async function ensureRemoteWatcher(agentId: string): Promise<void> {repoDir: remoteRepoDir,deeplinkScheme: DEEPLINK_SCHEME,autoApprove: agent.autoApprove,+ credsSlug: agent.definitionName ?? agent.id,+ definitionName: agent.definitionName ?? null,ctx,connectionId,host,});- await writeWatchEnabled(host, true);+ await writeWatchEnabled(host, agent.definitionName ?? agent.id, true);log.info('ensureRemoteWatcher: sidecar deployed + watching', {agentId,switchAgentId: agent.switchAgentId,@@ -140,6 +142,6 @@ export async function stopRemoteWatcher(agentId: string): Promise<void> {if (!agent || !(await getRemoteAgentLocation(agent))) return;remoteSessionReconciler.stop(agentId);const { host } = await connectRemoteAgent(agent);- await writeWatchEnabled(host, false);+ await writeWatchEnabled(host, agent.definitionName ?? agent.id, false);log.info('stopRemoteWatcher: watching disabled', { agentId });}diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/reset-remote-agent-tmux.ts b/dash/apps/switchdash-desktop/src/main/core/agents/reset-remote-agent-tmux.tsindex 3a3f96c63..d29248f1a 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/reset-remote-agent-tmux.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/reset-remote-agent-tmux.ts@@ -4,11 +4,19 @@ import { quoteShellArg } from '@main/utils/shellEscape';/*** The tmux session names to kill when resetting an agent: one per agent session- * id plus the agent's sidecar session. Deduplicated by name.+ * id plus the agent's own sidecar session (keyed by repo dir + creds slug, so a+ * co-located agent's sidecar is left running). Deduplicated by name.*/-export function resetTmuxTargets(sessionIds: string[], remoteRepoDir: string): string[] {+export function resetTmuxTargets(+ sessionIds: string[],+ remoteRepoDir: string,+ slug: string+): string[] {return [- ...new Set([...sessionIds.map(makeAgentTmuxSessionName), agentSidecarTmuxName(remoteRepoDir)]),+ ...new Set([+ ...sessionIds.map(makeAgentTmuxSessionName),+ agentSidecarTmuxName(remoteRepoDir, slug),+ ]),];}diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/reset-remote-agent.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/reset-remote-agent.test.tsindex f1122aac8..fc2afc4ff 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/reset-remote-agent.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/reset-remote-agent.test.ts@@ -4,23 +4,28 @@ import { exactTmuxTarget, makeAgentTmuxSessionName } from '@main/core/pty/tmux-simport { buildKillTmuxScript, resetTmuxTargets } from './reset-remote-agent-tmux';const REPO = '/home/dev/repo';+const SLUG = 'agent-a';describe('resetTmuxTargets', () => {- it('kills every agent session plus the sidecar', () => {- const targets = resetTmuxTargets(['s1', 's2'], REPO);+ it('kills every agent session plus this agent’s sidecar', () => {+ const targets = resetTmuxTargets(['s1', 's2'], REPO, SLUG);expect(targets).toContain(makeAgentTmuxSessionName('s1'));expect(targets).toContain(makeAgentTmuxSessionName('s2'));- expect(targets).toContain(agentSidecarTmuxName(REPO));+ expect(targets).toContain(agentSidecarTmuxName(REPO, SLUG));expect(targets).toHaveLength(3);});it('kills the sidecar even when the agent has no sessions', () => {- expect(resetTmuxTargets([], REPO)).toEqual([agentSidecarTmuxName(REPO)]);+ expect(resetTmuxTargets([], REPO, SLUG)).toEqual([agentSidecarTmuxName(REPO, SLUG)]);+ });++ it('targets only this agent’s sidecar, not a co-located agent’s', () => {+ expect(resetTmuxTargets([], REPO, SLUG)).not.toContain(agentSidecarTmuxName(REPO, 'agent-b'));});it('deduplicates repeated session ids', () => {- const targets = resetTmuxTargets(['s1', 's1'], REPO);- expect(targets).toEqual([makeAgentTmuxSessionName('s1'), agentSidecarTmuxName(REPO)]);+ const targets = resetTmuxTargets(['s1', 's1'], REPO, SLUG);+ expect(targets).toEqual([makeAgentTmuxSessionName('s1'), agentSidecarTmuxName(REPO, SLUG)]);});});diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/reset-remote-agent.ts b/dash/apps/switchdash-desktop/src/main/core/agents/reset-remote-agent.tsindex b76792d56..d12ce55ec 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/reset-remote-agent.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/reset-remote-agent.ts@@ -46,6 +46,8 @@ async function fetchSidecarSessionIds(agent: Agent, conn: RemoteConn): Promise<srepoDir: conn.remoteRepoDir,deeplinkScheme: DEEPLINK_SCHEME,autoApprove: agent.autoApprove,+ credsSlug: agent.definitionName ?? agent.id,+ definitionName: agent.definitionName ?? null,ctx: conn.ctx,connectionId: conn.connectionId,host: conn.host,@@ -139,10 +141,11 @@ export async function resetRemoteAgent(agentId: string): Promise<void> {remoteSessionReconciler.stop(agentId);const conn = await connectRemoteAgent(agent);+ const credsSlug = agent.definitionName ?? agent.id;// Silence the VM watcher first so it cannot auto-start a fresh session between// the /sessions snapshot and the kill (whose pane we would then miss).- await writeWatchEnabled(conn.host, false);+ await writeWatchEnabled(conn.host, credsSlug, false);const dbSessionIds = (await db.select({ id: sessions.id }).from(sessions).where(eq(sessions.agentId, agentId))@@ -150,7 +153,7 @@ export async function resetRemoteAgent(agentId: string): Promise<void> {const sidecarSessionIds = await fetchSidecarSessionIds(agent, conn);const sessionIds = [...new Set([...dbSessionIds, ...sidecarSessionIds])];- await killTmuxSessions(conn.host, resetTmuxTargets(sessionIds, conn.remoteRepoDir));+ await killTmuxSessions(conn.host, resetTmuxTargets(sessionIds, conn.remoteRepoDir, credsSlug));log.info('resetRemoteAgent: killed remote tmux sessions', {agentId,sessions: sessionIds.length,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 f25086d02..034d70f99 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@@ -23,6 +23,38 @@ export const SWITCH_SETTINGS_RELATIVE_PATH = path.join('.claude', 'settings.locaexport const SWITCH_SUBAGENTS_DIR_RELATIVE = path.join('.claude', 'switch-subagents');/** Absolute path to a subagent's Switch credentials file under `dir`. */-export function subagentSettingsPath(dir: string, subagentName: string): string {- return path.join(dir, SWITCH_SUBAGENTS_DIR_RELATIVE, `${subagentName}.settings.json`);+export function subagentSettingsPath(dir: string, agentName: string): string {+ return path.join(dir, SWITCH_SUBAGENTS_DIR_RELATIVE, `${agentName}.settings.json`);+}++/**+ * Provider-neutral directory, relative to a location's working directory, where+ * switchdash writes one Switch credentials file per agent (`<slug>.json`). This+ * replaces the two Claude-specific layouts — the shared `.claude/settings.local.json`+ * for a "main" agent and `.claude/switch-subagents/<name>.settings.json` for a+ * subagent — with a single per-agent format that works for every provider+ * (CHOO-1440). The `.claude/agents/<name>.md` *definition* stays under `.claude`+ * because it is Claude-specific; only the Switch credentials move here.+ */+export const SWITCH_AGENTS_DIR_RELATIVE = path.join('.switch', 'agents');++/**+ * Relative path to the `.gitignore` that keeps the per-agent credentials files+ * (which contain `SWITCH_API_TOKEN`) out of version control. Its content is `*`+ * so the whole directory is ignored.+ */+export const SWITCH_AGENTS_GITIGNORE_RELATIVE = path.join(SWITCH_AGENTS_DIR_RELATIVE, '.gitignore');++/**+ * Relative path (from a location dir) to an agent's provider-neutral Switch+ * credentials file. `slug` is a filesystem-safe per-agent key — the agent's+ * definition name for a subagent-derived agent, or its stable name otherwise.+ */+export function agentSettingsRelativePath(slug: string): string {+ return path.join(SWITCH_AGENTS_DIR_RELATIVE, `${slug}.json`);+}++/** Absolute path to an agent's provider-neutral Switch credentials file under `dir`. */+export function agentSettingsPath(dir: string, slug: string): string {+ return path.join(dir, agentSettingsRelativePath(slug));}diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/updateAgent.ts b/dash/apps/switchdash-desktop/src/main/core/agents/updateAgent.tsindex a7d4bc59d..c30268fd9 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/updateAgent.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/updateAgent.ts@@ -11,6 +11,7 @@ export type UpdateAgentParams = {apiEndpoint?: string | null;serverId?: string;autoApprove?: boolean;+ definitionName?: string | null;};type AgentUpdateSet = Parameters<ReturnType<typeof db.update<typeof agents>>['set']>[0];@@ -22,6 +23,7 @@ export async function updateAgent(params: UpdateAgentParams): Promise<Agent | unif (params.apiEndpoint !== undefined) set.apiEndpoint = params.apiEndpoint;if (params.serverId !== undefined) set.serverId = params.serverId;if (params.autoApprove !== undefined) set.autoApprove = params.autoApprove;+ if (params.definitionName !== undefined) set.definitionName = params.definitionName;const [row] = await db.update(agents).set(set).where(eq(agents.id, params.agentId)).returning();if (!row) return undefined;diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/utils.ts b/dash/apps/switchdash-desktop/src/main/core/agents/utils.tsindex 8608a249b..cd52a1bbd 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/utils.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/utils.ts@@ -7,6 +7,7 @@ export function mapAgentRowToAgent(row: AgentRow): Agent {locationId: row.locationId,name: row.name,providerId: row.providerId,+ definitionName: row.definitionName ?? null,switchAgentId: row.switchAgentId ?? null,apiEndpoint: row.apiEndpoint ?? null,serverId: row.serverId ?? null,diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.ts b/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.tsindex aef407283..96f6c0379 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.ts@@ -1,7 +1,11 @@import { promises as fs } from 'node:fs';import path from 'node:path';import { SWITCH_CONNECTOR_TOOL_RULES } from '@switchdash/core/agents/plugins';-import { SWITCH_SETTINGS_RELATIVE_PATH } from './switch-settings-paths';+import {+ agentSettingsRelativePath,+ SWITCH_AGENTS_GITIGNORE_RELATIVE,+ SWITCH_SETTINGS_RELATIVE_PATH,+} from './switch-settings-paths';export interface SwitchSettingsCredentials {apiEndpoint: string;@@ -241,3 +245,42 @@ export async function writeSwitchSettings(params: {await fs.mkdir(path.dirname(settingsPath), { recursive: true });await fs.writeFile(settingsPath, merged, 'utf8');}++/**+ * Write an agent's Switch credentials to its provider-neutral per-agent file+ * `.switch/agents/<slug>.json` (CHOO-1440), alongside the connector-owned+ * `.claude/settings.local.json`. switchdash injects this file's env at launch, so+ * it is the authoritative per-agent identity — letting multiple agents share a+ * location without colliding on the single `settings.local.json` identity.+ *+ * `apiToken` is the agent's secret API key — written here and never returned to+ * the renderer or logged. A `.gitignore` keeps the directory out of version+ * control.+ */+export async function writeAgentNeutralSettings(params: {+ dir: string;+ slug: string;+ apiEndpoint: string;+ apiToken: string;+ agentId: string;+}): Promise<void> {+ const settingsPath = path.join(params.dir, agentSettingsRelativePath(params.slug));+ const gitignorePath = path.join(params.dir, SWITCH_AGENTS_GITIGNORE_RELATIVE);++ let existingRaw: string | null = null;+ try {+ existingRaw = await fs.readFile(settingsPath, 'utf8');+ } catch (error) {+ const code = (error as NodeJS.ErrnoException).code;+ if (code !== 'ENOENT' && code !== 'ENOTDIR') throw error;+ }++ const merged = mergeSwitchSettings(existingRaw, params);+ await fs.mkdir(path.dirname(settingsPath), { recursive: true });+ await fs.writeFile(settingsPath, merged, 'utf8');+ try {+ await fs.access(gitignorePath);+ } catch {+ await fs.writeFile(gitignorePath, '*\n', 'utf8');+ }+}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 8432308e7..099633179 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@@ -162,3 +162,41 @@ describe('SshFileSystem.watch', () => {watcher.close();});});++function makeReaddirFs(base: string, filenames: string[]) {+ const readdirPaths: string[] = [];+ const sftp = {+ on: vi.fn(),+ readdir: vi.fn(+ (dirPath: string, callback: (error: Error | undefined, list?: unknown[]) => void) => {+ readdirPaths.push(dirPath);+ callback(+ undefined,+ filenames.map((filename) => ({+ filename,+ attrs: { isDirectory: () => false, size: 1, mtime: 0, atime: 0, mode: 0o100644 },+ }))+ );+ }+ ),+ };+ const proxy = {+ sftp: vi.fn((callback: (error: Error | undefined, sftp: unknown) => void) => {+ callback(undefined, sftp);+ }),+ };+ return { fs: new SshFileSystem(proxy as never, base), readdirPaths };+}++describe('SshFileSystem trailing-slash tolerance', () => {+ it('resolves + relativizes identically whether the base has a trailing slash or not', async () => {+ for (const base of ['/repo', '/repo/']) {+ const { fs, readdirPaths } = makeReaddirFs(base, ['code-reviewer.md']);+ const result = await fs.list('.claude/agents', { includeHidden: true });+ // No double slash from the base, and entries come back relative (a+ // trailing-slash base previously leaked absolute paths).+ expect(readdirPaths[0]).toBe('/repo/.claude/agents');+ expect(result.entries.map((e) => e.path)).toEqual(['.claude/agents/code-reviewer.md']);+ }+ });+});diff --git a/dash/apps/switchdash-desktop/src/main/core/fs/impl/ssh-fs.ts b/dash/apps/switchdash-desktop/src/main/core/fs/impl/ssh-fs.tsindex fb7a1c96a..694c05dc8 100644--- a/dash/apps/switchdash-desktop/src/main/core/fs/impl/ssh-fs.ts+++ b/dash/apps/switchdash-desktop/src/main/core/fs/impl/ssh-fs.ts@@ -73,8 +73,11 @@ export class SshFileSystem implements FileSystemProvider {if (!remotePath) {throw new FileSystemError('Remote path is required', FileSystemErrorCodes.INVALID_PATH);}- // Normalize remote path to use forward slashes- this.remotePath = remotePath.replace(/\\/g, '/');+ // Normalize the base: forward slashes, and strip any trailing slash (except a+ // bare root) so `/repo` and `/repo/` resolve identically — relativePath and+ // isWithinBase compare against this base, so a trailing slash would otherwise+ // make them return absolute paths / mis-scope (CHOO-1440).+ this.remotePath = remotePath.replace(/\\/g, '/').replace(/\/+$/, '') || '/';}// ─── Private helpers ──────────────────────────────────────────────────────diff --git a/dash/apps/switchdash-desktop/src/main/core/locations/location-runtime-factory.test.ts b/dash/apps/switchdash-desktop/src/main/core/locations/location-runtime-factory.test.tsindex e063fd57f..f7b6e8ce9 100644--- a/dash/apps/switchdash-desktop/src/main/core/locations/location-runtime-factory.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/locations/location-runtime-factory.test.ts@@ -36,6 +36,7 @@ const OPTS = {sessionPath: '/home/dev/r',tmuxEnabled: false, // location setting is off; remote must still force tmux onsessionEnvVars: {},+ credsRelPaths: ['.switch/agents/agent-1.json', '.claude/settings.local.json'],};describe('buildAgentRuntime (ssh)', () => {diff --git a/dash/apps/switchdash-desktop/src/main/core/locations/location-runtime-factory.ts b/dash/apps/switchdash-desktop/src/main/core/locations/location-runtime-factory.tsindex ca2cb1343..a54bfcf90 100644--- a/dash/apps/switchdash-desktop/src/main/core/locations/location-runtime-factory.ts+++ b/dash/apps/switchdash-desktop/src/main/core/locations/location-runtime-factory.ts@@ -218,6 +218,10 @@ type AgentRuntimeOpts = {tmuxEnabled: boolean;shellSetup?: string;sessionEnvVars: Record<string, string>;+ /** Candidate creds files (relative to the working dir) the remote preflight+ * checks, in priority order — the agent's neutral `.switch/agents/<name>.json`+ * first, then the legacy `.claude/settings.local.json` (CHOO-1440). */+ credsRelPaths: string[];};async function resolveLocalAgentShellProfile(sessionId: string): Promise<ResolvedShellProfile> {@@ -247,7 +251,14 @@ export async function buildAgentRuntime(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: transport.host, workDir: transport.dir });+ await preflightRemoteSession({+ ctx,+ fs,+ log,+ host: transport.host,+ workDir: transport.dir,+ credsRelPaths: opts.credsRelPaths,+ });// 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({diff --git a/dash/apps/switchdash-desktop/src/main/core/providers/agent-payload-builder.ts b/dash/apps/switchdash-desktop/src/main/core/providers/agent-payload-builder.tsindex 2f0876770..3326b1587 100644--- a/dash/apps/switchdash-desktop/src/main/core/providers/agent-payload-builder.ts+++ b/dash/apps/switchdash-desktop/src/main/core/providers/agent-payload-builder.ts@@ -52,7 +52,7 @@ function buildMetadata(provider: CLIAgentPluginProvider): AgentMetadata {hooks: capabilities.hooks,mcp: capabilities.mcp,plugins: capabilities.plugins,- subagents: capabilities.subagents,+ repoAgents: capabilities.repoAgents,switchSetup: capabilities.switchSetup,},installDocs: capabilities.hostDependency.installDocs ?? null,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 7726d80dc..1cfb0c239 100644--- a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/createSession.ts+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/createSession.ts@@ -31,7 +31,13 @@ export async function createSession(const configObj: SessionConfig = {};if (params.autoApprove !== undefined) configObj.autoApprove = params.autoApprove;if (params.initialPrompt?.trim()) configObj.initialPrompt = params.initialPrompt.trim();- if (params.subagentName?.trim()) configObj.subagentName = params.subagentName.trim();+ // A subagent is just an agent that launches as a provider definition. When the+ // owning agent carries a definitionName, its sessions launch with+ // `--agent <definitionName>` — derive it here so the runtime needs no DB+ // lookup. An explicit param still wins (legacy "run this session as subagent+ // X of parent" callers) (CHOO-1440).+ const launchDefinition = params.agentName?.trim() || agent.definitionName?.trim();+ if (launchDefinition) configObj.agentName = launchDefinition;const config = Object.keys(configObj).length > 0 ? configObj : undefined;const [row] = await dbdiff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/remote-session-preflight.test.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/remote-session-preflight.test.tsindex cb6d27934..edf8e39aa 100644--- a/dash/apps/switchdash-desktop/src/main/core/sessions/remote-session-preflight.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/remote-session-preflight.test.ts@@ -43,12 +43,20 @@ function makeDeps(opts: {return { stdout: '', stderr: '' };});const fs = {- read: vi.fn(async () => {+ read: vi.fn(async (_path: string) => {if (opts.credsFile == null) throw new Error('no such file');return { content: opts.credsFile };}),};- return { ctx: { exec }, fs, log, host: 'box', workDir: '/home/agent/repo', exec };+ return {+ ctx: { exec },+ fs,+ log,+ host: 'box',+ workDir: '/home/agent/repo',+ credsRelPaths: ['.switch/agents/agent-1.json', '.claude/settings.local.json'],+ exec,+ };}describe('preflightRemoteSession', () => {@@ -99,6 +107,27 @@ describe('preflightRemoteSession', () => {await expect(preflightRemoteSession(deps)).rejects.toThrow(/no Switch credentials/);});+ it('reads the neutral per-agent creds path in preference to the legacy one', async () => {+ const deps = makeDeps({ endpointReachable: true });+ // Neutral path has creds; the legacy path is absent — the preflight should+ // still pass by reading the neutral file first (CHOO-1440).+ deps.fs.read = vi.fn(async (path: string) => {+ if (path === '.switch/agents/agent-1.json') return { content: CREDS_FILE };+ throw new Error('no such file');+ });+ await expect(preflightRemoteSession(deps)).resolves.toBeUndefined();+ expect(deps.fs.read).toHaveBeenCalledWith('.switch/agents/agent-1.json');+ });++ it('falls back to the legacy settings.local.json when the neutral file is absent', async () => {+ const deps = makeDeps({ endpointReachable: true });+ deps.fs.read = vi.fn(async (path: string) => {+ if (path === '.claude/settings.local.json') return { content: CREDS_FILE };+ throw new Error('no such file');+ });+ await expect(preflightRemoteSession(deps)).resolves.toBeUndefined();+ });+it('fails loud when the creds file is incomplete', async () => {const deps = makeDeps({ credsFile: JSON.stringify({ env: { SWITCH_AGENT_ID: 'a' } }) });await expect(preflightRemoteSession(deps)).rejects.toThrow(/incomplete/);diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/remote-session-preflight.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/remote-session-preflight.tsindex 6c00023c9..4ef4d20e6 100644--- a/dash/apps/switchdash-desktop/src/main/core/sessions/remote-session-preflight.ts+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/remote-session-preflight.ts@@ -18,8 +18,10 @@ import { parseSwitchAgentCredentials } from '@main/core/switch-rooms/switch-cred* opaque "sidecar exited during startup" — the sidecar bundle (and this* module's own reachability probe) rely on `fetch`/optional chaining, which* only stabilised in Node 18;- * 2. the agent's Switch creds exist in the remote `.claude/settings.local.json`- * (the sidecar reads them from there) — read in parallel with (1);+ * 2. the agent's Switch creds exist on the remote host — checked at the agent's+ * provider-neutral per-agent path (`.switch/agents/<name>.json`) first, then+ * the legacy `.claude/settings.local.json` for un-migrated installs+ * (CHOO-1440) — read in parallel with (1);* 3. the host can actually reach the Switch API endpoint — the sidecar polls* from the VM, so no egress means a dead agent.*@@ -29,7 +31,6 @@ import { parseSwitchAgentCredentials } from '@main/core/switch-rooms/switch-cred*/const REQUIRED_BINARIES = ['tmux', 'node', 'git'] as const;-const REMOTE_SETTINGS_PATH = '.claude/settings.local.json';const REACHABILITY_TIMEOUT_MS = 5000;// Global `fetch` and `AbortSignal.timeout` (used by the reachability probe below// and throughout the sidecar bundle) are only stable from Node 18.@@ -63,6 +64,10 @@ export interface RemotePreflightDeps {log: CredentialsLogger;host: string;workDir: string;+ /** Candidate creds files (relative to the working dir) to check, in priority+ * order — the agent's neutral `.switch/agents/<name>.json` first, then the+ * legacy `.claude/settings.local.json`. The first that parses is used. */+ credsRelPaths: string[];}export async function preflightRemoteSession(deps: RemotePreflightDeps): Promise<void> {@@ -145,21 +150,31 @@ async function assertHostReady(}async function readRemoteEndpoint(deps: RemotePreflightDeps): Promise<string> {- let content: string;- try {- ({ content } = await deps.fs.read(REMOTE_SETTINGS_PATH));- } catch {- throw new Error(- `no Switch credentials at ${REMOTE_SETTINGS_PATH} on remote host '${deps.host}' — run remote setup for this agent first.`- );+ const primary = deps.credsRelPaths[0] ?? '.switch/agents';+ // Track the FIRST file that was present but unparseable/incomplete, so the+ // error names the actual offending file rather than always the primary path —+ // a stale fallback (an old id-keyed `.switch/agents/<id>.json` or the legacy+ // `.claude/settings.local.json`) is a common cause and must be pinpointed.+ let incompletePath: string | null = null;+ for (const relPath of deps.credsRelPaths) {+ let content: string;+ try {+ ({ content } = await deps.fs.read(relPath));+ } catch {+ continue;+ }+ const creds = parseSwitchAgentCredentials(content, deps.log);+ if (creds) return creds.apiEndpoint;+ if (incompletePath === null) incompletePath = relPath;}- const creds = parseSwitchAgentCredentials(content, deps.log);- if (!creds) {+ if (incompletePath !== null) {throw new Error(- `Switch credentials at ${REMOTE_SETTINGS_PATH} on remote host '${deps.host}' are incomplete — re-run remote setup for this agent.`+ `Switch credentials at ${incompletePath} on remote host '${deps.host}' are incomplete — re-run remote setup for this agent.`);}- return creds.apiEndpoint;+ throw new Error(+ `no Switch credentials at ${primary} on remote host '${deps.host}' — run remote setup for this agent first.`+ );}async function assertEndpointReachable(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 0a221312f..6aabc4a15 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,3 +1,8 @@+import { getAgentById } from '@main/core/agents/getAgentById';+import {+ agentSettingsRelativePath,+ SWITCH_SETTINGS_RELATIVE_PATH,+} from '@main/core/agents/switch-settings-paths';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';@@ -104,6 +109,21 @@ export async function buildSessionFromRuntime(settings);+ // The remote preflight verifies the session's own creds file, keyed by the+ // agent's NAME (`.switch/agents/<name>.json`). Resolve the name from the agent+ // row's definitionName — the source of truth, so a session picks up the right+ // name even if it was created (or restored) before the agent was migrated — and+ // fall back to the session's own agentName. The agent-id path and the legacy+ // shared `.claude/settings.local.json` are last-resort fallbacks for agents not+ // yet migrated (CHOO-1440).+ const agent = await getAgentById(session.agentId);+ const slug = agent?.definitionName ?? session.agentName;+ const credsRelPaths = [+ ...(slug ? [agentSettingsRelativePath(slug)] : []),+ agentSettingsRelativePath(session.agentId),+ SWITCH_SETTINGS_RELATIVE_PATH,+ ];+return buildAgentRuntime(transport, {locationId: runtime.id,sessionId: session.id,@@ -111,5 +131,6 @@ export async function buildSessionFromRuntime(tmuxEnabled,shellSetup,sessionEnvVars,+ credsRelPaths,});}diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/utils/utils.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/utils/utils.tsindex b0455fdef..799e47f28 100644--- a/dash/apps/switchdash-desktop/src/main/core/sessions/utils/utils.ts+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/utils/utils.ts@@ -26,7 +26,7 @@ export function mapSessionRowToSession(row: SessionRow, providerId: AgentProvidelastInteractedAt: row.lastInteractedAt ?? undefined,autoApprove: config.autoApprove,providerSessionId: config.providerSessionId,- subagentName: config.subagentName,+ agentName: config.agentName ?? config.subagentName,createdAt: row.createdAt,updatedAt: row.updatedAt,};diff --git a/dash/apps/switchdash-desktop/src/main/core/subagents/controller.ts b/dash/apps/switchdash-desktop/src/main/core/subagents/controller.tsdeleted file mode 100644index 50214268c..000000000--- a/dash/apps/switchdash-desktop/src/main/core/subagents/controller.ts+++ /dev/null@@ -1,92 +0,0 @@-import type {- SubagentAttributes,- SubagentDefinition,- SubagentField,-} from '@switchdash/core/agents/plugins';-import { createPluginFs } from '@main/core/providers/plugin-fs';-import { getPlugin } from '@main/core/providers/plugin-registry';-import { createRPCController } from '@shared/lib/ipc/rpc';-import { createSubagent, type CreateSubagentParams } from './create-subagent';-import { deleteSubagent, type DeleteSubagentParams } from './delete-subagent';-import { editSubagent, type EditSubagentParams } from './edit-subagent';-import { listSubagents } from './list-subagents';-import {- registerSubagents,- registerSubagentsRemote,- type RegisterSubagentsParams,- type RegisterSubagentsRemoteParams,-} from './register-subagents';-import { openRemoteSubagentFs, resolveSubagentFs } from './resolve-subagent-fs';-import {- getSubagentAutoSession,- setSubagentAutoSession,- type SubagentAutoSessionParams,-} from './setSubagentAutoSession';--/** Discover the subagent definitions a provider can onboard from `dir`. */-function listDefinitions(params: {- dir: string;- providerId: string;-}): Promise<SubagentDefinition[]> {- const subagents = getPlugin(params.providerId).behavior.subagents;- if (!subagents) return Promise.resolve([]);- return subagents.discoverDefinitions(createPluginFs(params.dir));-}--/** Discover the subagent definitions a provider can onboard from a remote agent's- * working dir over SSH — the onboarding counterpart of `listDefinitions` for- * agents that run on an SSH host and have no local directory. */-async function listRemoteDefinitions(params: {- sshHost: string;- remoteRepoDir: string;- providerId: string;-}): Promise<SubagentDefinition[]> {- const subagents = getPlugin(params.providerId).behavior.subagents;- if (!subagents) return [];- const remote = await openRemoteSubagentFs(params.sshHost, params.remoteRepoDir);- try {- return await subagents.discoverDefinitions(remote.fs);- } finally {- remote.close();- }-}--/** The attribute fields a provider's subagents support (drives the form). Empty- * for providers without subagents. */-function attributeFields(providerId: string): Promise<SubagentField[]> {- const subagents = getPlugin(providerId).behavior.subagents;- return Promise.resolve(subagents ? subagents.attributeFields() : []);-}--/** The current attribute values of an existing subagent definition, for edit- * prefill. Resolves the parent's working directory (local or remote) from the- * agent. Null when the provider has no subagents or the definition is gone. */-async function readDefinition(params: {- parentAgentId: string;- name: string;-}): Promise<SubagentAttributes | null> {- const ctx = await resolveSubagentFs(params.parentAgentId);- try {- const subagents = getPlugin(ctx.agent.providerId).behavior.subagents;- if (!subagents) return null;- return await subagents.readDefinition(ctx.fs, params.name);- } finally {- ctx.close();- }-}--export const subagentsController = createRPCController({- list: (parentAgentId: string) => listSubagents(parentAgentId),- listDefinitions,- listRemoteDefinitions,- attributeFields: (providerId: string) => attributeFields(providerId),- readDefinition,- register: (params: RegisterSubagentsParams) => registerSubagents(params),- registerRemote: (params: RegisterSubagentsRemoteParams) => registerSubagentsRemote(params),- create: (params: CreateSubagentParams) => createSubagent(params),- edit: (params: EditSubagentParams) => editSubagent(params),- delete: (params: DeleteSubagentParams) => deleteSubagent(params),- getAutoSession: (params: { parentAgentId: string; name: string }) =>- getSubagentAutoSession(params),- setAutoSession: (params: SubagentAutoSessionParams) => setSubagentAutoSession(params),-});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.tsdeleted file mode 100644index 5b09cd7b4..000000000--- a/dash/apps/switchdash-desktop/src/main/core/subagents/create-subagent.test.ts+++ /dev/null@@ -1,115 +0,0 @@-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 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-subagent-fs', () => ({ resolveSubagentFs }));-vi.mock('./setSubagentAutoSession', () => ({ applyLocalSubagentAutoSessionState }));-vi.mock('@main/lib/logger', () => ({ log: { warn: logWarn, error: vi.fn() } }));--const { createSubagent } = await import('./create-subagent');--const behavior = {- readDefinition: vi.fn(),- writeDefinition: vi.fn(async () => {}),- removeLocal: vi.fn(async () => {}),-};--function mockSubagentFs(agent: Record<string, unknown>) {- resolveSubagentFs.mockResolvedValue({ agent, fs: {}, close: vi.fn() });-}--const LOCAL_PARENT = {- id: 'local-parent',- providerId: 'claude',- serverId: 'srv-1',- switchAgentId: 'sw-parent',- locationId: 'loc-1',-};--const PARAMS = {- parentAgentId: 'local-parent',- attributes: { name: 'code-reviewer', description: 'reviews' },-};--describe('createSubagent', () => {- beforeEach(() => {- vi.clearAllMocks();- getPlugin.mockReturnValue({ behavior: { subagents: behavior } });- 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 () => {- mockSubagentFs(LOCAL_PARENT);-- const result = await createSubagent(PARAMS);-- expect(registerSubagentsCore).toHaveBeenCalledWith(- expect.objectContaining({- parentSwitchAgentId: 'sw-parent',- subagents: [{ name: 'code-reviewer', description: 'reviews' }],- autoSession: true,- })- );- expect(applyLocalSubagentAutoSessionState).toHaveBeenCalledWith(- 'local-parent',- 'code-reviewer',- true- );- expect(result).toEqual({ name: 'code-reviewer' });- });-- it('registers with auto_session off and starts no watcher for a remote parent', async () => {- mockSubagentFs(LOCAL_PARENT);- getRemoteAgentLocation.mockResolvedValueOnce({- id: 'loc-remote',- name: 'r',- sshHost: 'vm',- dir: '/home/dev/r',- createdAt: '',- updatedAt: '',- } as never);-- await createSubagent(PARAMS);-- expect(registerSubagentsCore).toHaveBeenCalledWith(- expect.objectContaining({ autoSession: false })- );- expect(applyLocalSubagentAutoSessionState).not.toHaveBeenCalled();- });-- it('does not fail creation when starting the watcher fails', async () => {- mockSubagentFs(LOCAL_PARENT);- applyLocalSubagentAutoSessionState.mockRejectedValueOnce(new Error('watcher boom'));-- const result = await createSubagent(PARAMS);-- expect(result).toEqual({ name: 'code-reviewer' });- expect(logWarn).toHaveBeenCalledWith(- expect.stringContaining('failed to start auto_session watcher'),- expect.objectContaining({ name: 'code-reviewer' })- );- });-- it('removes the written definition when registration fails', async () => {- mockSubagentFs(LOCAL_PARENT);- registerSubagentsCore.mockRejectedValueOnce(new Error('gateway boom'));-- await expect(createSubagent(PARAMS)).rejects.toThrow('gateway boom');-- expect(behavior.removeLocal).toHaveBeenCalledWith({}, 'code-reviewer');- expect(applyLocalSubagentAutoSessionState).not.toHaveBeenCalled();- });-});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.tsdeleted file mode 100644index 44781ddc0..000000000--- a/dash/apps/switchdash-desktop/src/main/core/subagents/create-subagent.ts+++ /dev/null@@ -1,94 +0,0 @@-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 { resolveSubagentFs } from './resolve-subagent-fs';-import { applyLocalSubagentAutoSessionState } from './setSubagentAutoSession';--export type CreateSubagentParams = {- /** The parent agent to create the subagent under. Its provider, Switch server,- * identity, and working directory (local or remote) are resolved from it. */- parentAgentId: string;- /** The subagent's attributes, keyed by the provider's attribute fields. Must- * include `name` and `description`. */- attributes: SubagentAttributes;-};--function requireString(attributes: SubagentAttributes, key: string): string {- const value = attributes[key];- return typeof value === 'string' ? value.trim() : '';-}--/**- * Author a new subagent from switchdash: write its definition from the given- * attributes, then register it on the gateway and write its credentials so it is- * immediately launchable. Works for both local and remote parents — the parent's- * working directory (local disk or its SSH host over SFTP) is resolved from the- * agent. If gateway registration fails the just-written definition is removed so- * a half-created subagent isn't left behind.- */-export async function createSubagent(params: CreateSubagentParams): Promise<{ name: string }> {- const name = requireString(params.attributes, 'name');- const description = requireString(params.attributes, 'description');- if (!name) throw new Error('A subagent name is required.');- if (!description) throw new Error('A subagent description is required.');-- const ctx = await resolveSubagentFs(params.parentAgentId);- try {- const { agent } = ctx;- const behavior = getPlugin(agent.providerId).behavior.subagents;- if (!behavior) {- throw new Error(`Provider ${agent.providerId} does not support subagents.`);- }- if (!agent.serverId) {- throw new Error(`Agent ${params.parentAgentId} is not linked to a Switch server.`);- }- if (!agent.switchAgentId) {- throw new Error(`Agent ${params.parentAgentId} has no Switch identity.`);- }-- if (await behavior.readDefinition(ctx.fs, name)) {- throw new Error(`A subagent named "${name}" already exists.`);- }-- await behavior.writeDefinition(ctx.fs, params.attributes);-- // Subagents of remote parents register with auto_session off: neither the- // 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}`);- await registerSubagentsCore({- behavior,- server,- parentSwitchAgentId: agent.switchAgentId,- fs: ctx.fs,- subagents: [{ name, description }],- autoSession,- });- } catch (error) {- await behavior.removeLocal(ctx.fs, name);- throw error;- }-- // Seed the local auto_session mirror + start the watcher so the new- // subagent begins watching now, without an off→on toggle. Best-effort: a- // failure must not fail creation (the settings panel reconciles later).- if (autoSession) {- await applyLocalSubagentAutoSessionState(params.parentAgentId, name, true).catch((error) => {- log.warn('createSubagent: failed to start auto_session watcher for new subagent', {- parentAgentId: params.parentAgentId,- name,- error: String(error),- });- });- }-- return { name };- } finally {- 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.tsdeleted file mode 100644index 9b86cea5b..000000000--- a/dash/apps/switchdash-desktop/src/main/core/subagents/delete-subagent.ts+++ /dev/null@@ -1,43 +0,0 @@-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 { resolveSubagentFs } from './resolve-subagent-fs';--export type DeleteSubagentParams = {- /** The parent agent the subagent belongs to. */- parentAgentId: string;- name: string;- /** The subagent's own Switch agent id, when known, so its child identity can- * be deregistered on the gateway. Null skips the gateway delete (local-only- * drift). */- switchAgentId: string | null;-};--/**- * Remove a subagent: deregister its child identity on the gateway (when known),- * then delete its on-disk definition and credentials from the parent's working- * directory (local or remote). The gateway delete runs first so a failure there- * surfaces before the local files are removed.- */-export async function deleteSubagent(params: DeleteSubagentParams): Promise<void> {- const ctx = await resolveSubagentFs(params.parentAgentId);- try {- const behavior = getPlugin(ctx.agent.providerId).behavior.subagents;- if (!behavior) {- throw new Error(`Provider ${ctx.agent.providerId} does not support subagents.`);- }-- if (params.switchAgentId) {- if (!ctx.agent.serverId) {- throw new Error(`Agent ${params.parentAgentId} is not linked to a Switch server.`);- }- 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(ctx.fs, params.name);- } finally {- 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.tsdeleted file mode 100644index 8edce8ad9..000000000--- a/dash/apps/switchdash-desktop/src/main/core/subagents/edit-subagent.ts+++ /dev/null@@ -1,38 +0,0 @@-import type { SubagentAttributes } from '@switchdash/core/agents/plugins';-import { getPlugin } from '@main/core/providers/plugin-registry';-import { resolveSubagentFs } from './resolve-subagent-fs';--export type EditSubagentParams = {- /** The parent agent whose subagent definition to rewrite. */- parentAgentId: string;- /** The subagent's attributes. `name` is the agent's identity and immutable, so- * it only selects which definition to rewrite. */- attributes: SubagentAttributes;-};--/**- * Update an existing subagent's definition in place from the given attributes.- * The name is the agent's Switch identity and so is immutable here; it only- * selects the definition to rewrite. Resolves the parent's working directory- * (local or remote) from the agent.- */-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 ctx = await resolveSubagentFs(params.parentAgentId);- try {- const behavior = getPlugin(ctx.agent.providerId).behavior.subagents;- if (!behavior) {- throw new Error(`Provider ${ctx.agent.providerId} does not support subagents.`);- }-- if (!(await behavior.readDefinition(ctx.fs, name))) {- throw new Error(`No subagent definition named "${name}".`);- }-- await behavior.writeDefinition(ctx.fs, params.attributes);- } finally {- 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.tsdeleted file mode 100644index bea4a65ca..000000000--- a/dash/apps/switchdash-desktop/src/main/core/subagents/list-subagents.ts+++ /dev/null@@ -1,71 +0,0 @@-import type { LocalSubagent } from '@switchdash/core/agents/plugins';-import { getAgentById } from '@main/core/agents/getAgentById';-import { getPlugin } from '@main/core/providers/plugin-registry';-import { fetchAgentChildren, 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 { SubagentListResult } from '@shared/core/subagents/subagents';-import { reconcileSubagents } from './reconcile';-import { resolveSubagentFs } from './resolve-subagent-fs';--/**- * List a parent agent's Claude Code subagents: discover them from the parent's- * `.claude/switch-subagents/` credentials — on local disk or, for a remote- * agent, on its SSH host over SFTP — then reconcile against the gateway's- * registered children. Both discovery and reconciliation are best-effort: if the- * parent has no directory, its host is unreachable, or the gateway is- * unreachable, the listing degrades rather than failing (empty local set and/or- * `registered: null`).- */-export async function listSubagents(parentAgentId: string): Promise<SubagentListResult> {- const parent = await getAgentById(parentAgentId);- if (!parent) {- return { parentAgentId, subagents: [], remoteOnly: [], reconciled: false };- }-- const subagentsBehavior = getPlugin(parent.providerId).behavior.subagents;- let local: LocalSubagent[] = [];- if (subagentsBehavior) {- try {- const ctx = await resolveSubagentFs(parentAgentId);- try {- local = await subagentsBehavior.discoverLocal(ctx.fs, ctx.homeFs);- } finally {- ctx.close();- }- } catch (error) {- // Discovery is best-effort: an unreachable host or a parent without a- // directory degrades to gateway-only reconciliation, it does not fail.- log.warn('subagents: local discovery failed', {- parentAgentId,- error: error instanceof Error ? error.message : String(error),- });- }- }-- let remote: Awaited<ReturnType<typeof fetchAgentChildren>> | null = null;- if (parent.serverId && parent.switchAgentId) {- const server = await getServer(parent.serverId);- if (server) {- try {- remote = await fetchAgentChildren(server, parent.switchAgentId);- } catch (error) {- // Reconciliation is best-effort: a sign-in or connectivity problem- // degrades to local-only, it does not fail the listing.- log.warn('subagents: gateway reconciliation failed', {- parentAgentId,- error: error instanceof GatewayError ? error.message : String(error),- });- }- }- }-- const { subagents, remoteOnly } = reconcileSubagents({- parentAgentId,- serverId: parent.serverId,- local,- remote,- });-- return { parentAgentId, subagents, remoteOnly, reconciled: remote !== null };-}diff --git a/dash/apps/switchdash-desktop/src/main/core/subagents/reconcile.test.ts b/dash/apps/switchdash-desktop/src/main/core/subagents/reconcile.test.tsdeleted file mode 100644index e365b72f4..000000000--- a/dash/apps/switchdash-desktop/src/main/core/subagents/reconcile.test.ts+++ /dev/null@@ -1,83 +0,0 @@-import type { LocalSubagent } from '@switchdash/core/agents/plugins';-import { describe, expect, it } from 'vitest';-import { reconcileSubagents } from './reconcile';--const local = (name: string, switchAgentId: string | null): LocalSubagent => ({- name,- description: null,- model: null,- switchAgentId,- apiEndpoint: switchAgentId ? 'https://gw.example' : null,-});--describe('reconcileSubagents', () => {- it('marks registered=null and reports no drift when there is no remote', () => {- const { subagents, remoteOnly } = reconcileSubagents({- parentAgentId: 'p1',- serverId: 's1',- local: [local('reviewer', 'sa-1')],- remote: null,- });- expect(subagents).toEqual([- {- name: 'reviewer',- description: null,- model: null,- switchAgentId: 'sa-1',- apiEndpoint: 'https://gw.example',- parentAgentId: 'p1',- serverId: 's1',- registered: null,- },- ]);- expect(remoteOnly).toEqual([]);- });-- it('flags a local subagent registered when its id is a gateway child', () => {- const { subagents, remoteOnly } = reconcileSubagents({- parentAgentId: 'p1',- serverId: 's1',- local: [local('reviewer', 'sa-1')],- remote: { parentName: 'main', children: [{ id: 'sa-1', name: 'main.reviewer' }] },- });- expect(subagents[0].registered).toBe(true);- expect(remoteOnly).toEqual([]);- });-- it('flags a local subagent not on the gateway as registered=false', () => {- const { subagents } = reconcileSubagents({- parentAgentId: 'p1',- serverId: 's1',- local: [local('reviewer', 'sa-1'), local('orphan', null)],- remote: { parentName: 'main', children: [{ id: 'sa-1', name: 'main.reviewer' }] },- });- expect(subagents.find((s) => s.name === 'reviewer')?.registered).toBe(true);- expect(subagents.find((s) => s.name === 'orphan')?.registered).toBe(false);- });-- it('reports gateway children with no local file as remote-only, prefix stripped', () => {- const { remoteOnly } = reconcileSubagents({- parentAgentId: 'p1',- serverId: 's1',- local: [local('reviewer', 'sa-1')],- remote: {- parentName: 'main',- children: [- { id: 'sa-1', name: 'main.reviewer' },- { id: 'sa-2', name: 'main.planner' },- ],- },- });- expect(remoteOnly).toEqual([{ name: 'planner', switchAgentId: 'sa-2' }]);- });-- it('keeps the raw child name when it lacks the parent prefix', () => {- const { remoteOnly } = reconcileSubagents({- parentAgentId: 'p1',- serverId: 's1',- local: [],- remote: { parentName: 'main', children: [{ id: 'sa-9', name: 'weird-name' }] },- });- expect(remoteOnly).toEqual([{ name: 'weird-name', switchAgentId: 'sa-9' }]);- });-});diff --git a/dash/apps/switchdash-desktop/src/main/core/subagents/reconcile.ts b/dash/apps/switchdash-desktop/src/main/core/subagents/reconcile.tsdeleted file mode 100644index 2d45df6b5..000000000--- a/dash/apps/switchdash-desktop/src/main/core/subagents/reconcile.ts+++ /dev/null@@ -1,46 +0,0 @@-import type { LocalSubagent } from '@switchdash/core/agents/plugins';-import type { RemoteChildAgent } from '@main/core/switch-servers/gateway-client';-import type { RemoteOnlySubagent, Subagent } from '@shared/core/subagents/subagents';--/** Strip the `<parent>.` prefix from a server-side child name, if present. */-function displayChildName(childName: string, parentName: string): string {- const prefix = `${parentName}.`;- return childName.startsWith(prefix) ? childName.slice(prefix.length) : childName;-}--/**- * Reconcile locally-discovered subagents against the gateway's children of the- * parent. Pure so it can be unit-tested without a gateway. When `remote` is- * null (reconciliation could not run) every subagent's `registered` is null and- * no drift is reported.- */-export function reconcileSubagents(args: {- parentAgentId: string;- serverId: string | null;- local: LocalSubagent[];- remote: { parentName: string; children: RemoteChildAgent[] } | null;-}): { subagents: Subagent[]; remoteOnly: RemoteOnlySubagent[] } {- const { parentAgentId, serverId, local, remote } = args;-- if (!remote) {- return {- subagents: local.map((l) => ({ ...l, parentAgentId, serverId, registered: null })),- remoteOnly: [],- };- }-- const childIds = new Set(remote.children.map((c) => c.id));- const matchedChildIds = new Set<string>();-- const subagents: Subagent[] = local.map((l) => {- const registered = !!l.switchAgentId && childIds.has(l.switchAgentId);- if (registered && l.switchAgentId) matchedChildIds.add(l.switchAgentId);- return { ...l, parentAgentId, serverId, registered };- });-- const remoteOnly: RemoteOnlySubagent[] = remote.children- .filter((c) => !matchedChildIds.has(c.id))- .map((c) => ({ name: displayChildName(c.name, remote.parentName), switchAgentId: c.id }));-- return { subagents, remoteOnly };-}diff --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.tsdeleted file mode 100644index 411ac29d8..000000000--- a/dash/apps/switchdash-desktop/src/main/core/subagents/register-subagents.test.ts+++ /dev/null@@ -1,205 +0,0 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';--const getPlugin = vi.hoisted(() => vi.fn());-const getServer = vi.hoisted(() => vi.fn());-const registerSubagentsBulk = vi.hoisted(() => vi.fn());-const parseSwitchAgentCredentials = vi.hoisted(() => vi.fn());-const readSwitchAgentCredentials = vi.hoisted(() => vi.fn());-const openRemoteSubagentFs = vi.hoisted(() => vi.fn());-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 getLocationByHostDir = vi.hoisted(() => vi.fn());-const applyLocalSubagentAutoSessionState = vi.hoisted(() => vi.fn(async () => {}));-const logWarn = vi.hoisted(() => vi.fn());--vi.mock('@main/core/providers/plugin-registry', () => ({ getPlugin }));-vi.mock('@main/core/providers/plugin-fs', () => ({ createPluginFs: vi.fn() }));-vi.mock('@main/core/switch-servers/servers-store', () => ({ getServer }));-vi.mock('@main/core/switch-servers/gateway-client', () => ({ registerSubagentsBulk }));-vi.mock('@main/core/switch-rooms/switch-credentials', () => ({- parseSwitchAgentCredentials,- readSwitchAgentCredentials,-}));-vi.mock('./resolve-subagent-fs', () => ({ openRemoteSubagentFs }));-vi.mock('@main/core/agents/getAgents', () => ({ getAgents }));-vi.mock('@main/core/locations/store', () => ({ getLocationByHostDir }));-vi.mock('./setSubagentAutoSession', () => ({ applyLocalSubagentAutoSessionState }));-vi.mock('@main/lib/logger', () => ({ log: { warn: logWarn, error: vi.fn() } }));--const { registerSubagents, registerSubagentsRemote } = await import('./register-subagents');--const REMOTE = {- providerId: 'claude',- serverId: 'srv-1',- sshHost: 'box',- remoteRepoDir: '/home/dev/r',-};--describe('registerSubagentsRemote', () => {- beforeEach(() => {- vi.clearAllMocks();- getPlugin.mockReturnValue({ behavior: { subagents: { writeSettings } } });- getServer.mockResolvedValue({ id: 'srv-1', apiUrl: 'https://switch.example.com' });- openRemoteSubagentFs.mockResolvedValue({- fs: { read: remoteRead },- close: remoteClose,- });- });-- it('returns early without connecting when there are no subagents', async () => {- const result = await registerSubagentsRemote({ ...REMOTE, subagents: [] });- expect(result).toEqual({ registered: [] });- expect(openRemoteSubagentFs).not.toHaveBeenCalled();- });-- it('reads parent creds from the remote settings, registers, writes creds, and closes', async () => {- remoteRead.mockResolvedValueOnce('{"env":{"SWITCH_AGENT_ID":"sw-parent"}}');- parseSwitchAgentCredentials.mockReturnValueOnce({- agentId: 'sw-parent',- apiEndpoint: 'https://switch.example.com',- token: 'tok',- });- registerSubagentsBulk.mockResolvedValueOnce([- { subagentName: 'code-reviewer', id: 'child-1', apiKey: 'key-1' },- ]);-- const result = await registerSubagentsRemote({- ...REMOTE,- subagents: [{ name: 'code-reviewer', description: 'reviews' }],- });-- expect(remoteRead).toHaveBeenCalledWith('.claude/settings.local.json');- expect(registerSubagentsBulk).toHaveBeenCalledWith(- expect.objectContaining({ apiUrl: 'https://switch.example.com' }),- {- parentAgentId: 'sw-parent',- subagents: [{ subagentName: 'code-reviewer', description: 'reviews' }],- autoSession: false,- }- );- expect(applyLocalSubagentAutoSessionState).not.toHaveBeenCalled();- expect(writeSettings).toHaveBeenCalledWith(- { read: remoteRead },- expect.objectContaining({- subagentName: 'code-reviewer',- apiToken: 'key-1',- agentId: 'child-1',- })- );- expect(result).toEqual({ registered: ['code-reviewer'] });- expect(remoteClose).toHaveBeenCalledTimes(1);- });-- it('fails loud (and still closes) when the remote host has no parent creds', async () => {- remoteRead.mockResolvedValueOnce(null);- parseSwitchAgentCredentials.mockReturnValueOnce(null);-- await expect(- registerSubagentsRemote({- ...REMOTE,- subagents: [{ name: 'x', description: 'y' }],- })- ).rejects.toThrow(/No Switch agent configured/);-- expect(registerSubagentsBulk).not.toHaveBeenCalled();- expect(remoteClose).toHaveBeenCalledTimes(1);- });-});--const LOCAL = {- providerId: 'claude',- serverId: 'srv-1',- dir: '/home/dev/r',-};--describe('registerSubagents', () => {- beforeEach(() => {- vi.clearAllMocks();- getPlugin.mockReturnValue({ behavior: { subagents: { writeSettings } } });- getServer.mockResolvedValue({ id: 'srv-1', apiUrl: 'https://switch.example.com' });- readSwitchAgentCredentials.mockResolvedValue({- agentId: 'sw-parent',- apiEndpoint: 'https://switch.example.com',- token: 'tok',- });- });-- it('registers with auto_session on and starts a watcher per new subagent', async () => {- registerSubagentsBulk.mockResolvedValueOnce([- { subagentName: 'code-reviewer', id: 'child-1', apiKey: 'key-1' },- { subagentName: 'doc-writer', id: 'child-2', apiKey: 'key-2' },- ]);- getLocationByHostDir.mockResolvedValueOnce({ id: 'loc-1' });- getAgents.mockResolvedValueOnce([- { id: 'local-other', switchAgentId: 'sw-other' },- { id: 'local-parent', switchAgentId: 'sw-parent' },- ]);-- const result = await registerSubagents({- ...LOCAL,- subagents: [- { name: 'code-reviewer', description: 'reviews' },- { name: 'doc-writer', description: 'writes docs' },- ],- });-- expect(registerSubagentsBulk).toHaveBeenCalledWith(- expect.objectContaining({ apiUrl: 'https://switch.example.com' }),- expect.objectContaining({ parentAgentId: 'sw-parent', autoSession: true })- );- expect(getLocationByHostDir).toHaveBeenCalledWith(null, '/home/dev/r');- expect(applyLocalSubagentAutoSessionState).toHaveBeenCalledTimes(2);- expect(applyLocalSubagentAutoSessionState).toHaveBeenCalledWith(- 'local-parent',- 'code-reviewer',- true- );- expect(applyLocalSubagentAutoSessionState).toHaveBeenCalledWith(- 'local-parent',- 'doc-writer',- true- );- expect(result).toEqual({ registered: ['code-reviewer', 'doc-writer'] });- });-- it('warns instead of failing when no local agent matches the dir', async () => {- registerSubagentsBulk.mockResolvedValueOnce([- { subagentName: 'code-reviewer', id: 'child-1', apiKey: 'key-1' },- ]);- getLocationByHostDir.mockResolvedValueOnce(undefined);-- const result = await registerSubagents({- ...LOCAL,- subagents: [{ name: 'code-reviewer', description: 'reviews' }],- });-- expect(result).toEqual({ registered: ['code-reviewer'] });- expect(applyLocalSubagentAutoSessionState).not.toHaveBeenCalled();- expect(logWarn).toHaveBeenCalledWith(- expect.stringContaining('no local agent for dir'),- expect.objectContaining({ dir: '/home/dev/r' })- );- });-- it('does not fail registration when starting a watcher fails', async () => {- registerSubagentsBulk.mockResolvedValueOnce([- { subagentName: 'code-reviewer', id: 'child-1', apiKey: 'key-1' },- ]);- getLocationByHostDir.mockResolvedValueOnce({ id: 'loc-1' });- getAgents.mockResolvedValueOnce([{ id: 'local-parent', switchAgentId: 'sw-parent' }]);- applyLocalSubagentAutoSessionState.mockRejectedValueOnce(new Error('watcher boom'));-- const result = await registerSubagents({- ...LOCAL,- subagents: [{ name: 'code-reviewer', description: 'reviews' }],- });-- expect(result).toEqual({ registered: ['code-reviewer'] });- expect(logWarn).toHaveBeenCalledWith(- expect.stringContaining('failed to start auto_session watcher'),- expect.objectContaining({ name: 'code-reviewer' })- );- });-});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.tsdeleted file mode 100644index ec9faf02a..000000000--- a/dash/apps/switchdash-desktop/src/main/core/subagents/register-subagents.ts+++ /dev/null@@ -1,208 +0,0 @@-import type { ISubagentsBehavior, PluginFs } from '@switchdash/core/agents/plugins';-import { getAgents } from '@main/core/agents/getAgents';-import { getLocationByHostDir } from '@main/core/locations/store';-import { createPluginFs } from '@main/core/providers/plugin-fs';-import { getPlugin } from '@main/core/providers/plugin-registry';-import {- parseSwitchAgentCredentials,- readSwitchAgentCredentials,-} from '@main/core/switch-rooms/switch-credentials';-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-subagent-fs';-import { applyLocalSubagentAutoSessionState } from './setSubagentAutoSession';--// Remote hosts are POSIX; use a forward-slash literal rather than path.join-// (which emits backslashes on Windows). SshFileSystem normalises separators, but-// keeping this explicit matches writeRemoteSwitchSettings.-const REMOTE_SETTINGS_PATH = '.claude/settings.local.json';--export type RegisterSubagentsParams = {- /** The agent type the subagents belong to — selects the subagent mechanism. */- providerId: string;- /** The registered Switch server the parent belongs to. */- serverId: string;- /** The agent's working directory. Its `.claude/settings.local.json` is the- * parent identity (its agent id + API endpoint), and credentials files are- * written under it. */- dir: string;- subagents: { name: string; description: string }[];-};--/**- * Register subagents on the gateway under an already-resolved parent identity and- * filesystem, then write each one's credentials to- * `.claude/switch-subagents/<name>.settings.json` (via `fs`, so this works- * against a local dir or a remote host over SFTP) to make them launchable. The- * secret API keys are written to disk in the main process and never returned to- * the renderer — the result is just the registered subagent names.- */-export async function registerSubagentsCore(params: {- behavior: ISubagentsBehavior;- server: SwitchServer;- /** The parent's Switch (gateway) agent id — the child agents hang off it. */- parentSwitchAgentId: string;- fs: PluginFs;- subagents: { name: string; description: string }[];- /** Register the subagents with `auto_session` on, so a watcher auto-spawns a- * session when one is addressed. Only pass true for local parents — subagents- * of remote parents have no watcher (neither here nor in the VM sidecar). */- autoSession: boolean;-}): Promise<{ registered: string[] }> {- if (params.subagents.length === 0) return { registered: [] };-- const results = await registerSubagentsBulk(params.server, {- parentAgentId: params.parentSwitchAgentId,- subagents: params.subagents.map((s) => ({- subagentName: s.name,- description: s.description,- })),- autoSession: params.autoSession,- });-- for (const result of results) {- await params.behavior.writeSettings(params.fs, {- subagentName: result.subagentName,- // Subagents talk to the Switch core (agent bridge), same as the parent.- apiEndpoint: params.server.apiUrl,- apiToken: result.apiKey,- agentId: result.id,- });- }-- return { registered: results.map((r) => r.subagentName) };-}--/**- * 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 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).- */-async function startAutoSessionWatchers(- dir: string,- parentSwitchAgentId: string,- names: string[]-): Promise<void> {- const location = await getLocationByHostDir(null, dir);- const localParent = location- ? (await getAgents(location.id)).find((a) => a.switchAgentId === parentSwitchAgentId)- : undefined;- if (!localParent) {- log.warn(- 'registerSubagents: no local agent for dir; auto_session watchers start on reconcile',- {- dir,- parentSwitchAgentId,- }- );- return;- }- for (const name of names) {- await applyLocalSubagentAutoSessionState(localParent.id, name, true).catch((error) => {- log.warn('registerSubagents: failed to start auto_session watcher for new subagent', {- parentAgentId: localParent.id,- name,- error: String(error),- });- });- }-}--/**- * Register the given subagents under the directory's parent agent on the gateway- * and write their credentials. Used by the local onboarding flow, which knows the- * parent only by its directory: the parent's gateway id and API endpoint are read- * from its `.claude/settings.local.json`, and files are written to the same local- * dir.- */-export async function registerSubagents(- params: RegisterSubagentsParams-): Promise<{ registered: string[] }> {- if (params.subagents.length === 0) return { registered: [] };-- const behavior = getPlugin(params.providerId).behavior.subagents;- if (!behavior) {- throw new Error(`Provider ${params.providerId} does not support subagents.`);- }-- const server = await getServer(params.serverId);- if (!server) throw new Error(`No Switch server with id ${params.serverId}`);-- const parent = await readSwitchAgentCredentials(params.dir, log);- if (!parent) {- throw new Error(- `No Switch agent configured at ${params.dir} — cannot register subagents under it.`- );- }-- const result = await registerSubagentsCore({- behavior,- server,- parentSwitchAgentId: parent.agentId,- fs: createPluginFs(params.dir),- subagents: params.subagents,- autoSession: true,- });- await startAutoSessionWatchers(params.dir, parent.agentId, result.registered);- return result;-}--export type RegisterSubagentsRemoteParams = {- /** The parent agent type — selects the subagent mechanism. */- providerId: string;- /** The registered Switch server the parent belongs to. */- serverId: string;- /** The parent's SSH host + remote working dir. */- sshHost: string;- remoteRepoDir: string;- subagents: { name: string; description: string }[];-};--/**- * Remote counterpart of {@link registerSubagents} for the onboarding flow: the- * parent lives on an SSH host with no local dir. Its gateway id is read from the- * remote `.claude/settings.local.json` over SFTP, and each subagent's definition- * and credentials are written back to the same remote dir.- */-export async function registerSubagentsRemote(- params: RegisterSubagentsRemoteParams-): Promise<{ registered: string[] }> {- if (params.subagents.length === 0) return { registered: [] };-- const behavior = getPlugin(params.providerId).behavior.subagents;- if (!behavior) {- throw new Error(`Provider ${params.providerId} does not support subagents.`);- }-- const server = await getServer(params.serverId);- if (!server) throw new Error(`No Switch server with id ${params.serverId}`);-- const remote = await openRemoteSubagentFs(params.sshHost, params.remoteRepoDir);- try {- const raw = await remote.fs.read(REMOTE_SETTINGS_PATH);- const parent = raw ? parseSwitchAgentCredentials(raw, log) : null;- if (!parent) {- throw new Error(- `No Switch agent configured at ${params.sshHost}:${params.remoteRepoDir} — cannot register subagents under it.`- );- }- // Subagents of remote parents register with auto_session off: neither the- // 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,- server,- parentSwitchAgentId: parent.agentId,- fs: remote.fs,- subagents: params.subagents,- autoSession: false,- });- } finally {- remote.close();- }-}diff --git a/dash/apps/switchdash-desktop/src/main/core/subagents/resolve-subagent-fs.test.ts b/dash/apps/switchdash-desktop/src/main/core/subagents/resolve-subagent-fs.test.tsdeleted file mode 100644index 9431f5b85..000000000--- a/dash/apps/switchdash-desktop/src/main/core/subagents/resolve-subagent-fs.test.ts+++ /dev/null@@ -1,130 +0,0 @@-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 })));--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) {- SshFileSystemCtor(proxy, root);- this.close = sshClose;- }),-}));-vi.mock('@main/core/providers/plugin-fs', () => ({ createPluginFs }));-vi.mock('@main/core/providers/remote-plugin-fs', () => ({ createRemotePluginFs }));--const { resolveSubagentFs, openRemoteSubagentFs } = await import('./resolve-subagent-fs');--function agent(overrides: Partial<Agent>): Agent {- return {- id: 'agent-1',- locationId: 'loc-1',- name: 'parent',- providerId: 'claude',- switchAgentId: 'sw-1',- apiEndpoint: 'https://switch.example.com',- serverId: 'srv-1',- status: null,- autoApprove: false,- createdAt: '',- updatedAt: '',- ...overrides,- };-}--function location(overrides: Partial<Location>): Location {- return {- id: 'loc-1',- name: 'parent',- sshHost: null,- dir: '/local/proj',- createdAt: '',- updatedAt: '',- ...overrides,- };-}--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(resolveSubagentFs('missing')).rejects.toThrow(/No agent with id missing/);- });-- 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 resolveSubagentFs('agent-1');-- expect(createPluginFs).toHaveBeenCalledWith('/local/proj');- expect(ws.fs).toEqual({ __local: '/local/proj' });- expect(ensureSshConnected).not.toHaveBeenCalled();- // close is a no-op for local — must not throw.- expect(() => ws.close()).not.toThrow();- });-- 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({ locationId: 'loc-remote' }));- getRemoteAgentLocation.mockResolvedValueOnce(- location({ id: 'loc-remote', sshHost: 'box', dir: '/home/dev/r' }) as Location & {- sshHost: string;- }- );-- const ws = await resolveSubagentFs('agent-1');-- expect(ensureSshConnected).toHaveBeenCalledWith('agent-ssh:box', 'box');- expect(SshFileSystemCtor).toHaveBeenCalledWith(expect.anything(), '/home/dev/r');- expect(createRemotePluginFs).toHaveBeenCalledTimes(1);- expect(ws.fs).toEqual({ __remote: true });- // Home scope is empty for remote agents.- expect(await ws.homeFs.list('.')).toEqual([]);-- ws.close();- expect(sshClose).toHaveBeenCalledTimes(1);- });-});--describe('openRemoteSubagentFs', () => {- beforeEach(() => {- vi.clearAllMocks();- createRemotePluginFs.mockReturnValue({ __remote: true });- });-- it('connects over SSH, roots a remote plugin fs at the repo dir, and closes it', async () => {- const { fs, close } = await openRemoteSubagentFs('box', '/home/dev/r');-- expect(ensureSshConnected).toHaveBeenCalledWith('agent-ssh:box', 'box');- expect(SshFileSystemCtor).toHaveBeenCalledWith(expect.anything(), '/home/dev/r');- expect(fs).toEqual({ __remote: true });-- close();- expect(sshClose).toHaveBeenCalledTimes(1);- });-});diff --git a/dash/apps/switchdash-desktop/src/main/core/subagents/resolve-subagent-fs.ts b/dash/apps/switchdash-desktop/src/main/core/subagents/resolve-subagent-fs.tsdeleted file mode 100644index ca7d21286..000000000--- a/dash/apps/switchdash-desktop/src/main/core/subagents/resolve-subagent-fs.ts+++ /dev/null@@ -1,81 +0,0 @@-import { homedir } from 'node:os';-import type { PluginFs } from '@switchdash/core/agents/plugins';-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 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 — location-scoped subagent IO,- * which is what switchdash authors, is unaffected.- */-const EMPTY_PLUGIN_FS: PluginFs = {- read: () => Promise.resolve(null),- write: () => Promise.reject(new Error('home scope is read-only for remote agents')),- delete: () => Promise.resolve(),- exists: () => Promise.resolve(false),- list: () => Promise.resolve([]),-};--export type SubagentFsContext = {- agent: Agent;- /** FS rooted at the parent's working dir — local disk or the remote repo dir. */- fs: PluginFs;- /** FS for user-scoped (`~/.claude`) definitions; empty for remote agents. */- homeFs: PluginFs;- /** Release resources (the remote SFTP channel). Always call in a `finally`. */- close: () => void;-};--/**- * 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 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(sshConnectionIdForHost(sshHost), sshHost);- const sshFs = new SshFileSystem(proxy, remoteRepoDir);- return { fs: createRemotePluginFs(sshFs), close: () => sshFs.close() };-}--/**- * Resolve the filesystem where a parent agent's subagent definitions and- * credentials live, transparently for local and remote agents. Local agents use- * 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 resolveSubagentFs(parentAgentId: string): Promise<SubagentFsContext> {- const agent = await getAgentById(parentAgentId);- if (!agent) throw new Error(`No agent with id ${parentAgentId}`);-- 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 location = await getLocationById(agent.locationId);- if (!location) {- throw new Error(`Agent ${parentAgentId} has no location on disk.`);- }- return {- agent,- fs: createPluginFs(location.dir),- homeFs: createPluginFs(homedir()),- close: () => {},- };-}diff --git a/dash/apps/switchdash-desktop/src/main/core/subagents/setSubagentAutoSession.ts b/dash/apps/switchdash-desktop/src/main/core/subagents/setSubagentAutoSession.tsdeleted file mode 100644index 2c43c30bc..000000000--- a/dash/apps/switchdash-desktop/src/main/core/subagents/setSubagentAutoSession.ts+++ /dev/null@@ -1,105 +0,0 @@-import { getAgentById } from '@main/core/agents/getAgentById';-import {- listAutoSessionSubagents,- setAutoSessionSubagent,-} from '@main/core/switch-rooms/auto-session-store';-import { autoSessionWatcher } from '@main/core/switch-rooms/auto-session-watcher';-import {- fetchAgentOptions,- GatewayError,- setAutoSession,-} from '@main/core/switch-servers/gateway-client';-import { getServer } from '@main/core/switch-servers/servers-store';-import { log } from '@main/lib/logger';-import { listSubagents } from './list-subagents';--export type SubagentAutoSessionParams = {- parentAgentId: string;- name: string;- enabled: boolean;-};--/**- * Apply a subagent's auto_session state to the LOCAL side only: mirror the flag- * and start/stop its watcher. Does NOT touch the gateway profile — callers that- * also mutate the gateway must do so separately.- */-export async function applyLocalSubagentAutoSessionState(- parentAgentId: string,- name: string,- enabled: boolean-): Promise<void> {- await setAutoSessionSubagent(parentAgentId, name, enabled);- await autoSessionWatcher.reconcileSubagent(parentAgentId, name, enabled);-}--/** Resolve a subagent's own Switch agent id (needed to flip its gateway profile). */-async function resolveSubagentSwitchId(- parentAgentId: string,- name: string-): Promise<string | null> {- const { subagents } = await listSubagents(parentAgentId);- return subagents.find((s) => s.name === name)?.switchAgentId ?? null;-}--/**- * Toggle a subagent's auto_session capability. Same single write path as- * {@link setAgentAutoSession}, but keyed by the subagent's own Switch agent id:- * flips its gateway profile (`connection_model` ⇄ `auto_session`), mirrors the- * flag locally, and starts/stops a watcher that spawns sessions launched as that- * subagent. The parent agent must be linked to a Switch server.- */-export async function setSubagentAutoSession(params: SubagentAutoSessionParams): Promise<void> {- const parent = await getAgentById(params.parentAgentId);- if (!parent) throw new Error(`No agent with id ${params.parentAgentId}`);- if (!parent.serverId || !parent.switchAgentId) {- throw new Error('Parent agent is not linked to a Switch server; cannot set auto_session.');- }- const server = await getServer(parent.serverId);- if (!server) throw new Error(`No Switch server with id ${parent.serverId}`);-- const switchAgentId = await resolveSubagentSwitchId(params.parentAgentId, params.name);- if (!switchAgentId) {- throw new Error(`Subagent ${params.name} has no Switch agent id; cannot set auto_session.`);- }-- await setAutoSession(server, switchAgentId, params.enabled);- await applyLocalSubagentAutoSessionState(params.parentAgentId, params.name, params.enabled);-}--/**- * Read whether a subagent has auto_session enabled, reconciling the local mirror- * (and the watcher) from the subagent's gateway profile. Falls back to the local- * mirror if the gateway is unreachable, so the UI can still render a value.- */-export async function getSubagentAutoSession(params: {- parentAgentId: string;- name: string;-}): Promise<boolean> {- const parent = await getAgentById(params.parentAgentId);- if (!parent?.serverId || !parent.switchAgentId) return false;- const server = await getServer(parent.serverId);- if (!server) return false;-- const switchAgentId = await resolveSubagentSwitchId(params.parentAgentId, params.name);- if (!switchAgentId) return false;-- try {- const { connectionModel } = await fetchAgentOptions(server, switchAgentId);- const enabled = connectionModel === 'auto_session';- await applyLocalSubagentAutoSessionState(params.parentAgentId, params.name, enabled);- return enabled;- } catch (error) {- if (error instanceof GatewayError) {- log.warn('getSubagentAutoSession: could not read gateway profile; using local mirror', {- parentAgentId: params.parentAgentId,- name: params.name,- error: error.message,- });- return (await listAutoSessionSubagents()).some(- (s) => s.parentAgentId === params.parentAgentId && s.name === params.name- );- }- throw error;- }-}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 65471b863..370e83cdf 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@@ -2,7 +2,10 @@ import { randomUUID } from 'node:crypto';import path from 'node:path';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 {+ agentSettingsPath,+ 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 { events } from '@main/lib/events';@@ -39,12 +42,12 @@ const INFLIGHT_TTL_MS = 120_000;interface AgentWatcher {abort: AbortController;- /** Map key: the local agent id for a parent, or `parentId::subagentName`. */+ /** Map key: the local agent id for a parent, or `parentId::agentName`. */key: string;/** Local agent that owns spawned sessions (the parent for a subagent). */localAgentId: string;/** When set, spawn sessions as this Claude Code subagent of `localAgentId`. */- subagentName?: string;+ agentName?: string;creds: SwitchAgentCredentials;/** Room ids with a spawn in flight (booting / connecting) → guards against* duplicate spawns while a notification storm lands during the boot window. */@@ -196,7 +199,13 @@ class AutoSessionWatcher {});return;}- const creds = await readSwitchAgentCredentials(rootPath, log);+ // Read the agent's own identity from its provider-neutral per-agent file so+ // agents sharing a location watch as themselves; fall back to the location's+ // `.claude/settings.local.json` for un-migrated installs (CHOO-1440).+ const slug = agent?.definitionName ?? localAgentId;+ const creds =+ (await readSwitchAgentCredentialsFromSettings(agentSettingsPath(rootPath, slug), log)) ??+ (await readSwitchAgentCredentials(rootPath, log));if (!creds) {log.warn('AutoSessionWatcher: missing Switch credentials; cannot watch', {localAgentId,@@ -225,28 +234,29 @@ class AutoSessionWatcher {});return;}- const settingsPath = path.join(- rootPath,- SWITCH_SUBAGENTS_DIR_RELATIVE,- `${name}.settings.json`- );- const creds = await readSwitchAgentCredentialsFromSettings(settingsPath, log);+ // A subagent's credentials now live in the provider-neutral+ // `.switch/agents/<name>.json`; fall back to the legacy+ // `.claude/switch-subagents/<name>.settings.json` for un-migrated installs+ // (CHOO-1440).+ const legacyPath = path.join(rootPath, SWITCH_SUBAGENTS_DIR_RELATIVE, `${name}.settings.json`);+ const creds =+ (await readSwitchAgentCredentialsFromSettings(agentSettingsPath(rootPath, name), log)) ??+ (await readSwitchAgentCredentialsFromSettings(legacyPath, log));if (!creds) {log.warn('AutoSessionWatcher: missing subagent credentials; cannot watch', {parentAgentId,name,- settingsPath,});return;}- this.startWatcher({ key, localAgentId: parentAgentId, subagentName: name, creds });+ this.startWatcher({ key, localAgentId: parentAgentId, agentName: name, creds });}private startWatcher(init: {key: string;localAgentId: string;- subagentName?: string;+ agentName?: string;creds: SwitchAgentCredentials;}): void {const abort = new AbortController();@@ -255,7 +265,7 @@ class AutoSessionWatcher {log.info('AutoSessionWatcher: watching agent', {key: init.key,localAgentId: init.localAgentId,- subagentName: init.subagentName,+ agentName: init.agentName,agentId: init.creds.agentId,});@@ -402,7 +412,7 @@ class AutoSessionWatcher {const result = await sessionService.createSession({id: randomUUID(),agentId: watcher.localAgentId,- subagentName: watcher.subagentName,+ agentName: watcher.agentName,title: `Switch room ${roomId}`,// Bootstrap: tell the fresh session to join the room. Once it calls// connect_to_room, the connect hook starts the per-room poller, whichdiff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-credentials.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-credentials.tsindex 0820fff0d..fd44a05f9 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-credentials.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-credentials.ts@@ -64,6 +64,25 @@ export async function readSwitchAgentCredentialsFromSettings(return parseSwitchAgentCredentials(raw, log);}+/**+ * Read an agent's Switch credentials from a settings file and return them as the+ * `SWITCH_*` env vars a launched session needs, or `{}` when the file is+ * missing/incomplete. Used to inject an agent's identity at launch from its+ * provider-neutral `.switch/agents/<id>.json` (CHOO-1440).+ */+export async function readAgentSwitchEnv(+ settingsPath: string,+ log: CredentialsLogger+): Promise<Record<string, string>> {+ const creds = await readSwitchAgentCredentialsFromSettings(settingsPath, log);+ if (!creds) return {};+ return {+ SWITCH_API_ENDPOINT: creds.apiEndpoint,+ SWITCH_API_TOKEN: creds.token,+ SWITCH_AGENT_ID: creds.agentId,+ };+}+/*** Parse Switch agent credentials from the raw text of a `.claude/settings.local.json`.* Transport-agnostic (no filesystem): used by both the local readers above anddiff --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 a45a67179..39feb7847 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@@ -2,7 +2,7 @@ import * as os from 'node:os';import * as path from 'node:path';import { eq } from 'drizzle-orm';import { DEEPLINK_SCHEME } from '@main/app/deeplinks';-import { subagentSettingsPath } from '@main/core/agents/switch-settings-paths';+import { agentSettingsPath, subagentSettingsPath } from '@main/core/agents/switch-settings-paths';import { getLocationById } from '@main/core/locations/store';import { isHumanInputRecent } from '@main/core/pty/human-activity';import { loadSessionWithAgent } from '@main/core/sessions/session-join';@@ -97,22 +97,35 @@ class SwitchNotificationPoller {// not the parent's `.claude/settings.local.json` — otherwise it receives the// events addressed to the parent rather than to the subagent.const [sessionRow] = await db- .select({ config: sessions.config })+ .select({ config: sessions.config, agentId: sessions.agentId }).from(sessions).where(eq(sessions.id, ctx.sessionId)).limit(1);- const subagentName = sessionRow?.config?.subagentName;+ const agentName = sessionRow?.config?.agentName;+ const agentId = sessionRow?.agentId;- const creds = subagentName- ? await readSwitchAgentCredentialsFromSettings(- subagentSettingsPath(rootPath, subagentName),+ // Credentials come from the agent's provider-neutral per-agent file — a+ // subagent's `.switch/agents/<name>.json` or a plain agent's+ // `.switch/agents/<agentId>.json` — so a session polls as its own identity+ // even when agents share a location. Fall back to the legacy subagent path,+ // then the location's `.claude/settings.local.json`, for un-migrated installs+ // (CHOO-1440).+ const creds = agentName+ ? ((await readSwitchAgentCredentialsFromSettings(+ agentSettingsPath(rootPath, agentName),log- )- : await readSwitchAgentCredentials(rootPath, log);+ )) ??+ (await readSwitchAgentCredentialsFromSettings(+ subagentSettingsPath(rootPath, agentName),+ log+ )))+ : ((agentId+ ? await readSwitchAgentCredentialsFromSettings(agentSettingsPath(rootPath, agentId), log)+ : null) ?? (await readSwitchAgentCredentials(rootPath, log)));if (!creds) {log.warn('SwitchNotificationPoller: missing Switch credentials (SWITCH_API_TOKEN/ENDPOINT/AGENT_ID) — cannot poll room',- { sessionId: ctx.sessionId, dir: rootPath, roomId, subagentName }+ { sessionId: ctx.sessionId, dir: rootPath, roomId, agentName });return;}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 e64fad1ae..959f33d90 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@@ -1,6 +1,7 @@import type { Result } from '@switchdash/shared';import { suggestAgentDefaults } from '@main/core/agents/agent-defaults';import { propagateServerApiUrl } from '@main/core/agents/propagate-server-api-url';+import { registerAgentIdentity } from '@main/core/agents/register-agent-identity';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';@@ -9,7 +10,6 @@ import { SshFileSystem } from '@main/core/fs/impl/ssh-fs';import { sshConnectionIdForHost } from '@main/core/locations/location-transport';import { isManagedServerRunning } from '@main/core/managed-switch-server/managed-server-status';import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';-import type { AgentProviderKind } from '@shared/core/switch-servers/switch-servers';import type {AddressingPolicy,AddServerParams,@@ -47,7 +47,6 @@ import {fetchRoomRoles,fetchRooms,GatewayError,- registerKnownAgent,updateAddressingPolicy,} from './gateway-client';import { openAuthenticatedGatewayPage } from './gateway-web';@@ -71,53 +70,6 @@ async function requireServer(serverId: string): Promise<SwitchServer> {return server;}-type RegisterAgentInput = {- name: string;- description: string;- providerKind: AgentProviderKind;- repoDir: string;- notifyUser?: string;- autoSession?: boolean;-};--/**- * Register a new Claude Code agent on `server` and map recoverable gateway- * failures to a typed `ProvisionAgentResult` (unauthorized→unauthenticated,- * 409→name-conflict, 400→invalid-name, else error). Shared by the local and- * remote provisioning flows so the option mapping stays identical.- */-async function registerProvisionedAgent(- server: SwitchServer,- input: RegisterAgentInput-): Promise<- | { kind: 'created'; id: string; apiKey: string }- | Exclude<ProvisionAgentResult, { kind: 'created' }>-> {- try {- const registered = await registerKnownAgent(server, {- name: input.name,- description: input.description,- options: {- channels_enabled: input.providerKind === 'anthropic',- repo_dir: input.repoDir,- ...(input.autoSession ? { auto_session: true } : {}),- ...(input.notifyUser ? { notify_user: input.notifyUser } : {}),- },- });- return { kind: 'created', id: registered.id, apiKey: registered.apiKey };- } catch (cause) {- if (cause instanceof GatewayError) {- if (cause.kind === 'unauthorized') return { kind: 'unauthenticated' };- if (cause.kind === 'http' && cause.status === 409) return { kind: 'name-conflict' };- if (cause.kind === 'http' && cause.status === 400) {- return { kind: 'invalid-name', message: cause.message };- }- return { kind: 'error', message: cause.message };- }- throw cause;- }-}-export const switchServersController = createRPCController({listServers: (): Promise<SwitchServer[]> => listServers(),@@ -272,12 +224,10 @@ export const switchServersController = createRPCController({provisionAgent: async (params: ProvisionAgentParams): Promise<ProvisionAgentResult> => {const server = await requireServer(params.serverId);- const registered = await registerProvisionedAgent(server, {+ const registered = await registerAgentIdentity(server, {name: params.name,description: params.description,- providerKind: params.providerKind,repoDir: params.dir,- notifyUser: params.notifyUser,autoSession: params.autoSession,});if (registered.kind !== 'created') return registered;@@ -305,12 +255,10 @@ export const switchServersController = createRPCController({): Promise<ProvisionAgentResult> => {const server = await requireServer(params.serverId);- const registered = await registerProvisionedAgent(server, {+ const registered = await registerAgentIdentity(server, {name: params.name,description: params.description,- providerKind: params.providerKind,repoDir: params.remoteRepoDir,- notifyUser: params.notifyUser,autoSession: params.autoSession,});if (registered.kind !== 'created') return registered;diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.ts b/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.tsindex bf9a76696..9e77c9315 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.ts@@ -457,41 +457,11 @@ export async function fetchAllExternalUsers(server: SwitchServer): Promise<Remotreturn [...byId.values()];}-/** A gateway child agent (e.g. a Claude Code subagent) of some parent agent. */-export type RemoteChildAgent = {- id: string;- /** Server-side name, e.g. `<parent-name>.<subagent-name>`. */- name: string;-};--/**- * The parent agent's child agents, from its `AgentDetail.children`- * (`GET /agents/{id}`). Used to reconcile locally-discovered subagents against- * what the gateway actually has registered. `parentName` is returned alongside- * so callers can strip the `<parent>.<subagent>` prefix from child names.- */-export async function fetchAgentChildren(- server: SwitchServer,- parentAgentId: string-): Promise<{ parentName: string; children: RemoteChildAgent[] }> {- const res = await gatewayFetch(server, `/agents/${encodeURIComponent(parentAgentId)}`, {- authenticated: true,- });- const json = (await res.json()) as {- name: string;- children?: Array<{ id: string; name: string }>;- };- return {- parentName: json.name,- children: (json.children ?? []).map((c) => ({ id: c.id, name: c.name })),- };-}-/** A subagent registered via the bulk endpoint. `apiKey` is a secret — keep it* in the main process (write it to the subagent's settings file); never pass it* to the renderer. */export type BulkRegisteredSubagent = {- subagentName: string;+ agentName: string;name: string;id: string;apiKey: string;@@ -507,7 +477,7 @@ export async function registerSubagentsBulk(server: SwitchServer,params: {parentAgentId: string;- subagents: { subagentName: string; description: string }[];+ subagents: { agentName: string; description: string }[];/** Register every subagent with the `auto_session` connection model, so a* watcher auto-spawns a session when the subagent is addressed. */autoSession: boolean;@@ -522,7 +492,7 @@ export async function registerSubagentsBulk(parent_agent_id: params.parentAgentId,options: params.autoSession ? { auto_session: true } : {},subagents: params.subagents.map((s) => ({- subagent_name: s.subagentName,+ subagent_name: s.agentName,description: s.description,})),overwrite: params.overwrite ?? false,@@ -532,7 +502,7 @@ export async function registerSubagentsBulk(results: Array<{ subagent_name: string; name: string; id: string; api_key: string }>;};return json.results.map((r) => ({- subagentName: r.subagent_name,+ agentName: r.subagent_name,name: r.name,id: r.id,apiKey: r.api_key,diff --git a/dash/apps/switchdash-desktop/src/main/db/schema.ts b/dash/apps/switchdash-desktop/src/main/db/schema.tsindex 9c274200e..1446124f6 100644--- a/dash/apps/switchdash-desktop/src/main/db/schema.ts+++ b/dash/apps/switchdash-desktop/src/main/db/schema.ts@@ -147,6 +147,13 @@ export const agents = sqliteTable(.references(() => locations.id),name: text('name').notNull(),providerId: text('provider_id').$type<AgentProviderId>().notNull(),+ // The provider-level agent definition this row launches as, when it is one+ // (e.g. a Claude Code subagent: the `.claude/agents/<name>.md` stem, passed+ // to the CLI as `--agent <name>`). Null for a plain agent that launches the+ // provider CLI with no definition. This single field replaces the former+ // separate "subagent" concept — a subagent is just an agent with a+ // definitionName sharing its location with other agents (CHOO-1440).+ definitionName: text('definition_name'),switchAgentId: text('switch_agent_id'),apiEndpoint: text('api_endpoint'),serverId: text('server_id').references(() => switchServers.id, { onDelete: 'set null' }),diff --git a/dash/apps/switchdash-desktop/src/main/index.ts b/dash/apps/switchdash-desktop/src/main/index.tsindex f772333ed..809b1a1f6 100644--- a/dash/apps/switchdash-desktop/src/main/index.ts+++ b/dash/apps/switchdash-desktop/src/main/index.ts@@ -10,6 +10,7 @@ import { setupApplicationMenu } from './app/menu';import { registerAppScheme, setupAppProtocol } from './app/protocol';import { createMainWindow, getMainWindow } from './app/window';import { agentHookService } from './core/agent-hooks/agent-hook-service';+import { migrateAgentStorage } from './core/agents/migrate-agent-storage';import { initializeRemoteDiscovery, initializeRemoteWatchers } from './core/agents/remote-watcher';import { resolveAgentServers } from './core/agents/resolve-servers';import { appService } from './core/app/service';@@ -120,6 +121,12 @@ void app.whenReady().then(async () => {log.warn('switch-agents: failed to reconcile agent → server links at boot', { error: e });}+ try {+ await migrateAgentStorage();+ } catch (e) {+ log.warn('switch-agents: failed to migrate agent storage layout at boot', { error: e });+ }+const agentHookReady = agentHookService.initialize().catch((e) => {log.error('Failed to start agent event service:', e);});diff --git a/dash/apps/switchdash-desktop/src/main/rpc.ts b/dash/apps/switchdash-desktop/src/main/rpc.tsindex 120b7eeea..32145f0ad 100644--- a/dash/apps/switchdash-desktop/src/main/rpc.ts+++ b/dash/apps/switchdash-desktop/src/main/rpc.ts@@ -15,7 +15,6 @@ import { searchController } from './core/search/controller';import { sessionController } from './core/sessions/controller';import { appSettingsController } from './core/settings/controller';import { providerSettingsController } from './core/settings/provider-settings-controller';-import { subagentsController } from './core/subagents/controller';import { switchRoomsController } from './core/switch-rooms/controller';import { switchServersController } from './core/switch-servers/controller';import { switchSetupController } from './core/switch-setup/controller';@@ -37,7 +36,6 @@ export const rpcRouter = createRPCRouter({viewState: viewStateController,search: searchController,switchRooms: switchRoomsController,- subagents: subagentsController,locationRuntimeSettings: locationRuntimeSettingsController,switchServers: switchServersController,switchSetup: switchSetupController,diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsxindex 836c6a7a3..d7a04e67d 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx@@ -1,3 +1,4 @@+import type { RepoAgentAttributes } from '@switchdash/core/agents/plugins';import { useQuery } from '@tanstack/react-query';import { CheckCircle2, CircleAlert } from 'lucide-react';import { observer } from 'mobx-react-lite';@@ -40,11 +41,12 @@ import {import { log } from '@renderer/utils/logger';import type { ProvisionAgentResult } from '@shared/core/switch-servers/switch-servers';import { basenameFromAnyPath } from '@shared/path-name';+import { AgentAdvancedConfig } from './agent-advanced-config';import { AgentTypePicker } from './agent-type-picker';import { ConfigureAgentPanel } from './configure-agent-panel';import { PickExistingPanel } from './content';import { useConfigureAgentForm, usePickMode } from './modes';-import { SubagentOnboardingSection, type SubagentSelection } from './subagent-onboarding-section';+import { OnboardExistingPanel } from './onboard-existing-panel';// switchdash adds a Switch *agent* by pointing at a local directory that the// switch-connector `configure` skill has set up (its `.claude/settings.local.json`@@ -55,6 +57,15 @@ export type AddLocationModalProps = BaseModalProps<void>;/** Sentinel `runHost` value meaning "run on this machine" (no remote host). */const LOCAL_RUN_LOCATION = 'local';+/** Canonical working-directory path: trimmed, with trailing slashes removed+ * (except a bare root), so `/repo` and `/repo/` behave identically through+ * detection, discovery, and location keying — the flow must not care (CHOO-1440). */+function canonicalDir(dir: string): string {+ const trimmed = dir.trim();+ const stripped = trimmed.replace(/\/+$/, '');+ return stripped || (trimmed.startsWith('/') ? '/' : '');+}+export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLocationModalProps) {const [submitState, setSubmitState] = useState<'idle' | 'creating'>('idle');const [verifyState, setVerifyState] = useState<ServerVerifyState>('idle');@@ -68,7 +79,13 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLoc// Run location: 'local' (default) or an onboarded remote host's SSH alias. A// remote agent runs its sessions on the host and needs a remote working dir.const [runHost, setRunHost] = useState<string>(LOCAL_RUN_LOCATION);+ // `remoteRepoDir` is the *committed* remote working dir that drives discovery+ // (SSH agent-detect, agent defaults, subagent scan). `remoteRepoDirDraft` is+ // the raw text field. They are split so typing does not refire those queries+ // on every keystroke — discovery runs only when the user commits the dir+ // (the "Set location" button or Enter). See CHOO-1440.const [remoteRepoDir, setRemoteRepoDir] = useState('');+ const [remoteRepoDirDraft, setRemoteRepoDirDraft] = useState('');// Configure form for onboarding a brand-new agent in the remote dir. Defaults// (name/description) are derived from the remote dir just like a local agent.const remoteConfigureForm = useConfigureAgentForm(remoteRepoDir.trim(), true);@@ -128,11 +145,19 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLoc}}, [allowedHosts, runHost]);- // The subagents the user chose to onboard alongside the parent. Held in a ref- // (not state) so the section can report changes without re-rendering the modal.- const subagentSelectionRef = useRef<SubagentSelection>([]);- const onSubagentSelectionChange = useCallback((selection: SubagentSelection) => {- subagentSelectionRef.current = selection;+ // Reset the remote working dir when the run host changes so a committed dir+ // from a previous host does not leak into discovery for the new one.+ useEffect(() => {+ setRemoteRepoDir('');+ setRemoteRepoDirDraft('');+ }, [runHost]);++ // Advanced definition attributes (model, effort, tools, system prompt, …) the+ // user set in the collapsed Advanced section. Held in a ref (not state) so the+ // section can report changes without re-rendering the modal.+ const advancedAttributesRef = useRef<RepoAgentAttributes>({});+ const onAdvancedChange = useCallback((attributes: RepoAgentAttributes) => {+ advancedAttributesRef.current = attributes;}, []);const shouldCheckPathStatus = !isRemoteRun && pickState.path.trim().length > 0;@@ -153,14 +178,74 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLocenabled: shouldDetectRemote,});+ // Provider agents defined in the picked dir (`.claude/agents/*.md`) — both those+ // already set up for Switch and plain provider subagents a user created directly.+ // The modal suggests onboarding them alongside the create flow; a directory is a+ // flat container of agents (CHOO-1440). Works for local and remote dirs.+ const discoverDir = isRemoteRun ? trimmedRemoteDir : pickState.path;+ const discoverSshHost = isRemoteRun ? runHost : null;+ const discoverQuery = useQuery({+ queryKey: [+ 'discoverLocationAgents',+ discoverSshHost ?? 'local',+ discoverDir,+ pickState.providerId,+ ],+ queryFn: () =>+ rpc.agents.discoverLocationAgents({+ sshHost: discoverSshHost,+ dir: discoverDir,+ providerId: pickState.providerId!,+ }),+ enabled: !!pickState.providerId && discoverDir.trim().length > 0,+ });+ // Definitions that can join Switch and switchdash hasn't already onboarded — the+ // ones worth offering. Already-onboarded ones (on THIS client) are excluded so+ // the modal never offers to re-add a row it already has; ones registered on the+ // gateway by another client are still offered (imported, not re-minted). CHOO-1440.+ const onboardableAgents = (discoverQuery.data ?? []).filter((a) => a.eligible && !a.alreadyAgent);+ const hasOnboardable = onboardableAgents.length > 0;++ // Branch the flow when a directory has onboardable definitions: `createMode`+ // false shows the multi-select adopt list; true reveals the create form. When+ // there is nothing to onboard, the create form always shows. `selectedNames`+ // are the checked definitions to onboard (default: all).+ const [createMode, setCreateMode] = useState(false);+ const [selectedNames, setSelectedNames] = useState<Set<string>>(new Set());+ const onboardableKey = onboardableAgents.map((a) => a.name).join('|');+ useEffect(() => {+ setSelectedNames(new Set(onboardableKey ? onboardableKey.split('|') : []));+ setCreateMode(false);+ }, [onboardableKey]);+ const showCreate = !hasOnboardable || createMode;+ const toggleSelected = useCallback((name: string, checked: boolean) => {+ setSelectedNames((prev) => {+ const next = new Set(prev);+ if (checked) next.add(name);+ else next.delete(name);+ return next;+ });+ }, []);+const inspection = pathStatusQuery.data;- const isChecking = isRemoteRun- ? shouldDetectRemote && remoteAgentQuery.isPending- : shouldCheckPathStatus && pathStatusQuery.isPending;+ // Discovery (`.claude/agents` scan) is a separate query from agent-detection;+ // fold its pending state into `isChecking` so the modal decides "onboard+ // existing vs create new" only once BOTH have settled — otherwise the create+ // form flashes up first and then flips to the onboard list when discovery lands+ // (CHOO-1440).+ const isDiscovering =+ !!pickState.providerId && discoverDir.trim().length > 0 && discoverQuery.isPending;+ const isChecking =+ (isRemoteRun+ ? shouldDetectRemote && remoteAgentQuery.isPending+ : shouldCheckPathStatus && pathStatusQuery.isPending) || isDiscovering;const switchAgent = isRemoteRun? (remoteAgentQuery.data ?? null): (inspection?.switchAgent ?? null);- // A local directory with no Switch agent config offers the configure flow.+ // A local directory with no legacy Switch agent config offers the create flow.+ // This is available even when the directory already contains other agents — a+ // directory is a flat container, so you can always add another (CHOO-1440);+ // onboarding pre-existing definitions is offered alongside it (see below).const isMissingSwitchAgent = !isRemoteRun && !isChecking && shouldCheckPathStatus && !switchAgent;// A remote dir with no Switch agent offers the remote configure flow: register// the agent on the server and write its creds into the remote dir over SSH.@@ -294,39 +379,6 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLocreturn result.locationId;};- /** Onboard the subagents the user selected, after the parent is added. A- * failure here is surfaced but does not block adding the parent (which already- * succeeded). */- const registerSelectedSubagents = async () => {- const selection = subagentSelectionRef.current;- if (selection.length === 0 || !pickState.serverId || !pickState.providerId) return;- try {- const { registered } = isRemoteRun- ? await rpc.subagents.registerRemote({- providerId: pickState.providerId,- serverId: pickState.serverId,- sshHost: runHost,- remoteRepoDir: trimmedRemoteDir,- subagents: selection,- })- : await rpc.subagents.register({- providerId: pickState.providerId,- serverId: pickState.serverId,- dir: pickState.path,- subagents: selection,- });- if (registered.length > 0) {- toast({ title: `Onboarded ${registered.length} subagent(s)` });- }- } catch (error) {- toast({- title: 'Failed to onboard subagents',- description: error instanceof Error ? error.message : String(error),- variant: 'destructive',- });- }- };-const handleSubmit = async () => {if (!canSubmitDetected) return;setSubmitState('creating');@@ -334,7 +386,6 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLoctry {const locationId = await startCreate();if (locationId) {- await registerSelectedSubagents();finishWith(locationId);} else {setCloseGuard(false);@@ -383,19 +434,24 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLoc}};- const handleConfigure = async () => {- if (!canSubmitConfigure || !pickState.serverId || !configureForm.providerKind) return;+ /** Create a brand-new flat agent in the chosen directory (local or remote):+ * mint its identity, write its `.claude/agents/<name>.md` definition + its+ * per-agent credentials, and create the row — all via `addAgent`. */+ const createNewAgent = async (form: ReturnType<typeof useConfigureAgentForm>) => {+ if (!pickState.serverId || !pickState.providerId) return;setSubmitState('creating');setCloseGuard(true);try {- const result = await rpc.switchServers.provisionAgent({+ const result = await getLocationManagerStore().addAgentAndOpen({+ sshHost: isRemoteRun ? runHost : null,+ dir: isRemoteRun ? trimmedRemoteDir : pickState.path,+ name: form.agentName,+ providerId: pickState.providerId,serverId: pickState.serverId,- dir: pickState.path,- name: configureForm.agentName,- description: configureForm.description.trim(),- providerKind: configureForm.providerKind,- notifyUser: configureForm.notifyUser.trim() || undefined,- autoSession: configureForm.autoSession,+ description: form.description.trim(),+ autoSession: form.autoSession,+ autoApprove: form.autoApprove,+ definitionAttributes: advancedAttributesRef.current,});if (result.kind !== 'created') {reportProvisionError(result);@@ -403,90 +459,70 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLocsetSubmitState('idle');return;}- if (configureForm.addressingPolicy !== null) {+ if (form.addressingPolicy !== null && result.agent.switchAgentId) {await rpc.switchServers.updateAddressingPolicy({serverId: pickState.serverId,- agentId: result.agentId,- policy: configureForm.addressingPolicy,+ agentId: result.agent.switchAgentId,+ policy: form.addressingPolicy,});}- // 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 locationId = await startCreate();- if (locationId) {- await registerSelectedSubagents();- finishWith(locationId);- } else {- setCloseGuard(false);- setSubmitState('idle');- }+ void agentsStore.load();+ finishWith(result.agent.locationId);} catch (error) {log.error(error);setCloseGuard(false);setSubmitState('idle');toast({- title: 'Failed to register agent',+ title: 'Failed to add agent',description: String(error),variant: 'destructive',});}};- const handleConfigureRemote = async () => {- if (!canSubmitConfigureRemote || !pickState.serverId || !remoteConfigureForm.providerKind) {- return;- }+ const handleConfigure = () => createNewAgent(configureForm);+ const handleConfigureRemote = () => createNewAgent(remoteConfigureForm);++ /** Onboard (or adopt) the selected agents already defined in the picked+ * directory — importing those already registered on the gateway and minting a+ * fresh identity for plain provider definitions. */+ const handleOnboard = async () => {+ if (!pickState.serverId || !pickState.providerId || selectedNames.size === 0) return;setSubmitState('creating');setCloseGuard(true);try {- const result = await rpc.switchServers.provisionRemoteAgent({+ const result = await rpc.agents.onboardLocationAgents({+ sshHost: discoverSshHost,+ dir: discoverDir,+ providerId: pickState.providerId,serverId: pickState.serverId,- sshHost: runHost,- remoteRepoDir: trimmedRemoteDir,- name: remoteConfigureForm.agentName,- description: remoteConfigureForm.description.trim(),- providerKind: remoteConfigureForm.providerKind,- notifyUser: remoteConfigureForm.notifyUser.trim() || undefined,- autoSession: remoteConfigureForm.autoSession,+ names: [...selectedNames],});- if (result.kind !== 'created') {- reportProvisionError(result);+ if (!result.success) {+ reportCreationError(result.error);setCloseGuard(false);setSubmitState('idle');return;}- if (remoteConfigureForm.addressingPolicy !== null) {- await rpc.switchServers.updateAddressingPolicy({- serverId: pickState.serverId,- agentId: result.agentId,- policy: remoteConfigureForm.addressingPolicy,- });- }- // Credentials are now written to the remote dir's .claude/settings.local.json,- // 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 locationId = await startCreate();- if (locationId) {- await registerSelectedSubagents();- finishWith(locationId);- } else {- setCloseGuard(false);- setSubmitState('idle');- }+ // reload (not load) — the initial load is memoized, so a plain load() would+ // no-op and the onboarded location wouldn't mount until a restart (CHOO-1440).+ await agentsStore.load();+ await getLocationManagerStore().reload();+ finishWith(result.data[0].locationId);} catch (error) {log.error(error);setCloseGuard(false);setSubmitState('idle');toast({- title: 'Failed to register agent',+ title: 'Failed to onboard agents',description: String(error),variant: 'destructive',});}};+ const canOnboard =+ hasOnboardable && selectedNames.size > 0 && !!pickState.serverId && submitState === 'idle';const submitLabel = submitState === 'creating' ? 'Adding...' : 'Add Agent';return (@@ -498,7 +534,25 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLoc}footer={<DialogFooter>- {isMissingRemoteAgent ? (+ {switchAgent ? (+ <ConfirmButton+ type="button"+ onClick={() => void handleSubmit()}+ disabled={!canSubmitDetected}+ >+ {submitLabel}+ </ConfirmButton>+ ) : hasOnboardable && !createMode ? (+ <ConfirmButton+ type="button"+ onClick={() => void handleOnboard()}+ disabled={!canOnboard}+ >+ {submitState === 'creating'+ ? 'Onboarding...'+ : `Onboard ${selectedNames.size} selected`}+ </ConfirmButton>+ ) : isMissingRemoteAgent ? (<ConfirmButtontype="button"onClick={() => void handleConfigureRemote()}@@ -555,26 +609,69 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLoc</p>)}{isRemoteRun && (- <Input- value={remoteRepoDir}- placeholder="Remote working directory, e.g. /home/agent/repo"- onChange={(e) => setRemoteRepoDir(e.target.value)}- />+ <div className="flex items-center gap-2">+ <Input+ value={remoteRepoDirDraft}+ placeholder="Remote working directory, e.g. /home/agent/repo"+ onChange={(e) => setRemoteRepoDirDraft(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === 'Enter') {+ e.preventDefault();+ setRemoteRepoDir(canonicalDir(remoteRepoDirDraft));+ }+ }}+ />+ <Button+ type="button"+ variant="outline"+ onClick={() => setRemoteRepoDir(canonicalDir(remoteRepoDirDraft))}+ disabled={canonicalDir(remoteRepoDirDraft) === remoteRepoDir}+ >+ Set location+ </Button>+ </div>)}</Field>{!isRemoteRun && <PickExistingPanel state={pickState} showName={!isMissingSwitchAgent} />}- {isMissingRemoteAgent && (+ {isChecking && (+ <p className="text-sm text-foreground-muted">Scanning directory for agents…</p>+ )}+ {hasOnboardable && !createMode && (+ <>+ <OnboardExistingPanel+ agents={onboardableAgents}+ selected={selectedNames}+ onToggle={toggleSelected}+ />+ <Button+ type="button"+ variant="outline"+ className="self-start"+ onClick={() => setCreateMode(true)}+ >+ Create a new agent instead+ </Button>+ </>+ )}+ {hasOnboardable && createMode && (+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className="self-start"+ onClick={() => setCreateMode(false)}+ >+ ← Back to existing agents+ </Button>+ )}+ {isMissingRemoteAgent && showCreate && (<><ConfigureAgentPanelform={remoteConfigureForm}serverId={pickState.serverId}onAddServer={() => showAddServerModal({})}/>- <SubagentOnboardingSection- source={{ kind: 'remote', sshHost: runHost, remoteRepoDir: trimmedRemoteDir }}- providerId={pickState.providerId}- onSelectionChange={onSubagentSelectionChange}- />+ <AgentAdvancedConfig providerId={pickState.providerId} onChange={onAdvancedChange} /></>)}{switchAgent && (@@ -606,29 +703,16 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLoc</div></div>)}- <SubagentOnboardingSection- source={- isRemoteRun- ? { kind: 'remote', sshHost: runHost, remoteRepoDir: trimmedRemoteDir }- : { kind: 'local', dir: pickState.path }- }- providerId={pickState.providerId}- onSelectionChange={onSubagentSelectionChange}- /></>)}- {isMissingSwitchAgent && (+ {isMissingSwitchAgent && showCreate && (<><ConfigureAgentPanelform={configureForm}serverId={pickState.serverId}onAddServer={() => showAddServerModal({})}/>- <SubagentOnboardingSection- source={{ kind: 'local', dir: pickState.path }}- providerId={pickState.providerId}- onSelectionChange={onSubagentSelectionChange}- />+ <AgentAdvancedConfig providerId={pickState.providerId} onChange={onAdvancedChange} /></>)}</DialogContentArea>diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/agent-advanced-config.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/agent-advanced-config.tsxnew file mode 100644index 000000000..c20cc25db--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/agent-advanced-config.tsx@@ -0,0 +1,93 @@+import type { RepoAgentAttributes } from '@switchdash/core/agents/plugins';+import { useQuery } from '@tanstack/react-query';+import { ChevronRight } from 'lucide-react';+import { useEffect, useMemo, useState } from 'react';+import { rpc } from '@renderer/lib/ipc';+import { Field, FieldDescription, FieldLabel } from '@renderer/lib/ui/field';+import { cn } from '@renderer/utils/utils';+import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';+import {+ advancedFields,+ attributesFromForm,+ DefinitionFieldInput,+ emptyForm,+ type FormState,+ type FormValue,+} from '../agent-definition-fields';++/**+ * Collapsed "Advanced configuration" section for the add-agent modal. Renders the+ * provider's definition attribute fields (model, effort, tools, system prompt, …)+ * beyond name/description, and reports the assembled attributes so the modal can+ * pass them to `addAgent`, which writes them into the agent's on-disk definition.+ * Collapsed by default so ordinary users are not overwhelmed (CHOO-1440).+ */+export function AgentAdvancedConfig({+ providerId,+ onChange,+}: {+ providerId: AgentProviderId | null;+ onChange: (attributes: RepoAgentAttributes) => void;+}) {+ const [open, setOpen] = useState(false);+ const { data: allFields } = useQuery({+ queryKey: ['agentDefinitionFields', providerId],+ queryFn: () => (providerId ? rpc.agents.definitionFields({ providerId }) : Promise.resolve([])),+ enabled: !!providerId,+ });++ const fields = useMemo(() => advancedFields(allFields ?? []), [allFields]);++ const [state, setState] = useState<FormState>({});+ // Reset the form (and reported attributes) whenever the provider's field set+ // changes, so switching agent type does not carry stale values. `onChange` is a+ // stable callback from the modal, so including it does not re-run this.+ useEffect(() => {+ const initial = emptyForm(fields);+ setState(initial);+ onChange(attributesFromForm(fields, initial));+ }, [fields, onChange]);++ if (!providerId || fields.length === 0) return null;++ const setField = (key: string, value: FormValue) => {+ setState((prev) => {+ const next = { ...prev, [key]: value };+ onChange(attributesFromForm(fields, next));+ return next;+ });+ };++ return (+ <div className="rounded-md border border-border">+ <button+ type="button"+ className="flex w-full items-center gap-1.5 px-2 py-2 text-sm text-foreground-muted"+ onClick={() => setOpen((v) => !v)}+ >+ <ChevronRight className={cn('h-4 w-4 transition-transform', open && 'rotate-90')} />+ Advanced configuration+ </button>+ {open && (+ <div className="flex flex-col gap-4 border-t border-border px-3 py-3">+ {fields.map((field) => (+ <Field key={field.key}>+ <FieldLabel htmlFor={`agent-advanced-${field.key}`}>+ {field.label}+ {field.required || field.type === 'boolean' ? '' : ' (optional)'}+ </FieldLabel>+ <DefinitionFieldInput+ field={field}+ value={state[field.key] ?? (field.type === 'boolean' ? false : '')}+ onChange={(value) => setField(field.key, value)}+ />+ {field.help && (+ <FieldDescription className="text-foreground-muted">{field.help}</FieldDescription>+ )}+ </Field>+ ))}+ </div>+ )}+ </div>+ );+}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsxindex 861e4fe29..bf4aaf1f4 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsx@@ -11,30 +11,16 @@ import { rpc } from '@renderer/lib/ipc';import { Button } from '@renderer/lib/ui/button';import { Field, FieldGroup, FieldLabel } from '@renderer/lib/ui/field';import { Input } from '@renderer/lib/ui/input';-import { RadioGroup, RadioGroupItem } from '@renderer/lib/ui/radio-group';import { Switch } from '@renderer/lib/ui/switch';-import type { AgentProviderKind } from '@shared/core/switch-servers/switch-servers';import type { ConfigureAgentFormState } from './modes';-const PROVIDER_OPTIONS: { value: AgentProviderKind; label: string; hint: string }[] = [- {- value: 'anthropic',- label: 'Anthropic (claude.ai / Console / API key)',- hint: 'Channels work — the agent is session-addressable and replies in real time.',- },- {- value: 'third-party',- label: 'Third-party provider (Vertex AI / Bedrock / other)',- hint: 'Channels are ignored — the agent is session-passive (no synchronous replies).',- },-];-/**- * Onboarding form for a directory with no Switch agent yet. Collects everything- * the switch-connector `configure` skill asks for — target server, Switch agent- * name, description, provider kind (drives channels / addressability), and an- * optional notify handle — so the agent can be registered and its credentials- * written without leaving the app.+ * Create form for a new Switch agent in a directory. Collects the target server,+ * Switch agent name, and description, then the managed-session options+ * (auto-session, bypass permissions, addressing policy). switchdash always+ * registers the agent as a managed, session-addressable identity — there is no+ * run-mode or notify-handle choice (CHOO-1440); advanced definition attributes+ * live in the collapsed Advanced section.*/export const ConfigureAgentPanel = observer(function ConfigureAgentPanel({form,@@ -47,7 +33,6 @@ export const ConfigureAgentPanel = observer(function ConfigureAgentPanel({}) {const nameId = useId();const descriptionId = useId();- const notifyId = useId();useEffect(() => {if (switchServersStore.servers.length === 0) void switchServersStore.init();@@ -111,15 +96,6 @@ export const ConfigureAgentPanel = observer(function ConfigureAgentPanel({return (<FieldGroup>- <div className="flex items-start gap-2 rounded-md border border-border bg-background-1 px-2 py-1.5 text-xs text-foreground-muted">- <CircleAlert className="mt-0.5 size-3.5 shrink-0 text-amber-500" />- <span>- No Switch agent here yet. Register one below — its credentials are written to this- directory's- <span className="mx-1 font-mono">.claude/settings.local.json</span>.- </span>- </div>-<Field><FieldLabel>Switch server</FieldLabel><div className="rounded-md border border-border bg-background-1 px-3 py-1.5 text-sm">@@ -161,42 +137,6 @@ export const ConfigureAgentPanel = observer(function ConfigureAgentPanel({/></Field>- <Field>- <FieldLabel>How do you run Claude Code?</FieldLabel>- <RadioGroup- value={form.providerKind ?? ''}- onValueChange={(value) => form.setProviderKind(value as AgentProviderKind)}- className="gap-2"- >- {PROVIDER_OPTIONS.map((option) => (- <label- key={option.value}- className="flex cursor-pointer items-start gap-2 rounded-md border border-border px-2 py-1.5"- >- <RadioGroupItem value={option.value} className="mt-0.5" />- <span className="flex flex-col gap-0.5">- <span className="text-sm">{option.label}</span>- <span className="text-xs text-foreground-muted">{option.hint}</span>- </span>- </label>- ))}- </RadioGroup>- </Field>-- <Field>- <FieldLabel htmlFor={notifyId}>Notify handle (optional)</FieldLabel>- <Input- id={notifyId}- placeholder="your Slack / Mattermost handle"- value={form.notifyUser}- onChange={(e) => form.setNotifyUser(e.target.value)}- />- <span className="text-xs text-foreground-muted">- When someone addresses this agent while it's offline, Switch @-mentions this handle- so you get pinged. Leave blank to skip.- </span>- </Field>-<Field><label className="flex cursor-pointer items-start justify-between gap-3 rounded-md border border-border px-2 py-1.5"><span className="flex flex-col gap-0.5">diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/modes.ts b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/modes.tsindex 7c5677685..bdaa04744 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/modes.ts+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/modes.ts@@ -2,10 +2,7 @@ import { useQuery } from '@tanstack/react-query';import { useEffect, useState } from 'react';import { rpc } from '@renderer/lib/ipc';import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';-import type {- AddressingPolicy,- AgentProviderKind,-} from '@shared/core/switch-servers/switch-servers';+import type { AddressingPolicy } from '@shared/core/switch-servers/switch-servers';import { basenameFromAnyPath } from '@shared/path-name';/** Switch agent-name charset, enforced server-side too: lowercase letters,@@ -50,19 +47,18 @@ export function usePickMode() {export type PickModeState = ReturnType<typeof usePickMode>;/**- * Form state for onboarding a brand-new Switch agent (a directory with no- * `.claude/settings.local.json` yet). Collects the fields the `configure` skill- * asks for — Switch agent name, description, provider kind (channels), and an- * optional notify handle — seeding name/description from a server-derived- * default until the user edits them.+ * Form state for creating a brand-new Switch agent in a directory. Collects the+ * Switch agent name and description (advanced definition attributes are gathered+ * separately in the Advanced section), seeding name/description from a+ * server-derived default until the user edits them. switchdash always registers+ * the agent as a managed, session-addressable identity — there is no run-mode or+ * notify-handle choice (CHOO-1440).*/export function useConfigureAgentForm(dir: string, defaultAutoApprove: boolean) {const [agentName, setAgentNameRaw] = useState('');const [agentNameTouched, setAgentNameTouched] = useState(false);const [description, setDescriptionRaw] = useState('');const [descriptionTouched, setDescriptionTouched] = useState(false);- const [providerKind, setProviderKind] = useState<AgentProviderKind | null>(null);- const [notifyUser, setNotifyUser] = useState('');const [autoSession, setAutoSession] = useState(true);const [autoApprove, setAutoApprove] = useState(defaultAutoApprove);// Scoped addressing policy (CHOO-1585). null = open (default); set to restrict@@ -96,7 +92,7 @@ export function useConfigureAgentForm(dir: string, defaultAutoApprove: boolean)};const nameIsValid = AGENT_NAME_PATTERN.test(agentName);- const isValid = nameIsValid && description.trim().length > 0 && providerKind !== null;+ const isValid = nameIsValid && description.trim().length > 0;return {agentName,@@ -104,10 +100,6 @@ export function useConfigureAgentForm(dir: string, defaultAutoApprove: boolean)nameIsValid,description,setDescription,- providerKind,- setProviderKind,- notifyUser,- setNotifyUser,autoSession,setAutoSession,autoApprove,diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/onboard-existing-panel.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/onboard-existing-panel.tsxnew file mode 100644index 000000000..870b75709--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/onboard-existing-panel.tsx@@ -0,0 +1,63 @@+import { Checkbox } from '@renderer/lib/ui/checkbox';++/** A discovered definition the modal can onboard. Structurally a subset of the+ * main-process `DiscoveredLocationAgent`, kept local so the renderer does not+ * import across the process boundary. */+export type OnboardableAgent = {+ name: string;+ description: string | null;+ /** Already a Switch agent on disk (import its identity) vs a plain provider+ * definition to adopt (mint a fresh identity). */+ registered: boolean;+};++/**+ * Multi-select list of provider definitions found in a directory that aren't yet+ * switchdash agents on this client — including ones already registered on the+ * gateway by another client (imported, not re-minted). The user picks which to+ * onboard, or switches to creating a brand-new agent (CHOO-1440).+ */+export function OnboardExistingPanel({+ agents,+ selected,+ onToggle,+}: {+ agents: OnboardableAgent[];+ selected: Set<string>;+ onToggle: (name: string, checked: boolean) => void;+}) {+ return (+ <div className="flex flex-col gap-2 rounded-md border border-border bg-background-1 px-3 py-2.5 text-sm">+ <span className="text-foreground-muted">+ {agents.length} agent{agents.length === 1 ? '' : 's'} defined in this directory{' '}+ {agents.length === 1 ? "isn't" : "aren't"} in switchdash yet — pick which to onboard, or+ create a new one below.+ </span>+ <div className="flex flex-col gap-0.5">+ {agents.map((a) => (+ <label+ key={a.name}+ className="flex cursor-pointer items-start gap-2 rounded px-1.5 py-1 hover:bg-background-2"+ >+ <Checkbox+ checked={selected.has(a.name)}+ onCheckedChange={(checked) => onToggle(a.name, checked === true)}+ className="mt-0.5"+ />+ <div className="flex min-w-0 flex-col">+ <div className="flex items-center gap-2">+ <span className="font-mono text-xs text-foreground">{a.name}</span>+ <span className="rounded bg-background-2 px-1 py-0.5 text-[10px] text-foreground-muted">+ {a.registered ? 'Switch agent · import' : 'adopt as new'}+ </span>+ </div>+ {a.description && (+ <span className="truncate text-xs text-foreground-muted">{a.description}</span>+ )}+ </div>+ </label>+ ))}+ </div>+ </div>+ );+}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/subagent-onboarding-section.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/subagent-onboarding-section.tsxdeleted file mode 100644index 6b4b4c529..000000000--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/subagent-onboarding-section.tsx+++ /dev/null@@ -1,140 +0,0 @@-import { useQuery } from '@tanstack/react-query';-import { CheckCircle2 } from 'lucide-react';-import { useCallback, useEffect, useMemo, useState } from 'react';-import { rpc } from '@renderer/lib/ipc';-import { useAgent } from '@renderer/lib/stores/use-agents';-import { Checkbox } from '@renderer/lib/ui/checkbox';-import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';-import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';--export type SubagentSelection = { name: string; description: string }[];--/** 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 }- | { kind: 'remote'; sshHost: string; remoteRepoDir: string };--/**- * Lists the agent's subagents in the Add Agent modal and lets the user pick- * which not-yet-registered, Switch-eligible ones to onboard alongside the parent.- * Already-registered ones are shown as done; ineligible ones (no Switch tool- * access) are shown disabled. Reports the current selection to the parent via- * `onSelectionChange`. Renders nothing for agent types with no subagents- * capability. Works for both local and remote (SSH) agents.- */-export function SubagentOnboardingSection({- source,- providerId,- onSelectionChange,-}: {- source: SubagentOnboardingSource;- providerId: AgentProviderId | null;- onSelectionChange: (selection: SubagentSelection) => void;-}) {- const { data: agent } = useAgent(providerId ?? '');- const supportsSubagents = !!providerId && agent?.capabilities.subagents.kind !== 'none';-- const sourceReady =- source.kind === 'local'- ? source.dir.length > 0- : source.sshHost.length > 0 && source.remoteRepoDir.length > 0;- const sourceKey =- source.kind === 'local' ? source.dir : `${source.sshHost}:${source.remoteRepoDir}`;-- const defsQuery = useQuery({- queryKey: ['subagentDefs', source.kind, sourceKey, providerId],- queryFn: () =>- source.kind === 'local'- ? rpc.subagents.listDefinitions({ dir: source.dir, providerId: providerId! })- : rpc.subagents.listRemoteDefinitions({- sshHost: source.sshHost,- remoteRepoDir: source.remoteRepoDir,- providerId: providerId!,- }),- enabled: sourceReady && supportsSubagents,- });- const defs = useMemo(() => defsQuery.data ?? [], [defsQuery.data]);- const onboardable = useMemo(() => defs.filter((d) => d.eligible && !d.registered), [defs]);-- const [selected, setSelected] = useState<Set<string>>(new Set());-- // Default to selecting every onboardable subagent. `onboardable` is memoized- // on the query data, so this re-inits only when the discovered set actually- // changes (e.g. the user picks a different directory).- useEffect(() => {- setSelected(new Set(onboardable.map((d) => d.name)));- }, [onboardable]);-- useEffect(() => {- onSelectionChange(- onboardable- .filter((d) => selected.has(d.name))- .map((d) => ({ name: d.name, description: d.description ?? '' }))- );- }, [selected, onboardable, onSelectionChange]);-- const toggle = useCallback((name: string, checked: boolean) => {- setSelected((prev) => {- const next = new Set(prev);- if (checked) next.add(name);- else next.delete(name);- return next;- });- }, []);-- if (defs.length === 0) return null;-- return (- <div className="flex flex-col gap-1.5">- <span className="text-xs font-medium text-foreground-muted">- Subagents ({onboardable.length} to onboard)- </span>- <div className="flex max-h-40 flex-col gap-0.5 overflow-y-auto rounded-md border border-border bg-background-1 p-1">- {defs.map((def) => {- const canSelect = def.eligible && !def.registered;- return (- <div key={def.name} className="flex items-center gap-2 rounded px-1.5 py-1 text-sm">- {def.registered ? (- <Tooltip>- <TooltipTrigger- render={<CheckCircle2 className="size-4 shrink-0 text-green-500" />}- />- <TooltipContent>Already registered on the server</TooltipContent>- </Tooltip>- ) : (- <Checkbox- checked={canSelect && selected.has(def.name)}- disabled={!canSelect}- onCheckedChange={(checked) => toggle(def.name, checked === true)}- aria-label={`Onboard subagent ${def.name}`}- />- )}- <span className="min-w-0 flex-1 truncate" title={def.description ?? undefined}>- {def.name}- </span>- {!def.eligible && (- <Tooltip>- <TooltipTrigger- render={- <span className="shrink-0 rounded bg-background-2 px-1 text-[10px] text-foreground-muted">- no Switch access- </span>- }- />- <TooltipContent>- This subagent's tools don't include the Switch MCP server, so it can't- participate in Switch rooms.- </TooltipContent>- </Tooltip>- )}- {def.registered && (- <span className="shrink-0 text-[10px] text-foreground-muted">registered</span>- )}- </div>- );- })}- </div>- </div>- );-}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/agent-definition-fields.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/agent-definition-fields.tsxnew file mode 100644index 000000000..f25ee6c87--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/agent-definition-fields.tsx@@ -0,0 +1,141 @@+import type {+ RepoAgentAttributes,+ RepoAgentAttributeValue,+ RepoAgentField,+} from '@switchdash/core/agents/plugins';+import { Input } from '@renderer/lib/ui/input';+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@renderer/lib/ui/select';+import { Switch } from '@renderer/lib/ui/switch';+import { Textarea } from '@renderer/lib/ui/textarea';++/** Sentinel for a select's "unset" choice (an empty string is not a valid item). */+const UNSET = '__unset__';++/** A field's value as held in the form: strings for everything except booleans. */+export type FormValue = string | boolean;+export type FormState = Record<string, FormValue>;++/** name/description are collected as top-level fields, not advanced ones. */+export const TOP_LEVEL_KEYS = new Set(['name', 'description']);++/** The advanced (non top-level) attribute fields, in provider display order. */+export function advancedFields(allFields: RepoAgentField[]): RepoAgentField[] {+ return allFields.filter((f) => !TOP_LEVEL_KEYS.has(f.key));+}++export function emptyForm(fields: RepoAgentField[]): FormState {+ const state: FormState = {};+ for (const field of fields) state[field.key] = field.type === 'boolean' ? false : '';+ return state;+}++/** Seed a form from existing attribute values (for editing an existing agent). */+export function formFromAttributes(+ fields: RepoAgentField[],+ attributes: RepoAgentAttributes+): FormState {+ const state: FormState = {};+ for (const field of fields) {+ const value: RepoAgentAttributeValue | undefined = attributes[field.key];+ if (field.type === 'boolean') {+ state[field.key] = value === true;+ } else if (field.type === 'list') {+ state[field.key] = Array.isArray(value) ? value.join(', ') : '';+ } else if (value === null || value === undefined) {+ state[field.key] = '';+ } else {+ state[field.key] = String(value);+ }+ }+ return state;+}++export function attributesFromForm(+ fields: RepoAgentField[],+ state: FormState+): RepoAgentAttributes {+ const attributes: RepoAgentAttributes = {};+ for (const field of fields) {+ const value = state[field.key];+ if (field.type === 'boolean') {+ attributes[field.key] = value === true;+ } else if (field.type === 'list') {+ attributes[field.key] = String(value)+ .split(',')+ .map((t) => t.trim())+ .filter((t) => t.length > 0);+ } else if (field.type === 'number') {+ const trimmed = String(value).trim();+ attributes[field.key] = trimmed.length > 0 ? Number(trimmed) : null;+ } else {+ attributes[field.key] = String(value).trim();+ }+ }+ return attributes;+}++/** One provider-declared definition attribute, rendered by its field type. */+export function DefinitionFieldInput({+ field,+ value,+ onChange,+}: {+ field: RepoAgentField;+ value: FormValue;+ onChange: (value: FormValue) => void;+}) {+ const id = `agent-definition-${field.key}`;+ if (field.type === 'boolean') {+ return <Switch id={id} checked={value === true} onCheckedChange={onChange} />;+ }+ if (field.type === 'textarea') {+ return (+ <Textarea+ id={id}+ value={String(value)}+ rows={5}+ placeholder={field.placeholder}+ onChange={(e) => onChange(e.target.value)}+ />+ );+ }+ if (field.type === 'select') {+ const current = String(value);+ const selected = current.length > 0 ? current : UNSET;+ const options = field.options ?? [];+ const selectedLabel =+ options.find((o) => (o.value.length > 0 ? o.value : UNSET) === selected)?.label ?? '';+ return (+ <Select+ value={selected}+ onValueChange={(next) => onChange(next === UNSET ? '' : (next ?? ''))}+ >+ <SelectTrigger id={id}>+ <SelectValue>{selectedLabel}</SelectValue>+ </SelectTrigger>+ <SelectContent>+ {options.map((option) => (+ <SelectItem key={option.value} value={option.value.length > 0 ? option.value : UNSET}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ );+ }+ return (+ <Input+ id={id}+ type={field.type === 'number' ? 'number' : 'text'}+ value={String(value)}+ placeholder={field.placeholder}+ onChange={(e) => onChange(e.target.value)}+ />+ );+}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/delete-agent-modal.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/delete-agent-modal.tsxindex d8fed7a22..f3ae8cade 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/delete-agent-modal.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/delete-agent-modal.tsx@@ -1,7 +1,4 @@-import { useQuery } from '@tanstack/react-query';-import { TriangleAlert } from 'lucide-react';import { useState } from 'react';-import { rpc } from '@renderer/lib/ipc';import type { BaseModalProps } from '@renderer/lib/modal/modal-provider';import { Button } from '@renderer/lib/ui/button';import { Checkbox } from '@renderer/lib/ui/checkbox';@@ -25,20 +22,9 @@ export type DeleteAgentModalResult = { deleteInSwitch: boolean };type Props = BaseModalProps<DeleteAgentModalResult> & DeleteAgentModalArgs;-export function DeleteAgentModal({ agentId, agentLabel, onSuccess, onClose }: Props) {+export function DeleteAgentModal({ agentLabel, onSuccess, onClose }: Props) {const [deleteInSwitch, setDeleteInSwitch] = useState(false);- // The subagents that a Switch delete would cascade to. Best-effort: if the- // listing can't load (offline, no server) we simply show no subagent warning.- const { data } = useQuery({- queryKey: ['subagents', agentId],- queryFn: () => rpc.subagents.list(agentId),- });- const subagentNames = data- ? [...data.subagents.map((s) => s.name), ...data.remoteOnly.map((r) => r.name)]- : [];- const subagentCount = subagentNames.length;-return (<><DialogHeader showCloseButton={false}>@@ -60,23 +46,11 @@ export function DeleteAgentModal({ agentId, agentLabel, onSuccess, onClose }: Pr<span className="flex flex-col gap-0.5"><span className="text-sm font-medium">Also delete this agent in Switch</span><span className="text-xs text-foreground-muted">- Permanently deletes its identity on the Switch server. This can’t be undone.+ Permanently deletes its identity on the Switch server. This can’t be undone. Only this+ agent is affected — others in the same directory are left alone.</span></span></label>-- {deleteInSwitch && subagentCount > 0 && (- <div className="border-destructive/30 bg-destructive/10 flex items-start gap-2.5 rounded-md border p-3 text-sm">- <TriangleAlert className="mt-0.5 size-4 shrink-0 text-foreground-destructive" />- <div className="flex flex-col gap-1">- <span className="font-medium text-foreground">- {subagentCount} subagent{subagentCount === 1 ? '' : 's'} will also be deleted in- Switch- </span>- <span className="text-foreground-muted">{subagentNames.join(', ')}</span>- </div>- </div>- )}</DialogContentArea><DialogFooter><Button variant="outline" onClick={onClose}>diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/location-view-wrapper.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/location-view-wrapper.tsxindex efd0fb36e..b9437aa29 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/location-view-wrapper.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/location-view-wrapper.tsx@@ -5,7 +5,7 @@ interface LocationViewWrapperProps {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;+ agentName?: string;}export function LocationViewWrapper({ children }: LocationViewWrapperProps) {diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/main-panel/active-location.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/main-panel/active-location.tsxindex 0f0ddddaa..7ce8cccbd 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/main-panel/active-location.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/main-panel/active-location.tsx@@ -1,16 +1,12 @@-import { useQuery } from '@tanstack/react-query';import { observer } from 'mobx-react-lite';import { SessionList } from '@renderer/features/locations/components/session-view/session-list';import { SettingsPanel } from '@renderer/features/locations/components/settings-view/settings-panel';-import { 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 LocationViewNav({@@ -51,34 +47,19 @@ function LocationViewNav({export const ActiveLocation = observer(function ActiveLocation() {const {- params: { locationId, subagentName },+ params: { locationId },} = useParams('location');const store = asMounted(getLocationStore(locationId));- const { data: agents } = useQuery({- queryKey: ['location-agents', locationId],- queryFn: () => rpc.agents.getAgents(locationId),- });- const agent = agents?.[0] ?? null;- const { data: providerMeta } = useAgent(agent?.providerId ?? '');- // Only a parent agent can have subagents — a subagent can't have its own, so- // hide the tab when the view is scoped to a subagent.- const supportsSubagents =- !subagentName && !!agent && providerMeta?.capabilities.subagents.kind !== 'none';-if (!store) return null;const items: Array<{ id: LocationView; label: string }> = [{ id: 'sessions', label: 'Sessions' },- ...(supportsSubagents ? ([{ id: 'subagents', label: 'Subagents' }] as const) : []),{ id: 'settings', label: 'Settings' },];- // Don't strand the user on a tab the current agent doesn't offer.- const activeView =- store.view.activeView === 'subagents' && !supportsSubagents- ? 'sessions'- : store.view.activeView;+ // 'subagents' is a retired view; fall back to Sessions if a stale view sticks.+ const activeView = store.view.activeView === 'settings' ? 'settings' : 'sessions';return (<div className="flex h-full min-h-0 w-full flex-1 flex-col overflow-hidden">@@ -92,7 +73,6 @@ export const ActiveLocation = observer(function ActiveLocation() {<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">{activeView === 'sessions' && <SessionList />}- {activeView === 'subagents' && <SubagentsPanel />}{activeView === 'settings' && <SettingsPanel />}</div></div>diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/session-view/session-list-empty-state.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/session-view/session-list-empty-state.tsxindex 0cdbd9a11..6dbe25a21 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/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@@ -6,21 +6,21 @@ import { ActionListItem } from '@renderer/lib/ui/action-list-item';export const SessionListEmptyState = observer(function SessionListEmptyState({locationId,- subagentName,+ agentName,}: {locationId: string;- subagentName?: string;+ agentName?: string;}) {const showSessionModal = useShowModal('sessionModal');const actions = [{label: 'New Session',- description: subagentName- ? `Spawn a claude session as ${subagentName}`+ description: agentName+ ? `Spawn a claude session as ${agentName}`: 'Spawn a claude session for this agent',icon: Plus,- onActivate: () => showSessionModal({ locationId, subagentName }),+ onActivate: () => showSessionModal({ locationId, agentName }),},];diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/session-view/session-list.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/session-view/session-list.tsxindex 62349931a..8e1d2f6c2 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/session-view/session-list.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/session-view/session-list.tsx@@ -134,7 +134,7 @@ function SelectionBar({export const SessionList = observer(function SessionList() {const {- params: { locationId, subagentName },+ params: { locationId, agentName },} = useParams('location');const store = asMounted(getLocationStore(locationId));const sessionManager = getSessionManagerStore(locationId);@@ -149,7 +149,7 @@ export const SessionList = observer(function SessionList() {.filter((t): t is ReadySession => t.state !== 'unregistered')// Scope to the active subagent: its own page lists only sessions// launched as it; the parent agent's page excludes subagent sessions.- .filter((t) => (subagentName ? t.data.subagentName === subagentName : !t.data.subagentName))+ .filter((t) => (agentName ? t.data.agentName === agentName : !t.data.agentName)): [];const activeSessions = allSessions.filter((t) => !t.data.archivedAt);const archivedSessions = allSessions.filter((t) => Boolean(t.data.archivedAt));@@ -237,7 +237,7 @@ export const SessionList = observer(function SessionList() {onChange={(e) => sessionView.setSearchQuery(e.target.value)}className="flex-1"/>- <Button onClick={() => showCreateSessionModal({ locationId, subagentName })}>+ <Button onClick={() => showCreateSessionModal({ locationId, agentName })}>Create Session <BoundShortcut settingsKey="newSession" /></Button></div>@@ -245,7 +245,7 @@ export const SessionList = observer(function SessionList() {</div>{filteredSessions.length === 0 && sessionView.tab === 'active' ? (- <SessionListEmptyState locationId={locationId} subagentName={subagentName} />+ <SessionListEmptyState locationId={locationId} agentName={agentName} />) : (<SessionVirtualListsessions={filteredSessions}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section.tsxindex 76e5e7569..6898cef0a 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section.tsx@@ -16,13 +16,22 @@ import type { AddressingPolicy } from '@shared/core/switch-servers/switch-server* agent (@mention, targeted message, task delegation). One editor per* Switch-linked agent in the location; hidden when the location has none.*/-export function AddressingPolicySettingsSection({ locationId }: { locationId: string }) {+export function AddressingPolicySettingsSection({+ locationId,+ agentId,+}: {+ locationId: string;+ /** Scope to a single agent; omit to show every Switch-linked agent. */+ agentId?: string;+}) {const { data: agents } = useQuery({queryKey: ['location-agents', locationId],queryFn: () => rpc.agents.getAgents(locationId),});- const switchAgents = (agents ?? []).filter((a) => a.serverId && a.switchAgentId);+ const switchAgents = (agents ?? []).filter(+ (a) => a.serverId && a.switchAgentId && (!agentId || a.id === agentId)+ );if (switchAgents.length === 0) return null;return (diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/agent-definition-settings-section.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/agent-definition-settings-section.tsxnew file mode 100644index 000000000..151ee8154--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/agent-definition-settings-section.tsx@@ -0,0 +1,132 @@+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';+import { useEffect, useMemo, useState } from 'react';+import {+ advancedFields,+ attributesFromForm,+ DefinitionFieldInput,+ emptyForm,+ formFromAttributes,+ type FormState,+ type FormValue,+} from '@renderer/features/locations/components/agent-definition-fields';+import { toast } from '@renderer/lib/hooks/use-toast';+import { rpc } from '@renderer/lib/ipc';+import { Button } from '@renderer/lib/ui/button';+import { Field, FieldDescription, FieldLabel, FieldTitle } from '@renderer/lib/ui/field';+import { log } from '@renderer/utils/logger';++/**+ * Per-agent "Advanced configuration" editor in the Settings tab: the provider's+ * definition attributes (model, effort, tools, system prompt, …) for an existing+ * agent, prefilled from its on-disk definition and saved back by rewriting it+ * (`.claude/agents/<name>.md`). The name is immutable — it is the agent's+ * identity — so only advanced attributes are editable here (CHOO-1440).+ */+export function AgentDefinitionSettingsSection({+ locationId,+ agentId,+}: {+ locationId: string;+ agentId: string | undefined;+}) {+ const { data: agents } = useQuery({+ queryKey: ['location-agents', locationId],+ queryFn: () => rpc.agents.getAgents(locationId),+ });+ const agent = (agents ?? []).find((a) => a.id === agentId);+ const providerId = agent?.providerId ?? null;+ const editable = !!agent && agent.definitionName != null;++ const { data: allFields } = useQuery({+ queryKey: ['agentDefinitionFields', providerId],+ queryFn: () => (providerId ? rpc.agents.definitionFields({ providerId }) : Promise.resolve([])),+ enabled: !!providerId,+ });+ const fields = useMemo(() => advancedFields(allFields ?? []), [allFields]);++ const { data: current } = useQuery({+ queryKey: ['agent-definition', agentId],+ queryFn: () => (agentId ? rpc.agents.readAgentDefinition({ agentId }) : Promise.resolve(null)),+ enabled: !!agentId && editable,+ });++ const savedForm = useMemo(+ () => (current ? formFromAttributes(fields, current) : emptyForm(fields)),+ [fields, current]+ );++ const [form, setForm] = useState<FormState>({});+ // Seed (and re-seed after save/agent change) from the persisted values. During+ // editing no refetch fires, so local edits are preserved until Save.+ useEffect(() => {+ setForm(savedForm);+ }, [savedForm]);++ const queryClient = useQueryClient();+ const mutation = useMutation({+ mutationFn: () =>+ rpc.agents.updateAgentDefinition({+ agentId: agentId as string,+ attributes: attributesFromForm(fields, form),+ }),+ onSuccess: () => {+ toast({ title: 'Advanced configuration saved' });+ void queryClient.invalidateQueries({ queryKey: ['agent-definition', agentId] });+ },+ onError: (error) => {+ log.error('Failed to save agent definition', { agentId, error });+ toast({+ title: 'Failed to save configuration',+ description: String(error),+ variant: 'destructive',+ });+ },+ });++ if (!editable || fields.length === 0) return null;++ const dirty =+ JSON.stringify(attributesFromForm(fields, form)) !==+ JSON.stringify(attributesFromForm(fields, savedForm));++ const setField = (key: string, value: FormValue) =>+ setForm((prev) => ({ ...prev, [key]: value }));++ return (+ <Field>+ <FieldTitle>Advanced configuration</FieldTitle>+ <FieldDescription className="text-foreground-muted">+ The agent's model, reasoning effort, tools, and system prompt. Saving rewrites its+ on-disk definition; the agent name is fixed.+ </FieldDescription>+ <div className="flex flex-col gap-4 rounded-md border border-border px-3 py-3">+ {fields.map((field) => (+ <Field key={field.key}>+ <FieldLabel htmlFor={`agent-definition-${field.key}`}>+ {field.label}+ {field.required || field.type === 'boolean' ? '' : ' (optional)'}+ </FieldLabel>+ <DefinitionFieldInput+ field={field}+ value={form[field.key] ?? (field.type === 'boolean' ? false : '')}+ onChange={(value) => setField(field.key, value)}+ />+ {field.help && (+ <FieldDescription className="text-foreground-muted">{field.help}</FieldDescription>+ )}+ </Field>+ ))}+ <div className="flex justify-end">+ <Button+ type="button"+ size="sm"+ disabled={!dirty || mutation.isPending}+ onClick={() => mutation.mutate()}+ >+ {mutation.isPending ? 'Saving...' : 'Save'}+ </Button>+ </div>+ </div>+ </Field>+ );+}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/auto-approve-settings-section.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/auto-approve-settings-section.tsxindex f12a10c0a..48cb85c72 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/auto-approve-settings-section.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/auto-approve-settings-section.tsx@@ -14,13 +14,20 @@ import { log } from '@renderer/utils/logger';* also pushes the change to a remote agent's on-VM watcher so it takes effect* live (CHOO-1664).*/-export function AutoApproveSettingsSection({ locationId }: { locationId: string }) {+export function AutoApproveSettingsSection({+ locationId,+ agentId,+}: {+ locationId: string;+ /** Scope to a single agent (e.g. a subagent's own row); omit for every agent. */+ agentId?: string;+}) {const { data: agents } = useQuery({queryKey: ['location-agents', locationId],queryFn: () => rpc.agents.getAgents(locationId),});- const list = agents ?? [];+ const list = (agents ?? []).filter((a) => !agentId || a.id === agentId);if (list.length === 0) return null;// Single-agent locations don't need the (directory-derived) agent name label —// the section title identifies the setting, so the toggle sits inline with it.diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/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.tsxindex a4450d1e4..fdc21b0c8 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/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@@ -13,13 +13,22 @@ import { log } from '@renderer/utils/logger';* no local config to stage. Renders one row per Switch-linked agent in the* location; hidden entirely when the location has none.*/-export function AutoSessionSettingsSection({ locationId }: { locationId: string }) {+export function AutoSessionSettingsSection({+ locationId,+ agentId,+}: {+ locationId: string;+ /** Scope to a single agent (e.g. a subagent's own row); omit for every agent. */+ agentId?: string;+}) {const { data: agents } = useQuery({queryKey: ['location-agents', locationId],queryFn: () => rpc.agents.getAgents(locationId),});- const switchAgents = (agents ?? []).filter((a) => a.serverId && a.switchAgentId);+ const switchAgents = (agents ?? [])+ .filter((a) => a.serverId && a.switchAgentId)+ .filter((a) => !agentId || a.id === agentId);if (switchAgents.length === 0) return null;// The agent name only disambiguates when a location has more than one agent;// for the common single-agent case the section title already identifies it, sodiff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/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.tsxdeleted file mode 100644index b6c59096f..000000000--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/subagent-auto-session-settings-section.tsx+++ /dev/null@@ -1,97 +0,0 @@-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';-import { useState } from 'react';-import { rpc } from '@renderer/lib/ipc';-import { Field, FieldDescription, FieldTitle } from '@renderer/lib/ui/field';-import { Spinner } from '@renderer/lib/ui/spinner';-import { Switch } from '@renderer/lib/ui/switch';-import { log } from '@renderer/utils/logger';--/**- * Per-subagent "auto-create session on notify" toggle. Mirrors- * {@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- * location's agent is not linked to a Switch server.- */-export function SubagentAutoSessionSettingsSection({- locationId,- subagentName,-}: {- locationId: string;- subagentName: string;-}) {- const { data: agents, isLoading: agentsLoading } = useQuery({- queryKey: ['location-agents', locationId],- queryFn: () => rpc.agents.getAgents(locationId),- });-- const parent = (agents ?? []).find((a) => a.serverId && a.switchAgentId);-- if (agentsLoading) {- return (- <div className="flex items-center justify-center py-10">- <Spinner />- </div>- );- }- if (!parent) return null;-- return (- <Field>- <FieldTitle>Auto-create a session on notify</FieldTitle>- <FieldDescription className="text-foreground-muted">- When on, switchdash watches this subagent's Switch rooms and automatically starts a- session — launched as {subagentName}, connected to the room and ready to reply — whenever- it's addressed with no session running.- </FieldDescription>- <SubagentAutoSessionRow parentAgentId={parent.id} name={subagentName} label={subagentName} />- </Field>- );-}--function SubagentAutoSessionRow({- parentAgentId,- name,- label,-}: {- parentAgentId: string;- name: string;- label: string;-}) {- const queryClient = useQueryClient();- const [pending, setPending] = useState(false);- const queryKey = ['subagent-auto-session', parentAgentId, name];-- const { data: enabled, isLoading } = useQuery({- queryKey,- queryFn: () => rpc.subagents.getAutoSession({ parentAgentId, name }),- });-- const mutation = useMutation({- mutationFn: (next: boolean) =>- rpc.subagents.setAutoSession({ parentAgentId, name, enabled: next }),- onMutate: (next) => {- setPending(true);- queryClient.setQueryData(queryKey, next);- },- onError: (error, next) => {- queryClient.setQueryData(queryKey, !next);- log.error('Failed to update auto_session for subagent', { parentAgentId, name, error });- },- onSettled: () => {- setPending(false);- void queryClient.invalidateQueries({ queryKey });- },- });-- return (- <div className="flex items-center justify-between gap-3 rounded-md border border-border px-2 py-1.5">- <span className="truncate text-sm">{label}</span>- <Switch- checked={enabled === true}- disabled={isLoading || pending}- onCheckedChange={(checked) => mutation.mutate(checked)}- />- </div>- );-}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/settings-panel.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/settings-panel.tsxindex a37f3ab9a..d4b055695 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/settings-panel.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/settings-panel.tsx@@ -1,21 +1,31 @@+import { useQuery } from '@tanstack/react-query';import { observer } from 'mobx-react-lite';import { AddressingPolicySettingsSection } from '@renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section';+import { AgentDefinitionSettingsSection } from '@renderer/features/locations/components/settings-view/sections/agent-definition-settings-section';import { AutoApproveSettingsSection } from '@renderer/features/locations/components/settings-view/sections/auto-approve-settings-section';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 { rpc } from '@renderer/lib/ipc';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 },+ params: { locationId, agentName },} = useParams('location');const mounted = asMounted(getLocationStore(locationId));+ // Resolve the specific agent the page is scoped to (by its definition name),+ // so its settings render through the normal per-agent sections. switchdash has+ // no main/subagent split — every agent gets the same settings (CHOO-1440).+ const { data: agents } = useQuery({+ queryKey: ['location-agents', locationId],+ queryFn: () => rpc.agents.getAgents(locationId),+ });+if (!mounted) {return (<div className="flex items-center justify-center py-10">@@ -24,17 +34,17 @@ export const SettingsPanel = observer(function SettingsPanel() {);}+ const agent = agentName+ ? (agents ?? []).find((a) => a.definitionName === agentName)+ : (agents ?? [])[0];+ const agentId = agent?.id;+return (<div className="flex flex-col gap-6">- {subagentName ? (- <SubagentAutoSessionSettingsSection locationId={locationId} subagentName={subagentName} />- ) : (- <>- <AutoSessionSettingsSection locationId={locationId} />- <AutoApproveSettingsSection locationId={locationId} />- <AddressingPolicySettingsSection locationId={locationId} />- </>- )}+ <AutoSessionSettingsSection locationId={locationId} agentId={agentId} />+ <AutoApproveSettingsSection locationId={locationId} agentId={agentId} />+ <AddressingPolicySettingsSection locationId={locationId} agentId={agentId} />+ <AgentDefinitionSettingsSection locationId={locationId} agentId={agentId} /></div>);});diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/subagents-view/subagents-panel.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/subagents-view/subagents-panel.tsxdeleted file mode 100644index 636717e5c..000000000--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/subagents-view/subagents-panel.tsx+++ /dev/null@@ -1,534 +0,0 @@-import type { SubagentAttributes, SubagentField } from '@switchdash/core/agents/plugins';-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,- 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';-import { Button } from '@renderer/lib/ui/button';-import { Field, FieldDescription, FieldLabel, FieldTitle } from '@renderer/lib/ui/field';-import { Input } from '@renderer/lib/ui/input';-import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,-} from '@renderer/lib/ui/select';-import { Spinner } from '@renderer/lib/ui/spinner';-import { Switch } from '@renderer/lib/ui/switch';-import { Textarea } from '@renderer/lib/ui/textarea';-import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';-import { log } from '@renderer/utils/logger';-import type { Subagent } from '@shared/core/subagents/subagents';--/** Subagent name rule: tokenises as a single `@`-mention and is a valid file stem. */-const NAME_PATTERN = /^[a-z0-9][a-z0-9._-]*$/;--/** Sentinel for a select's "unset" choice, since an empty string isn't a valid- * Select item value. */-const UNSET = '__unset__';--function validateName(name: string, existing: string[]): string | null {- if (name.length === 0) return 'Enter a name.';- if (!NAME_PATTERN.test(name)) {- return 'Use lowercase letters, digits, and . _ - (must start with a letter or digit).';- }- if (existing.includes(name)) return `A subagent named "${name}" already exists.`;- return null;-}--/** A field's value as held in the form: strings for everything except booleans. */-type FormValue = string | boolean;-type FormState = Record<string, FormValue>;--function emptyForm(fields: SubagentField[]): FormState {- const state: FormState = {};- for (const field of fields) state[field.key] = field.type === 'boolean' ? false : '';- return state;-}--function formFromAttributes(fields: SubagentField[], attributes: SubagentAttributes): FormState {- const state: FormState = {};- for (const field of fields) {- const value = attributes[field.key];- if (field.type === 'boolean') {- state[field.key] = value === true;- } else if (field.type === 'list') {- state[field.key] = Array.isArray(value) ? value.join(', ') : '';- } else {- state[field.key] = value === null || value === undefined ? '' : String(value);- }- }- return state;-}--function attributesFromForm(fields: SubagentField[], state: FormState): SubagentAttributes {- const attributes: SubagentAttributes = {};- for (const field of fields) {- const value = state[field.key];- if (field.type === 'boolean') {- attributes[field.key] = value === true;- } else if (field.type === 'list') {- attributes[field.key] = String(value)- .split(',')- .map((t) => t.trim())- .filter((t) => t.length > 0);- } else if (field.type === 'number') {- const trimmed = String(value).trim();- attributes[field.key] = trimmed.length > 0 ? Number(trimmed) : null;- } else {- attributes[field.key] = String(value).trim();- }- }- return attributes;-}--/**- * The "Subagents" tab for an agent that supports them: lists the agent's- * subagents and lets you create, edit, and delete them directly. Gated upstream- * by the provider's subagents capability, and by the parent being linked to a- * Switch server (creating/deleting touches the gateway).- */-export const SubagentsPanel = observer(function SubagentsPanel() {- const {- params: { locationId },- } = useParams('location');- const mounted = asMounted(getLocationStore(locationId));-- const { data: agents, isLoading: agentsLoading } = useQuery({- queryKey: ['location-agents', locationId],- queryFn: () => rpc.agents.getAgents(locationId),- });-- const parent = (agents ?? []).find((a) => a.serverId && a.switchAgentId) ?? null;-- const subagentsQuery = useQuery({- queryKey: ['subagents', parent?.id],- queryFn: () => rpc.subagents.list(parent!.id),- enabled: !!parent,- });-- if (!mounted || agentsLoading) {- return (- <div className="flex items-center justify-center py-10">- <Spinner />- </div>- );- }-- if (!parent) {- return (- <Field>- <FieldTitle>Subagents</FieldTitle>- <FieldDescription className="text-foreground-muted">- Link this agent to a Switch server first — subagents are registered as child agents on the- gateway, so the parent needs a Switch identity before you can create them.- </FieldDescription>- </Field>- );- }-- const subagents = subagentsQuery.data?.subagents ?? [];-- return (- <SubagentsList- providerId={parent.providerId}- parentAgentId={parent.id}- subagents={subagents}- loading={subagentsQuery.isLoading}- />- );-});--type FormMode = { kind: 'list' } | { kind: 'create' } | { kind: 'edit'; subagent: Subagent };--function SubagentsList({- providerId,- parentAgentId,- subagents,- loading,-}: {- providerId: string;- parentAgentId: string;- subagents: Subagent[];- loading: boolean;-}) {- const [mode, setMode] = useState<FormMode>({ kind: 'list' });-- if (mode.kind === 'create' || mode.kind === 'edit') {- return (- <SubagentForm- providerId={providerId}- parentAgentId={parentAgentId}- existingNames={subagents.map((s) => s.name)}- editingName={mode.kind === 'edit' ? mode.subagent.name : null}- onDone={() => setMode({ kind: 'list' })}- />- );- }-- return (- <Field>- <div className="flex items-start justify-between gap-3">- <div className="flex flex-col gap-1">- <FieldTitle>Subagents</FieldTitle>- <FieldDescription className="text-foreground-muted">- Child agents this agent can launch, each with its own Switch identity. Create one to- register it on the gateway and make it immediately launchable.- </FieldDescription>- </div>- <Button size="sm" onClick={() => setMode({ kind: 'create' })}>- <Plus />- Create subagent- </Button>- </div>-- {loading ? (- <div className="flex items-center justify-center py-10">- <Spinner />- </div>- ) : subagents.length === 0 ? (- <p className="rounded-md border border-dashed border-border px-3 py-6 text-center text-sm text-foreground-muted">- No subagents yet.- </p>- ) : (- <div className="flex flex-col gap-2">- {subagents.map((subagent) => (- <SubagentRow- key={subagent.name}- parentAgentId={parentAgentId}- subagent={subagent}- onEdit={() => setMode({ kind: 'edit', subagent })}- />- ))}- </div>- )}- </Field>- );-}--function SubagentRow({- parentAgentId,- subagent,- onEdit,-}: {- parentAgentId: string;- subagent: Subagent;- onEdit: () => void;-}) {- const queryClient = useQueryClient();- const { toast } = useToast();- const [confirmingDelete, setConfirmingDelete] = useState(false);-- const deleteMutation = useMutation({- mutationFn: () =>- rpc.subagents.delete({- parentAgentId,- name: subagent.name,- switchAgentId: subagent.switchAgentId,- }),- onSuccess: () => {- toast({ title: `Deleted subagent ${subagent.name}` });- // Prefix match: refresh every subagent list (this panel and the sidebar,- // which key their queries on different agent ids).- void queryClient.invalidateQueries({ queryKey: ['subagents'] });- },- onError: (error) => {- log.error('Failed to delete subagent', { name: subagent.name, error });- toast({- title: 'Failed to delete subagent',- description: error instanceof Error ? error.message : String(error),- variant: 'destructive',- });- setConfirmingDelete(false);- },- });-- return (- <div className="flex items-center justify-between gap-3 rounded-md border border-border px-3 py-2">- <div className="flex min-w-0 flex-1 flex-col gap-0.5">- <div className="flex items-center gap-2">- <span className="truncate text-sm font-medium">{subagent.name}</span>- {subagent.model && (- <span className="shrink-0 rounded bg-background-2 px-1 text-[10px] text-foreground-muted">- {subagent.model}- </span>- )}- {subagent.registered === false && (- <Tooltip>- <TooltipTrigger- render={- <span className="shrink-0 rounded bg-amber-500/15 px-1 text-[10px] text-amber-600 dark:text-amber-400">- local- </span>- }- />- <TooltipContent>- Discovered locally but not registered on the Switch server.- </TooltipContent>- </Tooltip>- )}- </div>- {subagent.description && (- <span className="truncate text-xs text-foreground-muted">{subagent.description}</span>- )}- </div>- <div className="flex shrink-0 items-center gap-1.5">- {confirmingDelete ? (- <>- <Button- size="xs"- variant="destructive"- disabled={deleteMutation.isPending}- onClick={() => deleteMutation.mutate()}- >- {deleteMutation.isPending ? 'Deleting…' : 'Confirm delete'}- </Button>- <Button- size="xs"- variant="ghost"- disabled={deleteMutation.isPending}- onClick={() => setConfirmingDelete(false)}- >- Cancel- </Button>- </>- ) : (- <>- <Button size="xs" variant="outline" onClick={onEdit}>- Edit- </Button>- <Button size="xs" variant="ghost" onClick={() => setConfirmingDelete(true)}>- Delete- </Button>- </>- )}- </div>- </div>- );-}--function SubagentForm({- providerId,- parentAgentId,- existingNames,- editingName,- onDone,-}: {- providerId: string;- parentAgentId: string;- existingNames: string[];- editingName: string | null;- onDone: () => void;-}) {- const queryClient = useQueryClient();- const { toast } = useToast();-- const fieldsQuery = useQuery({- queryKey: ['subagent-fields', providerId],- queryFn: () => rpc.subagents.attributeFields(providerId),- });-- const prefillQuery = useQuery({- queryKey: ['subagent-definition', parentAgentId, editingName],- queryFn: () => rpc.subagents.readDefinition({ parentAgentId, name: editingName! }),- enabled: !!editingName,- });-- const fields = useMemo(() => fieldsQuery.data ?? [], [fieldsQuery.data]);- const loading = fieldsQuery.isLoading || (!!editingName && prefillQuery.isLoading);-- if (loading) {- return (- <div className="flex items-center justify-center py-10">- <Spinner />- </div>- );- }-- return (- <SubagentFormFields- fields={fields}- initial={- editingName && prefillQuery.data- ? formFromAttributes(fields, prefillQuery.data)- : emptyForm(fields)- }- editingName={editingName}- existingNames={existingNames}- submit={async (attributes) => {- if (editingName) {- await rpc.subagents.edit({ parentAgentId, attributes });- } else {- await rpc.subagents.create({ parentAgentId, attributes });- }- }}- onSaved={(name) => {- toast({ title: editingName ? `Updated ${name}` : `Created subagent ${name}` });- // Prefix match: refresh every subagent list (this panel and the sidebar,- // which key their queries on different agent ids).- void queryClient.invalidateQueries({ queryKey: ['subagents'] });- onDone();- }}- onError={(error) => {- log.error('Failed to save subagent', { editingName, error });- toast({- title: editingName ? 'Failed to update subagent' : 'Failed to create subagent',- description: error instanceof Error ? error.message : String(error),- variant: 'destructive',- });- }}- onCancel={onDone}- />- );-}--function SubagentFormFields({- fields,- initial,- editingName,- existingNames,- submit,- onSaved,- onError,- onCancel,-}: {- fields: SubagentField[];- initial: FormState;- editingName: string | null;- existingNames: string[];- submit: (attributes: SubagentAttributes) => Promise<void>;- onSaved: (name: string) => void;- onError: (error: unknown) => void;- onCancel: () => void;-}) {- const [state, setState] = useState<FormState>(initial);- const setField = (key: string, value: FormValue) =>- setState((prev) => ({ ...prev, [key]: value }));-- const name = String(state.name ?? '').trim();- const description = String(state.description ?? '').trim();- // The name is immutable on edit, so don't re-validate it against siblings.- const nameError = editingName ? null : validateName(name, existingNames);- const canSubmit = description.length > 0 && (editingName ? true : !nameError);-- const mutation = useMutation({- mutationFn: () => submit(attributesFromForm(fields, state)),- onSuccess: () => onSaved(name),- onError,- });-- return (- <div className="flex flex-col gap-5">- <FieldTitle>{editingName ? `Edit ${editingName}` : 'Create subagent'}</FieldTitle>-- {fields.map((field) => {- const disabled = mutation.isPending || (!!editingName && field.immutableOnEdit === true);- const showNameError = field.key === 'name' && !editingName && name.length > 0 && nameError;-- return (- <Field key={field.key}>- <FieldLabel htmlFor={`subagent-${field.key}`}>- {field.label}- {field.required ? '' : field.type === 'boolean' ? '' : ' (optional)'}- </FieldLabel>- <SubagentFieldInput- field={field}- value={state[field.key]}- disabled={disabled}- onChange={(value) => setField(field.key, value)}- />- {showNameError ? (- <FieldDescription className="text-destructive">{nameError}</FieldDescription>- ) : (- field.help && (- <FieldDescription className="text-foreground-muted">{field.help}</FieldDescription>- )- )}- </Field>- );- })}-- <div className="flex items-center justify-end gap-2">- <Button variant="ghost" disabled={mutation.isPending} onClick={onCancel}>- Cancel- </Button>- <Button disabled={!canSubmit || mutation.isPending} onClick={() => mutation.mutate()}>- {mutation.isPending ? 'Saving…' : editingName ? 'Save changes' : 'Create subagent'}- </Button>- </div>- </div>- );-}--function SubagentFieldInput({- field,- value,- disabled,- onChange,-}: {- field: SubagentField;- value: FormValue;- disabled: boolean;- onChange: (value: FormValue) => void;-}) {- const id = `subagent-${field.key}`;-- if (field.type === 'boolean') {- return (- <Switch id={id} checked={value === true} disabled={disabled} onCheckedChange={onChange} />- );- }-- if (field.type === 'textarea') {- return (- <Textarea- id={id}- value={String(value)}- rows={5}- placeholder={field.placeholder}- disabled={disabled}- onChange={(e) => onChange(e.target.value)}- />- );- }-- if (field.type === 'select') {- const current = String(value);- return (- <Select- value={current.length > 0 ? current : UNSET}- disabled={disabled}- onValueChange={(next) => onChange(next === UNSET ? '' : (next ?? ''))}- >- <SelectTrigger id={id}>- <SelectValue />- </SelectTrigger>- <SelectContent>- {(field.options ?? []).map((option) => (- <SelectItem key={option.value} value={option.value.length > 0 ? option.value : UNSET}>- {option.label}- </SelectItem>- ))}- </SelectContent>- </Select>- );- }-- return (- <Input- id={id}- type={field.type === 'number' ? 'number' : 'text'}- value={String(value)}- placeholder={field.placeholder}- disabled={disabled}- onChange={(e) => onChange(e.target.value)}- />- );-}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.tsxindex d13167d67..3aa021ab1 100644--- 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.tsx@@ -1,3 +1,4 @@+import { useQueryClient } from '@tanstack/react-query';import { getLocationManagerStore } from '@renderer/features/locations/stores/location-selectors';import { useToast } from '@renderer/lib/hooks/use-toast';import { rpc } from '@renderer/lib/ipc';@@ -7,32 +8,48 @@ import { log } from '@renderer/utils/logger';export function useConfirmDeleteAgent() {const showDeleteAgent = useShowModal('deleteAgentModal');const { toast } = useToast();+ const queryClient = useQueryClient();return async ({locationId,+ agentId,locationLabel,onDeleted,}: {locationId: string;+ /** The specific agent to delete. Omit to fall back to the location's first+ * agent (legacy single-agent callers). */+ agentId?: string;locationLabel: string;onDeleted?: () => void;}) => {- // Resolve the specific agent at this location so the delete is per-agent- // (creds teardown + optional Switch delete), not a blanket location removal.- const agents = await rpc.agents.getAgents(locationId);- const agent = agents[0];- if (!agent) return;+ // Resolve the specific agent so the delete is per-agent (creds teardown ++ // optional Switch delete), not a blanket location removal.+ let targetAgentId = agentId;+ if (!targetAgentId) {+ const agents = await rpc.agents.getAgents(locationId);+ targetAgentId = agents[0]?.id;+ }+ if (!targetAgentId) return;+ const resolvedAgentId = targetAgentId;showDeleteAgent({- agentId: agent.id,+ agentId: resolvedAgentId,agentLabel: locationLabel,onSuccess: ({ deleteInSwitch }) => {void (async () => {try {- await getLocationManagerStore().removeAgent(locationId, agent.id, { deleteInSwitch });+ await getLocationManagerStore().removeAgent(locationId, resolvedAgentId, {+ deleteInSwitch,+ });+ // Refresh the detail views that list a location's agents (settings+ // sections, delete modal) so the removed agent drops and its siblings+ // stay (CHOO-1440).+ void queryClient.invalidateQueries({ queryKey: ['location-agents', locationId] });+ void queryClient.invalidateQueries({ queryKey: ['agents'] });onDeleted?.();} catch (error) {- log.error('Failed to remove agent', { agentId: agent.id, error });+ log.error('Failed to remove agent', { agentId: resolvedAgentId, error });toast({title: 'Failed to remove agent',description: error instanceof Error ? error.message : String(error),diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/location-manager.test.ts b/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/location-manager.test.tsindex ff4118b81..cac4b4d0b 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/location-manager.test.ts+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/location-manager.test.ts@@ -1,11 +1,14 @@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 { agentsStore } from './agents-store';+import { isUnregisteredLocation, type LocationStore } from './location';import { LocationManagerStore } from './location-manager';const mocks = vi.hoisted(() => ({onboardAgent: vi.fn(),+ getAgents: vi.fn(async () => [] as Agent[]),+ deleteAgent: vi.fn(async () => {}),getLocations: vi.fn(async () => [] as Location[]),inspectLocationPath: vi.fn(),openLocation: vi.fn(),@@ -19,7 +22,8 @@ vi.mock('@renderer/lib/ipc', () => ({rpc: {agents: {onboardAgent: mocks.onboardAgent,- getAgents: vi.fn(async () => [] as Agent[]),+ getAgents: mocks.getAgents,+ deleteAgent: mocks.deleteAgent,},locations: {getLocations: mocks.getLocations,@@ -63,6 +67,7 @@ function agent(overrides: Partial<Agent> = {}): Agent {locationId: 'location-id',name: 'Agent',providerId: 'claude',+ definitionName: null,switchAgentId: 'sw-1',apiEndpoint: 'https://switch.example.com',serverId: 'server-1',@@ -176,3 +181,61 @@ describe('LocationManagerStore agent onboarding', () => {}});});++describe('LocationManagerStore removeAgent', () => {+ // removeAgent only gets/deletes the location by key, so a placeholder stands in+ // for the (heavy) real LocationStore.+ const stubLocation = {} as LocationStore;++ beforeEach(() => {+ vi.clearAllMocks();+ agentsStore.byLocation.clear();+ mocks.deleteAgent.mockResolvedValue(undefined);+ });++ it('removes only the target agent and keeps the location when siblings remain', async () => {+ const a = agent({ id: 'a', locationId: 'loc' });+ const b = agent({ id: 'b', locationId: 'loc' });+ agentsStore.byLocation.set('loc', [a, b]);+ mocks.getAgents.mockResolvedValue([b]); // source of truth after the delete++ const store = new LocationManagerStore();+ store.locations.set('loc', stubLocation);++ await store.removeAgent('loc', 'a', { deleteInSwitch: false });++ expect(mocks.deleteAgent).toHaveBeenCalledWith({ agentId: 'a', deleteInSwitch: false });+ expect(store.locations.has('loc')).toBe(true);+ expect(agentsStore.byLocation.get('loc')?.map((x) => x.id)).toEqual(['b']);+ });++ it('removes the location when the last agent is deleted', async () => {+ const a = agent({ id: 'a', locationId: 'loc' });+ agentsStore.byLocation.set('loc', [a]);+ mocks.getAgents.mockResolvedValue([]);++ const store = new LocationManagerStore();+ store.locations.set('loc', stubLocation);++ await store.removeAgent('loc', 'a', { deleteInSwitch: true });++ expect(mocks.deleteAgent).toHaveBeenCalledWith({ agentId: 'a', deleteInSwitch: true });+ expect(store.locations.has('loc')).toBe(false);+ expect(agentsStore.byLocation.has('loc')).toBe(false);+ });++ it('restores the agent and location when the delete fails', async () => {+ const a = agent({ id: 'a', locationId: 'loc' });+ agentsStore.byLocation.set('loc', [a]);+ mocks.deleteAgent.mockRejectedValueOnce(new Error('gateway down'));++ const store = new LocationManagerStore();+ store.locations.set('loc', stubLocation);++ await expect(store.removeAgent('loc', 'a', { deleteInSwitch: true })).rejects.toThrow(+ 'gateway down'+ );+ expect(store.locations.has('loc')).toBe(true);+ expect(agentsStore.byLocation.get('loc')?.map((x) => x.id)).toEqual(['a']);+ });+});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.tsindex f4feeebda..ec83e8fcf 100644--- 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.ts@@ -12,6 +12,7 @@ import type {StartAgentOnboardingOptions,StartAgentOnboardingResult,} from './agent-onboarding-types';+import { agentsStore } from './agents-store';import {createUnmountedLocation,createUnregisteredLocation,@@ -37,6 +38,17 @@ export class LocationManagerStore {return this._loadPromise;}+ /**+ * Force a fresh reconcile, bypassing the memoized initial {@link load}. Mounts+ * any location that gained agents since the last load (and drops nothing that is+ * already mounted). Called after onboarding agents into a directory so the new+ * location appears immediately instead of only after a restart (CHOO-1440).+ */+ reload(): Promise<void> {+ 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.@@ -65,6 +77,29 @@ export class LocationManagerStore {return completion.success ? result.locationId : undefined;}+ /**+ * Add a brand-new agent to a location (local or remote): mint its identity,+ * write its definition + credentials, and create the row — all server-side via+ * `addAgent` — then mount the resulting location so it shows immediately. The+ * flat-agent create path (CHOO-1440); returns the typed `addAgent` result so+ * the caller can surface recoverable gateway failures.+ */+ async addAgentAndOpen(+ params: Parameters<typeof rpc.agents.addAgent>[0]+ ): Promise<Awaited<ReturnType<typeof rpc.agents.addAgent>>> {+ const result = await rpc.agents.addAgent(params);+ if (result.kind === 'created') {+ const location = (await rpc.locations.getLocations()).find(+ (l) => l.id === result.agent.locationId+ );+ if (!location) {+ throw new Error(`Added agent's location ${result.agent.locationId} not found`);+ }+ this._setAndOpenLocation(location.id, location);+ }+ return result;+ }+async startAgentOnboarding(data: ModeData,options: StartAgentOnboardingOptions = {}@@ -258,17 +293,33 @@ export class LocationManagerStore {agentId: string,options: { deleteInSwitch: boolean }): Promise<void> {- const snapshot = this.locations.get(locationId);+ // A directory is a flat container of independent agents (CHOO-1440), so+ // deleting one must remove only that agent — its siblings, and the location+ // itself, stay put. Optimistically drop the agent from the cache; remove the+ // location row only when it was this agent's last one.+ const prevAgents = agentsStore.byLocation.get(locationId);+ const remaining = (prevAgents ?? []).filter((a) => a.id !== agentId);+ const locationSnapshot = remaining.length === 0 ? this.locations.get(locationId) : undefined;+runInAction(() => {- this.locations.delete(locationId);+ if (prevAgents) {+ if (remaining.length > 0) agentsStore.byLocation.set(locationId, remaining);+ else agentsStore.byLocation.delete(locationId);+ }+ if (remaining.length === 0) this.locations.delete(locationId);});- appState.navigation.revalidate();+ if (remaining.length === 0) appState.navigation.revalidate();+try {await rpc.agents.deleteAgent({ agentId, deleteInSwitch: options.deleteInSwitch });+ // Reconcile against the source of truth (also corrects the optimistic guess).+ await agentsStore.load();} catch (error) {runInAction(() => {- if (snapshot) this.locations.set(locationId, snapshot);+ if (prevAgents) agentsStore.byLocation.set(locationId, prevAgents);+ if (locationSnapshot) this.locations.set(locationId, locationSnapshot);});+ if (locationSnapshot) appState.navigation.revalidate();throw error;}}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/view.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/view.tsxindex d26a1320d..3c033bbc1 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/view.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/view.tsx@@ -19,4 +19,4 @@ export const locationView = {? { ok: true }: { ok: false, redirect: 'home' };},-} satisfies ViewDefinition<{ locationId: string; subagentName?: string }>;+} satisfies ViewDefinition<{ locationId: string; agentName?: string }>;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 aa6c4ab64..0f20a7ae7 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/create-session-modal/create-session-modal.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/create-session-modal/create-session-modal.tsx@@ -37,6 +37,7 @@ import {import { Textarea } from '@renderer/lib/ui/textarea';import { log } from '@renderer/utils/logger';import { cn } from '@renderer/utils/utils';+import { representativeAgent } from '@shared/core/agents/agents';import type { RemoteAgentRoom } from '@shared/core/switch-servers/switch-servers';import { buildConnectPrompt } from './build-connect-prompt';@@ -70,12 +71,12 @@ function useDefaultLocationId(propLocationId?: string): string | undefined {export const CreateSessionModal = observer(function CreateSessionModal({locationId,- subagentName,+ agentName,onClose,}: BaseModalProps & {locationId?: string;/** When set, start the session as this Claude Code subagent of the agent. */- subagentName?: string;+ agentName?: string;// Accepted for source compatibility with switchdash callers; ignored in switchdash v0.strategy?: string;initialPR?: unknown;@@ -90,31 +91,23 @@ export const CreateSessionModal = observer(function CreateSessionModal({// 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: ['locationAgent', selectedLocationId],- queryFn: async () => {- const agents = await rpc.agents.getAgents(selectedLocationId);- return agents[0] ?? null;- },+ const agentsQuery = useQuery({+ queryKey: ['location-agents', selectedLocationId],+ queryFn: () => rpc.agents.getAgents(selectedLocationId),enabled: !!selectedLocationId,});- const agent = agentQuery.data ?? null;+ const locationAgents = agentsQuery.data ?? [];+ const agent = representativeAgent(locationAgents) ?? null;// When launching as a subagent, the session joins rooms under the subagent's- // own Switch identity, so the room picker must use the subagent's id/server —- // not the parent agent's.- const subagentsQuery = useQuery({- queryKey: ['subagents', agent?.id],- queryFn: () => rpc.subagents.list(agent!.id),- enabled: !!agent && !!subagentName,- });- const subagent =- subagentName && subagentsQuery.data- ? (subagentsQuery.data.subagents.find((s) => s.name === subagentName) ?? null)- : null;+ // own Switch identity — its own agent row (a definitionName agent) — so the+ // room picker uses the subagent's id/server, not the parent agent's (CHOO-1440).+ const subagent = agentName+ ? (locationAgents.find((a) => a.definitionName === agentName) ?? null)+ : null;- const serverId = subagentName ? (subagent?.serverId ?? null) : (agent?.serverId ?? null);- const switchAgentId = subagentName+ const serverId = agentName ? (subagent?.serverId ?? null) : (agent?.serverId ?? null);+ const switchAgentId = agentName? (subagent?.switchAgentId ?? null): (agent?.switchAgentId ?? null);@@ -154,7 +147,8 @@ export const CreateSessionModal = observer(function CreateSessionModal({const initialPrompt = buildConnectPrompt(room?.roomName ?? null, chosenRole, prompt);void (async () => {- const resolvedAgent = agent ?? (await rpc.agents.getAgents(selectedLocationId))[0];+ const resolvedAgent =+ agent ?? representativeAgent(await rpc.agents.getAgents(selectedLocationId));if (!resolvedAgent) {log.error('spawn session failed: location has no agents', selectedLocationId);return;@@ -168,7 +162,7 @@ export const CreateSessionModal = observer(function CreateSessionModal({title: trimmedName || 'Session',autoApprove: resolvedAgent.autoApprove,initialPrompt,- subagentName: subagentName || undefined,+ agentName: agentName || undefined,});navigate('session', { locationId: selectedLocationId, sessionId: id });onClose();@@ -179,7 +173,7 @@ export const CreateSessionModal = observer(function CreateSessionModal({return (<><DialogHeader className="flex items-center gap-2">- <DialogTitle>{subagentName ? `New Session · @${subagentName}` : 'New Session'}</DialogTitle>+ <DialogTitle>{agentName ? `New Session · @${agentName}` : 'New Session'}</DialogTitle></DialogHeader><DialogContentArea><div className="flex w-full flex-col gap-5">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 6e10d10e5..f0f4f923f 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@@ -188,7 +188,7 @@ export class SessionManagerStore {status: 'in_progress',statusChangedAt: new Date().toISOString(),isPinned: false,- subagentName: params.subagentName,+ agentName: params.agentName,}));});@@ -220,7 +220,7 @@ export class SessionManagerStore {isInitialSession: true,isPinned: false,autoApprove: params.autoApprove ?? false,- subagentName: params.subagentName,+ agentName: params.agentName,createdAt: now,updatedAt: now,};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 9c6661317..06352514c 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@@ -29,7 +29,7 @@ export type UnregisteredSessionData = {statusChangedAt: string;isPinned: boolean;/** Set when this session runs as a Claude Code subagent of its agent. */- subagentName?: string;+ agentName?: string;};export class SessionStore {diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/agent-item.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/agent-item.tsxnew file mode 100644index 000000000..b6cef47d2--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/agent-item.tsx@@ -0,0 +1,260 @@+import { useQuery } from '@tanstack/react-query';+import {+ Bot,+ ChevronRight,+ ExternalLink,+ Plus,+ RotateCcw,+ Server,+ Trash2,+ TriangleAlert,+} from 'lucide-react';+import { observer } from 'mobx-react-lite';+import { useConfirmDeleteAgent } from '@renderer/features/locations/hooks/use-confirm-delete-agent';+import {+ getLocationStore,+ locationViewKind,+} from '@renderer/features/locations/stores/location-selectors';+import { hasSessionError } from '@renderer/features/sessions/stores/session-selectors';+import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';+import { AgentIcon } from '@renderer/lib/components/agent-icon';+import { useToast } from '@renderer/lib/hooks/use-toast';+import { rpc } from '@renderer/lib/ipc';+import {+ useNavigate,+ useParams,+ useWorkspaceSlots,+} from '@renderer/lib/layout/navigation-provider';+import { useShowModal } from '@renderer/lib/modal/modal-provider';+import { sidebarStore } from '@renderer/lib/stores/app-state';+import {+ ContextMenu,+ ContextMenuContent,+ ContextMenuItem,+ ContextMenuTrigger,+} from '@renderer/lib/ui/context-menu';+import { BoundShortcut } from '@renderer/lib/ui/shortcut';+import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';+import { cn } from '@renderer/utils/utils';+import type { Agent } from '@shared/core/agents/agents';+import { SidebarItemMiniButton, SidebarMenuAction, SidebarMenuRow } from './sidebar-primitives';+import { depthIndent } from './sidebar-store';++/** Expand-state key for an agent row (default open; its sessions live below it). */+export function agentExpandKey(agentId: string): string {+ return `ag:${agentId}`;+}++/**+ * A single agent in the flat sidebar list. switchdash has no main/subagent+ * distinction — every agent is a first-class row, launched as its own provider+ * definition with its own Switch identity (CHOO-1440). The row opens the agent's+ * page, starts sessions as that agent, and its sessions nest underneath.+ */+export const SidebarAgentItem = observer(function SidebarAgentItem({+ agent,+ depth = 0,+}: {+ agent: Agent;+ depth?: number;+}) {+ const { navigate } = useNavigate();+ const { currentView } = useWorkspaceSlots();+ const { params: locationParams } = useParams('location');+ const { params: sessionParams } = useParams('session');+ const showCreateSessionModal = useShowModal('sessionModal');+ const showConfirmReset = useShowModal('resetAgentModal');+ const confirmDeleteAgent = useConfirmDeleteAgent();+ const { toastPromise } = useToast();++ const agentName = agent.definitionName ?? undefined;+ const location = getLocationStore(agent.locationId);++ // The row is labelled by the agent's registered Switch name; fall back to the+ // stored name until (or unless) the lookup resolves.+ const remoteAgentQuery = useQuery({+ queryKey: ['remoteAgentName', agent.serverId, agent.switchAgentId],+ queryFn: () =>+ rpc.switchServers.getRemoteAgent({+ serverId: agent.serverId!,+ agentId: agent.switchAgentId!,+ }),+ enabled: !!agent.serverId && !!agent.switchAgentId,+ });+ const label = remoteAgentQuery.data?.name?.trim() || agent.name || agentName || 'Unnamed agent';++ const expanded = sidebarStore.isGroupExpanded(agentExpandKey(agent.id));+ const toggle = () => sidebarStore.toggleGroupExpanded(agentExpandKey(agent.id));++ const currentLocationId =+ currentView === 'session'+ ? sessionParams.locationId+ : currentView === 'location'+ ? locationParams.locationId+ : null;+ const currentSubagentName = currentView === 'location' ? locationParams.agentName : undefined;+ const isActive =+ currentView === 'location' &&+ currentLocationId === agent.locationId &&+ currentSubagentName === agentName;++ if (!location) return null;++ const iconClass =+ 'absolute h-4 w-4 opacity-100 transition-opacity duration-150 group-hover/row:opacity-0';+ const gatewayUrl =+ agent.serverId && agent.switchAgentId+ ? switchRoomsStore.gatewayAgentUrl(agent.serverId, agent.switchAgentId)+ : null;++ const open = () => {+ sidebarStore.ensureGroupExpanded(agentExpandKey(agent.id));+ navigate('location', { locationId: agent.locationId, agentName });+ };++ return (+ <ContextMenu>+ <ContextMenuTrigger>+ <SidebarMenuRow+ className="group/row flex h-8 justify-between px-1"+ style={depthIndent(depth)}+ data-active={isActive || undefined}+ isActive={isActive}+ onMouseDown={(e) => e.preventDefault()}+ onClick={open}+ >+ <div className="flex min-w-0 flex-1 items-center gap-1">+ <SidebarItemMiniButton+ type="button"+ aria-label={`${expanded ? 'Collapse' : 'Expand'} ${label}`}+ className="relative"+ onClick={(e) => {+ e.stopPropagation();+ toggle();+ }}+ >+ {agent.providerId ? (+ <AgentIcon id={agent.providerId} size={16} className={iconClass} />+ ) : (+ <Bot className={iconClass} />+ )}+ <ChevronRight+ className={cn(+ 'absolute h-4 w-4 opacity-0 transition-all duration-150 group-hover/row:opacity-100',+ expanded && 'rotate-90'+ )}+ />+ </SidebarItemMiniButton>+ <SidebarMenuAction aria-label={`Open agent ${label}`} className="truncate select-none">+ <span className="flex min-w-0 items-center gap-1.5">+ <span className="truncate">{label}</span>+ {location.data?.sshHost != null && (+ <Tooltip>+ <TooltipTrigger>+ <Server className="h-3.5 w-3.5 shrink-0 text-foreground-muted" />+ </TooltipTrigger>+ <TooltipContent>+ Runs remotely on {location.data.sshHost}+ {location.data.dir ? ` · ${location.data.dir}` : ''}+ </TooltipContent>+ </Tooltip>+ )}+ {locationViewKind(location) === 'ready' && hasSessionError(agent.locationId) && (+ <Tooltip>+ <TooltipTrigger>+ <TriangleAlert className="h-3.5 w-3.5 shrink-0 text-foreground-destructive" />+ </TooltipTrigger>+ <TooltipContent>A session failed to connect</TooltipContent>+ </Tooltip>+ )}+ </span>+ </SidebarMenuAction>+ </div>+ {gatewayUrl && agent.serverId && (+ <Tooltip>+ <TooltipTrigger+ render={+ <SidebarItemMiniButton+ type="button"+ aria-label={`Open ${label} in gateway`}+ className="opacity-0 transition-opacity duration-150 group-hover/row:opacity-100"+ onClick={(e) => {+ e.stopPropagation();+ void rpc.switchServers.openGatewayPage({+ serverId: agent.serverId!,+ url: gatewayUrl,+ });+ }}+ >+ <ExternalLink className="h-3.5 w-3.5" />+ </SidebarItemMiniButton>+ }+ />+ <TooltipContent>Open in gateway</TooltipContent>+ </Tooltip>+ )}+ <Tooltip>+ <TooltipTrigger+ className="h-6"+ render={+ <SidebarItemMiniButton+ type="button"+ aria-label={`New session for ${label}`}+ className="opacity-0 transition-opacity duration-150 group-hover/row:opacity-100"+ onClick={(e) => {+ e.stopPropagation();+ showCreateSessionModal({ locationId: agent.locationId, agentName });+ }}+ >+ <Plus className="h-4 w-4" />+ </SidebarItemMiniButton>+ }+ />+ <TooltipContent>+ New Session+ <BoundShortcut settingsKey="newSession" variant="badge" />+ </TooltipContent>+ </Tooltip>+ </SidebarMenuRow>+ </ContextMenuTrigger>+ <ContextMenuContent>+ {location.data?.sshHost != null && (+ <ContextMenuItem+ onClick={() => {+ showConfirmReset({+ agentLabel: label,+ onSuccess: () => {+ void toastPromise(rpc.agents.resetRemoteAgent({ agentId: agent.id }), {+ loading: `Resetting ${label}…`,+ success: `${label} was reset`,+ error: (error) =>+ `Failed to reset agent: ${error instanceof Error ? error.message : String(error)}`,+ });+ },+ });+ }}+ >+ <RotateCcw className="size-4" />+ Reset agent+ </ContextMenuItem>+ )}+ <ContextMenuItem+ variant="destructive"+ onClick={() => {+ void confirmDeleteAgent({+ locationId: agent.locationId,+ agentId: agent.id,+ locationLabel: label,+ onDeleted: () => {+ if (isActive) navigate('home');+ },+ });+ }}+ >+ <Trash2 className="size-4" />+ Remove Agent+ </ContextMenuItem>+ </ContextMenuContent>+ </ContextMenu>+ );+});diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/location-item.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/location-item.tsxdeleted file mode 100644index 6ba76b3f2..000000000--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/location-item.tsx+++ /dev/null@@ -1,366 +0,0 @@-import { useQuery } from '@tanstack/react-query';-import {- Bot,- ChevronRight,- ExternalLink,- Loader2,- Plus,- RefreshCw,- RotateCcw,- Server,- Trash2,- TriangleAlert,-} from 'lucide-react';-import { observer } from 'mobx-react-lite';-import React from 'react';-import { useConfirmDeleteAgent } from '@renderer/features/locations/hooks/use-confirm-delete-agent';-import {- isUnregisteredLocation,- type UnregisteredLocation,-} from '@renderer/features/locations/stores/location';-import {- getLocationManagerStore,- getLocationStore,- locationViewKind,-} from '@renderer/features/locations/stores/location-selectors';-import { hasSessionError } from '@renderer/features/sessions/stores/session-selectors';-import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';-import { AgentIcon } from '@renderer/lib/components/agent-icon';-import { useToast } from '@renderer/lib/hooks/use-toast';-import { rpc } from '@renderer/lib/ipc';-import {- useNavigate,- useParams,- useWorkspaceSlots,-} from '@renderer/lib/layout/navigation-provider';-import { useShowModal } from '@renderer/lib/modal/modal-provider';-import { sidebarStore } from '@renderer/lib/stores/app-state';-import {- ContextMenu,- ContextMenuContent,- ContextMenuItem,- ContextMenuTrigger,-} from '@renderer/lib/ui/context-menu';-import { BoundShortcut } from '@renderer/lib/ui/shortcut';-import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';-import { cn } from '@renderer/utils/utils';-import {- SidebarItemMiniButton,- SidebarMenuAction,- SidebarMenuButton,- SidebarMenuRow,-} from './sidebar-primitives';-import { depthIndent } from './sidebar-store';--const UNREGISTERED_PHASE_LABEL: Record<UnregisteredLocation['phase'], string> = {- registering: 'Registering…',- error: 'Failed',-};--export const SidebarLocationItem = observer(function SidebarLocationItem({- locationId,- depth = 0,-}: {- locationId: string;- depth?: number;-}) {- const { navigate } = useNavigate();- const { currentView } = useWorkspaceSlots();- const { params: locationParams } = useParams('location');- const { params: sessionParams } = useParams('session');- const showCreateSessionModal = useShowModal('sessionModal');- const showConfirmReset = useShowModal('resetAgentModal');- const confirmDeleteAgent = useConfirmDeleteAgent();- const { toastPromise } = useToast();-- // 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: ['locationAgent', locationId],- queryFn: async () => (await rpc.agents.getAgents(locationId))[0] ?? null,- enabled: !!locationId,- });-- // The row is labelled by the agent's registered Switch name (its identity on- // the server), not the local directory-derived location name. Resolve it by- // id from the gateway, keyed on (server, switch agent id) so it caches and is- // shared across rows for the same agent.- const remoteAgentQuery = useQuery({- queryKey: ['remoteAgentName', agentQuery.data?.serverId, agentQuery.data?.switchAgentId],- queryFn: async () =>- rpc.switchServers.getRemoteAgent({- serverId: agentQuery.data!.serverId!,- agentId: agentQuery.data!.switchAgentId!,- }),- enabled: !!agentQuery.data?.serverId && !!agentQuery.data?.switchAgentId,- });-- const location = getLocationStore(locationId);-- const currentLocationId =- currentView === 'session'- ? sessionParams.locationId- : currentView === 'location'- ? locationParams.locationId- : null;- const currentSessionId = currentView === 'session' ? sessionParams.sessionId : null;- // 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 === 'location' ? locationParams.subagentName : undefined;-- const isLocationActive =- currentLocationId === locationId && !currentSessionId && !currentSubagentName;-- const isExpanded = sidebarStore.expandedLocationIds.has(locationId);-- if (!location) return null;-- const iconClass =- 'absolute h-4 w-4 opacity-100 transition-opacity duration-150 group-hover/row:opacity-0';- // Registered Switch name wins. While the lookup is still in flight, keep the- // local name so the row does not flash; once it settles without a name- // (server unlinked, agent unregistered, or offline) show a stable placeholder.- const switchName = remoteAgentQuery.data?.name?.trim() || null;- const locationLabel =- switchName ??- (remoteAgentQuery.isLoading ? (location.name ?? 'Unnamed agent') : 'Unnamed 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 openLocation = () => {- if (isUnregisteredLocation(location)) {- toggleExpanded();- return;- }- sidebarStore.ensureLocationExpanded(locationId);- navigate('location', { locationId });- };-- const agent = agentQuery.data ?? null;- // 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 =- agent?.serverId && agent?.switchAgentId- ? switchRoomsStore.gatewayAgentUrl(agent.serverId, agent.switchAgentId)- : null;- const openInGateway = () => {- if (gatewayUrl && agent?.serverId) {- void rpc.switchServers.openGatewayPage({ serverId: agent.serverId, url: gatewayUrl });- }- };-- const renderSpinnerWithTooltip = () => {- if (!isUnregisteredLocation(location)) return null;- const label = UNREGISTERED_PHASE_LABEL[location.phase] ?? 'Loading…';- return (- <Tooltip>- <TooltipTrigger>- <SidebarItemMiniButton type="button" disabled aria-label="Loading">- <Loader2 className="h-4 w-4 animate-spin text-foreground/60" />- </SidebarItemMiniButton>- </TooltipTrigger>- <TooltipContent>{label}</TooltipContent>- </Tooltip>- );- };-- return (- <ContextMenu>- <ContextMenuTrigger>- <SidebarMenuRow- className={cn('group/row h-8 justify-between flex px-1')}- style={depthIndent(depth)}- data-active={isLocationActive || undefined}- isActive={isLocationActive}- onMouseDown={(e) => e.preventDefault()}- onClick={openLocation}- >- <div className="flex min-w-0 flex-1 items-center gap-1">- {location.state === 'unregistered' ? (- renderSpinnerWithTooltip()- ) : (- <SidebarItemMiniButton- type="button"- aria-label={`${isExpanded ? 'Collapse' : 'Expand'} ${locationLabel}`}- className="relative"- onClick={(e) => {- e.stopPropagation();- sidebarStore.toggleLocationExpanded(locationId);- }}- >- {providerId ? (- <AgentIcon id={providerId} size={16} className={iconClass} />- ) : (- <Bot className={iconClass} />- )}- <ChevronRight- className={cn(- 'absolute h-4 w-4 transition-all duration-150 opacity-0 group-hover/row:opacity-100',- isExpanded && 'rotate-90'- )}- />- </SidebarItemMiniButton>- )}- <SidebarMenuAction- aria-label={`Open agent ${locationLabel}`}- className={cn(- 'truncate transition-colors select-none',- locationViewKind(getLocationStore(locationId)) === 'bootstrapping' &&- 'text-foreground-tertiary-passive'- )}- >- <span className="flex min-w-0 items-center gap-1.5">- <span className="truncate">{locationLabel}</span>- {location.data?.sshHost != null && (- <Tooltip>- <TooltipTrigger>- <Server className="h-3.5 w-3.5 shrink-0 text-foreground-muted" />- </TooltipTrigger>- <TooltipContent>- Runs remotely on {location.data.sshHost}- {location.data.dir ? ` · ${location.data.dir}` : ''}- </TooltipContent>- </Tooltip>- )}- {locationViewKind(location) === 'path_not_found' && (- <Tooltip>- <TooltipTrigger>- <TriangleAlert className="h-3.5 w-3.5 shrink-0 text-foreground-destructive" />- </TooltipTrigger>- <TooltipContent>Agent not found at path</TooltipContent>- </Tooltip>- )}- {locationViewKind(location) === 'mount_error' && (- <Tooltip>- <TooltipTrigger- render={- <button- type="button"- className="inline-flex cursor-pointer"- onClick={(e) => {- e.stopPropagation();- void getLocationManagerStore().mountLocation(locationId);- }}- />- }- >- <RefreshCw className="h-3.5 w-3.5 shrink-0 text-foreground-destructive" />- </TooltipTrigger>- <TooltipContent>Connection failed — click to retry</TooltipContent>- </Tooltip>- )}- {locationViewKind(location) === 'ready' && hasSessionError(locationId) && (- <Tooltip>- <TooltipTrigger>- <TriangleAlert className="h-3.5 w-3.5 shrink-0 text-foreground-destructive" />- </TooltipTrigger>- <TooltipContent>A session failed to connect</TooltipContent>- </Tooltip>- )}- </span>- </SidebarMenuAction>- </div>- {gatewayUrl && (- <Tooltip>- <TooltipTrigger- render={- <SidebarItemMiniButton- type="button"- aria-label={`Open ${locationLabel} in gateway`}- className="opacity-0 transition-opacity duration-150 group-hover/row:opacity-100"- onClick={(e) => {- e.stopPropagation();- openInGateway();- }}- >- <ExternalLink className="h-3.5 w-3.5" />- </SidebarItemMiniButton>- }- />- <TooltipContent>Open in gateway</TooltipContent>- </Tooltip>- )}- <Tooltip>- <TooltipTrigger- className="h-6"- render={- <SidebarItemMiniButton- type="button"- aria-label={`New session for ${locationLabel}`}- className={- 'opacity-0 transition-opacity duration-150 group-hover/row:opacity-100'- }- onClick={(e) => {- e.stopPropagation();- showCreateSessionModal({ locationId });- }}- disabled={location.state === 'unregistered'}- >- <Plus className="h-4 w-4" />- </SidebarItemMiniButton>- }- />- <TooltipContent>- New Session- <BoundShortcut settingsKey="newSession" variant="badge" />- </TooltipContent>- </Tooltip>- </SidebarMenuRow>- </ContextMenuTrigger>- <ContextMenuContent>- {location.data?.sshHost != null && agent && (- <ContextMenuItem- onClick={() => {- showConfirmReset({- agentLabel: locationLabel,- onSuccess: () => {- void toastPromise(rpc.agents.resetRemoteAgent({ agentId: agent.id }), {- loading: `Resetting ${locationLabel}…`,- success: `${locationLabel} was reset`,- error: (error) =>- `Failed to reset agent: ${error instanceof Error ? error.message : String(error)}`,- });- },- });- }}- >- <RotateCcw className="size-4" />- Reset agent- </ContextMenuItem>- )}- <ContextMenuItem- variant="destructive"- onClick={() => {- void confirmDeleteAgent({- locationId,- locationLabel: switchName ?? location.name ?? 'this agent',- onDeleted: () => {- if (isLocationActive) navigate('home');- },- });- }}- >- <Trash2 className="size-4" />- Remove Agent- </ContextMenuItem>- </ContextMenuContent>- </ContextMenu>- );-});--interface BaseLocationItemProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {- isActive: boolean;-}--export function BaseLocationItem({ isActive, className, ...props }: BaseLocationItemProps) {- return (- <SidebarMenuButton- className={cn('justify-between flex item px-1 py-1', className)}- isActive={isActive}- {...props}- />- );-}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-dnd.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-dnd.tsxdeleted file mode 100644index ee332cd04..000000000--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-dnd.tsx+++ /dev/null@@ -1,122 +0,0 @@-import {- closestCenter,- PointerSensor,- useSensor,- useSensors,- type CollisionDetection,- type DragEndEvent,-} from '@dnd-kit/core';-import { arrayMove, useSortable } from '@dnd-kit/sortable';-import { CSS } from '@dnd-kit/utilities';-import type { CSSProperties, ReactNode } from 'react';--/**- * Drag-to-reorder plumbing for the grouped sidebar views.- *- * Every draggable carries a composite id `${containerId}~~${itemId}`. The- * container id identifies the sibling set an item belongs to (e.g. the- * top-level agents, the top-level rooms, or one group's sessions); reordering- * is restricted to within a container so a drag can only change order, never- * move an item into a different section.- */-const SEP = '~~';--export function makeDndId(containerId: string, itemId: string): string {- return `${containerId}${SEP}${itemId}`;-}--export function parseDndId(dndId: string): { containerId: string; itemId: string } | null {- const idx = dndId.indexOf(SEP);- if (idx === -1) return null;- return { containerId: dndId.slice(0, idx), itemId: dndId.slice(idx + SEP.length) };-}--/**- * Collision detection that only considers droppables in the same container as- * the active item, so a drag can only land among its own siblings.- */-const sameContainerCollision: CollisionDetection = (args) => {- const active = parseDndId(String(args.active.id));- if (!active) return [];- const droppableContainers = args.droppableContainers.filter((container) => {- const parsed = parseDndId(String(container.id));- return parsed?.containerId === active.containerId;- });- return closestCenter({ ...args, droppableContainers });-};--/**- * Build the props for the grouped views' single `DndContext`. `containers` maps- * each container id to its current ordered item ids (populated during render);- * on drop, the within-container `arrayMove` result is handed to `onReorder`.- */-export function useSidebarDnd(- containers: Record<string, string[]>,- onReorder: (containerId: string, orderedItemIds: string[]) => void-) {- const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 6 } }));-- function onDragEnd(event: DragEndEvent) {- const { active, over } = event;- if (!over || active.id === over.id) return;- const from = parseDndId(String(active.id));- const to = parseDndId(String(over.id));- if (!from || !to || from.containerId !== to.containerId) return;- const ids = containers[from.containerId];- if (!ids) return;- const oldIndex = ids.indexOf(from.itemId);- const newIndex = ids.indexOf(to.itemId);- if (oldIndex === -1 || newIndex === -1 || oldIndex === newIndex) return;- onReorder(from.containerId, arrayMove(ids, oldIndex, newIndex));- }-- return { sensors, collisionDetection: sameContainerCollision, onDragEnd };-}--function useSortableRow(id: string) {- const { setNodeRef, transform, transition, isDragging, listeners } = useSortable({ id });- const style: CSSProperties = {- transform: CSS.Transform.toString(transform),- transition,- opacity: isDragging ? 0.4 : undefined,- position: 'relative',- zIndex: isDragging ? 1 : undefined,- };- return { setNodeRef, style, listeners };-}--/**- * A leaf draggable: the whole row is the drag handle. Use for rows with no- * nested draggables (sessions).- */-export function SortableLeaf({ id, children }: { id: string; children: ReactNode }) {- const { setNodeRef, style, listeners } = useSortableRow(id);- return (- <div ref={setNodeRef} style={style} {...listeners}>- {children}- </div>- );-}--/**- * A branch draggable: only `header` is the drag handle, while `children`- * (nested rows, which may be draggable in their own container) move with it but- * do not start the branch's drag. Use for section rows (agents, rooms).- */-export function SortableBranch({- id,- header,- children,-}: {- id: string;- header: ReactNode;- children?: ReactNode;-}) {- const { setNodeRef, style, listeners } = useSortableRow(id);- return (- <div ref={setNodeRef} style={style}>- <div {...listeners}>{header}</div>- {children}- </div>- );-}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 3467e2e14..76d35ff31 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@@ -1,36 +1,58 @@-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/locations/stores/agents-store';+import type { LocationStore } from '@renderer/features/locations/stores/location';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 { SidebarLocationItem } from './location-item';+import type { Agent } from '@shared/core/agents/agents';+import { SidebarAgentItem, agentExpandKey } from './agent-item';import { SidebarSessionItem } from './session-item';-import { makeDndId, SortableBranch, SortableLeaf, useSidebarDnd } from './sidebar-dnd';import {groupByRoom,- isSubagentSession,openRoomInGateway,openRoomInMessagingApp,RoomRow,roomLabel,} from './sidebar-room-grouping';-import { agentRoomGroupKey, roomViewGroupKey } from './sidebar-store';-import { SidebarSubagentList } from './sidebar-subagent-list';+import { agentRoomGroupKey, roomViewGroupKey, UNASSIGNED_ROOM_KEY } from './sidebar-store';-/** dnd container ids. Each identifies a reorderable sibling set. */-const AGENTS_CONTAINER = 'agents';-const ROOMS_CONTAINER = 'rooms';-/** Sessions of one agent's room group (agent-focused view). */-const agentSessionsContainer = (locationId: string, roomKey: string): string =>- `as:${locationId}|${roomKey}`;-/** Sessions of one agent within a room (room-focused view). */-const roomSessionsContainer = (roomKey: string, locationId: string): string =>- `rs:${roomKey}|${locationId}`;+/** The provider definition a session was launched as, if any. */+function sessionDefinitionName(session: SessionStore): string | undefined {+ return 'agentName' in session.data ? session.data.agentName : undefined;+}++/** An agent paired with its (mounted) location, for the flat sidebar list. */+type AgentEntry = { agent: Agent; location: LocationStore };++/**+ * The flat list of agents in the active-server scope, newest first. switchdash+ * shows agents as a flat list — not grouped by directory (CHOO-1440).+ */+function scopedAgents(): AgentEntry[] {+ const entries: AgentEntry[] = [];+ for (const location of sidebarStore.filteredLocations) {+ for (const agent of agentsStore.byLocation.get(location.id) ?? []) {+ entries.push({ agent, location });+ }+ }+ return entries.sort(+ (a, b) =>+ b.agent.createdAt.localeCompare(a.agent.createdAt) || a.agent.name.localeCompare(b.agent.name)+ );+}++/** An agent's visible sessions: its location's sessions launched as its definition. */+function agentSessions(entry: AgentEntry): SessionStore[] {+ const all = sidebarStore.visibleSessionsForLocation(entry.location.id);+ const def = entry.agent.definitionName;+ return all.filter((session) => {+ const name = sessionDefinitionName(session);+ return def == null ? !name : name === def;+ });+}export const SidebarGroupedList = observer(function SidebarGroupedList() {// Live session→room connections + room names live on the server; pull them@@ -63,221 +85,154 @@ export const SidebarGroupedList = observer(function SidebarGroupedList() {);});-const AgentFocusedTree = observer(function AgentFocusedTree() {- 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]: locations.map((location) => location.id),- };- const dnd = useSidebarDnd(containers, (containerId, orderedIds) => {- if (containerId === AGENTS_CONTAINER) sidebarStore.setLocationOrder(orderedIds);- else sidebarStore.setGroupOrder(containerId, orderedIds);- });-- function renderSessionGroup(locationId: string, roomKey: string, roomSessions: SessionStore[]) {- const container = agentSessionsContainer(locationId, roomKey);- const ordered = sidebarStore.orderGroupItems(- container,- roomSessions,- (session) => session.data.id,- true- );- containers[container] = ordered.map((session) => session.data.id);- const depth = 2;- return (- <SortableContext- items={ordered.map((session) => makeDndId(container, session.data.id))}- strategy={verticalListSortingStrategy}- >- {ordered.map((session) => (- <SortableLeaf key={session.data.id} id={makeDndId(container, session.data.id)}>- <SidebarSessionItem locationId={locationId} sessionId={session.data.id} depth={depth} />- </SortableLeaf>- ))}- </SortableContext>- );- }-+/** Render an agent's sessions grouped by room, under the agent row. */+const AgentSessions = observer(function AgentSessions({+ agentId,+ locationId,+ sessions,+ depth,+}: {+ agentId: string;+ locationId: string;+ sessions: SessionStore[];+ depth: number;+}) {return (- <DndContext {...dnd}>- <SortableContext- items={locations.map((location) => makeDndId(AGENTS_CONTAINER, location.id))}- strategy={verticalListSortingStrategy}- >- {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={locationId}- id={makeDndId(AGENTS_CONTAINER, locationId)}- header={<SidebarLocationItem locationId={locationId} depth={0} />}- >- {/* The agent's own rooms/sessions come first, then its subagents. */}- {expanded &&- grouped.map(([roomKey, roomSessions]) => {- const groupKey = agentRoomGroupKey(locationId, roomKey);- const roomExpanded = sidebarStore.isGroupExpanded(groupKey);- return (- <div key={roomKey}>- <RoomRow- label={roomLabel(roomKey)}- count={roomSessions.length}- expanded={roomExpanded}- depth={1}- bridgeType={switchRoomsStore.roomBridgeTypeById(roomKey)}- onToggle={() => sidebarStore.toggleGroupExpanded(groupKey)}- onOpenGateway={() => openRoomInGateway(roomKey)}- onOpenChannel={- switchRoomsStore.roomChannelUrl(roomKey)- ? () => openRoomInMessagingApp(roomKey)- : null- }- />- {roomExpanded && renderSessionGroup(locationId, roomKey, roomSessions)}- </div>- );- })}- {expanded && (- <SidebarSubagentList+ <>+ {groupByRoom(sessions).map(([roomKey, roomSessions]) => {+ // Sessions with no room sit directly under the agent, no room header.+ if (roomKey === UNASSIGNED_ROOM_KEY) {+ return roomSessions.map((session) => (+ <SidebarSessionItem+ key={session.data.id}+ locationId={locationId}+ sessionId={session.data.id}+ depth={depth}+ />+ ));+ }+ const groupKey = agentRoomGroupKey(agentId, roomKey);+ const roomExpanded = sidebarStore.isGroupExpanded(groupKey);+ return (+ <div key={roomKey}>+ <RoomRow+ label={roomLabel(roomKey)}+ count={roomSessions.length}+ expanded={roomExpanded}+ depth={depth}+ bridgeType={switchRoomsStore.roomBridgeTypeById(roomKey)}+ onToggle={() => sidebarStore.toggleGroupExpanded(groupKey)}+ onOpenGateway={() => openRoomInGateway(roomKey)}+ onOpenChannel={+ switchRoomsStore.roomChannelUrl(roomKey)+ ? () => openRoomInMessagingApp(roomKey)+ : null+ }+ />+ {roomExpanded &&+ roomSessions.map((session) => (+ <SidebarSessionItem+ key={session.data.id}locationId={locationId}- sessions={subagentSessions}- depth={1}+ sessionId={session.data.id}+ depth={depth + 1}/>- )}- </SortableBranch>- );- })}- </SortableContext>- </DndContext>+ ))}+ </div>+ );+ })}+ </>+ );+});++const AgentFocusedTree = observer(function AgentFocusedTree() {+ const agents = scopedAgents();+ return (+ <>+ {agents.map((entry) => {+ const expanded = sidebarStore.isGroupExpanded(agentExpandKey(entry.agent.id));+ return (+ <div key={entry.agent.id}>+ <SidebarAgentItem agent={entry.agent} depth={0} />+ {expanded && (+ <AgentSessions+ agentId={entry.agent.id}+ locationId={entry.agent.locationId}+ sessions={agentSessions(entry)}+ depth={1}+ />+ )}+ </div>+ );+ })}+ </>);});const RoomFocusedTree = observer(function RoomFocusedTree() {- // Collect every visible session across mounted agents, tagged with its agent.- 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 });+ // Tag every visible session with the agent it belongs to, then group by room.+ const bySession = new Map<string, AgentEntry>();+ const allSessions: SessionStore[] = [];+ for (const entry of scopedAgents()) {+ for (const session of agentSessions(entry)) {+ bySession.set(session.data.id, entry);+ allSessions.push(session);}}- const grouped = groupByRoom(tagged.map((t) => t.session));- const byKey = new Map(grouped);- const orderedRoomKeys = sidebarStore.orderRoomKeys(grouped.map(([roomKey]) => roomKey));-- const containers: Record<string, string[]> = { [ROOMS_CONTAINER]: orderedRoomKeys };- const dnd = useSidebarDnd(containers, (containerId, orderedIds) => {- if (containerId === ROOMS_CONTAINER) sidebarStore.setRoomOrder(orderedIds);- else sidebarStore.setGroupOrder(containerId, orderedIds);- });-return (- <DndContext {...dnd}>- <SortableContext- items={orderedRoomKeys.map((roomKey) => makeDndId(ROOMS_CONTAINER, roomKey))}- strategy={verticalListSortingStrategy}- >- {orderedRoomKeys.map((roomKey) => {- const roomSessions = byKey.get(roomKey) ?? [];- // Rooms in this view always have sessions, so default to expanded.- const roomViewKey = roomViewGroupKey(roomKey);- const expanded = sidebarStore.isGroupExpanded(roomViewKey);- const sessionIds = new Set(roomSessions.map((s) => s.data.id));- const byLocation = sidebarStore.filteredLocations- .map((location) => ({- locationId: location.id,- sessions: tagged- .filter((t) => t.locationId === location.id && sessionIds.has(t.session.data.id))- .map((t) => t.session),- }))- .filter((entry) => entry.sessions.length > 0);-- return (- <SortableBranch- key={roomKey}- id={makeDndId(ROOMS_CONTAINER, roomKey)}- header={- <RoomRow- label={roomLabel(roomKey)}- count={roomSessions.length}- expanded={expanded}- depth={0}- bridgeType={switchRoomsStore.roomBridgeTypeById(roomKey)}- onToggle={() => sidebarStore.toggleGroupExpanded(roomViewKey)}- onOpenGateway={() => openRoomInGateway(roomKey)}- onOpenChannel={- switchRoomsStore.roomChannelUrl(roomKey)- ? () => openRoomInMessagingApp(roomKey)- : null- }- />+ <>+ {groupByRoom(allSessions).map(([roomKey, roomSessions]) => {+ const roomViewKey = roomViewGroupKey(roomKey);+ const expanded = sidebarStore.isGroupExpanded(roomViewKey);+ // Agents that have a session in this room, in first-seen order.+ const seen = new Set<string>();+ const agentsInRoom: AgentEntry[] = [];+ for (const session of roomSessions) {+ const entry = bySession.get(session.data.id);+ if (entry && !seen.has(entry.agent.id)) {+ seen.add(entry.agent.id);+ agentsInRoom.push(entry);+ }+ }+ return (+ <div key={roomKey}>+ <RoomRow+ label={roomLabel(roomKey)}+ count={roomSessions.length}+ expanded={expanded}+ depth={0}+ bridgeType={switchRoomsStore.roomBridgeTypeById(roomKey)}+ onToggle={() => sidebarStore.toggleGroupExpanded(roomViewKey)}+ onOpenGateway={() => openRoomInGateway(roomKey)}+ onOpenChannel={+ switchRoomsStore.roomChannelUrl(roomKey)+ ? () => openRoomInMessagingApp(roomKey)+ : null}- >- {expanded &&- byLocation.map((entry) => {- // Reuse the agent row so it matches the agent-focused view- // (icon, hover-chevron, sizing). Its expand state is the global- // 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.locationId);- const orderedParent = sidebarStore.orderGroupItems(- container,- parentSessions,- (session) => session.data.id,- true- );- containers[container] = orderedParent.map((session) => session.data.id);- return (- <Fragment key={entry.locationId}>- <SidebarLocationItem locationId={entry.locationId} depth={1} />- {agentExpanded && (- <SortableContext- items={orderedParent.map((session) =>- makeDndId(container, session.data.id)- )}- strategy={verticalListSortingStrategy}- >- {orderedParent.map((session) => (- <SortableLeaf- key={session.data.id}- id={makeDndId(container, session.data.id)}- >- <SidebarSessionItem- locationId={entry.locationId}- sessionId={session.data.id}- depth={2}- />- </SortableLeaf>- ))}- </SortableContext>- )}- {subagentSessions.length > 0 && (- <SidebarSubagentList- locationId={entry.locationId}- depth={1}- sessions={subagentSessions}- onlyWithSessions- groupSessionsByRoom={false}- />- )}- </Fragment>- );- })}- </SortableBranch>- );- })}- </SortableContext>- </DndContext>+ />+ {expanded &&+ agentsInRoom.map((entry) => {+ const agentSessionsHere = roomSessions.filter(+ (session) => bySession.get(session.data.id)?.agent.id === entry.agent.id+ );+ return (+ <Fragment key={entry.agent.id}>+ <SidebarAgentItem agent={entry.agent} depth={1} />+ {agentSessionsHere.map((session) => (+ <SidebarSessionItem+ key={session.data.id}+ locationId={entry.agent.locationId}+ sessionId={session.data.id}+ depth={2}+ />+ ))}+ </Fragment>+ );+ })}+ </div>+ );+ })}+ </>);});diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsxindex a70f62139..3b8f9cda1 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsx@@ -14,11 +14,6 @@ export function sessionRoomId(session: SessionStore): string | null {return roomConnectionsStore.roomForSession(session.data.id);}-/** Whether a session was launched as a subagent (it nests under the subagent row). */-export function isSubagentSession(session: SessionStore): boolean {- return 'subagentName' in session.data && !!session.data.subagentName;-}-export function roomLabel(roomKey: string): string {if (roomKey === UNASSIGNED_ROOM_KEY) return 'Unassigned';return switchRoomsStore.roomNameById(roomKey) ?? `Room ${roomKey.slice(0, 8)}`;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 1fa4396c2..d362fae5f 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-store.ts+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-store.ts@@ -11,6 +11,7 @@ import {import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';import type { Snapshottable } from '@renderer/lib/stores/snapshottable';import type { AgentConnectionKind } from '@shared/core/agents/agent-connection';+import { representativeAgent } from '@shared/core/agents/agents';import {AGENT_PROVIDER_IDS,isValidProviderId,@@ -206,9 +207,10 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {});}- /** The parent agent of a location (the agent shown on its sidebar row). */+ /** The representative agent of a location (the agent shown on its sidebar row):+ * the first real (non-definition) agent, not a former subagent's row. */private parentAgent(locationId: string) {- return agentsStore.byLocation.get(locationId)?.[0];+ return representativeAgent(agentsStore.byLocation.get(locationId) ?? []);}/** Where a location runs — `remote` when it has an SSH host, else `local`. */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.tsxdeleted file mode 100644index a905225d3..000000000--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-subagent-list.tsx+++ /dev/null@@ -1,275 +0,0 @@-import { useQuery } from '@tanstack/react-query';-import { Bot, ChevronRight, Plus } from 'lucide-react';-import { observer } from 'mobx-react-lite';-import type { SessionStore } from '@renderer/features/sessions/stores/session-store';-import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';-import { AgentIcon } from '@renderer/lib/components/agent-icon';-import { rpc } from '@renderer/lib/ipc';-import {- useNavigate,- useParams,- useWorkspaceSlots,-} from '@renderer/lib/layout/navigation-provider';-import { useShowModal } from '@renderer/lib/modal/modal-provider';-import { sidebarStore } from '@renderer/lib/stores/app-state';-import { useAgent } from '@renderer/lib/stores/use-agents';-import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';-import { cn } from '@renderer/utils/utils';-import { SidebarSessionItem } from './session-item';-import { SidebarItemMiniButton, SidebarMenuRow } from './sidebar-primitives';-import {- groupByRoom,- openRoomInGateway,- openRoomInMessagingApp,- RoomRow,- roomLabel,-} from './sidebar-room-grouping';-import { depthIndent, UNASSIGNED_ROOM_KEY } from './sidebar-store';--/** The subagent a session was launched as, if any. */-function subagentNameOf(session: SessionStore): string | undefined {- return 'subagentName' in session.data ? session.data.subagentName : undefined;-}--/** Expand-state key for a subagent row (its sessions live underneath). */-function subagentKey(locationId: string, name: string): string {- return `sa:${locationId}|${name}`;-}--/** Expand-state key for a room nested under a subagent. */-function subagentRoomKey(locationId: string, name: string, roomKey: string): string {- return `sar:${locationId}|${name}|${roomKey}`;-}--/**- * 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 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({- locationId,- sessions = [],- depth = 1,- onlyWithSessions = false,- groupSessionsByRoom = true,-}: {- locationId: string;- sessions?: SessionStore[];- /** Tree depth of the subagent rows; their rooms/sessions nest below it. */- depth?: number;- /** Only render subagents that have a session in `sessions` (room-focused- * view), instead of every discovered subagent. */- onlyWithSessions?: boolean;- /** Group each subagent's sessions by room (agent-focused view). When false,- * list them flat — used in the room-focused view, where the room is already- * the grouping. */- groupSessionsByRoom?: boolean;-}) {- const showCreateSessionModal = useShowModal('sessionModal');- const { navigate } = useNavigate();- const { currentView } = useWorkspaceSlots();- const { params: locationParams } = useParams('location');- const activeSubagent =- currentView === 'location' && locationParams.locationId === locationId- ? locationParams.subagentName- : undefined;-- const agentQuery = useQuery({- queryKey: ['locationAgent', locationId],- queryFn: async () => (await rpc.agents.getAgents(locationId))[0] ?? null,- enabled: !!locationId,- });- const agent = agentQuery.data ?? null;-- // Only agent types with a subagents capability discover/launch subagents.- const { data: providerMeta } = useAgent(agent?.providerId ?? '');- const supportsSubagents = !!agent && providerMeta?.capabilities.subagents.kind !== 'none';-- const subagentsQuery = useQuery({- queryKey: ['subagents', agent?.id],- queryFn: () => rpc.subagents.list(agent!.id),- enabled: !!agent && supportsSubagents,- });- const discovered = subagentsQuery.data?.subagents ?? [];-- // 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);- if (!name) continue;- const list = sessionsByName.get(name);- if (list) list.push(session);- else sessionsByName.set(name, [session]);- }-- const discoveredByName = new Map(discovered.map((s) => [s.name, s]));- const names = onlyWithSessions- ? // Room-focused view: only subagents with a session in this room.- [...sessionsByName.keys()]- : // Agent-focused view: every discovered subagent, plus any that still have- // sessions but are no longer discovered (creds/definition removed) so- // their runs are never orphaned.- [- ...discovered.map((s) => s.name),- ...[...sessionsByName.keys()].filter((name) => !discoveredByName.has(name)),- ];-- if (!supportsSubagents || names.length === 0) return null;-- return (- <>- {names.map((name) => {- const subagent = discoveredByName.get(name) ?? null;- const subSessions = sessionsByName.get(name) ?? [];- const expanded = sidebarStore.isGroupExpanded(subagentKey(locationId, name));- const toggle = () => sidebarStore.toggleGroupExpanded(subagentKey(locationId, name));- const isActive = activeSubagent === name;- const open = () => navigate('location', { locationId, subagentName: name });- return (- <div key={name}>- <SidebarMenuRow- className="group/row flex h-8 justify-between px-1"- style={depthIndent(depth)}- data-active={isActive || undefined}- isActive={isActive}- onMouseDown={(e) => e.preventDefault()}- onClick={open}- >- <div className="flex min-w-0 flex-1 items-center gap-1">- <SidebarItemMiniButton- type="button"- aria-label={`${expanded ? 'Collapse' : 'Expand'} ${name}`}- className="relative"- onClick={(e) => {- e.stopPropagation();- toggle();- }}- >- {/* A subagent's type is always its parent's, so it shows the- parent agent's icon (falling back until the parent loads). */}- {agent ? (- <AgentIcon- id={agent.providerId}- size={16}- className="absolute h-4 w-4 opacity-100 transition-opacity duration-150 group-hover/row:opacity-0"- />- ) : (- <Bot className="absolute h-4 w-4 opacity-100 transition-opacity duration-150 group-hover/row:opacity-0" />- )}- <ChevronRight- className={cn(- 'absolute h-4 w-4 opacity-0 transition-all duration-150 group-hover/row:opacity-100',- expanded && 'rotate-90'- )}- />- </SidebarItemMiniButton>- <span- className="min-w-0 flex-1 truncate text-sm"- title={subagent?.description ?? undefined}- >- {name}- </span>- {subagent?.registered === false && (- <Tooltip>- <TooltipTrigger- render={- <span className="shrink-0 rounded bg-amber-500/15 px-1 text-[10px] text-amber-600 dark:text-amber-400">- local- </span>- }- />- <TooltipContent>- Discovered locally but not registered on the Switch server.- </TooltipContent>- </Tooltip>- )}- </div>- <Tooltip>- <TooltipTrigger- className="h-6"- render={- <SidebarItemMiniButton- type="button"- aria-label={`New session as ${name}`}- className="opacity-0 transition-opacity duration-150 group-hover/row:opacity-100"- onClick={(e) => {- e.stopPropagation();- showCreateSessionModal({ locationId, subagentName: name });- }}- >- <Plus className="h-4 w-4" />- </SidebarItemMiniButton>- }- />- <TooltipContent>New session as {name}</TooltipContent>- </Tooltip>- </SidebarMenuRow>- {expanded &&- !groupSessionsByRoom &&- subSessions.map((session) => (- <SidebarSessionItem- key={session.data.id}- locationId={locationId}- sessionId={session.data.id}- depth={depth + 1}- />- ))}- {expanded &&- groupSessionsByRoom &&- groupByRoom(subSessions).map(([roomKey, roomSessions]) => {- // Sessions with no room sit at the same depth as the subagent's- // room rows — direct children of the subagent, just without a- // room header above them.- if (roomKey === UNASSIGNED_ROOM_KEY) {- return roomSessions.map((session) => (- <SidebarSessionItem- key={session.data.id}- locationId={locationId}- sessionId={session.data.id}- depth={depth + 1}- />- ));- }- const groupKey = subagentRoomKey(locationId, name, roomKey);- const roomExpanded = sidebarStore.isGroupExpanded(groupKey);- return (- <div key={roomKey}>- <RoomRow- label={roomLabel(roomKey)}- count={roomSessions.length}- expanded={roomExpanded}- depth={depth + 1}- bridgeType={switchRoomsStore.roomBridgeTypeById(roomKey)}- onToggle={() => sidebarStore.toggleGroupExpanded(groupKey)}- onOpenGateway={() => openRoomInGateway(roomKey)}- onOpenChannel={- switchRoomsStore.roomChannelUrl(roomKey)- ? () => openRoomInMessagingApp(roomKey)- : null- }- />- {roomExpanded &&- roomSessions.map((session) => (- <SidebarSessionItem- key={session.data.id}- locationId={locationId}- sessionId={session.data.id}- depth={depth + 2}- />- ))}- </div>- );- })}- </div>- );- })}- </>- );-});diff --git a/dash/apps/switchdash-desktop/src/shared/core/agents/agents.ts b/dash/apps/switchdash-desktop/src/shared/core/agents/agents.tsindex 7c8a90d36..bae321a39 100644--- a/dash/apps/switchdash-desktop/src/shared/core/agents/agents.ts+++ b/dash/apps/switchdash-desktop/src/shared/core/agents/agents.ts@@ -14,6 +14,10 @@ export type Agent = {locationId: string;name: string;providerId: AgentProviderId;+ /** The provider-level definition this agent launches as (e.g. a Claude Code+ * subagent — the `.claude/agents/<name>.md` stem, passed as `--agent <name>`),+ * or null for a plain agent with no definition. */+ definitionName: string | null;switchAgentId: string | null;apiEndpoint: string | null;serverId: string | null;@@ -26,11 +30,31 @@ export type Agent = {updatedAt: string;};+/** True for an agent that launches as a provider definition (a former subagent). */+export function isDefinitionAgent(agent: Pick<Agent, 'definitionName'>): boolean {+ return agent.definitionName != null;+}++/**+ * The agent that represents a location in single-agent UI surfaces (the sidebar+ * location row, a location's settings target): the first non-definition ("real")+ * agent, falling back to the first agent. Keeps a former subagent's agent row+ * from being mistaken for the location's primary agent (CHOO-1440).+ */+export function representativeAgent<T extends Pick<Agent, 'definitionName'>>(+ agents: readonly T[]+): T | undefined {+ return agents.find((a) => a.definitionName == null) ?? agents[0];+}+export type CreateAgentParams = {id: string;locationId: string;name: string;providerId: AgentProviderId;+ /** The provider-level definition to launch as (`--agent <name>`), or null for+ * a plain agent. */+ definitionName?: string | null;switchAgentId: string | null;apiEndpoint: string | null;/** The Switch server this agent belongs to. Every agent must have one — it isdiff --git a/dash/apps/switchdash-desktop/src/shared/core/providers/agent-payload.ts b/dash/apps/switchdash-desktop/src/shared/core/providers/agent-payload.tsindex ed8bccde7..66da0ca4d 100644--- a/dash/apps/switchdash-desktop/src/shared/core/providers/agent-payload.ts+++ b/dash/apps/switchdash-desktop/src/shared/core/providers/agent-payload.ts@@ -168,7 +168,7 @@ export type AgentCapabilities = {hooks: { kind: string; scope?: string };mcp: { kind: string };plugins: { kind: string };- subagents: { kind: string };+ repoAgents: { kind: string };switchSetup: { kind: string };};diff --git a/dash/apps/switchdash-desktop/src/shared/core/sessions/session-config.ts b/dash/apps/switchdash-desktop/src/shared/core/sessions/session-config.tsindex 6b3f12f60..0919a1a45 100644--- a/dash/apps/switchdash-desktop/src/shared/core/sessions/session-config.ts+++ b/dash/apps/switchdash-desktop/src/shared/core/sessions/session-config.ts@@ -14,12 +14,17 @@ const sessionConfigV0Schema = z.object({/** Initial prompt to deliver on the first spawn; cleared from config after the session starts. */initialPrompt: z.string().optional(),/**- * When set, this session runs as a Claude Code subagent of its (parent) agent:- * the CLI is launched with `--agent <subagentName>` and the subagent's own- * Switch credentials file, so it participates in rooms under the subagent's- * identity. The value is the bare subagent name (the `.claude/agents/<name>.md`- * file stem), which also names its `.claude/switch-subagents/<name>.settings.json`.+ * When set, this session runs as the repository-defined agent of this name: the+ * provider launches its CLI to run as that agent (Claude Code → `--agent <name>`)+ * with the agent's own Switch credentials, so it joins rooms under that identity.+ * The value is the agent's definition name (its `.switch/agents/<name>.json`+ * credentials key). switchdash has no "subagent" concept — how the provider runs+ * a named agent is the provider's business (CHOO-1440).*/+ agentName: z.string().optional(),+ /** Legacy key for {@link agentName}, kept so sessions persisted before the+ * rename still resolve their identity after an upgrade; coalesced into+ * `agentName` when read (CHOO-1440). */subagentName: z.string().optional(),});diff --git a/dash/apps/switchdash-desktop/src/shared/core/sessions/sessions.ts b/dash/apps/switchdash-desktop/src/shared/core/sessions/sessions.tsindex 77302fb62..a441e8fa1 100644--- a/dash/apps/switchdash-desktop/src/shared/core/sessions/sessions.ts+++ b/dash/apps/switchdash-desktop/src/shared/core/sessions/sessions.ts@@ -49,7 +49,7 @@ export type Session = {lastInteractedAt?: string;autoApprove?: boolean;/** Set when this session runs as a Claude Code subagent of its agent. */- subagentName?: string;+ agentName?: string;createdAt: string;updatedAt: string;};@@ -70,11 +70,11 @@ export type CreateSessionParams = {initialSize?: { cols: number; rows: number };/*** Run this session as a Claude Code subagent of `agentId`: launches the CLI- * with `--agent <subagentName>` and the subagent's own Switch credentials, so+ * with `--agent <agentName>` and the subagent's own Switch credentials, so* it joins rooms under the subagent's identity. The session is still owned by* the parent `agentId` (it runs in the parent's working directory).*/- subagentName?: string;+ agentName?: string;};export type CreateSessionError =diff --git a/dash/apps/switchdash-desktop/src/shared/core/subagents/subagents.ts b/dash/apps/switchdash-desktop/src/shared/core/subagents/subagents.tsdeleted file mode 100644index 241d56739..000000000--- a/dash/apps/switchdash-desktop/src/shared/core/subagents/subagents.ts+++ /dev/null@@ -1,48 +0,0 @@-/**- * A Claude Code subagent of a parent Switch agent. Subagents are defined as- * `.claude/agents/<name>.md` files in the parent's working directory and, once- * brought into Switch by the connector `configure` skill, registered on the- * gateway as child agents with their own credentials written to- * `.claude/switch-subagents/<name>.settings.json`.- *- * switchdash discovers them from those credential files (the launchable set) and- * reconciles against the gateway's children of the parent. A subagent is not a- * switchdash `agent` row of its own — sessions started "as a subagent" are owned- * by the parent agent and carry the subagent name in their config.- */-export type Subagent = {- /** switchdash id of the parent agent. */- parentAgentId: string;- /** Bare subagent name — the `.md` file stem and the `--agent` value. */- name: string;- description: string | null;- model: string | null;- /** The subagent's own Switch agent id, read from its credentials file. */- switchAgentId: string | null;- apiEndpoint: string | null;- /** Switch server the subagent belongs to (its parent's server). */- serverId: string | null;- /**- * Whether the gateway lists this subagent as a child of the parent. `null`- * when reconciliation could not run (parent has no linked server, or the app- * is not signed in to it) — discovery still returns the local subagent.- */- registered: boolean | null;-};--/** A gateway child agent of the parent with no matching local credentials file. */-export type RemoteOnlySubagent = {- /** Display name (the parent-name prefix stripped). */- name: string;- switchAgentId: string;-};--export type SubagentListResult = {- parentAgentId: string;- /** Subagents discovered locally, reconciled against the gateway when possible. */- subagents: Subagent[];- /** Gateway children of the parent with no local credentials file (drift). */- remoteOnly: RemoteOnlySubagent[];- /** Whether gateway reconciliation ran. When false, every `registered` is null. */- reconciled: boolean;-};diff --git a/dash/apps/switchdash-desktop/src/sidecar/index.ts b/dash/apps/switchdash-desktop/src/sidecar/index.tsindex 57f2996ff..6d469b4dd 100644--- a/dash/apps/switchdash-desktop/src/sidecar/index.ts+++ b/dash/apps/switchdash-desktop/src/sidecar/index.ts@@ -3,12 +3,22 @@ import { readFile } from 'node:fs/promises';import path from 'node:path';import { promisify } from 'node:util';import { HookEventLog, HookServer } from '@main/core/agent-hooks/hook-server';-import { readSwitchAgentCredentials } from '@main/core/switch-rooms/switch-credentials';+import { agentSettingsPath } from '@main/core/agents/switch-settings-paths';+import {+ readSwitchAgentCredentials,+ readSwitchAgentCredentialsFromSettings,+} from '@main/core/switch-rooms/switch-credentials';import { createTmuxRun } from '@main/core/switch-rooms/tmux-injection-sink';import { type AgentLaunchSpec } from './agent-launch-spec';import { NotificationWatcher } from './notification-watcher';import { InProcessSessionSpawner } from './session-spawner';import { createSidecarLogger, requireEnv } from './sidecar-logger';+import {+ LEGACY_LAUNCH_SPEC_REL_PATH,+ LEGACY_WATCH_ENABLED_REL_PATH,+ sidecarLaunchSpecRelPath,+ sidecarWatchEnabledRelPath,+} from './sidecar-paths';import { defaultRoomConnectionFactory, SidecarRuntime } from './sidecar-runtime';import { exactTmuxTarget, parseAgentTmuxSessionName } from './vm-tmux';@@ -28,20 +38,21 @@ import { exactTmuxTarget, parseAgentTmuxSessionName } from './vm-tmux';* with no live session.** Pure Node (no Electron, no database). The agent's Switch credentials come from- * its `.claude/settings.local.json`; the provider-specific launch recipe for- * auto-started sessions comes from the launch spec switchdash writes to the VM.+ * its provider-neutral per-agent file `.switch/agents/<slug>.json` (the slug is+ * passed in `SWITCHDASH_SIDECAR_AGENT_SLUG`), falling back to the legacy shared+ * `.claude/settings.local.json` for un-migrated installs (CHOO-1440); the+ * provider-specific launch recipe for auto-started sessions comes from the launch+ * spec switchdash writes to the VM.* On startup it prints one JSON line to stdout — `{event:"ready",port,token}` —* so the launcher can point switchdash's remote sessions at this hook server.*/const PANE_POLL_INTERVAL_MS = 2000;-const LAUNCH_SPEC_REL_PATH = '.switchdash/agent-launch-spec.json';-const WATCH_ENABLED_REL_PATH = '.switchdash/watch-enabled';const execFileAsync = promisify(execFile);-async function readLaunchSpec(repoDir: string): Promise<AgentLaunchSpec> {- const specPath = path.join(repoDir, LAUNCH_SPEC_REL_PATH);+async function readLaunchSpec(repoDir: string, specRelPath: string): Promise<AgentLaunchSpec> {+ const specPath = path.join(repoDir, specRelPath);let raw: string;try {raw = await readFile(specPath, 'utf8');@@ -61,13 +72,30 @@ async function main(): Promise<void> {const repoDir = requireEnv('SWITCHDASH_SIDECAR_REPO_DIR');const deeplinkScheme = process.env.SWITCHDASH_SIDECAR_DEEPLINK_SCHEME?.trim() || 'switchdash';- const creds = await readSwitchAgentCredentials(repoDir, log);+ // Prefer the agent's provider-neutral per-agent creds file; fall back to the+ // legacy shared settings.local.json for un-migrated installs (CHOO-1440).+ const credsSlug = process.env.SWITCHDASH_SIDECAR_AGENT_SLUG?.trim();+ const creds =+ (credsSlug+ ? await readSwitchAgentCredentialsFromSettings(agentSettingsPath(repoDir, credsSlug), log)+ : null) ?? (await readSwitchAgentCredentials(repoDir, log));if (!creds) {- throw new Error(- `sidecar: no Switch credentials in ${repoDir}/.claude/settings.local.json — run remote setup first`- );+ const where = credsSlug+ ? agentSettingsPath(repoDir, credsSlug)+ : `${repoDir}/.claude/settings.local.json`;+ throw new Error(`sidecar: no Switch credentials at ${where} — run remote setup first`);}- const launchSpec = await readLaunchSpec(repoDir);++ // Per-agent state paths, so multiple agents in one repo dir each drive their+ // own sidecar without clobbering each other's spec/watch flag (CHOO-1440).+ // Fall back to the legacy shared paths when launched without a slug.+ const launchSpecRel = credsSlug+ ? sidecarLaunchSpecRelPath(credsSlug)+ : LEGACY_LAUNCH_SPEC_REL_PATH;+ const watchEnabledRel = credsSlug+ ? sidecarWatchEnabledRelPath(credsSlug)+ : LEGACY_WATCH_ENABLED_REL_PATH;+ const launchSpec = await readLaunchSpec(repoDir, launchSpecRel);// Pane-liveness cache: a background poll marks each active/pending tmux target// live or dead so injection defers (rather than fails) when a pane is briefly@@ -180,6 +208,11 @@ async function main(): Promise<void> {hookPort: server.getPort(),hookToken: server.getToken(),runtime,+ switchEnv: {+ SWITCH_API_ENDPOINT: creds.apiEndpoint,+ SWITCH_API_TOKEN: creds.token,+ SWITCH_AGENT_ID: creds.agentId,+ },isPaneLive,log,});@@ -192,7 +225,7 @@ async function main(): Promise<void> {let watchEnabled = false;const refreshWatchEnabled = async (): Promise<void> => {try {- const raw = await readFile(path.join(repoDir, WATCH_ENABLED_REL_PATH), 'utf8');+ const raw = await readFile(path.join(repoDir, watchEnabledRel), 'utf8');watchEnabled = raw.trim() === '1';} catch {watchEnabled = false;@@ -207,7 +240,7 @@ async function main(): Promise<void> {const refreshLaunchSpec = async (): Promise<void> => {let spec: AgentLaunchSpec;try {- spec = await readLaunchSpec(repoDir);+ spec = await readLaunchSpec(repoDir, launchSpecRel);} catch (error) {log.warn('sidecar: failed to re-read launch spec; keeping current', {error: String(error),diff --git a/dash/apps/switchdash-desktop/src/sidecar/session-spawner.test.ts b/dash/apps/switchdash-desktop/src/sidecar/session-spawner.test.tsindex 1f20b6bef..eb0acf606 100644--- a/dash/apps/switchdash-desktop/src/sidecar/session-spawner.test.ts+++ b/dash/apps/switchdash-desktop/src/sidecar/session-spawner.test.ts@@ -35,6 +35,11 @@ function makeSpawner(over: Partial<InProcessSessionSpawnerDeps> = {}) {hookPort: 4321,hookToken: 'hooktok',runtime,+ switchEnv: {+ SWITCH_API_ENDPOINT: 'https://switch.example.com',+ SWITCH_API_TOKEN: 'tok',+ SWITCH_AGENT_ID: 'agent-1',+ },isPaneLive: () => true,log: silentLog,exec,@@ -54,6 +59,10 @@ describe('InProcessSessionSpawner.launch', () => {expect(inner).toContain("SWITCHDASH_HOOK_PORT='4321'");expect(inner).toContain("SWITCHDASH_HOOK_TOKEN='hooktok'");expect(inner).toContain("SWITCH_CHANNEL_DISABLE_POLL='1'");+ // The agent's identity is injected so the auto-started session authenticates+ // as this agent (CHOO-1440).+ expect(inner).toContain("SWITCH_API_ENDPOINT='https://switch.example.com'");+ expect(inner).toContain("SWITCH_AGENT_ID='agent-1'");expect(inner).toContain('connect to switch room room-x');expect(inner).not.toContain(SESSION_ID_PLACEHOLDER);expect(inner).not.toContain(INITIAL_PROMPT_PLACEHOLDER);diff --git a/dash/apps/switchdash-desktop/src/sidecar/session-spawner.ts b/dash/apps/switchdash-desktop/src/sidecar/session-spawner.tsindex 5658b4fdb..32a9a519e 100644--- a/dash/apps/switchdash-desktop/src/sidecar/session-spawner.ts+++ b/dash/apps/switchdash-desktop/src/sidecar/session-spawner.ts@@ -21,6 +21,10 @@ export interface InProcessSessionSpawnerDeps {hookToken: string;/** The multi-session runtime — a room it already serves needs no new session. */runtime: RoomLivenessSource;+ /** The agent's Switch identity as `SWITCH_*` env, injected into every+ * auto-started session so it authenticates as this agent — a `--settings` env+ * block is not reliably propagated to the spawned MCP server (CHOO-1440). */+ switchEnv: Record<string, string>;/** Whether a given tmux target is currently live (poller-backed cache). */isPaneLive: (tmuxTarget: string) => boolean;log: WatcherLogger;@@ -125,6 +129,7 @@ export class InProcessSessionSpawner implements SessionSpawner {const tmuxTarget = makeAgentTmuxSessionName(sessionId);const hookEnv = {+ ...this.deps.switchEnv,SWITCHDASH_HOOK_PORT: String(hookPort),SWITCHDASH_PTY_ID: makePtyId(spec.providerId, sessionId),SWITCHDASH_HOOK_TOKEN: hookToken,diff --git a/dash/apps/switchdash-desktop/src/sidecar/sidecar-paths.ts b/dash/apps/switchdash-desktop/src/sidecar/sidecar-paths.tsnew file mode 100644index 000000000..5e2f2b3e0--- /dev/null+++ b/dash/apps/switchdash-desktop/src/sidecar/sidecar-paths.ts@@ -0,0 +1,43 @@+/**+ * On-VM layout of the switchdash sidecar's files, relative to an agent's remote+ * repo dir. Shared by the launcher (main process) and the sidecar bundle so both+ * agree on where each file lives.+ *+ * The bundle is shared per directory (identical bytes — deduped on upload), but+ * every piece of per-agent STATE is keyed by the agent's creds slug so multiple+ * agents in one directory each get their own sidecar without clobbering each+ * other's launch spec, watch flag, ready file, or log (CHOO-1440). POSIX+ * separators — the host is always POSIX.+ */++export const SIDECAR_DIR = '.switchdash';++/** Shared sidecar bundle + its hash (identical for every agent in the dir). */+export const SIDECAR_BUNDLE_REL_PATH = `${SIDECAR_DIR}/sidecar.mjs`;+export const SIDECAR_BUNDLE_HASH_REL_PATH = `${SIDECAR_DIR}/sidecar.mjs.sha256`;++/** Per-agent state directory, keyed by the creds slug (definition name / id). */+export function sidecarAgentDir(slug: string): string {+ return `${SIDECAR_DIR}/agents/${slug}`;+}++export function sidecarLaunchSpecRelPath(slug: string): string {+ return `${sidecarAgentDir(slug)}/agent-launch-spec.json`;+}++export function sidecarWatchEnabledRelPath(slug: string): string {+ return `${sidecarAgentDir(slug)}/watch-enabled`;+}++export function sidecarReadyRelPath(slug: string): string {+ return `${sidecarAgentDir(slug)}/sidecar.ready`;+}++export function sidecarLogRelPath(slug: string): string {+ return `${sidecarAgentDir(slug)}/sidecar.log`;+}++/** Legacy pre-CHOO-1440 shared (per-dir) state paths, kept as a fallback for a+ * sidecar started without an agent slug. */+export const LEGACY_LAUNCH_SPEC_REL_PATH = `${SIDECAR_DIR}/agent-launch-spec.json`;+export const LEGACY_WATCH_ENABLED_REL_PATH = `${SIDECAR_DIR}/watch-enabled`;diff --git a/dash/packages/core/src/agents/plugins/capabilities/prompt.ts b/dash/packages/core/src/agents/plugins/capabilities/prompt.tsindex 47c42adef..815a1aad3 100644--- a/dash/packages/core/src/agents/plugins/capabilities/prompt.ts+++ b/dash/packages/core/src/agents/plugins/capabilities/prompt.ts@@ -4,6 +4,13 @@ import { definePluginCapability } from '../../../lib/plugins/capability';export type CommandContext = {cli: string; // absolute path to the cli binaryextraArgs?: string[]; // user-configured in settings+ /**+ * Provider-produced args that run the CLI as a specific named agent (from the+ * repo-agents capability's `launchArgs`), e.g. Claude's `--agent <name>+ * --settings <creds>`. Kept distinct from user `extraArgs`: switchdash asks the+ * provider how to run agent <name>, and the provider owns the answer (CHOO-1440).+ */+ agentArgs?: string[];autoApprove: boolean;initialPrompt?: string;/** Switchdash session UUID — used as the session token for providers that track theirdiff --git a/dash/packages/core/src/agents/plugins/capabilities/repo-agents.ts b/dash/packages/core/src/agents/plugins/capabilities/repo-agents.tsnew file mode 100644index 000000000..7e027798e--- /dev/null+++ b/dash/packages/core/src/agents/plugins/capabilities/repo-agents.ts@@ -0,0 +1,150 @@+import z from 'zod';+import { definePluginCapability } from '../../../lib/plugins/capability';+import type { PluginFs } from '../../runtime/fs';++/**+ * A repository-defined agent the provider can run, discovered locally from its+ * on-disk credentials/definition files (before gateway reconciliation).+ */+export type LocalRepoAgent = {+ name: string;+ description: string | null;+ model: string | null;+ switchAgentId: string | null;+ apiEndpoint: string | null;+};++/**+ * An agent definition discovered in a working directory, with whether it can join+ * Switch (`eligible`) and whether it already carries Switch credentials+ * (`registered`). Used by the Add Agent modal to offer onboarding a directory's+ * existing agents.+ */+export type RepoAgentDefinition = {+ name: string;+ description: string | null;+ model: string | null;+ eligible: boolean;+ registered: boolean;+};++/** Credentials written for an agent so its sessions act under its own identity. */+export type RepoAgentCredentials = {+ agentName: string;+ apiEndpoint: string;+ apiToken: string;+ agentId: string;+};++/**+ * The MCP permission rules that keep a Switch agent connected to the platform:+ * the connector's two MCP servers. Used both as `tools` allowlist entries (so an+ * agent that restricts its tools stays Switch-capable) and as `permissions.allow`+ * entries (so the connector's tools are auto-approved — "don't ask"). Authored+ * once here so every provider's onboarding path agrees.+ */+export const SWITCH_CONNECTOR_TOOL_RULES = [+ 'mcp__plugin_switch-connector_switch',+ 'mcp__plugin_switch-connector_switch-channel',+] as const;++/**+ * Provider-neutral directory (relative to a location's working directory) for+ * per-agent Switch credentials. One `<name>.json` per agent, keeping the store+ * out of any single provider's config tree (CHOO-1440). POSIX separator so it is+ * stable across local and SFTP filesystems.+ */+export const SWITCH_AGENT_SETTINGS_DIR = '.switch/agents';++/** A renderable input type for an agent attribute field. */+export type RepoAgentFieldType = 'text' | 'textarea' | 'select' | 'list' | 'number' | 'boolean';++export type RepoAgentFieldOption = { value: string; label: string };++/**+ * One editable attribute of an agent, declared by the agent provider. The+ * renderer builds the create/edit form from these descriptors, so the set of+ * attributes — and how they are presented — is provider-specific. `key` is the+ * attribute name in the {@link RepoAgentAttributes} map the provider serializes.+ */+export type RepoAgentField = {+ key: string;+ label: string;+ type: RepoAgentFieldType;+ required?: boolean;+ /** Fixed once the agent exists (e.g. the name, which is its identity). */+ immutableOnEdit?: boolean;+ placeholder?: string;+ help?: string;+ /** Choices for `select`. Include an empty-value option to mean "unset". */+ options?: RepoAgentFieldOption[];+};++/** A single attribute value; shape depends on the field's `type`. */+export type RepoAgentAttributeValue = string | string[] | number | boolean | null;++/** An agent's attributes, keyed by {@link RepoAgentField.key}. Always carries+ * `name` and `description`; the rest are provider-defined. */+export type RepoAgentAttributes = Record<string, RepoAgentAttributeValue>;++/**+ * How an agent provider creates, runs, and credentials the named agents defined+ * in a working directory. Switchdash has no notion of "subagents" — it just asks+ * a provider to create and run an agent with a given name in a directory, and to+ * support several such agents in one directory. HOW the provider does that (Claude+ * Code uses subagents; another provider might use something else) is entirely the+ * provider's business and lives behind this behavior; the main process supplies a+ * `PluginFs` for the IO and owns the provider-neutral gateway reconciliation.+ *+ * `workspaceFs` is rooted at the agent's working directory; `homeFs` at the user's+ * home — definitions may resolve in either scope.+ */+export type IRepoAgentsBehavior = {+ /** Runnable agents, from the working dir's on-disk credentials + definitions. */+ discoverLocal(workspaceFs: PluginFs, homeFs: PluginFs): Promise<LocalRepoAgent[]>;+ /** Agent definitions in the working dir, for onboarding (project scope). */+ discoverDefinitions(workspaceFs: PluginFs): Promise<RepoAgentDefinition[]>;+ /** Provider-specific CLI args that run the CLI as the named agent. Pure — the+ * caller passes them to `buildCommand` as `agentArgs` (not user extra args). */+ launchArgs(workingDir: string, agentName: string): string[];+ /** The named agent's Switch credentials as env vars, for the launched session. */+ readLaunchEnv(workspaceFs: PluginFs, agentName: string): Promise<Record<string, string>>;+ /** Write a named agent's credentials so it is immediately runnable. */+ writeCredentials(workspaceFs: PluginFs, credentials: RepoAgentCredentials): Promise<void>;+ /** The attribute fields this provider supports, in display order. Drives the+ * create/edit form; the first two are always `name` and `description`. */+ attributeFields(): RepoAgentField[];+ /** Create or overwrite a named agent's on-disk definition from its attributes+ * (workspace scope). `attributes.name` selects the agent. */+ writeDefinition(workspaceFs: PluginFs, attributes: RepoAgentAttributes): Promise<void>;+ /** The current attribute values for an existing agent definition, keyed to+ * {@link attributeFields}, or null if no definition exists. */+ readDefinition(workspaceFs: PluginFs, name: string): Promise<RepoAgentAttributes | null>;+ /** Remove a named agent's definition and credentials files (workspace scope). */+ removeLocal(workspaceFs: PluginFs, name: string): Promise<void>;+};++/**+ * kind: 'definitions' — the provider supports repository-defined named agents+ * (e.g. Claude Code implements this with its subagents: `.md` definitions under+ * `definitionsDirRelative`, launched with `--agent`/`--settings`).+ * kind: 'none' — the provider has no repository-agent concept; the UI surfaces+ * nothing beyond a single default agent.+ */+export const repoAgentsCapability = definePluginCapability<IRepoAgentsBehavior>()(+ 'repo-agents',+ z.discriminatedUnion('kind', [+ z.object({+ kind: z.literal('definitions'),+ /** Credentials dir, relative to the working dir, e.g. '.claude/switch-subagents'. */+ dirRelative: z.string(),+ /** Credentials filename suffix, e.g. '.settings.json'. */+ settingsSuffix: z.string(),+ /** Definitions dir, relative to the working dir, e.g. '.claude/agents'. */+ definitionsDirRelative: z.string(),+ }),+ z.object({ kind: z.literal('none') }),+ ])+);++export type RepoAgentsDescriptor = (typeof repoAgentsCapability)['_descriptor'];diff --git a/dash/packages/core/src/agents/plugins/capabilities/subagents.ts b/dash/packages/core/src/agents/plugins/capabilities/subagents.tsdeleted file mode 100644index 32f3b719c..000000000--- a/dash/packages/core/src/agents/plugins/capabilities/subagents.ts+++ /dev/null@@ -1,141 +0,0 @@-import z from 'zod';-import { definePluginCapability } from '../../../lib/plugins/capability';-import type { PluginFs } from '../../runtime/fs';--/**- * A subagent the parent can launch, discovered locally from the parent's- * credentials/definition files (before gateway reconciliation).- */-export type LocalSubagent = {- name: string;- description: string | null;- model: string | null;- switchAgentId: string | null;- apiEndpoint: string | null;-};--/**- * A subagent definition discovered in the parent's working directory, with- * whether it can join Switch (`eligible`) and whether it's already been brought- * into Switch (`registered`). Used by the Add Agent modal to offer onboarding the- * directory's subagents alongside the parent.- */-export type SubagentDefinition = {- name: string;- description: string | null;- model: string | null;- eligible: boolean;- registered: boolean;-};--/** Credentials written for a subagent so its sessions act under its own identity. */-export type SubagentCredentials = {- subagentName: string;- apiEndpoint: string;- apiToken: string;- agentId: string;-};--/**- * The MCP permission rules that keep a Switch agent (or subagent) connected to- * the platform: the connector's two MCP servers. Used both as `tools` allowlist- * entries (so a subagent that restricts its tools stays Switch-capable) and as- * `permissions.allow` entries (so the connector's tools are auto-approved —- * "don't ask"). Authored once here so the parent-onboarding and subagent paths- * agree.- */-export const SWITCH_CONNECTOR_TOOL_RULES = [- 'mcp__plugin_switch-connector_switch',- 'mcp__plugin_switch-connector_switch-channel',-] as const;--/** A renderable input type for a subagent attribute field. */-export type SubagentFieldType = 'text' | 'textarea' | 'select' | 'list' | 'number' | 'boolean';--export type SubagentFieldOption = { value: string; label: string };--/**- * One editable attribute of a subagent, declared by the agent type. The renderer- * builds the create/edit form from these descriptors, so the set of attributes- * — and how they are presented — is provider-specific. `key` is the attribute- * name in the {@link SubagentAttributes} map the provider serializes.- */-export type SubagentField = {- key: string;- label: string;- type: SubagentFieldType;- required?: boolean;- /** Fixed once the subagent exists (e.g. the name, which is its identity). */- immutableOnEdit?: boolean;- placeholder?: string;- help?: string;- /** Choices for `select`. Include an empty-value option to mean "unset". */- options?: SubagentFieldOption[];-};--/** A single attribute value; shape depends on the field's `type`. */-export type SubagentAttributeValue = string | string[] | number | boolean | null;--/** A subagent's attributes, keyed by {@link SubagentField.key}. Always carries- * `name` and `description`; the rest are provider-defined. */-export type SubagentAttributes = Record<string, SubagentAttributeValue>;--/**- * How an agent type discovers, launches, and credentials its subagents.- *- * Subagents are a per-provider feature: an agent that supports them spawns child- * agents that run with their own Switch identity. The mechanism (file layout,- * launch flags, credential injection) is provider-specific, so it lives behind- * this behavior; the main process supplies a `PluginFs` for the IO and owns the- * provider-neutral gateway reconciliation.- *- * `workspaceFs` is rooted at the agent's working directory; `homeFs` at the- * user's home — definitions may resolve in either scope.- */-export type ISubagentsBehavior = {- /** Launchable subagents, from the parent's on-disk credentials + definitions. */- discoverLocal(workspaceFs: PluginFs, homeFs: PluginFs): Promise<LocalSubagent[]>;- /** Subagent definitions in the working dir, for onboarding (project scope). */- discoverDefinitions(workspaceFs: PluginFs): Promise<SubagentDefinition[]>;- /** Extra CLI args that launch a session as `subagentName`. Pure. */- launchArgs(sessionPath: string, subagentName: string): string[];- /** The subagent's Switch credentials as env vars, for the launched session. */- readLaunchEnv(workspaceFs: PluginFs, subagentName: string): Promise<Record<string, string>>;- /** Write a subagent's credentials so it is immediately launchable. */- writeSettings(workspaceFs: PluginFs, credentials: SubagentCredentials): Promise<void>;- /** The attribute fields this agent type supports, in display order. Drives the- * create/edit form; the first two are always `name` and `description`. */- attributeFields(): SubagentField[];- /** Create or overwrite a subagent's on-disk definition from its attributes- * (workspace scope). `attributes.name` selects the file. */- writeDefinition(workspaceFs: PluginFs, attributes: SubagentAttributes): Promise<void>;- /** The current attribute values for an existing definition, keyed to- * {@link attributeFields}, or null if no definition exists. */- readDefinition(workspaceFs: PluginFs, name: string): Promise<SubagentAttributes | null>;- /** Remove a subagent's definition and credentials files (workspace scope). */- removeLocal(workspaceFs: PluginFs, name: string): Promise<void>;-};--/**- * kind: 'claude-agents' — Claude-Code-style subagents: `.md` definitions under- * `definitionsDirRelative` and per-subagent Switch credentials under- * `dirRelative/<name><settingsSuffix>`, launched with `--agent`/`--settings`.- * kind: 'none' — the agent has no subagent concept; the UI surfaces nothing.- */-export const subagentsCapability = definePluginCapability<ISubagentsBehavior>()(- 'subagents',- z.discriminatedUnion('kind', [- z.object({- kind: z.literal('claude-agents'),- /** Credentials dir, relative to the working dir, e.g. '.claude/switch-subagents'. */- dirRelative: z.string(),- /** Credentials filename suffix, e.g. '.settings.json'. */- settingsSuffix: z.string(),- /** Definitions dir, relative to the working dir, e.g. '.claude/agents'. */- definitionsDirRelative: z.string(),- }),- z.object({ kind: z.literal('none') }),- ])-);--export type SubagentsDescriptor = (typeof subagentsCapability)['_descriptor'];diff --git a/dash/packages/core/src/agents/plugins/helpers/standard-command.ts b/dash/packages/core/src/agents/plugins/helpers/standard-command.tsindex f620ec817..7a7eb012d 100644--- a/dash/packages/core/src/agents/plugins/helpers/standard-command.ts+++ b/dash/packages/core/src/agents/plugins/helpers/standard-command.ts@@ -126,6 +126,13 @@ export function buildStandardCommand(ctx: CommandContext, spec: StandardCommandSargs.push(...ctx.extraArgs);}+ // Provider-produced args to run as a specific named agent (repo-agents+ // capability). Distinct from user extra args; placed before the positional+ // prompt like them so flags are not mistaken for the prompt (CHOO-1440).+ if (ctx.agentArgs?.length) {+ args.push(...ctx.agentArgs);+ }+// Initial prompt — only on fresh sessionsif (!ctx.isResuming && ctx.initialPrompt) {if (spec.initialPromptViaStdinPipe) {diff --git a/dash/packages/core/src/agents/plugins/index.ts b/dash/packages/core/src/agents/plugins/index.tsindex a61721a89..bd4108ee8 100644--- a/dash/packages/core/src/agents/plugins/index.ts+++ b/dash/packages/core/src/agents/plugins/index.ts@@ -9,8 +9,8 @@ import { mcpCapability } from './capabilities/mcp';import { modelsCapability } from './capabilities/models';import { pluginsCapability } from './capabilities/plugins';import { promptCapability } from './capabilities/prompt';+import { repoAgentsCapability } from './capabilities/repo-agents';import { sessionsCapability } from './capabilities/sessions';-import { subagentsCapability } from './capabilities/subagents';import { switchSetupCapability } from './capabilities/switch-setup';export const PLUGIN_CAPABILITIES = {@@ -23,7 +23,7 @@ export const PLUGIN_CAPABILITIES = {plugins: pluginsCapability,prompt: promptCapability,sessions: sessionsCapability,- subagents: subagentsCapability,+ repoAgents: repoAgentsCapability,switchSetup: switchSetupCapability,} as const;@@ -71,19 +71,19 @@ export type { IHooksBehavior } from './capabilities/hooks';export type { IMcpBehavior, McpServerRegistration } from './capabilities/mcp';export type { IPlugins } from './capabilities/plugins';export type { ISessionsBehavior } from './capabilities/sessions';-export { SWITCH_CONNECTOR_TOOL_RULES } from './capabilities/subagents';+export { SWITCH_AGENT_SETTINGS_DIR, SWITCH_CONNECTOR_TOOL_RULES } from './capabilities/repo-agents';export type {- ISubagentsBehavior,- LocalSubagent,- SubagentAttributes,- SubagentAttributeValue,- SubagentCredentials,- SubagentDefinition,- SubagentField,- SubagentFieldOption,- SubagentFieldType,- SubagentsDescriptor,-} from './capabilities/subagents';+ IRepoAgentsBehavior,+ LocalRepoAgent,+ RepoAgentAttributes,+ RepoAgentAttributeValue,+ RepoAgentCredentials,+ RepoAgentDefinition,+ RepoAgentField,+ RepoAgentFieldOption,+ RepoAgentFieldType,+ RepoAgentsDescriptor,+} from './capabilities/repo-agents';export type { ISwitchSetupBehavior, SwitchSetupDescriptor } from './capabilities/switch-setup';// Typed registry factorydiff --git a/dash/packages/plugins/src/agents/impl/amp/index.ts b/dash/packages/plugins/src/agents/impl/amp/index.tsindex b33f68b6e..b4a934f18 100644--- a/dash/packages/plugins/src/agents/impl/amp/index.ts+++ b/dash/packages/plugins/src/agents/impl/amp/index.ts@@ -53,7 +53,7 @@ export const plugin = definePlugin(sessions: {kind: 'stateless',},- subagents: { kind: 'none' },+ repoAgents: { kind: 'none' },switchSetup: { kind: 'none' },},{ icon }diff --git a/dash/packages/plugins/src/agents/impl/antigravity/index.ts b/dash/packages/plugins/src/agents/impl/antigravity/index.tsindex 0b5514acc..42c01eb80 100644--- a/dash/packages/plugins/src/agents/impl/antigravity/index.ts+++ b/dash/packages/plugins/src/agents/impl/antigravity/index.ts@@ -63,7 +63,7 @@ export const plugin = definePlugin(sessions: {kind: 'resumable',},- subagents: { kind: 'none' },+ repoAgents: { kind: 'none' },switchSetup: { kind: 'none' },},{ icon }diff --git a/dash/packages/plugins/src/agents/impl/auggie/index.ts b/dash/packages/plugins/src/agents/impl/auggie/index.tsindex 9f1380eaa..891fea5d2 100644--- a/dash/packages/plugins/src/agents/impl/auggie/index.ts+++ b/dash/packages/plugins/src/agents/impl/auggie/index.ts@@ -37,7 +37,7 @@ export const plugin = definePlugin(sessions: {kind: 'resumable',},- subagents: { kind: 'none' },+ repoAgents: { kind: 'none' },switchSetup: { kind: 'none' },},{ icon }diff --git a/dash/packages/plugins/src/agents/impl/autohand/index.ts b/dash/packages/plugins/src/agents/impl/autohand/index.tsindex de7efe933..710316ff6 100644--- a/dash/packages/plugins/src/agents/impl/autohand/index.ts+++ b/dash/packages/plugins/src/agents/impl/autohand/index.ts@@ -37,7 +37,7 @@ export const plugin = definePlugin(sessions: {kind: 'stateless',},- subagents: { kind: 'none' },+ repoAgents: { kind: 'none' },switchSetup: { kind: 'none' },},{ icon }diff --git a/dash/packages/plugins/src/agents/impl/charm/index.ts b/dash/packages/plugins/src/agents/impl/charm/index.tsindex 824aa186f..d5676301b 100644--- a/dash/packages/plugins/src/agents/impl/charm/index.ts+++ b/dash/packages/plugins/src/agents/impl/charm/index.ts@@ -40,7 +40,7 @@ export const plugin = definePlugin(sessions: {kind: 'stateless',},- subagents: { kind: 'none' },+ repoAgents: { kind: 'none' },switchSetup: { kind: 'none' },},{ icon }diff --git a/dash/packages/plugins/src/agents/impl/claude/index.ts b/dash/packages/plugins/src/agents/impl/claude/index.tsindex 9a719fa83..293a61779 100644--- a/dash/packages/plugins/src/agents/impl/claude/index.ts+++ b/dash/packages/plugins/src/agents/impl/claude/index.ts@@ -7,7 +7,7 @@ import {import { SWITCH_MARKETPLACE_SOURCE } from '../../../distribution';import { buildClaudeHookConfig } from './hooks';import { icon } from './icon';-import { CLAUDE_SUBAGENTS, claudeSubagentsBehavior } from './subagents';+import { CLAUDE_SUBAGENTS, claudeRepoAgentsBehavior } from './subagents';export const plugin = definePlugin({@@ -100,8 +100,8 @@ export const plugin = definePlugin(sessions: {kind: 'resumable',},- subagents: {- kind: 'claude-agents',+ repoAgents: {+ kind: 'definitions',dirRelative: CLAUDE_SUBAGENTS.dirRelative,settingsSuffix: CLAUDE_SUBAGENTS.settingsSuffix,definitionsDirRelative: CLAUDE_SUBAGENTS.definitionsDirRelative,@@ -129,5 +129,5 @@ export const provider = registerPluginBehavior(plugin, {},hooks: buildClaudeHookConfig(),mcp: passthroughMcpAdapter('.claude.json'),- subagents: claudeSubagentsBehavior,+ repoAgents: claudeRepoAgentsBehavior,});diff --git a/dash/packages/plugins/src/agents/impl/claude/subagents.test.ts b/dash/packages/plugins/src/agents/impl/claude/subagents.test.tsindex 1289cb5ac..8a16fa775 100644--- a/dash/packages/plugins/src/agents/impl/claude/subagents.test.ts+++ b/dash/packages/plugins/src/agents/impl/claude/subagents.test.ts@@ -1,7 +1,7 @@import path from 'node:path';import type { PluginFs } from '@switchdash/core/agents/plugins';import { describe, expect, it } from 'vitest';-import { CLAUDE_SUBAGENTS, claudeSubagentsBehavior } from './subagents';+import { CLAUDE_SUBAGENTS, claudeRepoAgentsBehavior } from './subagents';/** Minimal in-memory PluginFs over a flat path→content map. */function fakeFs(files: Record<string, string>): PluginFs {@@ -30,20 +30,22 @@ function fakeFs(files: Record<string, string>): PluginFs {const settingsRel = (name: string) =>path.join(CLAUDE_SUBAGENTS.dirRelative, `${name}${CLAUDE_SUBAGENTS.settingsSuffix}`);+/** Provider-neutral per-agent credentials file (the current write location). */+const neutralRel = (name: string) => path.join('.switch', 'agents', `${name}.json`);const defRel = (name: string) => path.join(CLAUDE_SUBAGENTS.definitionsDirRelative, `${name}.md`);-describe('claudeSubagentsBehavior.launchArgs', () => {+describe('claudeRepoAgentsBehavior.launchArgs', () => {it('builds --agent and --settings for a subagent', () => {- expect(claudeSubagentsBehavior.launchArgs('/repo/agent', 'reviewer')).toEqual([+ expect(claudeRepoAgentsBehavior.launchArgs('/repo/agent', 'reviewer')).toEqual(['--agent','reviewer','--settings',- path.join('/repo/agent', '.claude', 'switch-subagents', 'reviewer.settings.json'),+ path.join('/repo/agent', '.switch', 'agents', 'reviewer.json'),]);});});-describe('claudeSubagentsBehavior.discoverDefinitions', () => {+describe('claudeRepoAgentsBehavior.discoverDefinitions', () => {it('parses definitions, eligibility, and registered state', async () => {const workspaceFs = fakeFs({[defRel('reviewer')]:@@ -54,7 +56,7 @@ describe('claudeSubagentsBehavior.discoverDefinitions', () => {[defRel('linter')]: '---\ndescription: Lints\ntools: Read, Edit\n---\n',});- const defs = await claudeSubagentsBehavior.discoverDefinitions(workspaceFs);+ const defs = await claudeRepoAgentsBehavior.discoverDefinitions(workspaceFs);expect(defs).toEqual([{ name: 'linter', description: 'Lints', model: null, eligible: false, registered: false },@@ -69,7 +71,7 @@ describe('claudeSubagentsBehavior.discoverDefinitions', () => {});});-describe('claudeSubagentsBehavior.discoverLocal', () => {+describe('claudeRepoAgentsBehavior.discoverLocal', () => {it('reads creds env and definition meta, project scope then home', async () => {const workspaceFs = fakeFs({[settingsRel('reviewer')]:@@ -81,7 +83,7 @@ describe('claudeSubagentsBehavior.discoverLocal', () => {[defRel('helper')]: '---\ndescription: From home\n---\n',});- const local = await claudeSubagentsBehavior.discoverLocal(workspaceFs, homeFs);+ const local = await claudeRepoAgentsBehavior.discoverLocal(workspaceFs, homeFs);expect(local).toEqual([{@@ -102,28 +104,28 @@ describe('claudeSubagentsBehavior.discoverLocal', () => {});});-describe('claudeSubagentsBehavior.readLaunchEnv', () => {+describe('claudeRepoAgentsBehavior.readLaunchEnv', () => {it('returns only non-empty SWITCH_* keys', async () => {const workspaceFs = fakeFs({[settingsRel('reviewer')]:'{"env":{"SWITCH_AGENT_ID":"a1","SWITCH_API_TOKEN":"t","SWITCH_API_ENDPOINT":" ","OTHER":"x"}}',});- expect(await claudeSubagentsBehavior.readLaunchEnv(workspaceFs, 'reviewer')).toEqual({+ expect(await claudeRepoAgentsBehavior.readLaunchEnv(workspaceFs, 'reviewer')).toEqual({SWITCH_AGENT_ID: 'a1',SWITCH_API_TOKEN: 't',});});it('returns {} when the credentials file is missing', async () => {- expect(await claudeSubagentsBehavior.readLaunchEnv(fakeFs({}), 'reviewer')).toEqual({});+ expect(await claudeRepoAgentsBehavior.readLaunchEnv(fakeFs({}), 'reviewer')).toEqual({});});});-describe('claudeSubagentsBehavior.writeDefinition / readDefinition', () => {+describe('claudeRepoAgentsBehavior.writeDefinition / readDefinition', () => {it('writes frontmatter + body without a tools line, and round-trips attributes', async () => {const workspaceFs = fakeFs({});- await claudeSubagentsBehavior.writeDefinition(workspaceFs, {+ await claudeRepoAgentsBehavior.writeDefinition(workspaceFs, {name: 'reviewer',description: 'Reviews diffs',model: 'opus',@@ -137,7 +139,7 @@ describe('claudeSubagentsBehavior.writeDefinition / readDefinition', () => {// No `tools:` line → the subagent inherits all tools and is Switch-eligible.expect(raw).not.toContain('tools:');- const attrs = await claudeSubagentsBehavior.readDefinition(workspaceFs, 'reviewer');+ const attrs = await claudeRepoAgentsBehavior.readDefinition(workspaceFs, 'reviewer');expect(attrs).toMatchObject({name: 'reviewer',description: 'Reviews diffs',@@ -149,7 +151,7 @@ describe('claudeSubagentsBehavior.writeDefinition / readDefinition', () => {it('always merges the Switch connector tools into a non-empty tools list', async () => {const workspaceFs = fakeFs({});- await claudeSubagentsBehavior.writeDefinition(workspaceFs, {+ await claudeRepoAgentsBehavior.writeDefinition(workspaceFs, {name: 'reviewer',description: 'Reviews diffs',tools: ['Read', 'Grep'],@@ -162,13 +164,13 @@ describe('claudeSubagentsBehavior.writeDefinition / readDefinition', () => {);// Read-back strips the Switch rules so the form shows only the user's tools.- const attrs = await claudeSubagentsBehavior.readDefinition(workspaceFs, 'reviewer');+ const attrs = await claudeRepoAgentsBehavior.readDefinition(workspaceFs, 'reviewer');expect(attrs?.tools).toEqual(['Read', 'Grep']);});it('serialises optional scalar, number, and boolean fields and omits empty ones', async () => {const workspaceFs = fakeFs({});- await claudeSubagentsBehavior.writeDefinition(workspaceFs, {+ await claudeRepoAgentsBehavior.writeDefinition(workspaceFs, {name: 'worker',description: 'line one\nline two',model: '',@@ -187,49 +189,49 @@ describe('claudeSubagentsBehavior.writeDefinition / readDefinition', () => {expect(raw).not.toContain('model:');expect(raw).not.toContain('permissionMode:');- const attrs = await claudeSubagentsBehavior.readDefinition(workspaceFs, 'worker');+ const attrs = await claudeRepoAgentsBehavior.readDefinition(workspaceFs, 'worker');expect(attrs).toMatchObject({ color: 'blue', maxTurns: 5, background: true, model: '' });});it('returns null when no definition exists', async () => {- expect(await claudeSubagentsBehavior.readDefinition(fakeFs({}), 'ghost')).toBeNull();+ expect(await claudeRepoAgentsBehavior.readDefinition(fakeFs({}), 'ghost')).toBeNull();});});-describe('claudeSubagentsBehavior.attributeFields', () => {+describe('claudeRepoAgentsBehavior.attributeFields', () => {it('declares name and description first, both required', () => {- const fields = claudeSubagentsBehavior.attributeFields();+ const fields = claudeRepoAgentsBehavior.attributeFields();expect(fields[0]).toMatchObject({ key: 'name', required: true, immutableOnEdit: true });expect(fields[1]).toMatchObject({ key: 'description', required: true });expect(fields.map((f) => f.key)).toContain('tools');});});-describe('claudeSubagentsBehavior.removeLocal', () => {+describe('claudeRepoAgentsBehavior.removeLocal', () => {it('deletes both the definition and credentials files', async () => {const workspaceFs = fakeFs({[defRel('reviewer')]: '---\nname: reviewer\ndescription: x\n---\n',[settingsRel('reviewer')]: '{"env":{}}',});- await claudeSubagentsBehavior.removeLocal(workspaceFs, 'reviewer');+ await claudeRepoAgentsBehavior.removeLocal(workspaceFs, 'reviewer');expect(await workspaceFs.exists(defRel('reviewer'))).toBe(false);expect(await workspaceFs.exists(settingsRel('reviewer'))).toBe(false);});});-describe('claudeSubagentsBehavior.writeSettings', () => {+describe('claudeRepoAgentsBehavior.writeSettings', () => {it('writes the credentials JSON, permissions.allow, and a gitignore', async () => {const workspaceFs = fakeFs({});- await claudeSubagentsBehavior.writeSettings(workspaceFs, {- subagentName: 'reviewer',+ await claudeRepoAgentsBehavior.writeCredentials(workspaceFs, {+ agentName: 'reviewer',apiEndpoint: 'https://s',apiToken: 'secret',agentId: 'a1',});- const written = await workspaceFs.read(settingsRel('reviewer'));+ const written = await workspaceFs.read(neutralRel('reviewer'));expect(JSON.parse(written!)).toEqual({permissions: {allow: [@@ -239,26 +241,24 @@ describe('claudeSubagentsBehavior.writeSettings', () => {},env: { SWITCH_API_ENDPOINT: 'https://s', SWITCH_API_TOKEN: 'secret', SWITCH_AGENT_ID: 'a1' },});- expect(await workspaceFs.read(path.join(CLAUDE_SUBAGENTS.dirRelative, '.gitignore'))).toBe(- '*\n'- );+ expect(await workspaceFs.read(path.join('.switch', 'agents', '.gitignore'))).toBe('*\n');});it('preserves existing permissions and env, unioning the Switch rules', async () => {const workspaceFs = fakeFs({- [settingsRel('reviewer')]: JSON.stringify({+ [neutralRel('reviewer')]: JSON.stringify({permissions: { allow: ['Bash'] },env: { KEEP: 'me' },}),});- await claudeSubagentsBehavior.writeSettings(workspaceFs, {- subagentName: 'reviewer',+ await claudeRepoAgentsBehavior.writeCredentials(workspaceFs, {+ agentName: 'reviewer',apiEndpoint: 'https://s',apiToken: 'secret',agentId: 'a1',});- const settings = JSON.parse((await workspaceFs.read(settingsRel('reviewer')))!);+ const settings = JSON.parse((await workspaceFs.read(neutralRel('reviewer')))!);expect(settings.permissions.allow).toEqual(['Bash','mcp__plugin_switch-connector_switch',diff --git a/dash/packages/plugins/src/agents/impl/claude/subagents.ts b/dash/packages/plugins/src/agents/impl/claude/subagents.tsindex 0bc650303..e37e2b8c0 100644--- a/dash/packages/plugins/src/agents/impl/claude/subagents.ts+++ b/dash/packages/plugins/src/agents/impl/claude/subagents.ts@@ -1,12 +1,13 @@import path from 'node:path';import {- type ISubagentsBehavior,- type LocalSubagent,+ type IRepoAgentsBehavior,+ type LocalRepoAgent,type PluginFs,- type SubagentAttributes,- type SubagentCredentials,- type SubagentDefinition,- type SubagentField,+ type RepoAgentAttributes,+ type RepoAgentCredentials,+ type RepoAgentDefinition,+ type RepoAgentField,+ SWITCH_AGENT_SETTINGS_DIR,SWITCH_CONNECTOR_TOOL_RULES,} from '@switchdash/core/agents/plugins';@@ -46,7 +47,7 @@ const BOOLEAN_KEYS = new Set(['background']);* field keys match the `.claude/agents/<name>.md` frontmatter keys verbatim* (`prompt` being the body). hooks / mcpServers / skills are intentionally* omitted — they are nested/block-list YAML, edit the `.md` directly for those. */-const CLAUDE_SUBAGENT_FIELDS: SubagentField[] = [+const CLAUDE_SUBAGENT_FIELDS: RepoAgentField[] = [{key: 'name',label: 'Name',@@ -243,13 +244,13 @@ function extractBody(content: string): string {return (match ? normalised.slice(match[0].length) : normalised).trim();}-function toScalar(value: SubagentAttributes[string] | undefined): string {+function toScalar(value: RepoAgentAttributes[string] | undefined): string {if (value === null || value === undefined) return '';if (Array.isArray(value)) return value.join(', ');return String(value).trim();}-function toList(value: SubagentAttributes[string] | undefined): string[] {+function toList(value: RepoAgentAttributes[string] | undefined): string[] {if (Array.isArray(value)) return value.map((v) => String(v).trim()).filter((v) => v.length > 0);if (typeof value === 'string') return splitList(value);return [];@@ -262,7 +263,7 @@ function toList(value: SubagentAttributes[string] | undefined): string[] {* `tools` is omitted entirely, which inherits all tools. The body defaults to* the description when no system prompt is given.*/-function serializeDefinition(attributes: SubagentAttributes): string {+function serializeDefinition(attributes: RepoAgentAttributes): string {const name = toScalar(attributes.name);const description = toScalar(attributes.description).replace(/\s*\r?\n\s*/g, ' ');const lines = ['---', `name: ${name}`, `description: ${description}`];@@ -324,10 +325,30 @@ function parseSettingsObject(raw: string | null): Record<string, unknown> {}}+/** Legacy per-subagent credentials file under `.claude/switch-subagents/`. */function settingsRelPath(name: string): string {return path.join(CLAUDE_SUBAGENTS.dirRelative, `${name}${CLAUDE_SUBAGENTS.settingsSuffix}`);}+/** Provider-neutral per-agent credentials file (the current location). */+function neutralSettingsRelPath(name: string): string {+ return path.join(SWITCH_AGENT_SETTINGS_DIR, `${name}.json`);+}++/**+ * Read an agent's credentials JSON, preferring the provider-neutral location and+ * falling back to the legacy `.claude/switch-subagents/` file for installs not+ * yet migrated (CHOO-1440).+ */+async function readCredsObject(+ workspaceFs: PluginFs,+ name: string+): Promise<Record<string, unknown>> {+ const neutral = await workspaceFs.read(neutralSettingsRelPath(name));+ if (neutral !== null) return parseSettingsObject(neutral);+ return parseSettingsObject(await workspaceFs.read(settingsRelPath(name)));+}+function definitionRelPath(name: string): string {return path.join(CLAUDE_SUBAGENTS.definitionsDirRelative, `${name}${MD_SUFFIX}`);}@@ -351,18 +372,37 @@ async function readDefinitionMeta(return { description: null, model: null };}-export const claudeSubagentsBehavior: ISubagentsBehavior = {- async discoverLocal(workspaceFs, homeFs): Promise<LocalSubagent[]> {- const entries = await workspaceFs.list(CLAUDE_SUBAGENTS.dirRelative);- const names = entries+export const claudeRepoAgentsBehavior: IRepoAgentsBehavior = {+ async discoverLocal(workspaceFs, homeFs): Promise<LocalRepoAgent[]> {+ // Names come from either credentials location — the neutral `.switch/agents`+ // dir and the legacy `.claude/switch-subagents` dir — so both migrated and+ // un-migrated installs are discovered (CHOO-1440). Plain agents' creds files+ // live in the neutral dir too (keyed by agent id, no `.claude/agents/<name>.md`+ // definition); a neutral file counts as a subagent only when it has a+ // definition, so those are filtered out here.+ const neutralCandidates = (await workspaceFs.list(SWITCH_AGENT_SETTINGS_DIR))+ .filter((entry) => entry.endsWith('.json'))+ .map((entry) => entry.slice(0, -'.json'.length))+ .filter((name) => name.length > 0);+ const neutralNames: string[] = [];+ for (const name of neutralCandidates) {+ if (+ (await workspaceFs.exists(definitionRelPath(name))) ||+ (await homeFs.exists(definitionRelPath(name)))+ ) {+ neutralNames.push(name);+ }+ }+ const legacyNames = (await workspaceFs.list(CLAUDE_SUBAGENTS.dirRelative)).filter((entry) => entry.endsWith(CLAUDE_SUBAGENTS.settingsSuffix))- .map((entry) => entry.slice(0, -CLAUDE_SUBAGENTS.settingsSuffix.length))+ .map((entry) => entry.slice(0, -CLAUDE_SUBAGENTS.settingsSuffix.length));+ const names = [...new Set([...neutralNames, ...legacyNames])].filter((name) => name.length > 0).sort((a, b) => a.localeCompare(b));return Promise.all(names.map(async (name) => {- const settings = parseSettingsObject(await workspaceFs.read(settingsRelPath(name)));+ const settings = await readCredsObject(workspaceFs, name);const env = (settings.env ?? {}) as Record<string, unknown>;const { description, model } = await readDefinitionMeta(workspaceFs, homeFs, name);return {@@ -376,7 +416,7 @@ export const claudeSubagentsBehavior: ISubagentsBehavior = {);},- async discoverDefinitions(workspaceFs): Promise<SubagentDefinition[]> {+ async discoverDefinitions(workspaceFs): Promise<RepoAgentDefinition[]> {const entries = await workspaceFs.list(CLAUDE_SUBAGENTS.definitionsDirRelative);const files = entries.filter((entry) => entry.endsWith(MD_SUFFIX))@@ -400,17 +440,17 @@ export const claudeSubagentsBehavior: ISubagentsBehavior = {);},- launchArgs(sessionPath, subagentName): string[] {+ launchArgs(workingDir, agentName): string[] {return ['--agent',- subagentName,+ agentName,'--settings',- path.join(sessionPath, settingsRelPath(subagentName)),+ path.join(workingDir, neutralSettingsRelPath(agentName)),];},- async readLaunchEnv(workspaceFs, subagentName): Promise<Record<string, string>> {- const settings = parseSettingsObject(await workspaceFs.read(settingsRelPath(subagentName)));+ async readLaunchEnv(workspaceFs, agentName): Promise<Record<string, string>> {+ const settings = await readCredsObject(workspaceFs, agentName);const env = (settings.env ?? {}) as Record<string, unknown>;const result: Record<string, string> = {};for (const key of SWITCH_ENV_KEYS) {@@ -420,14 +460,14 @@ export const claudeSubagentsBehavior: ISubagentsBehavior = {return result;},- async writeSettings(workspaceFs, credentials: SubagentCredentials): Promise<void> {+ async writeCredentials(workspaceFs, credentials: RepoAgentCredentials): Promise<void> {// Keep the tokens out of git — `*` ignores everything in the directory.- const gitignoreRel = path.join(CLAUDE_SUBAGENTS.dirRelative, '.gitignore');+ const gitignoreRel = path.join(SWITCH_AGENT_SETTINGS_DIR, '.gitignore');if (!(await workspaceFs.exists(gitignoreRel))) {await workspaceFs.write(gitignoreRel, '*\n');}- const relPath = settingsRelPath(credentials.subagentName);+ const relPath = neutralSettingsRelPath(credentials.agentName);const existing = parseSettingsObject(await workspaceFs.read(relPath));const currentEnv = (existing.env ?? {}) as Record<string, unknown>;const currentPerms =@@ -456,21 +496,21 @@ export const claudeSubagentsBehavior: ISubagentsBehavior = {await workspaceFs.write(relPath, `${JSON.stringify(settings, null, 2)}\n`);},- attributeFields(): SubagentField[] {+ attributeFields(): RepoAgentField[] {return CLAUDE_SUBAGENT_FIELDS;},- async writeDefinition(workspaceFs, attributes: SubagentAttributes): Promise<void> {+ async writeDefinition(workspaceFs, attributes: RepoAgentAttributes): Promise<void> {const name = toScalar(attributes.name);await workspaceFs.write(definitionRelPath(name), serializeDefinition(attributes));},- async readDefinition(workspaceFs, name): Promise<SubagentAttributes | null> {+ async readDefinition(workspaceFs, name): Promise<RepoAgentAttributes | null> {const content = await workspaceFs.read(definitionRelPath(name));if (content === null) return null;const fields = parseFrontmatterFields(content);- const attributes: SubagentAttributes = {+ const attributes: RepoAgentAttributes = {name: fields.name ?? name,description: fields.description ?? '',[BODY_KEY]: extractBody(content),@@ -494,6 +534,7 @@ export const claudeSubagentsBehavior: ISubagentsBehavior = {async removeLocal(workspaceFs, name): Promise<void> {await workspaceFs.delete(definitionRelPath(name));+ await workspaceFs.delete(neutralSettingsRelPath(name));await workspaceFs.delete(settingsRelPath(name));},};diff --git a/dash/packages/plugins/src/agents/impl/cline/index.ts b/dash/packages/plugins/src/agents/impl/cline/index.tsindex fffd2aaa6..04859446b 100644--- a/dash/packages/plugins/src/agents/impl/cline/index.ts+++ b/dash/packages/plugins/src/agents/impl/cline/index.ts@@ -37,7 +37,7 @@ export const plugin = definePlugin(sessions: {kind: 'stateless',},- subagents: { kind: 'none' },+ repoAgents: { kind: 'none' },switchSetup: { kind: 'none' },},{ icon }diff --git a/dash/packages/plugins/src/agents/impl/codebuff/index.ts b/dash/packages/plugins/src/agents/impl/codebuff/index.tsindex cbda54968..82f367912 100644--- a/dash/packages/plugins/src/agents/impl/codebuff/index.ts+++ b/dash/packages/plugins/src/agents/impl/codebuff/index.ts@@ -37,7 +37,7 @@ export const plugin = definePlugin(sessions: {kind: 'stateless',},- subagents: { kind: 'none' },+ repoAgents: { kind: 'none' },switchSetup: { kind: 'none' },},{ icon }diff --git a/dash/packages/plugins/src/agents/impl/codex/index.ts b/dash/packages/plugins/src/agents/impl/codex/index.tsindex 101715bfa..fdcafa59d 100644--- a/dash/packages/plugins/src/agents/impl/codex/index.ts+++ b/dash/packages/plugins/src/agents/impl/codex/index.ts@@ -63,7 +63,7 @@ export const plugin = definePlugin(sessions: {kind: 'resumable',},- subagents: { kind: 'none' },+ repoAgents: { kind: 'none' },switchSetup: { kind: 'none' },},{ icon }diff --git a/dash/packages/plugins/src/agents/impl/commandcode/index.ts b/dash/packages/plugins/src/agents/impl/commandcode/index.tsindex e0a4aba90..e26ab8263 100644--- a/dash/packages/plugins/src/agents/impl/commandcode/index.ts+++ b/dash/packages/plugins/src/agents/impl/commandcode/index.ts@@ -42,7 +42,7 @@ export const plugin = definePlugin(sessions: {kind: 'resumable',},- subagents: { kind: 'none' },+ repoAgents: { kind: 'none' },switchSetup: { kind: 'none' },},{ icon }diff --git a/dash/packages/plugins/src/agents/impl/continue/index.ts b/dash/packages/plugins/src/agents/impl/continue/index.tsindex f483bedc6..b14e975a2 100644--- a/dash/packages/plugins/src/agents/impl/continue/index.ts+++ b/dash/packages/plugins/src/agents/impl/continue/index.ts@@ -70,7 +70,7 @@ export const plugin = definePlugin(sessions: {kind: 'resumable',},- subagents: { kind: 'none' },+ repoAgents: { kind: 'none' },switchSetup: { kind: 'none' },},{ icon }diff --git a/dash/packages/plugins/src/agents/impl/copilot/index.ts b/dash/packages/plugins/src/agents/impl/copilot/index.tsindex 438ebca30..989e075e2 100644--- a/dash/packages/plugins/src/agents/impl/copilot/index.ts+++ b/dash/packages/plugins/src/agents/impl/copilot/index.ts@@ -46,7 +46,7 @@ export const plugin = definePlugin(sessions: {kind: 'resumable',},- subagents: { kind: 'none' },+ repoAgents: { kind: 'none' },switchSetup: { kind: 'none' },},{ icon }diff --git a/dash/packages/plugins/src/agents/impl/cursor/index.ts b/dash/packages/plugins/src/agents/impl/cursor/index.tsindex 321bce8ed..8204d2b4d 100644--- a/dash/packages/plugins/src/agents/impl/cursor/index.ts+++ b/dash/packages/plugins/src/agents/impl/cursor/index.ts@@ -65,7 +65,7 @@ export const plugin = definePlugin(sessions: {kind: 'resumable',},- subagents: { kind: 'none' },+ repoAgents: { kind: 'none' },switchSetup: { kind: 'none' },},{ icon }diff --git a/dash/packages/plugins/src/agents/impl/devin/index.ts b/dash/packages/plugins/src/agents/impl/devin/index.tsindex eed54d091..95539b07c 100644--- a/dash/packages/plugins/src/agents/impl/devin/index.ts+++ b/dash/packages/plugins/src/agents/impl/devin/index.ts@@ -66,7 +66,7 @@ export const plugin = definePlugin(sessions: {kind: 'resumable',},- subagents: { kind: 'none' },+ repoAgents: { kind: 'none' },switchSetup: { kind: 'none' },},{ icon }diff --git a/dash/packages/plugins/src/agents/impl/droid/index.ts b/dash/packages/plugins/src/agents/impl/droid/index.tsindex 3e43cf444..a371879a1 100644--- a/dash/packages/plugins/src/agents/impl/droid/index.ts+++ b/dash/packages/plugins/src/agents/impl/droid/index.ts@@ -67,7 +67,7 @@ export const plugin = definePlugin(sessions: {kind: 'resumable',},- subagents: { kind: 'none' },+ repoAgents: { kind: 'none' },switchSetup: { kind: 'none' },},{ icon }diff --git a/dash/packages/plugins/src/agents/impl/freebuff/index.ts b/dash/packages/plugins/src/agents/impl/freebuff/index.tsindex f804c65b9..0a2b305a3 100644--- a/dash/packages/plugins/src/agents/impl/freebuff/index.ts+++ b/dash/packages/plugins/src/agents/impl/freebuff/index.ts@@ -37,7 +37,7 @@ export const plugin = definePlugin(sessions: {kind: 'stateless',},- subagents: { kind: 'none' },+ repoAgents: { kind: 'none' },switchSetup: { kind: 'none' },},{ icon }diff --git a/dash/packages/plugins/src/agents/impl/gemini/index.ts b/dash/packages/plugins/src/agents/impl/gemini/index.tsindex 8db4a73f0..a1774d10c 100644--- a/dash/packages/plugins/src/agents/impl/gemini/index.ts+++ b/dash/packages/plugins/src/agents/impl/gemini/index.ts@@ -43,7 +43,7 @@ export const plugin = definePlugin(sessions: {kind: 'resumable',},- subagents: { kind: 'none' },+ repoAgents: { kind: 'none' },switchSetup: { kind: 'none' },},{ icon }diff --git a/dash/packages/plugins/src/agents/impl/goose/index.ts b/dash/packages/plugins/src/agents/impl/goose/index.tsindex c91dbf795..e8d0df69e 100644--- a/dash/packages/plugins/src/agents/impl/goose/index.ts+++ b/dash/packages/plugins/src/agents/impl/goose/index.ts@@ -65,7 +65,7 @@ export const plugin = definePlugin(sessions: {kind: 'resumable',},- subagents: { kind: 'none' },+ repoAgents: { kind: 'none' },switchSetup: { kind: 'none' },},{ icon }diff --git a/dash/packages/plugins/src/agents/impl/grok/index.ts b/dash/packages/plugins/src/agents/impl/grok/index.tsindex e5fd2f71d..c683b267b 100644--- a/dash/packages/plugins/src/agents/impl/grok/index.ts+++ b/dash/packages/plugins/src/agents/impl/grok/index.ts@@ -66,7 +66,7 @@ export const plugin = definePlugin(sessions: {kind: 'resumable',},- subagents: { kind: 'none' },+ repoAgents: { kind: 'none' },switchSetup: { kind: 'none' },},{ icon }diff --git a/dash/packages/plugins/src/agents/impl/hermes/index.ts b/dash/packages/plugins/src/agents/impl/hermes/index.tsindex 7140be03b..84ab50ddb 100644--- a/dash/packages/plugins/src/agents/impl/hermes/index.ts+++ b/dash/packages/plugins/src/agents/impl/hermes/index.ts@@ -62,7 +62,7 @@ export const plugin = definePlugin(sessions: {kind: 'resumable',},- subagents: { kind: 'none' },+ repoAgents: { kind: 'none' },switchSetup: { kind: 'none' },},{ icon }diff --git a/dash/packages/plugins/src/agents/impl/index.test.ts b/dash/packages/plugins/src/agents/impl/index.test.tsindex 78222ccd0..eca7bb7e0 100644--- a/dash/packages/plugins/src/agents/impl/index.test.ts+++ b/dash/packages/plugins/src/agents/impl/index.test.ts@@ -120,29 +120,29 @@ describe('pluginRegistry', () => {}});- it('each entry declares a subagents descriptor; only supporting types carry a behavior', () => {+ it('each entry declares a repo-agents descriptor; only supporting types carry a behavior', () => {for (const d of pluginRegistry.getAll()) {- const descriptor = d.capabilities.subagents;- expect(['claude-agents', 'none'], `${d.metadata.id}.subagents.kind`).toContain(+ const descriptor = d.capabilities.repoAgents;+ expect(['definitions', 'none'], `${d.metadata.id}.repoAgents.kind`).toContain(descriptor.kind);- // A 'none' provider must not ship a subagents behavior; a supporting one must.+ // A 'none' provider must not ship a repo-agents behavior; a supporting one must.if (descriptor.kind === 'none') {- expect(d.behavior.subagents, `${d.metadata.id} should have no subagents behavior`).toBe(+ expect(d.behavior.repoAgents, `${d.metadata.id} should have no repo-agents behavior`).toBe(undefined);} else {expect(- typeof d.behavior.subagents?.launchArgs,- `${d.metadata.id} should ship a subagents behavior`+ typeof d.behavior.repoAgents?.launchArgs,+ `${d.metadata.id} should ship a repo-agents behavior`).toBe('function');}}});- it('claude is the subagents-supporting provider', () => {- expect(pluginRegistry.get('claude')!.capabilities.subagents.kind).toBe('claude-agents');- expect(pluginRegistry.get('codex')!.capabilities.subagents.kind).toBe('none');+ it('claude is the repo-agents-supporting provider', () => {+ expect(pluginRegistry.get('claude')!.capabilities.repoAgents.kind).toBe('definitions');+ expect(pluginRegistry.get('codex')!.capabilities.repoAgents.kind).toBe('none');});it('each entry has a behavior.prompt.buildCommand function', () => {diff --git a/dash/packages/plugins/src/agents/impl/jules/index.ts b/dash/packages/plugins/src/agents/impl/jules/index.tsindex cd6d8874e..f0d405828 100644--- a/dash/packages/plugins/src/agents/impl/jules/index.ts+++ b/dash/packages/plugins/src/agents/impl/jules/index.ts@@ -40,7 +40,7 @@ export const plugin = definePlugin(sessions: {kind: 'stateless',},- subagents: { kind: 'none' },+ repoAgents: { kind: 'none' },switchSetup: { kind: 'none' },},{ icon }diff --git a/dash/packages/plugins/src/agents/impl/junie/index.ts b/dash/packages/plugins/src/agents/impl/junie/index.tsindex 05e46d714..52a6582fc 100644--- a/dash/packages/plugins/src/agents/impl/junie/index.ts+++ b/dash/packages/plugins/src/agents/impl/junie/index.ts@@ -63,7 +63,7 @@ export const plugin = definePlugin(sessions: {kind: 'resumable',},- subagents: { kind: 'none' },+ repoAgents: { kind: 'none' },switchSetup: { kind: 'none' },},{ icon }diff --git a/dash/packages/plugins/src/agents/impl/kilocode/index.ts b/dash/packages/plugins/src/agents/impl/kilocode/index.tsindex e9d2b400c..26a3169d6 100644--- a/dash/packages/plugins/src/agents/impl/kilocode/index.ts+++ b/dash/packages/plugins/src/agents/impl/kilocode/index.ts@@ -51,7 +51,7 @@ export const plugin = definePlugin(sessions: {kind: 'resumable',},- subagents: { kind: 'none' },+ repoAgents: { kind: 'none' },switchSetup: { kind: 'none' },},{ icon }diff --git a/dash/packages/plugins/src/agents/impl/kimi/index.ts b/dash/packages/plugins/src/agents/impl/kimi/index.tsindex 01e4e2aec..cd63fd86f 100644--- a/dash/packages/plugins/src/agents/impl/kimi/index.ts+++ b/dash/packages/plugins/src/agents/impl/kimi/index.ts@@ -89,7 +89,7 @@ export const plugin = definePlugin(sessions: {kind: 'resumable',},- subagents: { kind: 'none' },+ repoAgents: { kind: 'none' },switchSetup: { kind: 'none' },},{ icon }diff --git a/dash/packages/plugins/src/agents/impl/kiro/index.ts b/dash/packages/plugins/src/agents/impl/kiro/index.tsindex 1fe6c31de..bdabf89e9 100644--- a/dash/packages/plugins/src/agents/impl/kiro/index.ts+++ b/dash/packages/plugins/src/agents/impl/kiro/index.ts@@ -66,7 +66,7 @@ export const plugin = definePlugin(sessions: {kind: 'resumable',},- subagents: { kind: 'none' },+ repoAgents: { kind: 'none' },switchSetup: { kind: 'none' },},{ icon }diff --git a/dash/packages/plugins/src/agents/impl/letta/index.ts b/dash/packages/plugins/src/agents/impl/letta/index.tsindex bc085e69b..a167582c2 100644--- a/dash/packages/plugins/src/agents/impl/letta/index.ts+++ b/dash/packages/plugins/src/agents/impl/letta/index.ts@@ -40,7 +40,7 @@ export const plugin = definePlugin(sessions: {kind: 'resumable',},- subagents: { kind: 'none' },+ repoAgents: { kind: 'none' },switchSetup: { kind: 'none' },},{ icon }diff --git a/dash/packages/plugins/src/agents/impl/mistral/index.ts b/dash/packages/plugins/src/agents/impl/mistral/index.tsindex fe496d815..016a965d9 100644--- a/dash/packages/plugins/src/agents/impl/mistral/index.ts+++ b/dash/packages/plugins/src/agents/impl/mistral/index.ts@@ -67,7 +67,7 @@ export const plugin = definePlugin(sessions: {kind: 'stateless',},- subagents: { kind: 'none' },+ repoAgents: { kind: 'none' },switchSetup: { kind: 'none' },},{ icon }diff --git a/dash/packages/plugins/src/agents/impl/opencode/index.ts b/dash/packages/plugins/src/agents/impl/opencode/index.tsindex 99d418521..487534a7d 100644--- a/dash/packages/plugins/src/agents/impl/opencode/index.ts+++ b/dash/packages/plugins/src/agents/impl/opencode/index.ts@@ -51,7 +51,7 @@ export const plugin = definePlugin(sessions: {kind: 'resumable',},- subagents: { kind: 'none' },+ repoAgents: { kind: 'none' },switchSetup: { kind: 'none' },},{ icon }diff --git a/dash/packages/plugins/src/agents/impl/pi/index.ts b/dash/packages/plugins/src/agents/impl/pi/index.tsindex 87721cc58..edf75ea0d 100644--- a/dash/packages/plugins/src/agents/impl/pi/index.ts+++ b/dash/packages/plugins/src/agents/impl/pi/index.ts@@ -51,7 +51,7 @@ export const plugin = definePlugin(sessions: {kind: 'resumable',},- subagents: { kind: 'none' },+ repoAgents: { kind: 'none' },switchSetup: { kind: 'none' },},{ icon }diff --git a/dash/packages/plugins/src/agents/impl/qwen/index.ts b/dash/packages/plugins/src/agents/impl/qwen/index.tsindex e39f4fd7c..077035da7 100644--- a/dash/packages/plugins/src/agents/impl/qwen/index.ts+++ b/dash/packages/plugins/src/agents/impl/qwen/index.ts@@ -46,7 +46,7 @@ export const plugin = definePlugin(sessions: {kind: 'resumable',},- subagents: { kind: 'none' },+ repoAgents: { kind: 'none' },switchSetup: { kind: 'none' },},{ icon }diff --git a/dash/packages/plugins/src/agents/impl/rovo/index.ts b/dash/packages/plugins/src/agents/impl/rovo/index.tsindex ed314bb33..afe92bc37 100644--- a/dash/packages/plugins/src/agents/impl/rovo/index.ts+++ b/dash/packages/plugins/src/agents/impl/rovo/index.ts@@ -58,7 +58,7 @@ export const plugin = definePlugin(sessions: {kind: 'stateless',},- subagents: { kind: 'none' },+ repoAgents: { kind: 'none' },switchSetup: { kind: 'none' },},{ icon }