Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

fix(switchdash): scope agent onboarding and the sidebar by server (CHOO-2044)

Louis Amaudruz9950d92cee90
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3117af9ac..64f3439ff 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -301,7 +301,25 @@ version of their own to them without also giving them a release of their own.
so switchdash-launched Codex sessions run the published runtime. Ships in the
next switchdash release.
-### [0.19.3] - 2026-08-09
+#### Fixed
+- A directory that already holds agents for one Switch server can now onboard its
+ agents to another. "Already onboarded" was judged per directory rather than per
+ server, so every candidate was filtered out as a duplicate and the modal offered
+ an empty list — of agents that existed, on a server that did not have them
+ (CHOO-2044).
+- The sidebar no longer draws a directory's agents under a server they do not
+ belong to. A directory resolved to a single server — whichever of its agents was
+ returned first — and then every agent in it was rendered under that one, so
+ onboarding a single agent to a second server appeared to drag the rest across
+ with it. Nothing had been onboarded; each agent is now drawn under its own
+ server, and a shared directory shows under all of them (CHOO-2044).
+- The Add Agent modal no longer offers a permanently disabled button over a list
+ it will not submit. A directory carrying another server's leftover
+ `.claude/settings.local.json` took the detected-agent branch, verified that
+ foreign agent against the current server, failed, and disabled the only button
+ on screen — with the onboardable agents listed above it. The onboard action now
+ takes precedence, and a detected agent belonging to another server says so
+ (CHOO-2044).
#### Added
- Declares its `sidecar-control` range in the sidecar's ready file, and reads
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/attach-configured-agents.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/attach-configured-agents.test.ts
index d244d7a20..5078b9afb 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agents/attach-configured-agents.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/attach-configured-agents.test.ts
@@ -45,10 +45,11 @@ const h = vi.hoisted(() => {
}
const state: {
workspace: PluginFs | null;
- agentNames: string[];
+ /** Agent-row names already in the directory, per Switch server. */
+ agentNamesByServer: Record<string, string[]>;
existsOnServer: boolean;
existsThrows: Error | null;
- } = { workspace: null, agentNames: [], existsOnServer: true, existsThrows: null };
+ } = { workspace: null, agentNamesByServer: {}, existsOnServer: true, existsThrows: null };
return {
state,
GatewayError,
@@ -68,7 +69,9 @@ vi.mock('@main/core/locations/store', () => ({
ensureLocation: vi.fn(async () => ({ id: 'loc-1' })),
}));
vi.mock('./getAgents', () => ({
- getAgents: vi.fn(async () => h.state.agentNames.map((name) => ({ name }))),
+ getLocationAgentsOnServer: vi.fn(async (_locationId: string, serverId: string) =>
+ (h.state.agentNamesByServer[serverId] ?? []).map((name) => ({ name }))
+ ),
}));
vi.mock('./agent-workspace-fs', () => ({
resolveWorkspaceFsFor: vi.fn(async () => ({
@@ -111,7 +114,7 @@ function params(agents: Array<{ name: string; providerId: 'codex' | 'claude' }>)
describe('attachConfiguredAgents', () => {
beforeEach(() => {
vi.clearAllMocks();
- h.state.agentNames = [];
+ h.state.agentNamesByServer = {};
h.state.existsOnServer = true;
h.state.existsThrows = null;
h.state.workspace = readOnlyFs({ '.switch/agents/theirs.json': creds('sw-theirs') });
@@ -171,7 +174,7 @@ describe('attachConfiguredAgents', () => {
});
it('skips an agent this switchdash already has', async () => {
- h.state.agentNames = ['theirs'];
+ h.state.agentNamesByServer = { 'srv-1': ['theirs'] };
const result = await attachConfiguredAgents(params([{ name: 'theirs', providerId: 'codex' }]));
@@ -179,6 +182,18 @@ describe('attachConfiguredAgents', () => {
expect(h.createAgent).not.toHaveBeenCalled();
});
+ it('attaches an agent already attached to a different server (CHOO-2044)', async () => {
+ // Same directory, same name, other server — a separate agent, not a duplicate.
+ h.state.agentNamesByServer = { 'srv-other': ['theirs'] };
+
+ const result = await attachConfiguredAgents(params([{ name: 'theirs', providerId: 'codex' }]));
+
+ expect(result.success).toBe(true);
+ expect(h.createAgent).toHaveBeenCalledWith(
+ expect.objectContaining({ name: 'theirs', serverId: 'srv-1' })
+ );
+ });
+
it('keeps the directory endpoint and warns when it differs from the chosen server', async () => {
// One Switch server can be reachable at two URLs. The launch path reads the
// endpoint from the same file as the token, so the directory's value is what
diff --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.ts
index eb4eddcea..a26563a6f 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
@@ -76,10 +76,13 @@ export async function attachConfiguredAgents(
if (!server) throw new Error(`No Switch server with id ${params.serverId}`);
const discovered = new Map(
- (await discoverConfiguredAgents({ sshHost: params.sshHost, dir: params.dir })).map((d) => [
- d.name,
- d,
- ])
+ (
+ await discoverConfiguredAgents({
+ sshHost: params.sshHost,
+ dir: params.dir,
+ serverId: params.serverId,
+ })
+ ).map((d) => [d.name, d])
);
const selected: Array<{ name: string; providerId: AgentProviderId }> = [];
@@ -100,7 +103,7 @@ export async function attachConfiguredAgents(
return err({
type: 'invalid-directory',
dir: params.dir,
- message: 'Every selected agent is already attached here.',
+ message: `Every selected agent is already attached to ${server.name} here.`,
});
}
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/controller.ts b/dash/apps/switchdash-desktop/src/main/core/agents/controller.ts
index 1c2c6e858..087989f8e 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agents/controller.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/controller.ts
@@ -44,8 +44,9 @@ export const agentsController = createRPCController({
sshHost: string | null;
dir: string;
providerId: AgentProviderId;
+ serverId: string;
}) => discoverLocationAgents(params),
- discoverConfiguredAgents: (params: { sshHost: string | null; dir: string }) =>
+ discoverConfiguredAgents: (params: { sshHost: string | null; dir: string; serverId: string }) =>
discoverConfiguredAgents(params),
attachConfiguredAgents: (params: AttachConfiguredAgentsParams) => attachConfiguredAgents(params),
getAgents: (locationId?: string) => getAgents(locationId),
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/discover-configured-agents.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/discover-configured-agents.test.ts
index 1c85cc7f5..0b9e08374 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agents/discover-configured-agents.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/discover-configured-agents.test.ts
@@ -52,9 +52,10 @@ const h = vi.hoisted(() => {
const state: {
workspace: PluginFs | null;
location: { id: string } | undefined;
- agentNames: string[];
+ /** Agent-row names already in the directory, per Switch server. */
+ agentNamesByServer: Record<string, string[]>;
claudeDefinitions: Array<{ name: string; description: string | null }>;
- } = { workspace: null, location: { id: 'loc-1' }, agentNames: [], claudeDefinitions: [] };
+ } = { workspace: null, location: { id: 'loc-1' }, agentNamesByServer: {}, claudeDefinitions: [] };
return { state, warn: vi.fn() };
});
@@ -62,7 +63,9 @@ vi.mock('@main/core/locations/store', () => ({
getLocationByHostDir: vi.fn(async () => h.state.location),
}));
vi.mock('./getAgents', () => ({
- getAgents: vi.fn(async () => h.state.agentNames.map((name) => ({ name }))),
+ getLocationAgentsOnServer: vi.fn(async (_locationId: string, serverId: string) =>
+ (h.state.agentNamesByServer[serverId] ?? []).map((name) => ({ name }))
+ ),
}));
vi.mock('./agent-workspace-fs', () => ({
resolveWorkspaceFsFor: vi.fn(async () => ({
@@ -86,13 +89,14 @@ vi.mock('@main/lib/logger', () => ({ log: { info: vi.fn(), warn: h.warn, error:
const { discoverConfiguredAgents } = await import('./discover-configured-agents');
-const scan = () => discoverConfiguredAgents({ sshHost: 'vm-1', dir: '/repo' });
+const scan = (serverId = 'srv-a') =>
+ discoverConfiguredAgents({ sshHost: 'vm-1', dir: '/repo', serverId });
describe('discoverConfiguredAgents', () => {
beforeEach(() => {
vi.clearAllMocks();
h.state.location = { id: 'loc-1' };
- h.state.agentNames = [];
+ h.state.agentNamesByServer = {};
h.state.claudeDefinitions = [];
h.state.workspace = fakeFs();
});
@@ -157,7 +161,7 @@ describe('discoverConfiguredAgents', () => {
});
it('marks agents this switchdash already has a row for', async () => {
- h.state.agentNames = ['mine'];
+ h.state.agentNamesByServer = { 'srv-a': ['mine'] };
h.state.workspace = fakeFs({
'.switch/agents/mine.json': creds('sw-mine'),
'.switch/agents/theirs.json': creds('sw-theirs'),
@@ -168,6 +172,17 @@ describe('discoverConfiguredAgents', () => {
expect(byName.get('theirs')).toBe(false);
});
+ it('still offers an agent already attached to another server (CHOO-2044)', async () => {
+ // The directory is a place on disk, not one server's territory. An agent row
+ // for server A says nothing about server B, and treating it as "already got
+ // this" is what silently emptied the onboarding list.
+ h.state.agentNamesByServer = { 'srv-a': ['shared'] };
+ h.state.workspace = fakeFs({ '.switch/agents/shared.json': creds('sw-shared') });
+
+ expect((await scan('srv-a'))[0]).toMatchObject({ name: 'shared', alreadyAgent: true });
+ expect((await scan('srv-b'))[0]).toMatchObject({ name: 'shared', alreadyAgent: false });
+ });
+
it('treats a directory with no credentials dir as having no agents', async () => {
expect(await scan()).toEqual([]);
});
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/discover-configured-agents.ts b/dash/apps/switchdash-desktop/src/main/core/agents/discover-configured-agents.ts
index 2ce096656..14784468c 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agents/discover-configured-agents.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/discover-configured-agents.ts
@@ -9,7 +9,7 @@ import {
import type { AgentLaunchSpec } from '../../../sidecar/agent-launch-spec';
import { sidecarLaunchSpecRelPath } from '../../../sidecar/sidecar-paths';
import { resolveWorkspaceFsFor } from './agent-workspace-fs';
-import { getAgents } from './getAgents';
+import { getLocationAgentsOnServer } from './getAgents';
import { SWITCH_AGENTS_DIR_RELATIVE } from './switch-settings-paths';
/** How an agent's provider was inferred, so the UI can say whether to trust it. */
@@ -29,7 +29,8 @@ export type DiscoveredConfiguredAgent = {
/** Best-effort: null when nothing on disk names a provider. */
providerId: AgentProviderId | null;
providerSource: ProviderSource;
- /** Whether this switchdash already has a row for the name at this location. */
+ /** Whether this switchdash already has a row for the name at this location, on
+ * the server being onboarded to. */
alreadyAgent: boolean;
};
@@ -141,10 +142,14 @@ async function definitionOwners(workspaceFs: PluginFs): Promise<Map<string, Agen
export async function discoverConfiguredAgents(params: {
sshHost: string | null;
dir: string;
+ /** The Switch server being onboarded to — what `alreadyAgent` is judged against.
+ * A directory can hold agents for several servers, so the same name can be
+ * attached here already and still be attachable to another (CHOO-2044). */
+ serverId: string;
}): Promise<DiscoveredConfiguredAgent[]> {
const location = await getLocationByHostDir(params.sshHost, params.dir);
const existing = location
- ? new Set((await getAgents(location.id)).map((a) => a.name))
+ ? new Set((await getLocationAgentsOnServer(location.id, params.serverId)).map((a) => a.name))
: new Set<string>();
const workspace = await resolveWorkspaceFsFor(params.sshHost, params.dir);
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/discover-location-agents.ts b/dash/apps/switchdash-desktop/src/main/core/agents/discover-location-agents.ts
index 2b4f3adf4..8459bc674 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
@@ -2,7 +2,7 @@ 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';
+import { getLocationAgentsOnServer } from './getAgents';
export type DiscoveredLocationAgent = {
/** The definition/launch name (`.claude/agents/<name>.md` stem, `--agent <name>`). */
@@ -13,7 +13,8 @@ export type DiscoveredLocationAgent = {
/** 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. */
+ /** Whether switchdash already has an agent row for this definition in this dir,
+ * on the server being onboarded to. */
alreadyAgent: boolean;
};
@@ -23,21 +24,25 @@ export type DiscoveredLocationAgent = {
* 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.
+ * Switch agent. `alreadyAgent` marks definitions switchdash already has a row for
+ * *on `serverId`*, so the modal never offers to re-add them there — while the same
+ * definition stays offerable to a different server, which is a separate agent
+ * (CHOO-2044). 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;
+ /** The Switch server being onboarded to — what `alreadyAgent` is judged against. */
+ serverId: string;
}): 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.name))
+ ? new Set((await getLocationAgentsOnServer(location.id, params.serverId)).map((a) => a.name))
: new Set<string>();
const workspace = await resolveWorkspaceFsFor(params.sshHost, params.dir);
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/getAgents.ts b/dash/apps/switchdash-desktop/src/main/core/agents/getAgents.ts
index 62c410014..51edb0773 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agents/getAgents.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/getAgents.ts
@@ -1,4 +1,4 @@
-import { desc, eq } from 'drizzle-orm';
+import { and, desc, eq } from 'drizzle-orm';
import { db } from '@main/db/client';
import { agents } from '@main/db/schema';
import type { Agent } from '@shared/core/agents/agents';
@@ -14,3 +14,24 @@ export async function getAgents(locationId?: string): Promise<Agent[]> {
: await db.select().from(agents).orderBy(desc(agents.updatedAt));
return rows.map(mapAgentRowToAgent);
}
+
+/**
+ * A directory's agents that belong to one Switch server.
+ *
+ * A directory is a place on disk, not a server's territory: the same folder can
+ * hold agents registered against several servers. Anything answering "do I
+ * already have this agent" must therefore ask per server — asking per directory
+ * reports an agent on server A as already onboarded when the target is server B,
+ * and the candidate is silently dropped (CHOO-2044).
+ */
+export async function getLocationAgentsOnServer(
+ locationId: string,
+ serverId: string
+): Promise<Agent[]> {
+ const rows = await db
+ .select()
+ .from(agents)
+ .where(and(eq(agents.locationId, locationId), eq(agents.serverId, serverId)))
+ .orderBy(desc(agents.updatedAt));
+ return rows.map(mapAgentRowToAgent);
+}
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.ts
index 5c0919719..ae6dcb71d 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
@@ -17,7 +17,7 @@ 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 { getLocationAgentsOnServer } from './getAgents';
import { registerAgentIdentity } from './register-agent-identity';
import { reconcileAgentAutoSessionFromGateway } from './setAgentAutoSession';
import { writeNeutralAgentSettingsFs } from './write-switch-settings';
@@ -175,7 +175,9 @@ export async function onboardLocationAgents(
name: params.locationName ?? basenameFromAnyPath(params.dir) ?? params.providerId,
});
- const existing = new Set((await getAgents(location.id)).map((a) => a.name));
+ const existing = new Set(
+ (await getLocationAgentsOnServer(location.id, params.serverId)).map((a) => a.name)
+ );
const workspace = await resolveWorkspaceFsFor(params.sshHost, params.dir);
const created: Agent[] = [];
@@ -190,7 +192,7 @@ export async function onboardLocationAgents(
return err({
type: 'invalid-directory',
dir: params.dir,
- message: 'No Claude agents available to onboard in this directory.',
+ message: `No Claude agents available to onboard in this directory onto ${server.name}.`,
});
}
@@ -245,7 +247,7 @@ export async function onboardLocationAgents(
return err({
type: 'invalid-directory',
dir: params.dir,
- message: 'Every agent in this directory is already onboarded here.',
+ message: `Every agent in this directory is already onboarded onto ${server.name}.`,
});
}
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.tsx
index 20f622b6c..7aec201b9 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
@@ -223,14 +223,16 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLoc
discoverSshHost ?? 'local',
discoverDir,
pickState.providerId,
+ pickState.serverId,
],
queryFn: () =>
rpc.agents.discoverLocationAgents({
sshHost: discoverSshHost,
dir: discoverDir,
providerId: pickState.providerId!,
+ serverId: pickState.serverId!,
}),
- enabled: !!pickState.providerId && discoverDir.trim().length > 0,
+ enabled: !!pickState.providerId && !!pickState.serverId && discoverDir.trim().length > 0,
});
// Agents already configured in the directory, found by their provider-neutral
// Switch credentials rather than by any provider's definition format. This is
@@ -238,10 +240,19 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLoc
// way a provider with no definition concept (Codex) is visible at all
// (CHOO-1937). Provider-agnostic, so it does not wait on the type picker.
const configuredQuery = useQuery({
- queryKey: ['discoverConfiguredAgents', discoverSshHost ?? 'local', discoverDir],
+ queryKey: [
+ 'discoverConfiguredAgents',
+ discoverSshHost ?? 'local',
+ discoverDir,
+ pickState.serverId,
+ ],
queryFn: () =>
- rpc.agents.discoverConfiguredAgents({ sshHost: discoverSshHost, dir: discoverDir }),
- enabled: discoverDir.trim().length > 0,
+ rpc.agents.discoverConfiguredAgents({
+ sshHost: discoverSshHost,
+ dir: discoverDir,
+ serverId: pickState.serverId!,
+ }),
+ enabled: !!pickState.serverId && discoverDir.trim().length > 0,
});
// Definitions that can join Switch and switchdash hasn't already onboarded — the
@@ -316,9 +327,10 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLoc
// 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 scanTargetChosen = !!pickState.serverId && discoverDir.trim().length > 0;
const isDiscovering =
- (!!pickState.providerId && discoverDir.trim().length > 0 && discoverQuery.isPending) ||
- (discoverDir.trim().length > 0 && configuredQuery.isPending);
+ (!!pickState.providerId && scanTargetChosen && discoverQuery.isPending) ||
+ (scanTargetChosen && configuredQuery.isPending);
const isChecking =
(isRemoteRun
? shouldDetectRemote && remoteAgentQuery.isPending
@@ -693,21 +705,29 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLoc
}
footer={
<DialogFooter>
- {switchAgent ? (
+ {/* The onboard list comes first, and deliberately outranks a detected
+ legacy agent. The body renders the list whenever there is something
+ to onboard, so a footer that branched on detection first put the
+ wrong button under it: a directory carrying another server's
+ `.claude/settings.local.json` showed the detected-agent button, which
+ then verified that foreign agent against this server, failed, and
+ stayed disabled forever — with the onboardable list visible above it
+ and no way to submit it (CHOO-2044). */}
+ {hasOnboardable && !createMode ? (
<ConfirmButton
type="button"
- onClick={() => void handleSubmit()}
- disabled={!canSubmitDetected}
+ onClick={() => void handleOnboard()}
+ disabled={!canOnboard}
>
- {submitLabel}
+ {submitState === 'creating' ? 'Adding...' : `Add ${selectedNames.size} selected`}
</ConfirmButton>
- ) : hasOnboardable && !createMode ? (
+ ) : switchAgent ? (
<ConfirmButton
type="button"
- onClick={() => void handleOnboard()}
- disabled={!canOnboard}
+ onClick={() => void handleSubmit()}
+ disabled={!canSubmitDetected}
>
- {submitState === 'creating' ? 'Adding...' : `Add ${selectedNames.size} selected`}
+ {submitLabel}
</ConfirmButton>
) : isMissingRemoteAgent ? (
<ConfirmButton
@@ -866,6 +886,31 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLoc
</span>
</span>
</div>
+ {/* The detected agent belongs to whichever server its on-disk config
+ was written for, which need not be the one being added to. Saying
+ so is the difference between an explained dead end and a button
+ that is simply disabled for no stated reason (CHOO-2044). */}
+ {verifyState === 'not-found' && (
+ <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>
+ The agent configured in this directory is not registered on
+ {targetServer ? ` ${targetServer.name}` : ' the active server'} — it belongs to a
+ different Switch server. Onboard one of this directory&apos;s agents instead, or
+ switch to the server it belongs to.
+ </span>
+ </div>
+ )}
+ {verifyState === 'unauthenticated' && (
+ <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>
+ You are not signed in to
+ {targetServer ? ` ${targetServer.name}` : ' the active server'}, so this agent
+ cannot be verified.
+ </span>
+ </div>
+ )}
{switchServersStore.servers.length === 0 && (
<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" />
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/agents-store.test.ts b/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/agents-store.test.ts
new file mode 100644
index 000000000..7b14f5f30
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/agents-store.test.ts
@@ -0,0 +1,72 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import type { Agent } from '@shared/core/agents/agents';
+import { agentsStore } from './agents-store';
+
+vi.mock('@renderer/lib/ipc', () => ({ rpc: {} }));
+
+function agent(locationId: string, serverId: string | null, name: string): Agent {
+ return { locationId, serverId, name } as Agent;
+}
+
+/**
+ * The premise these cover: a directory can hold agents registered against
+ * several Switch servers at once, so "which server does this directory belong
+ * to" has no single answer and must not be asked (CHOO-2044).
+ */
+describe('AgentsStore server scoping', () => {
+ afterEach(() => {
+ agentsStore.byLocation.clear();
+ agentsStore.optimisticServerByLocation.clear();
+ });
+
+ it('returns only the agents belonging to the given server', () => {
+ agentsStore.byLocation.set('shared', [
+ agent('shared', 'server-1', 'a'),
+ agent('shared', 'server-2', 'b'),
+ agent('shared', null, 'unlinked'),
+ ]);
+
+ expect(agentsStore.agentsOnServerAtLocation('shared', 'server-1').map((a) => a.name)).toEqual([
+ 'a',
+ ]);
+ expect(agentsStore.agentsOnServerAtLocation('shared', 'server-2').map((a) => a.name)).toEqual([
+ 'b',
+ ]);
+ expect(agentsStore.agentsOnServerAtLocation('shared', 'server-3')).toEqual([]);
+ });
+
+ it('reports a shared directory as present on every server it has agents on', () => {
+ agentsStore.byLocation.set('shared', [
+ agent('shared', 'server-1', 'a'),
+ agent('shared', 'server-2', 'b'),
+ ]);
+
+ expect(agentsStore.locationHasAgentsOnServer('shared', 'server-1')).toBe(true);
+ expect(agentsStore.locationHasAgentsOnServer('shared', 'server-2')).toBe(true);
+ expect(agentsStore.locationHasAgentsOnServer('shared', 'server-3')).toBe(false);
+ expect(agentsStore.serverIdsForLocation('shared').sort()).toEqual(['server-1', 'server-2']);
+ });
+
+ it('keeps a just-created location in scope before its agent row lands', () => {
+ agentsStore.noteLocationServer('fresh', 'server-1');
+
+ expect(agentsStore.locationHasAgentsOnServer('fresh', 'server-1')).toBe(true);
+ expect(agentsStore.locationHasAgentsOnServer('fresh', 'server-2')).toBe(false);
+ expect(agentsStore.serverIdsForLocation('fresh')).toEqual(['server-1']);
+ });
+
+ it('ignores the optimistic note once real agents exist', () => {
+ agentsStore.noteLocationServer('shared', 'server-9');
+ agentsStore.byLocation.set('shared', [agent('shared', 'server-1', 'a')]);
+
+ expect(agentsStore.serverIdsForLocation('shared')).toEqual(['server-1']);
+ expect(agentsStore.locationHasAgentsOnServer('shared', 'server-9')).toBe(false);
+ });
+
+ it('treats a location with only unlinked agents as on no server', () => {
+ agentsStore.byLocation.set('orphan', [agent('orphan', null, 'a')]);
+
+ expect(agentsStore.serverIdsForLocation('orphan')).toEqual([]);
+ expect(agentsStore.locationHasAgentsOnServer('orphan', 'server-1')).toBe(false);
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/agents-store.ts b/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/agents-store.ts
index fec310b7d..b584c10d1 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/agents-store.ts
+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/agents-store.ts
@@ -3,14 +3,15 @@ import { rpc } from '@renderer/lib/ipc';
import type { Agent } from '@shared/core/agents/agents';
/**
- * Renderer cache of every agent across all locations, used to resolve which
- * Switch server a location belongs to. The sidebar scopes its tree to the active
- * server (see {@link switchServersStore.activeServerId}), so it needs a reactive
- * location→serverId lookup that does not depend on each row's own react-query.
+ * Renderer cache of every agent across all locations. The sidebar scopes its tree
+ * to the active server (see {@link switchServersStore.activeServerId}), so it needs
+ * a reactive lookup that does not depend on each row's own react-query.
*
- * A location holds one parent agent plus any subagents, which all share the same
- * server; {@link serverIdForLocation} returns the first non-null serverId among a
- * location's agents.
+ * **A server belongs to an agent, not to a directory.** A directory is a place on
+ * disk and can hold agents registered against several servers at once, so there is
+ * no such thing as "the location's server" to scope on — asking for one drags every
+ * agent in the directory under whichever answer came back first (CHOO-2044). Scope
+ * on {@link agentsOnServerAtLocation}; a location is in scope when it has any.
*/
export class AgentsStore {
/** All agents grouped by their location id. */
@@ -18,8 +19,8 @@ export class AgentsStore {
/**
* Server id a just-created location's agent will belong to, recorded by the
* add-agent modal before {@link load} has re-fetched the new agent. Used as a
- * fallback in {@link serverIdForLocation} so a freshly-created location does not
- * flicker out of the sidebar's server-scoped view during the gap between the
+ * fallback in {@link locationHasAgentsOnServer} so a freshly-created location does
+ * not flicker out of the sidebar's server-scoped view during the gap between the
* location mounting and the agent list refreshing.
*/
readonly optimisticServerByLocation = new Map<string, string>();
@@ -81,11 +82,37 @@ export class AgentsStore {
return matching.sort((a, b) => a.name.localeCompare(b.name));
}
- /** The Switch server a location's agents belong to, or null if unlinked. */
- serverIdForLocation(locationId: string): string | null {
+ /** A location's agents that belong to one server — what the sidebar renders
+ * under that server. Agents in the same directory registered elsewhere are not
+ * this server's to show. */
+ agentsOnServerAtLocation(locationId: string, serverId: string): Agent[] {
+ return (this.byLocation.get(locationId) ?? []).filter((a) => a.serverId === serverId);
+ }
+
+ /** Whether a location has anything to show under `serverId`. */
+ locationHasAgentsOnServer(locationId: string, serverId: string): boolean {
+ return this.serverIdsForLocation(locationId).includes(serverId);
+ }
+
+ /**
+ * The servers a location's agents belong to. A directory can span several, so
+ * this is a list rather than the one answer callers used to ask for.
+ *
+ * The optimistic note stands in only while the location has no agent rows at
+ * all — that is the gap it exists to cover. Letting it also speak for a location
+ * that already has agents would have it claim a server the location is not on.
+ */
+ serverIdsForLocation(locationId: string): string[] {
const agents = this.byLocation.get(locationId);
- const resolved = agents?.find((a) => a.serverId !== null)?.serverId ?? null;
- return resolved ?? this.optimisticServerByLocation.get(locationId) ?? null;
+ if (!agents || agents.length === 0) {
+ const optimistic = this.optimisticServerByLocation.get(locationId);
+ return optimistic ? [optimistic] : [];
+ }
+ const ids = new Set<string>();
+ for (const agent of agents) {
+ if (agent.serverId !== null) ids.add(agent.serverId);
+ }
+ return [...ids];
}
}
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-store.test.ts b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-store.test.ts
index 5a8eeeb97..f155adca0 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-store.test.ts
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-store.test.ts
@@ -280,6 +280,41 @@ describe('SidebarStore active-server scoping', () => {
expect(store.orderedLocations).toEqual([]);
expect(store.isEmpty).toBe(true);
});
+
+ it('shows a directory shared between servers under both (CHOO-2044)', () => {
+ // A directory is a place on disk, not one server's territory. Resolving it to
+ // a single server filed it under whichever agent came back first, and the
+ // other server's agents vanished from the tree.
+ const store = new SidebarStore(
+ locationManager([{ id: 'shared', createdAt: '2026-01-01T00:00:00.000Z' }])
+ );
+ agentsStore.byLocation.set('shared', [
+ { locationId: 'shared', serverId: 'server-1' } as Agent,
+ { locationId: 'shared', serverId: 'server-2' } as Agent,
+ ]);
+
+ switchServersStore.activeServerId = 'server-1';
+ expect(store.orderedLocations.map((p) => p.id)).toEqual(['shared']);
+
+ switchServersStore.activeServerId = 'server-2';
+ expect(store.orderedLocations.map((p) => p.id)).toEqual(['shared']);
+
+ switchServersStore.activeServerId = 'server-3';
+ expect(store.orderedLocations).toEqual([]);
+ });
+
+ it('describes a shared directory by an agent on the active server (CHOO-2044)', () => {
+ const store = new SidebarStore(
+ locationManager([{ id: 'shared', createdAt: '2026-01-01T00:00:00.000Z' }])
+ );
+ agentsStore.byLocation.set('shared', [
+ { locationId: 'shared', serverId: 'server-1', providerId: 'claude' } as Agent,
+ { locationId: 'shared', serverId: 'server-2', providerId: 'codex' } as Agent,
+ ]);
+
+ switchServersStore.activeServerId = 'server-2';
+ expect(store.locationProviderId('shared')).toBe('codex');
+ });
});
describe('SidebarStore filters', () => {
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.ts
index 918ff3e2b..90528499e 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
@@ -227,18 +227,23 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {
}
/**
- * Whether a location belongs to the active server. The whole sidebar tree is
- * scoped to one server at a time: a location shows only when its agents are
- * linked to {@link switchServersStore.activeServerId}. Unregistered locations
- * (mid-onboarding, no agent row yet) always show so the user sees progress.
- * When no server is active, nothing is hidden.
+ * Whether a location has anything to show under the active server. The whole
+ * sidebar tree is scoped to one server at a time: a location shows when it holds
+ * at least one agent linked to {@link switchServersStore.activeServerId}.
+ * Unregistered locations (mid-onboarding, no agent row yet) always show so the
+ * user sees progress. When no server is active, nothing is hidden.
+ *
+ * A directory can hold agents for several servers, so this is "has any here",
+ * not "belongs to". Which of its agents are then drawn is
+ * {@link scopedAgents}' business — a location being in scope does not put every
+ * agent in it on this server's tree (CHOO-2044).
*/
isLocationInActiveScope(locationId: string): boolean {
const activeServerId = switchServersStore.activeServerId;
if (!activeServerId) return true;
const location = this.locationManager.locations.get(locationId);
if (location && location.state === 'unregistered') return true;
- return agentsStore.serverIdForLocation(locationId) === activeServerId;
+ return agentsStore.locationHasAgentsOnServer(locationId, activeServerId);
}
/**
@@ -255,9 +260,15 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {
}
/** The representative agent of a location (the agent shown on its sidebar row):
- * the first real (non-definition) agent, not a former subagent's row. */
+ * the first real (non-definition) agent, not a former subagent's row. Restricted
+ * to the active server, so a directory shared with another server does not
+ * describe itself by an agent this tree is not showing. */
private parentAgent(locationId: string) {
- return (agentsStore.byLocation.get(locationId) ?? [])[0];
+ const activeServerId = switchServersStore.activeServerId;
+ const agents = activeServerId
+ ? agentsStore.agentsOnServerAtLocation(locationId, activeServerId)
+ : (agentsStore.byLocation.get(locationId) ?? []);
+ return agents[0] ?? (agentsStore.byLocation.get(locationId) ?? [])[0];
}
/** Where a location runs — `remote` when it has an SSH host, else `local`. */
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-tree-data.ts b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-tree-data.ts
index 92fc8a515..7d4def54c 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-tree-data.ts
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-tree-data.ts
@@ -1,6 +1,7 @@
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 { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
import { sidebarStore } from '@renderer/lib/stores/app-state';
import type { Agent } from '@shared/core/agents/agents';
@@ -13,6 +14,21 @@ import type { Agent } from '@shared/core/agents/agents';
/** An agent paired with its (mounted) location, for the flat sidebar list. */
export type AgentEntry = { agent: Agent; location: LocationStore };
+/**
+ * A location's agents that the active server's tree should draw.
+ *
+ * A location is in scope when *some* of its agents are on the active server, but a
+ * directory can hold agents for several servers at once — so scope has to be
+ * re-applied per agent here. Taking the location's whole list instead drew agents
+ * belonging to another server under this one, which read as "onboarding brought
+ * them across" when nothing had been onboarded at all (CHOO-2044).
+ */
+function agentsAtLocationInScope(location: LocationStore): Agent[] {
+ const activeServerId = switchServersStore.activeServerId;
+ if (!activeServerId) return agentsStore.byLocation.get(location.id) ?? [];
+ return agentsStore.agentsOnServerAtLocation(location.id, activeServerId);
+}
+
/**
* The flat list of agents in the active-server scope. switchdash shows agents
* as a flat list — not grouped by directory (CHOO-1440).
@@ -24,7 +40,7 @@ export type AgentEntry = { agent: Agent; location: LocationStore };
export function scopedAgents(): AgentEntry[] {
const entries: AgentEntry[] = [];
for (const location of sidebarStore.filteredLocations) {
- for (const agent of agentsStore.byLocation.get(location.id) ?? []) {
+ for (const agent of agentsAtLocationInScope(location)) {
entries.push({ agent, location });
}
}
@@ -46,7 +62,7 @@ export function scopedAgents(): AgentEntry[] {
export function agentsInActiveScope(): AgentEntry[] {
const entries: AgentEntry[] = [];
for (const location of sidebarStore.orderedLocations) {
- for (const agent of agentsStore.byLocation.get(location.id) ?? []) {
+ for (const agent of agentsAtLocationInScope(location)) {
entries.push({ agent, location });
}
}
diff --git a/dash/apps/switchdash-desktop/src/renderer/lib/layout/scope-to-server.ts b/dash/apps/switchdash-desktop/src/renderer/lib/layout/scope-to-server.ts
index 7161b8a2b..fe047b200 100644
--- a/dash/apps/switchdash-desktop/src/renderer/lib/layout/scope-to-server.ts
+++ b/dash/apps/switchdash-desktop/src/renderer/lib/layout/scope-to-server.ts
@@ -20,10 +20,20 @@ async function activateServer(serverId: string | null): Promise<void> {
await switchServersStore.setActive(serverId);
}
-/** Scope to the server owning `locationId` — for agents and sessions. */
+/**
+ * Scope to a server that shows `locationId` — for agents and sessions.
+ *
+ * A directory can hold agents for several servers, so there may be more than one
+ * right answer. If the active server is already one of them there is nothing to do;
+ * switching away would hide the row the caller is navigating to (CHOO-2044).
+ */
export async function scopeToLocationServer(locationId: string): Promise<void> {
if (!agentsStore.loaded) await agentsStore.load();
- await activateServer(agentsStore.serverIdForLocation(locationId));
+ const serverIds = agentsStore.serverIdsForLocation(locationId);
+ if (serverIds.length === 0) return;
+ const active = switchServersStore.activeServerId;
+ if (active && serverIds.includes(active)) return;
+ await activateServer(serverIds[0]);
}
/** Scope to the server owning `roomId`. */