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
fix(switchdash): refuse to import an identity issued by another server (CHOO-2044)
Louis Amaudruz5d7307af2cbe
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 64f3439ff..c5941598c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -313,6 +313,14 @@ version of their own to them without also giving them a release of their own.onboarding a single agent to a second server appeared to drag the rest acrosswith it. Nothing had been onboarded; each agent is now drawn under its ownserver, and a shared directory shows under all of them (CHOO-2044).+- Onboarding an agent whose credentials belong to **another** Switch server no+ longer overwrites those credentials. The import path looked the existing+ identity up on the target server, did not find it, and fell back to minting a+ fresh one — writing it back over the same `.switch/agents/<name>.json` and+ silently breaking the agent the other server was still running. It now refuses+ and names the server the identity belongs to. Such agents are listed in the+ Add Agent modal but not selectable, with the reason shown; a plain definition+ carrying no Switch identity is still adopted as before (CHOO-2044).- The Add Agent modal no longer offers a permanently disabled button over a listit will not submit. A directory carrying another server's leftover`.claude/settings.local.json` took the detected-agent branch, verified thatdiff --git a/dash/apps/switchdash-desktop/src/main/core/agents/attach-configured-agents.ts b/dash/apps/switchdash-desktop/src/main/core/agents/attach-configured-agents.tsindex a26563a6f..ed4aa77aa 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/attach-configured-agents.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/attach-configured-agents.ts@@ -10,6 +10,7 @@ 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 { sameApiEndpoint } from '@shared/core/switch-servers/switch-servers';import { basenameFromAnyPath } from '@shared/path-name';import { agentEvents } from './agent-events';import { createAgent } from './createAgent';@@ -32,11 +33,6 @@ export type AttachConfiguredAgentsParams = {export type AttachConfiguredAgentsResult = Result<Agent[], OnboardAgentError>;-/** Compare endpoints ignoring a trailing slash, which is not a difference. */-function sameEndpoint(a: string, b: string): boolean {- return a.replace(/\/+$/, '') === b.replace(/\/+$/, '');-}-/*** Adopt agents already configured in a working directory into this switchdash,* under the Switch identity they already have (CHOO-1937).@@ -145,7 +141,7 @@ export async function attachConfiguredAgents(// are read from the same on-disk file. A difference is legitimate (one Switch// server reachable at two URLs) so it is surfaced, not corrected — correcting// it would mean writing to another install's credentials.- if (!sameEndpoint(found.apiEndpoint, server.apiUrl)) {+ if (!sameApiEndpoint(found.apiEndpoint, server.apiUrl)) {log.warn('attachConfiguredAgents: directory endpoint differs from the chosen server', {name,dirEndpoint: found.apiEndpoint,diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/discover-location-agents.ts b/dash/apps/switchdash-desktop/src/main/core/agents/discover-location-agents.tsindex 8459bc674..be89f43a8 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/discover-location-agents.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/discover-location-agents.ts@@ -10,6 +10,12 @@ export type DiscoveredLocationAgent = {description: string | null;/** Whether the definition already carries Switch credentials on disk. */registered: boolean;+ /** The Switch endpoint those credentials name, when they carry one. This is+ * which server the existing identity belongs to — an identity can only be+ * imported into the server that issued it, so the modal needs it to tell an+ * importable row from one that belongs elsewhere (CHOO-2044). Null for a plain+ * definition with no Switch setup, which is adoptable anywhere. */+ credentialEndpoint: string | null;/** Whether the definition can join Switch (its tools allowlist keeps the* connector's MCP tools, or it inherits all tools). */eligible: boolean;@@ -49,11 +55,14 @@ export async function discoverLocationAgents(params: {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));+ const credentialled = new Map(+ local.filter((l) => l.switchAgentId !== null).map((l) => [l.name, l.apiEndpoint])+ );return definitions.map((def) => ({name: def.name,description: def.description,registered: def.registered || credentialled.has(def.name),+ credentialEndpoint: credentialled.get(def.name) ?? null,eligible: def.eligible,alreadyAgent: existing.has(def.name),}));diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/onboard-location-agents.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/onboard-location-agents.test.tsnew file mode 100644index 000000000..3dbdfb46a--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agents/onboard-location-agents.test.ts@@ -0,0 +1,215 @@+import type { PluginFs } from '@switchdash/core/agents/plugins';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const h = vi.hoisted(() => {+ class GatewayError extends Error {+ constructor(readonly kind: string) {+ super(kind);+ }+ }+ const state: {+ /** Agent-row names already in the directory, per Switch server. */+ agentNamesByServer: Record<string, string[]>;+ definitions: Array<{+ name: string;+ description: string | null;+ eligible: boolean;+ registered: boolean;+ }>;+ /** On-disk credentials per definition name. */+ local: Array<{ name: string; switchAgentId: string | null; apiEndpoint: string | null }>;+ /** Switch agent ids the target server admits to having. */+ idsOnServer: string[];+ } = { agentNamesByServer: {}, definitions: [], local: [], idsOnServer: [] };+ return {+ state,+ GatewayError,+ warn: vi.fn(),+ createAgent: vi.fn(async (input: Record<string, unknown>) => ({ ...input, id: 'agent-row' })),+ agentExistsOnServer: vi.fn(async (_server: unknown, agentId: string) =>+ h.state.idsOnServer.includes(agentId)+ ),+ registerAgentIdentity: vi.fn(async () => ({+ kind: 'created' as const,+ id: 'sw-fresh',+ apiKey: 'tok-fresh',+ })),+ writeNeutralAgentSettings: vi.fn(async () => {}),+ openLocation: vi.fn(async () => {}),+ emit: vi.fn(),+ };+});++vi.mock('@main/core/locations/store', () => ({+ ensureLocation: vi.fn(async () => ({ id: 'loc-1' })),+}));+vi.mock('./getAgents', () => ({+ getLocationAgentsOnServer: vi.fn(async (_locationId: string, serverId: string) =>+ (h.state.agentNamesByServer[serverId] ?? []).map((name) => ({ name }))+ ),+}));+vi.mock('./agent-workspace-fs', () => ({+ resolveWorkspaceFsFor: vi.fn(async () => ({+ fs: {} as PluginFs,+ homeFs: {} as PluginFs,+ close: vi.fn(),+ })),+}));+vi.mock('@main/core/providers/plugin-registry', () => ({+ getPlugin: () => ({+ behavior: {+ repoAgents: {+ discoverDefinitions: async () => h.state.definitions,+ discoverLocal: async () => h.state.local,+ },+ },+ }),+}));+vi.mock('@main/core/switch-servers/gateway-client', () => ({+ agentExistsOnServer: h.agentExistsOnServer,+ GatewayError: h.GatewayError,+}));+vi.mock('@main/core/switch-servers/servers-store', () => ({+ getServer: vi.fn(async () => ({+ id: 'srv-b',+ name: 'Server B',+ apiUrl: 'https://b.example.com',+ })),+}));+vi.mock('./createAgent', () => ({ createAgent: h.createAgent }));+vi.mock('./register-agent-identity', () => ({ registerAgentIdentity: h.registerAgentIdentity }));+vi.mock('./write-switch-settings', () => ({+ writeNeutralAgentSettingsFs: h.writeNeutralAgentSettings,+}));+vi.mock('./known-agent-type', () => ({ knownAgentTypeForProvider: () => 'claude-code' }));+vi.mock('@main/core/locations/path-utils', () => ({ checkIsValidDirectory: () => true }));+vi.mock('@main/core/locations/location-manager', () => ({+ locationManager: { openLocation: h.openLocation },+}));+vi.mock('./setAgentAutoSession', () => ({+ reconcileAgentAutoSessionFromGateway: vi.fn(async () => {}),+}));+vi.mock('./agent-events', () => ({ agentEvents: { _emit: h.emit } }));+vi.mock('@main/lib/logger', () => ({ log: { info: vi.fn(), warn: h.warn, error: vi.fn() } }));++const { onboardLocationAgents } = await import('./onboard-location-agents');++const onboard = (names: string[]) =>+ onboardLocationAgents({+ sshHost: null,+ dir: '/repo',+ providerId: 'claude',+ serverId: 'srv-b',+ names,+ });++function definition(name: string, registered: boolean) {+ return { name, description: null, eligible: true, registered };+}++describe('onboardLocationAgents identity resolution', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ h.state.agentNamesByServer = {};+ h.state.definitions = [];+ h.state.local = [];+ h.state.idsOnServer = [];+ });++ it('refuses an identity registered with another server, and writes nothing (CHOO-2044)', async () => {+ // The credentials name server A. Server B does not have that id, and the+ // tempting fallback — mint a fresh identity — writes back over the same+ // credentials file, breaking the agent server A is still running.+ h.state.definitions = [definition('test-1', true)];+ h.state.local = [+ { name: 'test-1', switchAgentId: 'sw-on-a', apiEndpoint: 'https://a.example.com' },+ ];+ h.state.idsOnServer = [];++ const result = await onboard(['test-1']);++ expect(result.success).toBe(false);+ expect(h.registerAgentIdentity).not.toHaveBeenCalled();+ expect(h.writeNeutralAgentSettings).not.toHaveBeenCalled();+ expect(h.createAgent).not.toHaveBeenCalled();+ });++ it('names the other server so the refusal can be acted on', async () => {+ h.state.definitions = [definition('test-1', true)];+ h.state.local = [+ { name: 'test-1', switchAgentId: 'sw-on-a', apiEndpoint: 'https://a.example.com' },+ ];++ const result = await onboard(['test-1']);++ expect(result.success).toBe(false);+ if (result.success) return;+ expect(result.error).toMatchObject({ type: 'error' });+ const message = 'message' in result.error ? result.error.message : '';+ expect(message).toContain('https://a.example.com');+ expect(message).toContain('Server B');+ });++ it('imports an identity the target server does have', async () => {+ h.state.definitions = [definition('mine', true)];+ h.state.local = [+ { name: 'mine', switchAgentId: 'sw-on-b', apiEndpoint: 'https://b.example.com' },+ ];+ h.state.idsOnServer = ['sw-on-b'];++ const result = await onboard(['mine']);++ expect(result.success).toBe(true);+ expect(h.registerAgentIdentity).not.toHaveBeenCalled();+ expect(h.writeNeutralAgentSettings).not.toHaveBeenCalled();+ expect(h.createAgent).toHaveBeenCalledWith(+ expect.objectContaining({ name: 'mine', switchAgentId: 'sw-on-b', serverId: 'srv-b' })+ );+ });++ it('still adopts a plain definition that carries no Switch identity', async () => {+ // The case adoption exists for: nothing on disk to overwrite, so minting is+ // the only way in and is safe.+ h.state.definitions = [definition('plain', false)];+ h.state.local = [{ name: 'plain', switchAgentId: null, apiEndpoint: null }];++ const result = await onboard(['plain']);++ expect(result.success).toBe(true);+ expect(h.registerAgentIdentity).toHaveBeenCalled();+ expect(h.writeNeutralAgentSettings).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ slug: 'plain', agentId: 'sw-fresh' })+ );+ });++ it('reports an unauthenticated server rather than minting past it', async () => {+ h.state.definitions = [definition('mine', true)];+ h.state.local = [+ { name: 'mine', switchAgentId: 'sw-on-b', apiEndpoint: 'https://b.example.com' },+ ];+ h.agentExistsOnServer.mockRejectedValueOnce(new h.GatewayError('unauthorized'));++ const result = await onboard(['mine']);++ expect(result.success).toBe(false);+ if (result.success) return;+ expect(result.error).toMatchObject({ type: 'switch-server-unauthenticated' });+ expect(h.registerAgentIdentity).not.toHaveBeenCalled();+ expect(h.writeNeutralAgentSettings).not.toHaveBeenCalled();+ });++ it('offers a definition already onboarded onto another server', async () => {+ // Same directory, same name, different server — a separate agent.+ h.state.agentNamesByServer = { 'srv-a': ['shared'] };+ h.state.definitions = [definition('shared', false)];+ h.state.local = [{ name: 'shared', switchAgentId: null, apiEndpoint: null }];++ const result = await onboard(['shared']);++ expect(result.success).toBe(true);+ expect(h.createAgent).toHaveBeenCalledWith(+ expect.objectContaining({ name: 'shared', serverId: 'srv-b' })+ );+ });+});diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/onboard-location-agents.ts b/dash/apps/switchdash-desktop/src/main/core/agents/onboard-location-agents.tsindex ae6dcb71d..266c8fdf1 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/onboard-location-agents.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/onboard-location-agents.ts@@ -70,6 +70,13 @@ function registrationError(* 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).+ *+ * A definition that already carries credentials naming an identity this server+ * does not have belongs to a *different* Switch server, and is refused. Minting a+ * fresh identity for it would be the natural-looking fallback and is exactly the+ * wrong move: the credentials are written back under the same name, so the other+ * server's agent is overwritten on disk and stops working, silently (CHOO-2044).+ * Adoption is for definitions with no Switch identity at all.*/async function resolveIdentity(name: string,@@ -104,6 +111,13 @@ async function resolveIdentity(}throw cause;}+ return {+ ok: false,+ error: {+ type: 'error',+ message: `"${name}" is already registered with another Switch server (${creds.apiEndpoint}) and cannot be imported into ${ctx.server.name}. Onboard it from that server, or create a new agent here under a different name.`,+ },+ };}// No usable credentials — adopt: mint a fresh identity and write its creds,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 7aec201b9..6d54dd5ff 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@@ -47,7 +47,10 @@ import {import { log } from '@renderer/utils/logger';import type { AgentProviderConfig } from '@shared/core/agents/agent-provider-config';import { getProvider } from '@shared/core/providers/agent-provider-registry';-import type { ProvisionAgentResult } from '@shared/core/switch-servers/switch-servers';+import {+ sameApiEndpoint,+ 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';@@ -267,24 +270,45 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLocconst attachableAgents = (configuredQuery.data ?? []).filter((a) => !a.alreadyAgent && !definitionNames.has(a.name));+ // An identity belongs to the server that issued it, so importing one into a+ // different server is not a thing that can happen: the onboard path would find+ // the id absent here, mint a replacement, and write it over the credentials the+ // other server's agent runs on. Say who it belongs to and leave it alone — the+ // way in is to create a new agent (CHOO-2044).+ const foreignCredentialReason = (endpoint: string | null): string | null => {+ if (endpoint === null || !targetServer) return null;+ if (sameApiEndpoint(endpoint, targetServer.apiUrl)) return null;+ return `Already registered with another Switch server (${endpoint}), so it cannot be imported into ${targetServer.name}. Create a new agent instead.`;+ };+const onboardableAgents: OnboardableAgent[] = [...definitionAgents.map((a) => ({name: a.name,description: a.description,kind: (a.registered ? 'import' : 'adopt') as AdoptKind,providerLabel: null,+ blockedReason: foreignCredentialReason(a.credentialEndpoint),})),...attachableAgents.map((a) => {const providerId = a.providerId ?? pickState.providerId ?? null;+ const providerLabel = providerId ? (getProvider(providerId)?.name ?? providerId) : null;return {name: a.name,description: null,kind: 'attach' as AdoptKind,- providerLabel: providerId ? (getProvider(providerId)?.name ?? providerId) : null,+ providerLabel,+ blockedReason:+ providerLabel === null+ ? 'Pick an agent type above to attach this one — the directory does not say which runs it.'+ : null,};}),];const hasOnboardable = onboardableAgents.length > 0;+ /** Rows that cannot be brought in — listed with their reason, never selectable. */+ const blockedNames = new Set(+ onboardableAgents.filter((a) => a.blockedReason !== null).map((a) => a.name)+ );/** Attachable rows keyed by name, with the provider resolved for submission. */const attachByName = new Map(attachableAgents.flatMap((a) => {@@ -299,12 +323,12 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLoc// are the checked definitions to onboard (default: all).const [createMode, setCreateMode] = useState(false);const [selectedNames, setSelectedNames] = useState<Set<string>>(new Set());- // Default-select only what can actually be submitted: an attach row whose- // provider is unknown is disabled until a type is picked, and pre-checking it- // would just block the button with no visible cause. Picking a type unblocks- // the row, which changes this key and folds it into the selection.+ // Default-select only what can actually be submitted: a blocked row (unknown+ // provider, or an identity belonging to another server) is disabled, and+ // pre-checking it would just block the button with no visible cause. Resolving+ // the block changes this key and folds the row into the selection.const onboardableKey = onboardableAgents- .filter((a) => !(a.kind === 'attach' && a.providerLabel === null))+ .filter((a) => a.blockedReason === null).map((a) => a.name).join('|');useEffect(() => {@@ -619,11 +643,15 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLocconst handleOnboard = async () => {// `canOnboard` already requires a server; repeated so the calls below narrow.if (!canOnboard || !pickState.serverId) return;- const attachSelected = [...selectedNames].flatMap((name) => {+ // Blocked rows are disabled in the list, so a selected one means the list went+ // stale under the user. Dropping them here keeps a stale tick from reaching a+ // path that would refuse it — or worse, act on it.+ const submittable = [...selectedNames].filter((name) => !blockedNames.has(name));+ const attachSelected = submittable.flatMap((name) => {const providerId = attachByName.get(name);return providerId ? [{ name, providerId }] : [];});- const onboardSelected = [...selectedNames].filter((name) => !attachByName.has(name));+ const onboardSelected = submittable.filter((name) => !attachByName.has(name));if (onboardSelected.length > 0 && !pickState.providerId) return;setSubmitState('creating');setCloseGuard(true);@@ -680,15 +708,16 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLoc}};+ const submittableNames = [...selectedNames].filter((name) => !blockedNames.has(name));// A definition still needs the picked agent type to run under; an attach row// carries its own (inferred from disk, or the picked one as a fallback).- const selectionNeedsProviderPick = [...selectedNames].some((name) => !attachByName.has(name));+ const selectionNeedsProviderPick = submittableNames.some((name) => !attachByName.has(name));// Adopting agents that already exist in the directory still puts them on this// host, so it answers to the same gates as creating one. Omitting them here// let you onboard onto a host that was unreachable or missing prerequisites.const canOnboard =hasOnboardable &&- selectedNames.size > 0 &&+ submittableNames.length > 0 &&!!pickState.serverId &&(!selectionNeedsProviderPick || !!pickState.providerId) &&runHostReachable &&@@ -719,7 +748,7 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLoconClick={() => void handleOnboard()}disabled={!canOnboard}>- {submitState === 'creating' ? 'Adding...' : `Add ${selectedNames.size} selected`}+ {submitState === 'creating' ? 'Adding...' : `Add ${submittableNames.length} selected`}</ConfirmButton>) : switchAgent ? (<ConfirmButtondiff --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.tsxindex fab212bf6..1d020bb57 100644--- 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.tsx@@ -25,6 +25,10 @@ export type OnboardableAgent = {* names one and the modal has no provider picked to fall back on, in which* case the row cannot be selected. */providerLabel: string | null;+ /** Why this row cannot be brought in, or null when it can. Listed-and-disabled+ * rather than hidden: a missing row says nothing, and the reason is usually+ * something the user can act on. */+ blockedReason: string | null;};const BADGE: Record<AdoptKind, string> = {@@ -57,7 +61,7 @@ export function OnboardExistingPanel({</span><div className="flex flex-col gap-0.5">{agents.map((a) => {- const blocked = a.kind === 'attach' && a.providerLabel === null;+ const blocked = a.blockedReason !== null;return (<labelkey={a.name}@@ -83,11 +87,8 @@ export function OnboardExistingPanel({</span>)}</div>- {blocked ? (- <span className="text-xs text-foreground-muted">- Pick an agent type above to attach this one — the directory does not say which- runs it.- </span>+ {a.blockedReason !== null ? (+ <span className="text-xs text-foreground-muted">{a.blockedReason}</span>) : (a.description && (<span className="truncate text-xs text-foreground-muted">{a.description}</span>diff --git a/dash/apps/switchdash-desktop/src/shared/core/switch-servers/switch-servers.ts b/dash/apps/switchdash-desktop/src/shared/core/switch-servers/switch-servers.tsindex ceaa12fd9..6f2399b35 100644--- a/dash/apps/switchdash-desktop/src/shared/core/switch-servers/switch-servers.ts+++ b/dash/apps/switchdash-desktop/src/shared/core/switch-servers/switch-servers.ts@@ -9,6 +9,17 @@* in the encrypted secrets store, never in plain settings.*/+/**+ * Whether two Switch API endpoints name the same server, ignoring a trailing+ * slash — which is not a difference. This is how an agent's on-disk+ * `SWITCH_API_ENDPOINT` is matched to a registered server, so the main process and+ * the renderer must agree on it: the renderer decides which discovered agents are+ * importable, and the main process enforces it.+ */+export function sameApiEndpoint(a: string, b: string): boolean {+ return a.replace(/\/+$/, '') === b.replace(/\/+$/, '');+}+/** A registered Switch server. Non-secret connection metadata only. */export type SwitchServer = {id: string;