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): agent delete cleanup — creds teardown + optional Switch delete (CHOO-1364) (#53)
Louis Amaudruz1df18e97c7dc
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/controller.ts b/dash/apps/switchdash-desktop/src/main/core/agents/controller.tsindex 84cd6af5c..0aec5e382 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/controller.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/controller.ts@@ -4,7 +4,7 @@ import type { AgentVerifyResult } from '@shared/core/switch-servers/switch-serveimport { createRPCController } from '@shared/lib/ipc/rpc';import { assignAgentServer } from './assignAgentServer';import { createAgent } from './createAgent';-import { deleteAgent } from './deleteAgent';+import { deleteAgent, type DeleteAgentOptions } from './deleteAgent';import { getAgentById } from './getAgentById';import { getAgents } from './getAgents';import { onboardAgent } from './onboard-agent';@@ -22,7 +22,8 @@ export const agentsController = createRPCController({getAgents: (locationId?: string) => getAgents(locationId),getAgentById: (agentId: string) => getAgentById(agentId),renameAgent: (params: RenameAgentParams) => renameAgent(params),- deleteAgent: (agentId: string) => deleteAgent(agentId),+ deleteAgent: (params: { agentId: string } & DeleteAgentOptions) =>+ deleteAgent(params.agentId, { deleteInSwitch: params.deleteInSwitch }),updateAgent: (params: UpdateAgentParams) => updateAgent(params),assignServer: (params: { agentId: string; serverId: string }): Promise<AgentVerifyResult> =>assignAgentServer(params),diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/deleteAgent.ts b/dash/apps/switchdash-desktop/src/main/core/agents/deleteAgent.tsindex bc11cb538..673e38d95 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/deleteAgent.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/deleteAgent.ts@@ -1,39 +1,126 @@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 { autoSessionWatcher } from '@main/core/switch-rooms/auto-session-watcher';+import {+ deleteAgent as gatewayDeleteAgent,+ fetchAgentChildren,+} 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 { sessionRuntimeManager } from '../sessions/session-runtime-manager';import { agentEvents } from './agent-events';import { getAgentLocation } from './agent-location';import { getAgentById } from './getAgentById';import { stopRemoteWatcher } from './remote-watcher';+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.+ */+ deleteInSwitch: boolean;+};++/**+ * Delete the agent's identity on the Switch server, cascading to its subagents.+ *+ * 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.+ */+async function deleteAgentInSwitch(agent: Agent): Promise<void> {+ if (!agent.serverId || !agent.switchAgentId) {+ throw new Error(+ `Agent ${agent.id} is not linked to a Switch server, so it cannot be deleted in Switch.`+ );+ }+ 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.+ *+ * 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);+ 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),+ });+ });+ }+ }+ await removeSwitchCredentials(agent.providerId, ctx.fs);+ } finally {+ ctx.close();+ }+}/*** Delete an agent — the one real delete entry point (the sidebar's Remove* Agent routes here). Tears down everything a bare row delete would leak:*- * 1. The agent's running sessions (runtime + view-state), which previously+ * 1. The agent's identity on the Switch server, cascading to its subagents —+ * 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.- * 2. Its auto_session watcher (or, for a remote agent, the on-VM sidecar's+ * 3. Its auto_session watcher (or, for a remote agent, the on-VM sidecar's* watch flag + reconciler) and the local auto_session mirror. The watcher* caches the agent's Switch credentials in memory, so without an explicit* stop it keeps heartbeating and polling notifications for an agent that* no longer exists.+ * 4. The Switch credentials + subagent files switchdash provisioned on disk+ * (local or remote), which a bare row delete would leave orphaned.** The agent's location row is intentionally kept — locations are reusable* and other agents may still live there.*/-export async function deleteAgent(agentId: string): Promise<void> {+export async function deleteAgent(agentId: string, options: DeleteAgentOptions): Promise<void> {const agent = await getAgentById(agentId);const location = agent ? await getAgentLocation(agent).catch(() => null) : null;+ // Gateway cascade first: fail loud before touching local state so a failure+ // never leaves the row deleted but the Switch identity orphaned.+ if (options.deleteInSwitch && agent) {+ await deleteAgentInSwitch(agent);+ }+const sessionRows = await db.select({ id: sessions.id }).from(sessions)@@ -60,6 +147,15 @@ export async function deleteAgent(agentId: string): Promise<void> {}await setAutoSessionAgent(agentId, false);+ if (agent) {+ await removeProvisionedFiles(agent).catch((error) => {+ log.warn('deleteAgent: failed to remove provisioned files', {+ agentId,+ error: String(error),+ });+ });+ }+await db.delete(agents).where(eq(agents.id, agentId));agentEvents._emit('agent:deleted', agentId);}diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/remove-switch-settings.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/remove-switch-settings.test.tsnew file mode 100644index 000000000..6c42510df--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agents/remove-switch-settings.test.ts@@ -0,0 +1,73 @@+import type { PluginFs } from '@switchdash/core/agents/plugins';+import { describe, expect, it } from 'vitest';+import { mergeSwitchSettings } from './write-switch-settings';+import { removeSwitchCredentials } from './remove-switch-settings';++const SETTINGS_PATH = '.claude/settings.local.json';++/** An in-memory PluginFs backed by a Map, enough for the default teardown path. */+function fakeFs(initial: Record<string, string>): PluginFs & { files: Map<string, string> } {+ const files = new Map(Object.entries(initial));+ return {+ files,+ read: (p: string) => Promise.resolve(files.get(p) ?? null),+ write: (p: string, content: string) => {+ files.set(p, content);+ return Promise.resolve();+ },+ delete: (p: string) => {+ files.delete(p);+ return Promise.resolve();+ },+ exists: (p: string) => Promise.resolve(files.has(p)),+ list: () => Promise.resolve([]),+ };+}++// The claude provider declares no switchSetup behavior, so it exercises the+// default `.claude/settings.local.json` reverse-merge path.+describe('removeSwitchCredentials (default .claude teardown)', () => {+ it('deletes a settings file that held only provisioned Switch credentials', async () => {+ const fs = fakeFs({+ [SETTINGS_PATH]: mergeSwitchSettings(null, {+ apiEndpoint: 'https://switch.example.com',+ apiToken: 'secret-token',+ agentId: 'agent-123',+ }),+ });++ await removeSwitchCredentials('claude', fs);++ expect(fs.files.has(SETTINGS_PATH)).toBe(false);+ });++ it('preserves the user’s own keys, stripping only the Switch block', async () => {+ const fs = fakeFs({+ [SETTINGS_PATH]: JSON.stringify({+ permissions: { allow: ['Bash', 'mcp__plugin_switch-connector_switch'] },+ env: { EDITOR: 'vim', SWITCH_API_ENDPOINT: 'e', SWITCH_API_TOKEN: 't', SWITCH_AGENT_ID: 'a' },+ }),+ });++ await removeSwitchCredentials('claude', fs);++ const parsed = JSON.parse(fs.files.get(SETTINGS_PATH)!) as Record<string, unknown>;+ expect(parsed.env).toEqual({ EDITOR: 'vim' });+ expect(parsed.permissions).toEqual({ allow: ['Bash'] });+ });++ it('leaves a file that is not a provisioned Switch agent untouched', async () => {+ const original = JSON.stringify({ env: { EDITOR: 'vim' } });+ const fs = fakeFs({ [SETTINGS_PATH]: original });++ await removeSwitchCredentials('claude', fs);++ expect(fs.files.get(SETTINGS_PATH)).toBe(original);+ });++ it('is a no-op when there is no settings file', async () => {+ const fs = fakeFs({});+ await expect(removeSwitchCredentials('claude', fs)).resolves.toBeUndefined();+ expect(fs.files.size).toBe(0);+ });+});diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/remove-switch-settings.ts b/dash/apps/switchdash-desktop/src/main/core/agents/remove-switch-settings.tsnew file mode 100644index 000000000..233aa9409--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agents/remove-switch-settings.ts@@ -0,0 +1,43 @@+import type { PluginFs } from '@switchdash/core/agents/plugins';+import { getPlugin } from '@main/core/providers/plugin-registry';+import { removeSwitchSettings } from './write-switch-settings';++// Rooted at the agent's working dir and used against both local and remote+// (SFTP) PluginFs, so use a forward-slash literal rather than the+// platform-dependent SWITCH_SETTINGS_RELATIVE_PATH (which emits backslashes on+// Windows and would not resolve on a POSIX host).+const SWITCH_SETTINGS_POSIX_PATH = '.claude/settings.local.json';++/**+ * Reverse the default `.claude/settings.local.json` provisioning: strip the+ * `SWITCH_*` env block and connector allow-rules, deleting the file if it was+ * ours alone and leaving it untouched if it was never a provisioned Switch agent.+ * Operates through `PluginFs`, so it works byte-identically for a local working+ * directory and a remote SSH host.+ */+async function removeDefaultSwitchCredentials(fs: PluginFs): Promise<void> {+ const existing = await fs.read(SWITCH_SETTINGS_POSIX_PATH);+ const result = removeSwitchSettings(existing);+ if (result.kind === 'skip') return;+ if (result.kind === 'delete') {+ await fs.delete(SWITCH_SETTINGS_POSIX_PATH);+ return;+ }+ await fs.write(SWITCH_SETTINGS_POSIX_PATH, result.content);+}++/**+ * Tear down the Switch credentials an agent of `providerId` wrote at provision+ * time. Providers that store their credentials somewhere other than the default+ * `.claude` layout own that teardown via `behavior.switchSetup.removeCredentials`;+ * every other provider falls through to the default reverse-merge. `fs` is rooted+ * at the agent's working directory (local or remote), so one call covers both.+ */+export async function removeSwitchCredentials(providerId: string, fs: PluginFs): Promise<void> {+ const behavior = getPlugin(providerId).behavior.switchSetup;+ if (behavior) {+ await behavior.removeCredentials(fs);+ return;+ }+ await removeDefaultSwitchCredentials(fs);+}diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.test.tsindex d61de7d60..1bc199834 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.test.ts@@ -4,7 +4,12 @@ import path from 'node:path';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { detectSwitchAgent } from './detect';import { SWITCH_SETTINGS_RELATIVE_PATH } from './switch-settings-paths';-import { mergeSwitchApiEndpoint, writeSwitchSettings } from './write-switch-settings';+import {+ mergeSwitchApiEndpoint,+ mergeSwitchSettings,+ removeSwitchSettings,+ writeSwitchSettings,+} from './write-switch-settings';let dir: string;@@ -131,3 +136,98 @@ describe('mergeSwitchApiEndpoint', () => {).toBeNull();});});++describe('removeSwitchSettings', () => {+ it('round-trips a freshly provisioned file to deletion', () => {+ // A file written by mergeSwitchSettings with no pre-existing content is ours+ // alone, so tearing it down should leave nothing behind.+ const provisioned = mergeSwitchSettings(null, {+ apiEndpoint: 'https://switch.example.com',+ apiToken: 'secret-token',+ agentId: 'agent-123',+ });++ expect(removeSwitchSettings(provisioned)).toEqual({ kind: 'delete' });+ });++ it('strips only the SWITCH_* keys and connector rules, preserving everything else', () => {+ const existing = JSON.stringify({+ permissions: { allow: ['Bash', 'mcp__plugin_switch-connector_switch'], deny: ['Read'] },+ hooks: { PostToolUse: [{ command: 'x' }] },+ env: {+ EXISTING_KEY: 'keep-me',+ SWITCH_API_ENDPOINT: 'https://switch.example.com',+ SWITCH_API_TOKEN: 'secret-token',+ SWITCH_AGENT_ID: 'agent-123',+ },+ });++ const result = removeSwitchSettings(existing);+ expect(result.kind).toBe('write');+ const parsed = JSON.parse((result as { content: string }).content) as Record<string, unknown>;++ // Our env keys are gone; the user's stays.+ expect(parsed.env).toEqual({ EXISTING_KEY: 'keep-me' });+ // The connector allow rule is removed; the user's allow/deny rules stay.+ expect(parsed.permissions).toEqual({ allow: ['Bash'], deny: ['Read'] });+ // Unrelated keys are untouched.+ expect(parsed.hooks).toEqual({ PostToolUse: [{ command: 'x' }] });+ });++ it('drops now-empty env and permissions blocks but keeps other keys', () => {+ const existing = JSON.stringify({+ hooks: { PostToolUse: [{ command: 'x' }] },+ permissions: {+ allow: [+ 'mcp__plugin_switch-connector_switch',+ 'mcp__plugin_switch-connector_switch-channel',+ ],+ },+ env: { SWITCH_API_ENDPOINT: 'e', SWITCH_API_TOKEN: 't', SWITCH_AGENT_ID: 'a' },+ });++ const result = removeSwitchSettings(existing);+ expect(result.kind).toBe('write');+ const parsed = JSON.parse((result as { content: string }).content) as Record<string, unknown>;++ // Both blocks held only our contributions, so both are dropped entirely.+ expect(parsed).toEqual({ hooks: { PostToolUse: [{ command: 'x' }] } });+ expect('env' in parsed).toBe(false);+ expect('permissions' in parsed).toBe(false);+ });++ it('skips files that are not a provisioned Switch agent', () => {+ // Absent file.+ expect(removeSwitchSettings(null)).toEqual({ kind: 'skip' });+ // Unparseable.+ expect(removeSwitchSettings('{not json')).toEqual({ kind: 'skip' });+ // Empty object.+ expect(removeSwitchSettings('{}')).toEqual({ kind: 'skip' });+ // A real config with no Switch creds -> leave it untouched.+ expect(removeSwitchSettings(JSON.stringify({ env: { OTHER: 'x' } }))).toEqual({ kind: 'skip' });+ });++ it('tears down even a partially-provisioned file (only some SWITCH_* keys)', () => {+ // Defensive: if a write was interrupted and only the token survived, teardown+ // must still remove it rather than leaving a dangling secret.+ const existing = JSON.stringify({ env: { SWITCH_API_TOKEN: 'secret-token' } });+ expect(removeSwitchSettings(existing)).toEqual({ kind: 'delete' });+ });++ it('leaves the directory undetectable as a Switch agent after teardown', async () => {+ await writeSwitchSettings({+ dir,+ apiEndpoint: 'https://switch.example.com',+ apiToken: 'secret-token',+ agentId: 'agent-123',+ });+ const raw = await fs.readFile(path.join(dir, SWITCH_SETTINGS_RELATIVE_PATH), 'utf8');++ const result = removeSwitchSettings(raw);+ // The file was ours alone -> delete it, which makes the dir undetectable.+ expect(result).toEqual({ kind: 'delete' });+ await fs.rm(path.join(dir, SWITCH_SETTINGS_RELATIVE_PATH), { force: true });++ expect(await detectSwitchAgent(dir)).toBeNull();+ });+});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 3915200a9..aef407283 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@@ -122,6 +122,92 @@ export function mergeSwitchApiEndpoint(return `${JSON.stringify(merged, null, 2)}\n`;}+/**+ * Reverse of {@link mergeSwitchSettings}: strip the `SWITCH_*` env block and the+ * connector tool-allow rules that provisioning added, returning what to do with+ * the file. Every other key — user env entries, other `permissions.allow` rules,+ * `hooks`, and any unrelated top-level keys — is preserved byte-for-byte.+ *+ * The result is a small command rather than a bare string so the caller can tell+ * "nothing of ours here, leave it" (`skip`) from "our keys were the only thing in+ * the file, remove it" (`delete`) from "rewrite with our keys gone" (`write`):+ * - `skip` — file absent/unparseable, or it carries no `SWITCH_*` credentials+ * (not a provisioned agent) — do not touch it.+ * - `delete` — after removing our keys the object is empty `{}` — the file was+ * ours alone, so remove it rather than leaving an empty husk.+ * - `write` — the cleaned file text, with our keys gone and everything else kept.+ *+ * Pure: takes the existing file text (or null when absent/unreadable) and returns+ * the command. Shared by the local and remote (SFTP) teardown paths so both+ * produce byte-identical results.+ */+export type RemoveSwitchSettingsResult =+ | { kind: 'skip' }+ | { kind: 'write'; content: string }+ | { kind: 'delete' };++export function removeSwitchSettings(existingRaw: string | null): RemoveSwitchSettingsResult {+ if (existingRaw === null) return { kind: 'skip' };++ let parsed: unknown;+ try {+ parsed = JSON.parse(existingRaw);+ } catch {+ return { kind: 'skip' };+ }+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return { kind: 'skip' };++ const existing = parsed as Record<string, unknown>;+ const env =+ existing.env && typeof existing.env === 'object' && !Array.isArray(existing.env)+ ? { ...(existing.env as Record<string, unknown>) }+ : null;++ // No `SWITCH_*` credentials -> this is not a provisioned Switch agent; leave the+ // file exactly as it is rather than rewriting someone else's config.+ const hasSwitchCreds =+ env !== null &&+ ('SWITCH_API_ENDPOINT' in env || 'SWITCH_API_TOKEN' in env || 'SWITCH_AGENT_ID' in env);+ if (!hasSwitchCreds) return { kind: 'skip' };++ const result: Record<string, unknown> = { ...existing };++ delete env.SWITCH_API_ENDPOINT;+ delete env.SWITCH_API_TOKEN;+ delete env.SWITCH_AGENT_ID;+ if (Object.keys(env).length > 0) {+ result.env = env;+ } else {+ delete result.env;+ }++ const perms =+ existing.permissions &&+ typeof existing.permissions === 'object' &&+ !Array.isArray(existing.permissions)+ ? { ...(existing.permissions as Record<string, unknown>) }+ : null;+ if (perms && Array.isArray(perms.allow)) {+ const connectorRules = SWITCH_CONNECTOR_TOOL_RULES as readonly string[];+ const allow = (perms.allow as unknown[])+ .map(String)+ .filter((rule) => !connectorRules.includes(rule));+ if (allow.length > 0) {+ perms.allow = allow;+ } else {+ delete perms.allow;+ }+ if (Object.keys(perms).length > 0) {+ result.permissions = perms;+ } else {+ delete result.permissions;+ }+ }++ if (Object.keys(result).length === 0) return { kind: 'delete' };+ return { kind: 'write', content: `${JSON.stringify(result, null, 2)}\n` };+}+/*** Write the `SWITCH_*` env block into a local directory's* `.claude/settings.local.json`, the same file the switch-connectordiff --git a/dash/apps/switchdash-desktop/src/renderer/app/modal-registry.ts b/dash/apps/switchdash-desktop/src/renderer/app/modal-registry.tsindex 58b8dcf12..1664f1b54 100644--- a/dash/apps/switchdash-desktop/src/renderer/app/modal-registry.ts+++ b/dash/apps/switchdash-desktop/src/renderer/app/modal-registry.ts@@ -1,5 +1,6 @@import { CommandPaletteModal } from '@renderer/features/command-palette/command-palette-modal';import { AddAgentModal } from '@renderer/features/locations/components/add-agent-modal/add-agent-modal';+import { DeleteAgentModal } from '@renderer/features/locations/components/delete-agent-modal';import { CreateSessionModal } from '@renderer/features/sessions/create-session-modal/create-session-modal';import { DeleteSessionModal } from '@renderer/features/sessions/delete-session-modal';import { RenameSessionModal } from '@renderer/features/sessions/rename-session-modal';@@ -32,6 +33,7 @@ export const modalRegistry = {sessionModal: createModal(CreateSessionModal),addAgentModal: createModal(AddAgentModal),confirmActionModal: createModal(ConfirmActionDialog, { size: 'xs' }),+ deleteAgentModal: createModal(DeleteAgentModal, { size: 'sm' }),confirmExternalLinkModal: createModal(ExternalLinkChoiceDialog, { size: 'sm' }),unsavedChangesModal: createModal(UnsavedChangesDialog, { size: 'xs' }),feedbackModal: createModal(FeedbackModal),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.tsxnew file mode 100644index 000000000..d8fed7a22--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/delete-agent-modal.tsx@@ -0,0 +1,91 @@+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';+import { ConfirmButton } from '@renderer/lib/ui/confirm-button';+import {+ DialogContentArea,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@renderer/lib/ui/dialog';++export type DeleteAgentModalArgs = {+ /** switchdash id of the agent to remove. */+ agentId: string;+ /** Display name for the agent (its Switch name, falling back to the location). */+ agentLabel: string;+};++/** What the confirm resolves with: whether to also delete the agent in Switch. */+export type DeleteAgentModalResult = { deleteInSwitch: boolean };++type Props = BaseModalProps<DeleteAgentModalResult> & DeleteAgentModalArgs;++export function DeleteAgentModal({ agentId, 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}>+ <DialogTitle>Remove agent</DialogTitle>+ </DialogHeader>+ <DialogContentArea className="flex flex-col gap-4 pt-0">+ <p className="text-sm text-foreground-muted">+ <span className="font-medium text-foreground">{agentLabel}</span> will be removed from+ switchdash and the Switch credentials it stored on this machine will be cleared. The+ folder stays on the filesystem.+ </p>++ <label className="group/field flex cursor-pointer items-start gap-2.5">+ <Checkbox+ checked={deleteInSwitch}+ onCheckedChange={(checked) => setDeleteInSwitch(checked === true)}+ className="mt-0.5"+ />+ <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.+ </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}>+ Cancel+ </Button>+ <ConfirmButton variant="destructive" onClick={() => onSuccess({ deleteInSwitch })}>+ {deleteInSwitch ? 'Remove & delete in Switch' : 'Remove'}+ </ConfirmButton>+ </DialogFooter>+ </>+ );+}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 521c9dca4..d13167d67 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,8 +1,12 @@import { getLocationManagerStore } from '@renderer/features/locations/stores/location-selectors';+import { useToast } from '@renderer/lib/hooks/use-toast';+import { rpc } from '@renderer/lib/ipc';import { useShowModal } from '@renderer/lib/modal/modal-provider';+import { log } from '@renderer/utils/logger';export function useConfirmDeleteAgent() {- const showConfirmDeleteLocation = useShowModal('confirmActionModal');+ const showDeleteAgent = useShowModal('deleteAgentModal');+ const { toast } = useToast();return async ({locationId,@@ -13,13 +17,29 @@ export function useConfirmDeleteAgent() {locationLabel: string;onDeleted?: () => void;}) => {- showConfirmDeleteLocation({- title: 'Remove agent',- description: `"${locationLabel}" will be removed from switchdash. The folder stays on the filesystem.`,- confirmLabel: 'Remove',- onSuccess: () => {- void getLocationManagerStore().removeLocation(locationId);- onDeleted?.();+ // 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;++ showDeleteAgent({+ agentId: agent.id,+ agentLabel: locationLabel,+ onSuccess: ({ deleteInSwitch }) => {+ void (async () => {+ try {+ await getLocationManagerStore().removeAgent(locationId, agent.id, { deleteInSwitch });+ onDeleted?.();+ } catch (error) {+ log.error('Failed to remove agent', { agentId: agent.id, error });+ toast({+ title: 'Failed to remove agent',+ description: error instanceof Error ? error.message : String(error),+ variant: 'destructive',+ });+ }+ })();},});};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 c266beff1..11754cf5b 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@@ -235,7 +235,35 @@ export class LocationManagerStore {});appState.navigation.revalidate();try {- await Promise.all(agents.map((agent) => rpc.agents.deleteAgent(agent.id)));+ await Promise.all(+ agents.map((agent) => rpc.agents.deleteAgent({ agentId: agent.id, deleteInSwitch: false }))+ );+ } catch (error) {+ runInAction(() => {+ if (snapshot) this.locations.set(locationId, snapshot);+ });+ throw error;+ }+ }++ /**+ * Remove a single agent (the sidebar's per-agent "Remove Agent" action),+ * optionally deleting its identity in Switch too. Drops the location from the+ * sidebar optimistically — an agent maps one-to-one to its location row here —+ * and rolls back if the delete fails.+ */+ async removeAgent(+ locationId: string,+ agentId: string,+ options: { deleteInSwitch: boolean }+ ): Promise<void> {+ const snapshot = this.locations.get(locationId);+ runInAction(() => {+ this.locations.delete(locationId);+ });+ appState.navigation.revalidate();+ try {+ await rpc.agents.deleteAgent({ agentId, deleteInSwitch: options.deleteInSwitch });} catch (error) {runInAction(() => {if (snapshot) this.locations.set(locationId, snapshot);diff --git a/dash/packages/core/src/agents/plugins/capabilities/switch-setup.ts b/dash/packages/core/src/agents/plugins/capabilities/switch-setup.tsindex ec31ecb4b..636dbd818 100644--- a/dash/packages/core/src/agents/plugins/capabilities/switch-setup.ts+++ b/dash/packages/core/src/agents/plugins/capabilities/switch-setup.ts@@ -1,5 +1,22 @@import z from 'zod';import { definePluginCapability } from '../../../lib/plugins/capability';+import type { PluginFs } from '../../runtime/fs';++/**+ * Provider-owned teardown of the Switch credentials this agent type wrote at+ * provision time — the inverse of the credential-writing side of setup.+ *+ * A provider only needs to implement this when it stores its Switch credentials+ * somewhere other than the default `.claude/settings.local.json` env block (which+ * the generic teardown already handles for every agent that follows the+ * Claude-Code layout). Implement it to remove whatever/wherever this agent type+ * persisted its `SWITCH_*` credentials, so deleting the agent leaves no orphaned+ * secrets. `fs` is rooted at the agent's working directory and works identically+ * for a local dir or a remote SSH host, so one implementation covers both.+ */+export type ISwitchSetupBehavior = {+ removeCredentials(fs: PluginFs): Promise<void>;+};/*** Describes how an agent type installs and manages its Switch connector plugin.@@ -10,10 +27,13 @@ import { definePluginCapability } from '../../../lib/plugins/capability';* service drives that CLI from these descriptor fields.* kind: 'none' — the agent has no Switch connector setup; the UI surfaces nothing.*- * No behavior contract: everything the service needs is declarative, so the- * generic CLI driver handles all agents that share the marketplace model.+ * The descriptor is purely declarative — the generic CLI driver handles plugin+ * install/update for every agent that shares the marketplace model. The optional+ * {@link ISwitchSetupBehavior} is only for the one thing that can be genuinely+ * provider-specific: where credentials live on disk, so they can be torn down on+ * delete. Providers using the default `.claude` layout omit it.*/-export const switchSetupCapability = definePluginCapability()(+export const switchSetupCapability = definePluginCapability<ISwitchSetupBehavior>()('switch-setup',z.discriminatedUnion('kind', [z.object({diff --git a/dash/packages/core/src/agents/plugins/index.ts b/dash/packages/core/src/agents/plugins/index.tsindex c4801137a..a61721a89 100644--- a/dash/packages/core/src/agents/plugins/index.ts+++ b/dash/packages/core/src/agents/plugins/index.ts@@ -84,7 +84,7 @@ export type {SubagentFieldType,SubagentsDescriptor,} from './capabilities/subagents';-export type { SwitchSetupDescriptor } from './capabilities/switch-setup';+export type { ISwitchSetupBehavior, SwitchSetupDescriptor } from './capabilities/switch-setup';// Typed registry factoryexport { createPluginRegistry } from '../../lib/plugins/registry';