Skip to content

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

feat(console): load agents from a remote host (CHOO-2560) (#364)

Abel Dantas4facce732a97
diff --git a/console/apps/switch-console-desktop/drizzle/0048_agent_owner_name.sql b/console/apps/switch-console-desktop/drizzle/0048_agent_owner_name.sql
new file mode 100644
index 000000000..d2e2254d4
--- /dev/null
+++ b/console/apps/switch-console-desktop/drizzle/0048_agent_owner_name.sql
@@ -0,0 +1 @@
+ALTER TABLE `agents` ADD `owner_name` text;
\ No newline at end of file
diff --git a/console/apps/switch-console-desktop/drizzle/meta/_journal.json b/console/apps/switch-console-desktop/drizzle/meta/_journal.json
index 2b8b7d0f6..8adcf9253 100644
--- a/console/apps/switch-console-desktop/drizzle/meta/_journal.json
+++ b/console/apps/switch-console-desktop/drizzle/meta/_journal.json
@@ -337,6 +337,13 @@
"when": 1786983032561,
"tag": "0047_materialise_telemetry_consent",
"breakpoints": true
+ },
+ {
+ "idx": 48,
+ "version": "6",
+ "when": 1788633600000,
+ "tag": "0048_agent_owner_name",
+ "breakpoints": true
}
]
}
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.ts
index 5c5bb36cd..65f20936b 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.ts
@@ -88,6 +88,19 @@ vi.mock('./setAgentAutoSession', () => ({
vi.mock('./agent-events', () => ({ agentEvents: { _emit: vi.fn() } }));
vi.mock('@main/core/telemetry/telemetry-service', () => ({ trackEvent: vi.fn() }));
vi.mock('@main/lib/logger', () => ({ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));
+vi.mock('@main/db/client', () => ({
+ db: {
+ select: () => ({
+ from: () => ({
+ where: () => ({
+ limit: () => Promise.resolve([]),
+ }),
+ }),
+ }),
+ },
+}));
+vi.mock('@main/db/schema', () => ({ agents: { id: 'id', switchAgentId: 'switchAgentId' } }));
+vi.mock('drizzle-orm', () => ({ eq: vi.fn() }));
const { addAgent } = await import('./add-agent');
const { trackEvent } = await import('@main/core/telemetry/telemetry-service');
@@ -222,6 +235,31 @@ describe('addAgent', () => {
).toBe(theirs);
});
+ it('refuses when same-server credentials exist but the agent is unknown to this install (CHOO-2560)', async () => {
+ // A colleague's Console provisioned this agent on the same Switch server.
+ // The credentials file carries the same endpoint, but its agent id is not
+ // in this install's database (the mock returns []). Minting over it would
+ // destroy their token.
+ const colleague = JSON.stringify({
+ env: {
+ SWITCH_API_ENDPOINT: 'https://switch.example.com',
+ SWITCH_API_TOKEN: 'colleague-token',
+ SWITCH_AGENT_ID: 'colleague-agent',
+ },
+ });
+ h.state.workspace = fakeFs({ [agentSettingsRelativePath('codex-hoot')]: colleague });
+
+ const result = await addAgent(params());
+
+ expect(result).toEqual({ kind: 'already-configured' });
+ expect(h.registerAgentIdentity).not.toHaveBeenCalled();
+ expect(h.createAgent).not.toHaveBeenCalled();
+ // The colleague's file is intact.
+ expect(
+ await (h.state.workspace as PluginFs).read(agentSettingsRelativePath('codex-hoot'))
+ ).toBe(colleague);
+ });
+
it('refuses a name already taken in the location, without minting an identity', async () => {
// The gateway's 409 is scoped to the Switch server, so it cannot see a name
// that is free there and taken in this directory — where both agents would
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.ts b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.ts
index 014df7a72..f86c988c9 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.ts
@@ -1,5 +1,6 @@
import { randomUUID } from 'node:crypto';
import type { RepoAgentAttributes } from '@switch-console/core/agents/plugins';
+import { eq } from 'drizzle-orm';
import { locationManager } from '@main/core/locations/location-manager';
import { checkIsValidDirectory } from '@main/core/locations/path-utils';
import { ensureLocation, getLocationByHostDir } from '@main/core/locations/store';
@@ -9,6 +10,8 @@ import { agentTypeOf } from '@main/core/telemetry/agent-type';
import type { TelemetryAgentCreateFailure } from '@main/core/telemetry/events';
import { entryPointOf } from '@main/core/telemetry/narrow';
import { trackEvent } from '@main/core/telemetry/telemetry-service';
+import { db } from '@main/db/client';
+import { agents as agentsTable } from '@main/db/schema';
import { log } from '@main/lib/logger';
import { agentAvatarUrlForName } from '@shared/core/agents/agent-avatar';
import type { AgentProviderConfig } from '@shared/core/agents/agent-provider-config';
@@ -18,7 +21,7 @@ import type { UiEntryPoint } from '@shared/core/telemetry/reporting';
import { basenameFromAnyPath } from '@shared/path-name';
import { writeAgentConfigFile } from './agent-config-file';
import { syncAgentConfig } from './agent-config-sync';
-import { foreignCredentialsOwner } from './agent-credentials-slot';
+import { foreignCredentialsOwner, sameEndpointAgentId } from './agent-credentials-slot';
import { agentEvents } from './agent-events';
import { agentNameTaken } from './agent-name-taken';
import { resolveWorkspaceFsFor } from './agent-workspace-fs';
@@ -72,6 +75,7 @@ export type AddAgentResult =
| { kind: 'unauthenticated' }
| { kind: 'name-conflict' }
| { kind: 'credentials-conflict'; endpoint: string }
+ | { kind: 'already-configured' }
| { kind: 'invalid-name'; message: string }
| { kind: 'error'; message: string };
@@ -83,6 +87,7 @@ const ADD_AGENT_FAILURE_REASON: Record<
unauthenticated: 'unauthenticated',
'name-conflict': 'name_conflict',
'credentials-conflict': 'credentials_conflict',
+ 'already-configured': 'already_configured',
'invalid-name': 'invalid_name',
error: 'error',
};
@@ -182,6 +187,28 @@ async function runAddAgent(params: AddAgentParams): Promise<AddAgentResult> {
});
}
+ // The cross-deployment check above passes when the slot belongs to the SAME
+ // server. That is safe when this install already manages the agent (the
+ // agentNameTaken check above covers it), but not when the file was written by another
+ // Console — its agent is in this install's blind spot. Minting here would
+ // overwrite the existing identity and destroy its token (CHOO-2560).
+ const slotAgentId = await sameEndpointAgentId(
+ params.sshHost,
+ params.dir,
+ params.name,
+ server.apiUrl
+ );
+ if (slotAgentId !== null) {
+ const [knownLocally] = await db
+ .select({ id: agentsTable.id })
+ .from(agentsTable)
+ .where(eq(agentsTable.switchAgentId, slotAgentId))
+ .limit(1);
+ if (!knownLocally) {
+ return reportFailedCreate(params, { kind: 'already-configured' });
+ }
+ }
+
const registered = await registerAgentIdentity(server, {
name: params.name,
description: params.description,
@@ -206,6 +233,7 @@ async function runAddAgent(params: AddAgentParams): Promise<AddAgentResult> {
apiEndpoint: server.apiUrl,
apiToken: registered.apiKey,
agentId: registered.id,
+ expectedAgentId: slotAgentId ?? undefined,
});
// The config file is the agent's configuration; the provider's own file is
// generated from it, here and on every later edit.
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-credentials-slot.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-credentials-slot.ts
index 1c66c3c23..81bafcd68 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-credentials-slot.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-credentials-slot.ts
@@ -1,5 +1,6 @@
import { resolveWorkspaceFsFor } from './agent-workspace-fs';
-import { foreignCredentialsOwnerFs } from './write-switch-settings';
+import { agentSettingsRelativePath } from './switch-settings-paths';
+import { existingAgentIdInSlot, foreignCredentialsOwnerFs } from './write-switch-settings';
/**
* The Switch deployment that already owns `.switch/agents/<slug>.json` in a
@@ -28,3 +29,28 @@ export async function foreignCredentialsOwner(
workspace.close();
}
}
+
+/**
+ * The `SWITCH_AGENT_ID` of an agent already configured in the credentials slot
+ * for `slug`, when the file belongs to the SAME deployment as `apiEndpoint` —
+ * otherwise null.
+ *
+ * The create path calls this after the cross-deployment check
+ * ({@link foreignCredentialsOwner}) and before minting a new identity. A
+ * same-server file whose agent id is unknown to this install's database is a
+ * colleague's agent: minting over it would overwrite their token (CHOO-2560).
+ */
+export async function sameEndpointAgentId(
+ sshHost: string | null,
+ dir: string,
+ slug: string,
+ apiEndpoint: string
+): Promise<string | null> {
+ const workspace = await resolveWorkspaceFsFor(sshHost, dir);
+ try {
+ const existingRaw = await workspace.fs.read(agentSettingsRelativePath(slug));
+ return existingAgentIdInSlot(existingRaw, apiEndpoint);
+ } finally {
+ workspace.close();
+ }
+}
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-events-renderer-bridge.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-events-renderer-bridge.ts
new file mode 100644
index 000000000..b67b9ddcf
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-events-renderer-bridge.ts
@@ -0,0 +1,14 @@
+import { events } from '@main/lib/events';
+import { agentsChangedChannel } from '@shared/events/appEvents';
+import { agentEvents } from './agent-events';
+
+/**
+ * Forward agent CRUD from the main-only `agentEvents` bus to the renderer, so
+ * renderer stores and queries can react to create/update/delete without each
+ * mutating call site refetching by hand.
+ */
+export function bridgeAgentEventsToRenderer(): void {
+ agentEvents.on('agent:created', () => events.emit(agentsChangedChannel, { kind: 'created' }));
+ agentEvents.on('agent:updated', () => events.emit(agentsChangedChannel, { kind: 'updated' }));
+ agentEvents.on('agent:deleted', () => events.emit(agentsChangedChannel, { kind: 'deleted' }));
+}
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.test.ts
index b99e25029..bf6e13a6a 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.test.ts
@@ -103,6 +103,7 @@ vi.mock('./setAgentAutoSession', () => ({
reconcileAgentAutoSessionFromGateway: vi.fn(async () => {}),
}));
vi.mock('./agent-events', () => ({ agentEvents: { _emit: h.emit } }));
+vi.mock('./remote-watcher', () => ({ startRemoteDiscovery: vi.fn(async () => {}) }));
vi.mock('@main/lib/logger', () => ({ log: { info: vi.fn(), warn: h.warn, error: vi.fn() } }));
const { attachConfiguredAgents } = await import('./attach-configured-agents');
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.ts b/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.ts
index f232387c2..a56bb053a 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.ts
@@ -28,7 +28,7 @@ export type AttachConfiguredAgentsParams = {
* taken from the scan: discovery infers it best-effort and reports `null` when
* the directory names none, in which case the user picks.
*/
- agents: Array<{ name: string; providerId: AgentProviderId }>;
+ agents: Array<{ name: string; providerId: AgentProviderId; ownerName?: string | null }>;
};
export type AttachConfiguredAgentsResult = Result<Agent[], OnboardAgentError>;
@@ -81,7 +81,8 @@ export async function attachConfiguredAgents(
).map((d) => [d.name, d])
);
- const selected: Array<{ name: string; providerId: AgentProviderId }> = [];
+ const selected: Array<{ name: string; providerId: AgentProviderId; ownerName?: string | null }> =
+ [];
for (const requested of params.agents) {
const found = discovered.get(requested.name);
if (!found) {
@@ -110,7 +111,7 @@ export async function attachConfiguredAgents(
});
const created: Agent[] = [];
- for (const { name, providerId } of selected) {
+ for (const { name, providerId, ownerName } of selected) {
const found = discovered.get(name);
if (!found) continue;
@@ -159,6 +160,7 @@ export async function attachConfiguredAgents(
apiEndpoint: found.apiEndpoint,
serverId: params.serverId,
autoApprove: params.sshHost !== null,
+ ownerName: ownerName ?? null,
});
created.push(agent);
@@ -171,9 +173,22 @@ export async function attachConfiguredAgents(
}
await locationManager.openLocation(location);
- // No control to name: an attach is driven by whichever screen offered the
- // scan, and nothing on the way here says which. `unknown` reports the absence
- // of a claim rather than inventing one.
for (const agent of created) agentEvents._emit('agent:created', agent, 'unknown');
+
+ if (params.sshHost !== null) {
+ // Lazy import: remote-watcher transitively loads Electron's `app` module at
+ // the top level, which breaks the unit-test environment where `app` is
+ // undefined. A dynamic import defers that cost to runtime (always Electron).
+ const { startRemoteDiscovery } = await import('./remote-watcher');
+ for (const agent of created) {
+ startRemoteDiscovery(agent.id).catch((error) => {
+ log.warn('attachConfiguredAgents: failed to start session discovery', {
+ agentId: agent.id,
+ error: String(error),
+ });
+ });
+ }
+ }
+
return ok(created);
}
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/controller.ts b/console/apps/switch-console-desktop/src/main/core/agents/controller.ts
index 39ec76ee3..f50e7725a 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/controller.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/controller.ts
@@ -23,11 +23,18 @@ import { createAgent } from './createAgent';
import { getAgentDefinitionFields } from './definition-fields';
import { deleteAgent, type DeleteAgentOptions } from './deleteAgent';
import { discoverConfiguredAgents } from './discover-configured-agents';
+import {
+ discoverLoadableAgentsInDir,
+ discoverLoadableAgentsOnHost,
+ type DiscoverLoadableAgentsParams,
+} from './discover-loadable-agents';
import { discoverLocationAgents } from './discover-location-agents';
import { getAgentById } from './getAgentById';
import { getAgents } from './getAgents';
import { onboardAgent } from './onboard-agent';
import { onboardLocationAgents, type OnboardLocationParams } from './onboard-location-agents';
+import type { RemoveLoadableAgentConfigParams } from './remove-loadable-agent-config';
+import { removeLoadableAgentConfig } from './remove-loadable-agent-config';
import { renameAgent } from './renameAgent';
import { resetRemoteAgent } from './reset-remote-agent';
import { setAgentAutoApprove, type AgentAutoApproveParams } from './setAgentAutoApprove';
@@ -85,13 +92,20 @@ export const agentsController = createRPCController({
}) => discoverLocationAgents(params),
discoverConfiguredAgents: (params: { sshHost: string | null; dir: string; serverId: string }) =>
discoverConfiguredAgents(params),
+ discoverLoadableAgentsOnHost: (params: DiscoverLoadableAgentsParams) =>
+ discoverLoadableAgentsOnHost(params),
+ discoverLoadableAgentsInDir: (params: { sshHost: string; dir: string; serverId: string }) =>
+ discoverLoadableAgentsInDir(params),
attachConfiguredAgents: (params: AttachConfiguredAgentsParams) => attachConfiguredAgents(params),
+ removeLoadableAgentConfig: (params: RemoveLoadableAgentConfigParams) =>
+ removeLoadableAgentConfig(params),
getAgents: (locationId?: string) => getAgents(locationId),
getAgentById: (agentId: string) => getAgentById(agentId),
renameAgent: (params: RenameAgentParams) => renameAgent(params),
deleteAgent: (params: { agentId: string } & DeleteAgentOptions) =>
deleteAgent(params.agentId, {
deleteInSwitch: params.deleteInSwitch,
+ removeProvisionedFiles: params.removeProvisionedFiles,
trigger: params.trigger,
}),
resetRemoteAgent: (params: { agentId: string }) => resetRemoteAgent(params.agentId),
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/createAgent.ts b/console/apps/switch-console-desktop/src/main/core/agents/createAgent.ts
index 52f875245..8cdebcabb 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/createAgent.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/createAgent.ts
@@ -16,6 +16,7 @@ export async function createAgent(params: CreateAgentParams): Promise<Agent> {
apiEndpoint: params.apiEndpoint,
serverId: params.serverId,
autoApprove: params.autoApprove,
+ ownerName: params.ownerName ?? null,
providerConfig: params.providerConfig ?? null,
updatedAt: sql`CURRENT_TIMESTAMP`,
})
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.test.ts
index 3780b49c8..29ae201d4 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.test.ts
@@ -119,7 +119,11 @@ describe('deleteAgent', () => {
const fs = fakeFs({ [agentSettingsRelativePath('codex-hoot')]: CREDS });
h.state.fs = fs;
- await deleteAgent('agent-1', { deleteInSwitch: false, trigger: 'user' });
+ await deleteAgent('agent-1', {
+ deleteInSwitch: false,
+ removeProvisionedFiles: true,
+ trigger: 'user',
+ });
expect(await fs.exists(agentSettingsRelativePath('codex-hoot'))).toBe(false);
});
@@ -131,12 +135,38 @@ describe('deleteAgent', () => {
});
h.state.fs = fs;
- await deleteAgent('agent-1', { deleteInSwitch: false, trigger: 'user' });
+ await deleteAgent('agent-1', {
+ deleteInSwitch: false,
+ removeProvisionedFiles: true,
+ trigger: 'user',
+ });
expect(await fs.exists(agentSettingsRelativePath('cc-hoot'))).toBe(false);
expect(await fs.exists('.claude/agents/cc-hoot.md')).toBe(false);
});
+ it('leaves the working directory untouched on a plain remove (CHOO-2560)', async () => {
+ // An agent loaded from a shared host has credentials another install owns;
+ // a remove without removeProvisionedFiles must not reach into the directory.
+ h.state.agent = { id: 'agent-1', name: 'cc-hoot', providerId: 'claude', locationId: 'loc' };
+ const fs = fakeFs({
+ [agentSettingsRelativePath('cc-hoot')]: CREDS,
+ '.claude/agents/cc-hoot.md': '# cc-hoot',
+ });
+ h.state.fs = fs;
+
+ await deleteAgent('agent-1', {
+ deleteInSwitch: false,
+ removeProvisionedFiles: false,
+ trigger: 'user',
+ });
+
+ expect(await fs.exists(agentSettingsRelativePath('cc-hoot'))).toBe(true);
+ expect(await fs.exists('.claude/agents/cc-hoot.md')).toBe(true);
+ expect(h.removeLocal).not.toHaveBeenCalled();
+ expect(h.removeSwitchCredentials).not.toHaveBeenCalled();
+ });
+
it('leaves a sibling agent sharing the directory untouched', async () => {
const fs = fakeFs({
[agentSettingsRelativePath('cc-hoot')]: CREDS,
@@ -144,14 +174,22 @@ describe('deleteAgent', () => {
});
h.state.fs = fs;
- await deleteAgent('agent-1', { deleteInSwitch: false, trigger: 'user' });
+ await deleteAgent('agent-1', {
+ deleteInSwitch: false,
+ removeProvisionedFiles: true,
+ trigger: 'user',
+ });
expect(await fs.exists(agentSettingsRelativePath('cc-sibling'))).toBe(true);
});
describe('what it reports', () => {
it('describes the agent that was removed, from the row before it goes', async () => {
- await deleteAgent('agent-1', { deleteInSwitch: false, trigger: 'user' });
+ await deleteAgent('agent-1', {
+ deleteInSwitch: false,
+ removeProvisionedFiles: false,
+ trigger: 'user',
+ });
expect(h.trackEvent).toHaveBeenCalledWith('agent_removed', {
agent_type: 'claude',
@@ -166,7 +204,11 @@ describe('deleteAgent', () => {
it('separates a server teardown from a person removing an agent', async () => {
// Wiping a managed server deletes every agent on it through this same
// function; without the distinction one click looks like an exodus.
- await deleteAgent('agent-1', { deleteInSwitch: false, trigger: 'server_teardown' });
+ await deleteAgent('agent-1', {
+ deleteInSwitch: false,
+ removeProvisionedFiles: false,
+ trigger: 'server_teardown',
+ });
expect(h.trackEvent).toHaveBeenCalledWith(
'agent_removed',
@@ -179,7 +221,11 @@ describe('deleteAgent', () => {
// every one of them reported starting.
h.state.sessionRows = [{ id: 's-1' }, { id: 's-2' }];
- await deleteAgent('agent-1', { deleteInSwitch: false, trigger: 'user' });
+ await deleteAgent('agent-1', {
+ deleteInSwitch: false,
+ removeProvisionedFiles: false,
+ trigger: 'user',
+ });
expect(h.sessionHookEmit).toHaveBeenCalledWith('session:deleted', 's-1');
expect(h.sessionHookEmit).toHaveBeenCalledWith('session:deleted', 's-2');
@@ -201,7 +247,11 @@ describe('deleteAgent', () => {
vi.mocked(getServer).mockResolvedValue({ id: 'srv-1' } as never);
await expect(
- deleteAgent('agent-1', { deleteInSwitch: true, trigger: 'user' })
+ deleteAgent('agent-1', {
+ deleteInSwitch: true,
+ removeProvisionedFiles: false,
+ trigger: 'user',
+ })
).rejects.toThrow();
expect(h.trackEvent).toHaveBeenCalledWith(
@@ -221,7 +271,11 @@ describe('deleteAgent', () => {
};
await expect(
- deleteAgent('agent-1', { deleteInSwitch: true, trigger: 'user' })
+ deleteAgent('agent-1', {
+ deleteInSwitch: true,
+ removeProvisionedFiles: false,
+ trigger: 'user',
+ })
).rejects.toThrow();
expect(h.trackEvent).toHaveBeenCalledWith(
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.ts b/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.ts
index cfa87aab4..57c312eea 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.ts
@@ -44,6 +44,19 @@ export type DeleteAgentOptions = {
* left registered on the server.
*/
deleteInSwitch: boolean;
+ /**
+ * Also tear down what was provisioned on disk for this agent (its
+ * `.switch/agents/<name>.json` credentials, provider definition files, launch
+ * profile) and kill its sidecar on the host.
+ *
+ * Required with no default, because the right answer depends on who owns the
+ * on-disk state: an agent this Console created can carry its files out, but an
+ * agent merely loaded from a shared host (CHOO-2560) has credentials that
+ * belong to ANOTHER install — deleting them there is data loss on a
+ * colleague's machine. Plain remove must mirror attach's guarantee: nothing in
+ * the working directory is touched.
+ */
+ removeProvisionedFiles: boolean;
/**
* Whether a person removed this agent or a server teardown swept it up.
*
@@ -188,9 +201,11 @@ async function killRemoteSidecar(agent: Agent): Promise<void> {
* caches the agent's Switch credentials in memory, so without an explicit
* stop it keeps heartbeating and polling notifications for an agent that
* no longer exists.
- * 4. The Switch credentials + definition file Switch Console provisioned on disk for
- * THIS agent (local or remote), which a bare row delete would leave orphaned.
- * Sibling agents' files in the same directory are untouched.
+ * 4. Only when `removeProvisionedFiles` is set: the Switch credentials +
+ * definition file provisioned on disk for THIS agent (local or remote), and
+ * its sidecar. A plain remove leaves the working directory and the host's
+ * processes untouched — on a shared host they may belong to another install
+ * (CHOO-2560). Sibling agents' files are never touched either way.
*
* The agent's location row is intentionally kept — locations are reusable
* and other agents may still live there.
@@ -247,14 +262,17 @@ async function removeAgent(
await stopRemoteWatcher(agentId).catch((error) => {
log.warn('deleteAgent: failed to stop remote watcher', { agentId, error: String(error) });
});
- if (agent) await killRemoteSidecar(agent);
+ // The sidecar is host state, like the files: killing it under an agent
+ // another install still manages takes their agent offline. Only tear it
+ // down when the on-disk teardown was asked for.
+ if (agent && options.removeProvisionedFiles) await killRemoteSidecar(agent);
} else {
autoSessionWatcher.stopForAgent(agentId);
}
await setAutoSessionAgent(agentId, false);
- if (agent && location) {
+ if (agent && location && options.removeProvisionedFiles) {
await removeProvisionedFiles(agent, location).catch((error) => {
log.warn('deleteAgent: failed to remove provisioned files', {
agentId,
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/discover-loadable-agents.ts b/console/apps/switch-console-desktop/src/main/core/agents/discover-loadable-agents.ts
new file mode 100644
index 000000000..b43e7a13b
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/agents/discover-loadable-agents.ts
@@ -0,0 +1,280 @@
+import { SshExecutionContext } from '@main/core/execution-context/ssh-execution-context';
+import { sshConnectionIdForHost } from '@main/core/locations/location-transport';
+import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';
+import { fetchAgents, fetchMe } from '@main/core/switch-servers/gateway-client';
+import { getServer } from '@main/core/switch-servers/servers-store';
+import { log } from '@main/lib/logger';
+import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';
+import { sameApiEndpoint } from '@shared/core/switch-servers/switch-servers';
+import type { DiscoveredConfiguredAgent, ProviderSource } from './discover-configured-agents';
+import { discoverConfiguredAgents } from './discover-configured-agents';
+
+/**
+ * An agent found on a remote host that can be loaded into this Console.
+ *
+ * Merges server-assisted discovery (which carries owner attribution) with a
+ * bounded on-host scan (which catches unregistered agents). Server-attributed
+ * entries win on dedup so attribution is preserved.
+ */
+export type LoadableAgent = {
+ name: string;
+ dir: string;
+ switchAgentId: string;
+ apiEndpoint: string;
+ providerId: AgentProviderId | null;
+ providerSource: ProviderSource;
+ /** Whether this Console already has a row for this agent. */
+ alreadyAgent: boolean;
+ /** The agent's owner on the server, when known via server-assisted discovery. */
+ ownerName: string | null;
+ /** True when the signed-in user is the agent's owner on the server. */
+ viewerIsOwner: boolean;
+ /** The agent's server-side description, when known via server-assisted discovery. */
+ description: string | null;
+ /** The source that found this agent. */
+ source: 'server' | 'scan';
+ /** True when the on-disk endpoint does not match the server's URL. */
+ endpointMismatch: boolean;
+ /** When set, the agent cannot be loaded and this is the human-readable reason. */
+ blockedReason: string | null;
+};
+
+export type DiscoverLoadableAgentsParams = {
+ sshHost: string;
+ serverId: string;
+ /** When true, run a depth-limited `find` over `$HOME` in addition to the
+ * cheap server-assisted discovery. Off by default — the walk can be slow
+ * on large VMs. */
+ includeHomeScan?: boolean;
+};
+
+export type DiscoverLoadableAgentsResult = {
+ agents: LoadableAgent[];
+ /** The target server's API URL, for rendering endpoint mismatches legibly. */
+ serverApiUrl: string;
+};
+
+/**
+ * Discover agents on a remote host that can be loaded into this Console,
+ * merging two sources and deduping by `(dir, name)`.
+ *
+ * 1. **Server-assisted:** `GET /agents` for the deployment's agents with
+ * `repo_dir`; confirm each dir on-host via `discoverConfiguredAgents`.
+ * 2. **Bounded `$HOME` scan:** depth-limited `find` under the host's `$HOME`
+ * for dirs holding `.switch/agents/*.json`.
+ *
+ * Server-attributed entries win on dedup so owner attribution is preserved.
+ */
+export async function discoverLoadableAgentsOnHost(
+ params: DiscoverLoadableAgentsParams
+): Promise<DiscoverLoadableAgentsResult> {
+ const server = await getServer(params.serverId);
+ if (!server) throw new Error(`No Switch server with id ${params.serverId}`);
+
+ // Key: "dir\0name" → LoadableAgent. Server entries inserted first win.
+ const seen = new Map<string, LoadableAgent>();
+
+ // --- Source 1: Server-assisted discovery ---
+ try {
+ const remoteAgents = await fetchAgents(server);
+ // Marks rows the signed-in user owns; an auth failure degrades to not-owner.
+ const me = await fetchMe(server).catch(() => null);
+
+ // Collect distinct repo_dirs from agents whose known_agent_options carry one.
+ type ServerAgentInfo = {
+ ownerName: string | null;
+ ownerId: string | null;
+ description: string | null;
+ };
+ const dirOwners = new Map<string, Map<string, ServerAgentInfo>>();
+ for (const agent of remoteAgents) {
+ const repoDir =
+ agent.knownAgentOptions &&
+ typeof agent.knownAgentOptions === 'object' &&
+ typeof (agent.knownAgentOptions as Record<string, unknown>).repo_dir === 'string'
+ ? ((agent.knownAgentOptions as Record<string, unknown>).repo_dir as string)
+ : null;
+ if (!repoDir) continue;
+
+ if (!dirOwners.has(repoDir)) dirOwners.set(repoDir, new Map());
+ dirOwners.get(repoDir)!.set(agent.name, {
+ ownerName: agent.ownerName,
+ ownerId: agent.ownerId,
+ description: agent.description ?? null,
+ });
+ }
+
+ for (const [dir, nameOwners] of dirOwners) {
+ try {
+ const discovered = await discoverConfiguredAgents({
+ sshHost: params.sshHost,
+ dir,
+ serverId: params.serverId,
+ });
+ for (const agent of discovered) {
+ const key = `${dir}\0${agent.name}`;
+ const info = nameOwners.get(agent.name) ?? null;
+ seen.set(key, {
+ name: agent.name,
+ dir,
+ switchAgentId: agent.switchAgentId,
+ apiEndpoint: agent.apiEndpoint,
+ providerId: agent.providerId,
+ providerSource: agent.providerSource,
+ alreadyAgent: agent.alreadyAgent,
+ ownerName: info?.ownerName ?? null,
+ viewerIsOwner: !!(me && info?.ownerId && info.ownerId === me.id),
+ description: info?.description ?? null,
+ source: 'server',
+ endpointMismatch: !sameApiEndpoint(agent.apiEndpoint, server.apiUrl),
+ blockedReason: blockedReasonFor(agent, server.apiUrl),
+ });
+ }
+ } catch (error) {
+ log.warn('discoverLoadableAgentsOnHost: server-assisted dir scan failed', {
+ dir,
+ sshHost: params.sshHost,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+ } catch (error) {
+ log.warn('discoverLoadableAgentsOnHost: server-assisted discovery failed', {
+ serverId: params.serverId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+
+ // --- Source 2: Bounded $HOME scan (opt-in) ---
+ if (!params.includeHomeScan) return { agents: [...seen.values()], serverApiUrl: server.apiUrl };
+ try {
+ const scannedDirs = await findSwitchAgentDirsOnHost(params.sshHost);
+ for (const dir of scannedDirs) {
+ try {
+ const discovered = await discoverConfiguredAgents({
+ sshHost: params.sshHost,
+ dir,
+ serverId: params.serverId,
+ });
+ for (const agent of discovered) {
+ const key = `${dir}\0${agent.name}`;
+ if (!seen.has(key)) {
+ seen.set(key, {
+ name: agent.name,
+ dir,
+ switchAgentId: agent.switchAgentId,
+ apiEndpoint: agent.apiEndpoint,
+ providerId: agent.providerId,
+ providerSource: agent.providerSource,
+ alreadyAgent: agent.alreadyAgent,
+ ownerName: null,
+ viewerIsOwner: false,
+ description: null,
+ source: 'scan',
+ endpointMismatch: !sameApiEndpoint(agent.apiEndpoint, server.apiUrl),
+ blockedReason: blockedReasonFor(agent, server.apiUrl),
+ });
+ }
+ }
+ } catch (error) {
+ log.warn('discoverLoadableAgentsOnHost: scan dir discovery failed', {
+ dir,
+ sshHost: params.sshHost,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+ } catch (error) {
+ log.warn('discoverLoadableAgentsOnHost: bounded scan failed', {
+ sshHost: params.sshHost,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+
+ return { agents: [...seen.values()], serverApiUrl: server.apiUrl };
+}
+
+function blockedReasonFor(agent: DiscoveredConfiguredAgent, serverApiUrl: string): string | null {
+ if (agent.alreadyAgent) return 'Already loaded in this Console';
+ if (!sameApiEndpoint(agent.apiEndpoint, serverApiUrl))
+ return 'Endpoint does not match this server';
+ return null;
+}
+
+/**
+ * Bounded depth-limited scan of `$HOME` on a remote host for directories
+ * containing `.switch/agents/*.json`. Prunes `node_modules` and every hidden
+ * directory except `.switch` itself — dot-trees like `.cargo`, `.npm` or
+ * `.vscode-server` hold hundreds of thousands of entries on a dev box and can
+ * never contain a working directory we would surface.
+ *
+ * Returns the parent working directories (the dirs that contain `.switch/`),
+ * not the `.switch/agents/` paths themselves.
+ */
+async function findSwitchAgentDirsOnHost(sshHost: string): Promise<string[]> {
+ const proxy = await ensureSshConnected(sshConnectionIdForHost(sshHost), sshHost);
+ const ctx = new SshExecutionContext(proxy);
+ let result: { stdout: string };
+ try {
+ result = await ctx.exec('sh', [
+ '-c',
+ [
+ 'find "$HOME" -maxdepth 6',
+ '-type d \\( -name node_modules -o \\( -name ".*" ! -name .switch \\) \\) -prune',
+ '-o -type f -path "*/.switch/agents/*.json" -print',
+ '2>/dev/null',
+ '| sed "s|/\\.switch/agents/.*||"',
+ '| sort -u',
+ ].join(' '),
+ ]);
+ } catch (error) {
+ // Disclosed fallback: an exec failure must not read as "empty host", so
+ // leave a trace even though discovery continues with the server source.
+ log.warn('findSwitchAgentDirsOnHost: $HOME scan failed', {
+ sshHost,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return [];
+ }
+ return result.stdout
+ .trim()
+ .split('\n')
+ .filter((line) => line.length > 0);
+}
+
+/**
+ * Discover agents in a single manually-specified directory — the "scan a
+ * directory" fallback. A thin wrapper that calls the existing per-dir scan
+ * and attaches the same metadata shape as the merged discovery.
+ */
+export async function discoverLoadableAgentsInDir(params: {
+ sshHost: string;
+ dir: string;
+ serverId: string;
+}): Promise<{ agents: LoadableAgent[]; serverApiUrl: string }> {
+ const server = await getServer(params.serverId);
+ if (!server) throw new Error(`No Switch server with id ${params.serverId}`);
+
+ const discovered = await discoverConfiguredAgents({
+ sshHost: params.sshHost,
+ dir: params.dir,
+ serverId: params.serverId,
+ });
+
+ const agents = discovered.map((agent) => ({
+ name: agent.name,
+ dir: params.dir,
+ switchAgentId: agent.switchAgentId,
+ apiEndpoint: agent.apiEndpoint,
+ providerId: agent.providerId,
+ providerSource: agent.providerSource,
+ alreadyAgent: agent.alreadyAgent,
+ ownerName: null,
+ viewerIsOwner: false,
+ description: null,
+ source: 'scan' as const,
+ endpointMismatch: !sameApiEndpoint(agent.apiEndpoint, server.apiUrl),
+ blockedReason: blockedReasonFor(agent, server.apiUrl),
+ }));
+ return { agents, serverApiUrl: server.apiUrl };
+}
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/remove-loadable-agent-config.ts b/console/apps/switch-console-desktop/src/main/core/agents/remove-loadable-agent-config.ts
new file mode 100644
index 000000000..dafa03c4e
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/agents/remove-loadable-agent-config.ts
@@ -0,0 +1,44 @@
+import { log } from '@main/lib/logger';
+import { resolveWorkspaceFsFor } from './agent-workspace-fs';
+import { agentSettingsRelativePath } from './switch-settings-paths';
+
+export type RemoveLoadableAgentConfigParams = {
+ sshHost: string | null;
+ dir: string;
+ name: string;
+};
+
+export type RemoveLoadableAgentConfigResult =
+ | { removed: true }
+ | { removed: false; reason: 'not-found' };
+
+/**
+ * Delete an agent's on-disk config (`.switch/agents/<name>.json`) from a
+ * working directory, so a stale or wrong-endpoint entry surfaced by "Load
+ * existing agents" can be cleaned up in place (CHOO-2560).
+ *
+ * Deliberately host-file-only: the agent's registration on the Switch server
+ * is untouched (deregistering is the owner's call, made from an attached
+ * agent's own page), and no Console rows anywhere are affected. Callers
+ * should not offer this for agents already loaded in this Console — deleting
+ * the file under a managed agent breaks its launches.
+ */
+export async function removeLoadableAgentConfig(
+ params: RemoveLoadableAgentConfigParams
+): Promise<RemoveLoadableAgentConfigResult> {
+ const relPath = agentSettingsRelativePath(params.name);
+ const ctx = await resolveWorkspaceFsFor(params.sshHost, params.dir);
+ try {
+ const existing = await ctx.fs.read(relPath);
+ if (existing === null) return { removed: false, reason: 'not-found' };
+ await ctx.fs.delete(relPath);
+ log.info('removeLoadableAgentConfig: deleted agent config', {
+ sshHost: params.sshHost,
+ dir: params.dir,
+ name: params.name,
+ });
+ return { removed: true };
+ } finally {
+ ctx.close();
+ }
+}
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/utils.ts b/console/apps/switch-console-desktop/src/main/core/agents/utils.ts
index f3a542541..801b36b72 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/utils.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/utils.ts
@@ -17,6 +17,7 @@ export function mapAgentRowToAgent(row: AgentRow): Agent {
serverId: row.serverId ?? null,
status: row.status ?? null,
autoApprove: row.autoApprove,
+ ownerName: row.ownerName ?? null,
providerConfig: row.providerConfig ?? null,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.test.ts
index d3722681d..f0a806d0e 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.test.ts
@@ -10,6 +10,7 @@ import {
SWITCH_SETTINGS_RELATIVE_PATH,
} from './switch-settings-paths';
import {
+ ExistingAgentCredentialsError,
ForeignAgentCredentialsError,
foreignCredentialsEndpoint,
foreignCredentialsOwnerFs,
@@ -219,11 +220,14 @@ describe('writeNeutralAgentSettingsFs, against another install of Switch Console
},
});
+ // The caller passes expectedAgentId to confirm it owns the slot — without
+ // this, the same-endpoint guard refuses the write (CHOO-2560).
await writeNeutralAgentSettingsFs(createPluginFs(dir), {
slug: 'ours',
apiEndpoint: 'https://switch.example.com',
apiToken: 'new-token',
agentId: 'new-agent',
+ expectedAgentId: 'old-agent',
});
const raw = await fs.readFile(path.join(dir, agentSettingsRelativePath('ours')), 'utf8');
@@ -234,6 +238,25 @@ describe('writeNeutralAgentSettingsFs, against another install of Switch Console
});
});
+ it('refuses when same-endpoint slot holds a different agent and no expectedAgentId is given (CHOO-2560)', async () => {
+ await seed('colleague', {
+ env: {
+ SWITCH_API_ENDPOINT: 'https://switch.example.com',
+ SWITCH_API_TOKEN: 'their-token',
+ SWITCH_AGENT_ID: 'their-agent',
+ },
+ });
+
+ await expect(
+ writeNeutralAgentSettingsFs(createPluginFs(dir), {
+ slug: 'colleague',
+ apiEndpoint: 'https://switch.example.com',
+ apiToken: 'our-token',
+ agentId: 'our-agent',
+ })
+ ).rejects.toBeInstanceOf(ExistingAgentCredentialsError);
+ });
+
it('reports the owning server through foreignCredentialsOwnerFs, for a caller checking before it registers', async () => {
await seed('shared-name', otherInstall);
const workspaceFs = createPluginFs(dir);
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.ts b/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.ts
index 3ca57d23c..b9019e6ad 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.ts
@@ -367,6 +367,36 @@ export class ForeignAgentCredentialsError extends Error {
}
}
+/**
+ * The credentials file for this agent name already belongs to a different
+ * agent on the SAME Switch deployment. Writing would overwrite that agent's
+ * identity and destroy its API token — the same hazard as
+ * {@link ForeignAgentCredentialsError}, but between agents on the same server
+ * rather than across deployments (CHOO-2560).
+ */
+export class ExistingAgentCredentialsError extends Error {
+ readonly slug: string;
+ readonly relPath: string;
+ readonly existingAgentId: string;
+ readonly incomingAgentId: string;
+
+ constructor(params: {
+ slug: string;
+ relPath: string;
+ existingAgentId: string;
+ incomingAgentId: string;
+ }) {
+ super(
+ `${params.relPath} in this directory already holds credentials for agent ${params.existingAgentId} on this Switch server. Writing it would overwrite that agent's identity and destroy its API token, which cannot be recovered. Load the existing agent instead, or use a different agent name.`
+ );
+ this.name = 'ExistingAgentCredentialsError';
+ this.slug = params.slug;
+ this.relPath = params.relPath;
+ this.existingAgentId = params.existingAgentId;
+ this.incomingAgentId = params.incomingAgentId;
+ }
+}
+
/**
* Read the per-agent credentials slot for `slug` and report the Switch
* deployment it already belongs to, when that is a different one. Callers use
@@ -383,6 +413,49 @@ export async function foreignCredentialsOwnerFs(
return foreignCredentialsEndpoint(existingRaw, apiEndpoint);
}
+/**
+ * The `SWITCH_AGENT_ID` already in a credentials slot when the file belongs to
+ * the SAME deployment — otherwise null (no file, not a provisioned agent, or a
+ * different deployment).
+ *
+ * This is the inverse of {@link foreignCredentialsEndpoint}: that one catches
+ * a different-server collision; this one catches a same-server collision where
+ * the identity exists on-disk but is unknown to this install's database — i.e.
+ * a colleague's agent that would be clobbered by a blind write.
+ *
+ * Pure: takes the existing file text, or null when no file exists. A failed
+ * read is not null — `PluginFs.read` throws on transport errors, and callers
+ * must let that propagate: mapping it to null would make a transient error
+ * read as "slot free" and clobber real credentials.
+ */
+export function existingAgentIdInSlot(
+ existingRaw: string | null,
+ apiEndpoint: string
+): string | null {
+ if (existingRaw === null) return null;
+
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(existingRaw);
+ } catch {
+ return null;
+ }
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
+
+ const env = (parsed as Record<string, unknown>).env;
+ if (!env || typeof env !== 'object' || Array.isArray(env)) return null;
+
+ const existingEndpoint = (env as Record<string, unknown>).SWITCH_API_ENDPOINT;
+ if (typeof existingEndpoint !== 'string' || existingEndpoint.trim() === '') return null;
+
+ if (!sameApiEndpoint(existingEndpoint, apiEndpoint)) return null;
+
+ const agentId = (env as Record<string, unknown>).SWITCH_AGENT_ID;
+ if (typeof agentId !== 'string' || agentId.trim() === '') return null;
+
+ return agentId;
+}
+
/**
* Write an agent's provider-neutral per-agent Switch credentials over a
* {@link PluginFs} (local disk or a remote repo dir via SFTP), keyed by `slug`
@@ -402,7 +475,7 @@ export async function foreignCredentialsOwnerFs(
*/
export async function writeNeutralAgentSettingsFs(
workspaceFs: PluginFs,
- params: { slug: string } & SwitchSettingsCredentials
+ params: { slug: string; expectedAgentId?: string } & SwitchSettingsCredentials
): Promise<void> {
const relPath = agentSettingsRelativePath(params.slug);
const existingRaw = await workspaceFs.read(relPath);
@@ -416,6 +489,25 @@ export async function writeNeutralAgentSettingsFs(
});
}
+ // Defence in depth: if the slot holds a same-endpoint identity that is NOT
+ // the one we are about to write, refuse — it belongs to a colleague's agent
+ // and overwriting it would destroy their token (CHOO-2560). Callers that have
+ // already verified the overwrite is safe pass `expectedAgentId` to bypass this
+ // guard for their own agent (e.g. runAddAgent after its pre-mint DB lookup).
+ const slotAgentId = existingAgentIdInSlot(existingRaw, params.apiEndpoint);
+ if (
+ slotAgentId !== null &&
+ slotAgentId !== params.agentId &&
+ slotAgentId !== params.expectedAgentId
+ ) {
+ throw new ExistingAgentCredentialsError({
+ slug: params.slug,
+ relPath,
+ existingAgentId: slotAgentId,
+ incomingAgentId: params.agentId,
+ });
+ }
+
if (!(await workspaceFs.exists(SWITCH_AGENTS_GITIGNORE_RELATIVE))) {
await workspaceFs.write(SWITCH_AGENTS_GITIGNORE_RELATIVE, '*\n');
}
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.test.ts
index b765f6040..90aee30fa 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.test.ts
@@ -42,6 +42,7 @@ function agent(overrides: Partial<RemoteAgentSummary>): RemoteAgentSummary {
ownerId: 'user-me',
ownerName: 'me',
knownAgentType: 'claude-code',
+ knownAgentOptions: null,
addressingPolicy: null,
iconUrl: null,
createdAt: '2026-01-01T00:00:00Z',
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/delete-server-agents.db.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/delete-server-agents.db.test.ts
index b38f92171..f9167e769 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/delete-server-agents.db.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/delete-server-agents.db.test.ts
@@ -82,6 +82,7 @@ describe('deleteAgentsForServer', () => {
expect(mocks.deleteAgent).toHaveBeenCalledWith('agent-a', {
deleteInSwitch: false,
+ removeProvisionedFiles: true,
// Wiping a server is one action, not a person deleting each agent.
trigger: 'server_teardown',
});
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/delete-server-agents.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/delete-server-agents.ts
index 2a3ebd6e1..6fd47dbde 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/delete-server-agents.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/delete-server-agents.ts
@@ -40,7 +40,13 @@ export async function deleteAgentsForServer(
for (const row of rows) {
try {
- await deleteAgent(row.id, { deleteInSwitch: false, trigger: 'server_teardown' });
+ // A destroyed managed server's agents were provisioned by this install,
+ // so their on-disk files go with them.
+ await deleteAgent(row.id, {
+ deleteInSwitch: false,
+ removeProvisionedFiles: true,
+ trigger: 'server_teardown',
+ });
deleted.push(row.id);
} catch (error) {
failed.push({ agentId: row.id, error: String(error) });
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
index cf5b98038..55a1825a6 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
@@ -353,6 +353,7 @@ type AgentSummaryJson = {
owner_id?: string | null;
owner_name: string | null;
known_agent_type: string | null;
+ known_agent_options?: Record<string, unknown> | null;
addressing_policy?: AddressingPolicy | null;
icon_url?: string | null;
created_at: string;
@@ -371,6 +372,7 @@ function toRemoteAgentSummary(json: AgentSummaryJson): RemoteAgentSummary {
ownerId: json.owner_id ?? null,
ownerName: json.owner_name,
knownAgentType: json.known_agent_type,
+ knownAgentOptions: json.known_agent_options ?? null,
addressingPolicy: json.addressing_policy ?? null,
iconUrl: json.icon_url ?? null,
createdAt: json.created_at,
diff --git a/console/apps/switch-console-desktop/src/main/core/telemetry/events.ts b/console/apps/switch-console-desktop/src/main/core/telemetry/events.ts
index d8c676766..582bb22ca 100644
--- a/console/apps/switch-console-desktop/src/main/core/telemetry/events.ts
+++ b/console/apps/switch-console-desktop/src/main/core/telemetry/events.ts
@@ -51,6 +51,7 @@ export type TelemetryAgentCreateFailure =
| 'unauthenticated'
| 'name_conflict'
| 'credentials_conflict'
+ | 'already_configured'
| 'invalid_name'
/**
* The two the other way into this — dropping a folder on the sidebar — hits
diff --git a/console/apps/switch-console-desktop/src/main/db/schema.ts b/console/apps/switch-console-desktop/src/main/db/schema.ts
index 98ce833e0..539b0e919 100644
--- a/console/apps/switch-console-desktop/src/main/db/schema.ts
+++ b/console/apps/switch-console-desktop/src/main/db/schema.ts
@@ -161,6 +161,9 @@ export const agents = sqliteTable(
// Defaults false for local agents; onboarding seeds it true for remote
// agents (see onboard-agent). Editable per agent in location settings.
autoApprove: integer('auto_approve', { mode: 'boolean' }).notNull().default(false),
+ // The display name of the agent's owner on the Switch server, set when the
+ // agent was loaded from another install rather than created here.
+ ownerName: text('owner_name'),
// Per-agent, provider-specific launch config (Codex model / effort /
// instructions folded into the agent's Codex profile). Null when unset.
providerConfig: versionedJsonColumn(agentProviderConfig)('provider_config'),
diff --git a/console/apps/switch-console-desktop/src/main/index.ts b/console/apps/switch-console-desktop/src/main/index.ts
index 59a96b772..15b449016 100644
--- a/console/apps/switch-console-desktop/src/main/index.ts
+++ b/console/apps/switch-console-desktop/src/main/index.ts
@@ -11,6 +11,7 @@ import { registerAppScheme, setupAppProtocol } from './app/protocol';
import { createMainWindow, getMainWindow } from './app/window';
import { agentHookService } from './core/agent-hooks/agent-hook-service';
import { reapOrphanedAgentRuntimes } from './core/agent-runtime/reap-orphaned-runtimes';
+import { bridgeAgentEventsToRenderer } from './core/agents/agent-events-renderer-bridge';
import { migrateAgentStorage } from './core/agents/migrate-agent-storage';
import { initializeRemoteDiscovery, initializeRemoteWatchers } from './core/agents/remote-watcher';
import { resolveAgentServers } from './core/agents/resolve-servers';
@@ -231,6 +232,7 @@ void app.whenReady().then(async () => {
log.error('Failed to initialise remote watchers at startup:', e);
}
try {
+ bridgeAgentEventsToRenderer();
await initializeRemoteDiscovery();
} catch (e) {
log.error('Failed to initialise remote session discovery at startup:', e);
diff --git a/console/apps/switch-console-desktop/src/renderer/App.tsx b/console/apps/switch-console-desktop/src/renderer/App.tsx
index 3e5c3e088..05264a712 100644
--- a/console/apps/switch-console-desktop/src/renderer/App.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/App.tsx
@@ -1,4 +1,5 @@
import { QueryClientProvider } from '@tanstack/react-query';
+import { AgentCrudEvents } from './app/agent-crud-events';
import { AppMenuEvents } from './app/app-menu-events';
import { Workspace } from './app/workspace';
import { SessionFocusReporter } from './features/sessions/session-focus-reporter-mount';
@@ -20,6 +21,7 @@ function AppContent() {
<TerminalPoolProvider>
<WorkspaceViewProvider>
<AppMenuEvents />
+ <AgentCrudEvents />
<SessionFocusReporter />
<SessionDeeplinkListener />
<RightSidebarProvider>
diff --git a/console/apps/switch-console-desktop/src/renderer/app/agent-crud-events.tsx b/console/apps/switch-console-desktop/src/renderer/app/agent-crud-events.tsx
new file mode 100644
index 000000000..64b91b02f
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/app/agent-crud-events.tsx
@@ -0,0 +1,29 @@
+import { useQueryClient } from '@tanstack/react-query';
+import { useEffect } from 'react';
+import { agentsStore } from '@renderer/features/locations/stores/agents-store';
+import { getLocationManagerStore } from '@renderer/features/locations/stores/location-selectors';
+import { LOAD_AGENTS_QUERY_KEY } from '@renderer/features/remote-hosts/load-existing-agents-section';
+import { events } from '@renderer/lib/ipc';
+import { agentsChangedChannel } from '@shared/events/appEvents';
+
+/**
+ * React to agent CRUD from the main process (CHOO-2560): reload the sidebar's
+ * agents store AND location manager, and refetch any open "Load existing
+ * agents" discovery, so a created or removed agent is reflected everywhere
+ * without per-call-site invalidation.
+ */
+export function AgentCrudEvents() {
+ const queryClient = useQueryClient();
+
+ useEffect(
+ () =>
+ events.on(agentsChangedChannel, () => {
+ void agentsStore.load();
+ void getLocationManagerStore().reload();
+ void queryClient.invalidateQueries({ queryKey: [LOAD_AGENTS_QUERY_KEY] });
+ }),
+ [queryClient]
+ );
+
+ return null;
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts b/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts
index ee1720368..22808fac9 100644
--- a/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts
+++ b/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts
@@ -3,6 +3,7 @@ import { AddAgentModal } from '@renderer/features/locations/components/add-agent
import { DeleteAgentModal } from '@renderer/features/locations/components/delete-agent-modal';
import { ResetAgentModal } from '@renderer/features/locations/components/reset-agent-modal';
import { AddHostModal } from '@renderer/features/remote-hosts/add-host-modal';
+import { RemoveAgentConfigModal } from '@renderer/features/remote-hosts/remove-agent-config-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';
@@ -52,6 +53,7 @@ export const modalRegistry = {
addAgentModal: createModal(AddAgentModal, { size: 'lg', dismissOnOutsideClick: false }),
confirmActionModal: createModal(ConfirmActionDialog, { size: 'xs' }),
deleteAgentModal: createModal(DeleteAgentModal, { size: 'sm' }),
+ removeAgentConfigModal: createModal(RemoveAgentConfigModal, { size: 'sm' }),
resetAgentModal: createModal(ResetAgentModal, { size: 'sm' }),
confirmExternalLinkModal: createModal(ExternalLinkChoiceDialog, { size: 'sm' }),
unsavedChangesModal: createModal(UnsavedChangesDialog, { size: 'xs' }),
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx
index 435c23376..91c607534 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx
@@ -293,6 +293,15 @@ export const AddAgentModal = observer(function AddAgentModal({
});
return;
}
+ if (result.kind === 'already-configured') {
+ toast({
+ title: 'An agent with this name is already configured here',
+ description:
+ 'This directory already holds credentials for an agent of that name. Load the existing agent instead of creating a new one.',
+ variant: 'destructive',
+ });
+ return;
+ }
if (result.kind === 'invalid-name') {
toast({
title: 'Switch rejected these agent details',
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/delete-agent-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/delete-agent-modal.tsx
index b56fa6431..f1346e772 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/delete-agent-modal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/delete-agent-modal.tsx
@@ -15,15 +15,21 @@ export type DeleteAgentModalArgs = {
agentId: string;
/** Display name for the agent (its Switch name, falling back to the location). */
agentLabel: string;
+ /** The agent's host (null = this machine), for naming where its files live. */
+ sshHost: string | null;
+ /** The agent's working directory, for naming where its files live. */
+ dir: string | null;
};
-/** What the confirm resolves with: whether to also delete the agent in Switch. */
-export type DeleteAgentModalResult = { deleteInSwitch: boolean };
+/** What the confirm resolves with: what to tear down beyond this Console's row. */
+export type DeleteAgentModalResult = { deleteInSwitch: boolean; removeProvisionedFiles: boolean };
type Props = BaseModalProps<DeleteAgentModalResult> & DeleteAgentModalArgs;
-export function DeleteAgentModal({ agentLabel, onSuccess, onClose }: Props) {
+export function DeleteAgentModal({ agentLabel, sshHost, dir, onSuccess, onClose }: Props) {
const [deleteInSwitch, setDeleteInSwitch] = useState(false);
+ const [removeProvisionedFiles, setRemoveProvisionedFiles] = useState(false);
+ const filesPlace = dir ? (sshHost ? `${sshHost}:${dir}` : dir) : null;
return (
<>
@@ -33,10 +39,32 @@ export function DeleteAgentModal({ agentLabel, onSuccess, onClose }: Props) {
<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
- Switch Console and the Switch credentials it stored on this machine will be cleared. The
- folder stays on the filesystem.
+ Switch Console. Its working directory, the credentials stored there, and any running
+ sidecar are untouched unless you choose below.
</p>
+ {filesPlace && (
+ <label className="group/field flex cursor-pointer items-start gap-2.5">
+ <Checkbox
+ checked={removeProvisionedFiles}
+ onCheckedChange={(checked) => setRemoveProvisionedFiles(checked === true)}
+ className="mt-0.5"
+ />
+ <span className="flex flex-col gap-0.5">
+ <span className="text-sm font-medium">
+ Also delete its files on <code className="break-all">{filesPlace}</code>
+ </span>
+ <span className="text-xs text-foreground-muted">
+ Removes the credentials and definition files provisioned in the working directory
+ and stops the agent{"'"}s sidecar.
+ {sshHost
+ ? ' On a shared host these may belong to another install — an agent you loaded rather than created should usually keep them.'
+ : ''}
+ </span>
+ </span>
+ </label>
+ )}
+
<label className="group/field flex cursor-pointer items-start gap-2.5">
<Checkbox
checked={deleteInSwitch}
@@ -56,7 +84,10 @@ export function DeleteAgentModal({ agentLabel, onSuccess, onClose }: Props) {
<Button variant="outline" onClick={onClose}>
Cancel
</Button>
- <ConfirmButton variant="destructive" onClick={() => onSuccess({ deleteInSwitch })}>
+ <ConfirmButton
+ variant="destructive"
+ onClick={() => onSuccess({ deleteInSwitch, removeProvisionedFiles })}
+ >
{deleteInSwitch ? 'Remove & delete in Switch' : 'Remove'}
</ConfirmButton>
</DialogFooter>
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/location-titlebar.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/location-titlebar.tsx
index e1bf11047..4dc8dfbfe 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/location-titlebar.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/location-titlebar.tsx
@@ -184,7 +184,16 @@ export const LocationTitlebar = observer(function LocationTitlebar() {
return (
<Titlebar
- leftSlot={<AgentCrumb agent={agent} />}
+ leftSlot={
+ <div className="flex items-center gap-2">
+ <AgentCrumb agent={agent} />
+ {agent?.ownerName && (
+ <span className="text-xs text-foreground-tertiary-passive">
+ loaded · by {agent.ownerName}
+ </span>
+ )}
+ </div>
+ }
rightSlot={
<div className="mr-1 flex items-center gap-1.5">
{mounted &&
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/hooks/use-confirm-delete-agent.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/hooks/use-confirm-delete-agent.tsx
index bc53689f0..9e7088214 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/hooks/use-confirm-delete-agent.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/hooks/use-confirm-delete-agent.tsx
@@ -34,14 +34,19 @@ export function useConfirmDeleteAgent() {
if (!targetAgentId) return;
const resolvedAgentId = targetAgentId;
+ const location = getLocationManagerStore().locations.get(locationId)?.data ?? null;
+
showDeleteAgent({
agentId: resolvedAgentId,
agentLabel: locationLabel,
- onSuccess: ({ deleteInSwitch }) => {
+ sshHost: location?.sshHost ?? null,
+ dir: location?.dir ?? null,
+ onSuccess: ({ deleteInSwitch, removeProvisionedFiles }) => {
void (async () => {
try {
await getLocationManagerStore().removeAgent(locationId, resolvedAgentId, {
deleteInSwitch,
+ removeProvisionedFiles,
});
// Refresh the detail views that list a location's agents (settings
// sections, delete modal) so the removed agent drops and its siblings
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/stores/location-manager.test.ts b/console/apps/switch-console-desktop/src/renderer/features/locations/stores/location-manager.test.ts
index ca400bed0..5954402f8 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/stores/location-manager.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/stores/location-manager.test.ts
@@ -77,6 +77,7 @@ function agent(overrides: Partial<Agent> = {}): Agent {
serverId: 'server-1',
status: null,
autoApprove: false,
+ ownerName: null,
providerConfig: null,
createdAt: '2026-05-28T00:00:00.000Z',
updatedAt: '2026-05-28T00:00:00.000Z',
@@ -211,6 +212,53 @@ describe('LocationManagerStore agent onboarding', () => {
});
});
+describe('LocationManagerStore reload', () => {
+ const stubLocation = {} as LocationStore;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.openLocation.mockResolvedValue({ success: true });
+ });
+
+ it('mounts a newly-appeared location on reload', async () => {
+ const store = new LocationManagerStore();
+ // First load: no locations, no agents.
+ mocks.getLocations.mockResolvedValueOnce([]);
+ mocks.getAgents.mockResolvedValueOnce([]);
+ await store.load();
+ expect(store.locations.size).toBe(0);
+
+ // An agent was loaded externally — reload should pick it up.
+ mocks.getLocations.mockResolvedValueOnce([location({ id: 'new-loc' })]);
+ mocks.getAgents.mockResolvedValueOnce([agent({ locationId: 'new-loc' })]);
+ await store.reload();
+ expect(store.locations.has('new-loc')).toBe(true);
+ });
+
+ it('drops a location whose last agent was removed on reload', async () => {
+ const store = new LocationManagerStore();
+ store.locations.set('stale-loc', stubLocation);
+
+ // The DB still has the location row but no agents point at it.
+ mocks.getLocations.mockResolvedValueOnce([location({ id: 'stale-loc' })]);
+ mocks.getAgents.mockResolvedValueOnce([]);
+ await store.reload();
+ expect(store.locations.has('stale-loc')).toBe(false);
+ });
+
+ it('preserves a pending-creation location during reload', async () => {
+ const store = new LocationManagerStore();
+ store.locations.set('onboarding-loc', stubLocation);
+ store.pendingCreationIds.add('onboarding-loc');
+
+ // A concurrent CRUD event triggers reload while onboarding is in flight.
+ mocks.getLocations.mockResolvedValueOnce([]);
+ mocks.getAgents.mockResolvedValueOnce([]);
+ await store.reload();
+ expect(store.locations.has('onboarding-loc')).toBe(true);
+ });
+});
+
describe('LocationManagerStore removeAgent', () => {
// removeAgent only gets/deletes the location by key, so a placeholder stands in
// for the (heavy) real LocationStore.
@@ -231,11 +279,12 @@ describe('LocationManagerStore removeAgent', () => {
const store = new LocationManagerStore();
store.locations.set('loc', stubLocation);
- await store.removeAgent('loc', 'a', { deleteInSwitch: false });
+ await store.removeAgent('loc', 'a', { deleteInSwitch: false, removeProvisionedFiles: false });
expect(mocks.deleteAgent).toHaveBeenCalledWith({
agentId: 'a',
deleteInSwitch: false,
+ removeProvisionedFiles: false,
trigger: 'user',
});
expect(store.locations.has('loc')).toBe(true);
@@ -250,11 +299,12 @@ describe('LocationManagerStore removeAgent', () => {
const store = new LocationManagerStore();
store.locations.set('loc', stubLocation);
- await store.removeAgent('loc', 'a', { deleteInSwitch: true });
+ await store.removeAgent('loc', 'a', { deleteInSwitch: true, removeProvisionedFiles: false });
expect(mocks.deleteAgent).toHaveBeenCalledWith({
agentId: 'a',
deleteInSwitch: true,
+ removeProvisionedFiles: false,
trigger: 'user',
});
expect(store.locations.has('loc')).toBe(false);
@@ -269,9 +319,9 @@ describe('LocationManagerStore removeAgent', () => {
const store = new LocationManagerStore();
store.locations.set('loc', stubLocation);
- await expect(store.removeAgent('loc', 'a', { deleteInSwitch: true })).rejects.toThrow(
- 'gateway down'
- );
+ await expect(
+ store.removeAgent('loc', 'a', { deleteInSwitch: true, removeProvisionedFiles: false })
+ ).rejects.toThrow('gateway down');
expect(store.locations.has('loc')).toBe(true);
expect(agentsStore.byLocation.get('loc')?.map((x) => x.id)).toEqual(['a']);
});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/stores/location-manager.ts b/console/apps/switch-console-desktop/src/renderer/features/locations/stores/location-manager.ts
index 27de5a71f..906d2530a 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/stores/location-manager.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/stores/location-manager.ts
@@ -79,6 +79,13 @@ export class LocationManagerStore {
const locationIdsWithAgents = new Set(agents.map((a) => a.locationId));
const toMount: string[] = [];
runInAction(() => {
+ // Drop locations whose last agent was removed since the previous load,
+ // but skip any mid-onboarding placeholder — it has no DB agent yet.
+ for (const id of this.locations.keys()) {
+ if (!locationIdsWithAgents.has(id) && !this.pendingCreationIds.has(id)) {
+ this.locations.delete(id);
+ }
+ }
for (const loc of rawLocations) {
if (!locationIdsWithAgents.has(loc.id)) continue;
if (this.locations.has(loc.id)) continue;
@@ -297,6 +304,9 @@ export class LocationManagerStore {
rpc.agents.deleteAgent({
agentId: agent.id,
deleteInSwitch: false,
+ // Removing a location forgets it here; files on disk (possibly a
+ // shared host's) stay put.
+ removeProvisionedFiles: false,
trigger: 'user',
})
)
@@ -318,7 +328,7 @@ export class LocationManagerStore {
async removeAgent(
locationId: string,
agentId: string,
- options: { deleteInSwitch: boolean }
+ options: { deleteInSwitch: boolean; removeProvisionedFiles: boolean }
): Promise<void> {
// A directory is a flat container of independent agents (CHOO-1440), so
// deleting one must remove only that agent — its siblings, and the location
@@ -341,6 +351,7 @@ export class LocationManagerStore {
await rpc.agents.deleteAgent({
agentId,
deleteInSwitch: options.deleteInSwitch,
+ removeProvisionedFiles: options.removeProvisionedFiles,
trigger: 'user',
});
// Reconcile against the source of truth (also corrects the optimistic guess).
diff --git a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/load-existing-agents-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/load-existing-agents-section.tsx
new file mode 100644
index 000000000..5b2890e03
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/load-existing-agents-section.tsx
@@ -0,0 +1,607 @@
+/**
+ * "Load existing agents" section for a remote host's page (CHOO-2560).
+ *
+ * Shows agents already configured on the host — by a colleague's Console or
+ * an earlier install — that this Console does not yet manage. The user
+ * selects which to load (attach); agents that need a provider pick get one
+ * inline. Already-loaded agents appear disabled.
+ *
+ * Discovery runs on demand when the user clicks "Discover agents".
+ */
+
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
+import {
+ ChevronDown,
+ ChevronRight,
+ Download,
+ FolderSearch,
+ Info,
+ RefreshCw,
+ ScanSearch,
+ Trash2,
+ X,
+} from 'lucide-react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { failureText } from '@renderer/lib/errors/describe-failure';
+import { toast } from '@renderer/lib/hooks/use-toast';
+import { rpc } from '@renderer/lib/ipc';
+import { useShowModal } from '@renderer/lib/modal/modal-provider';
+import { Button } from '@renderer/lib/ui/button';
+import { Checkbox } from '@renderer/lib/ui/checkbox';
+import { Input } from '@renderer/lib/ui/input';
+import { Label } from '@renderer/lib/ui/label';
+import { Progress } from '@renderer/lib/ui/progress';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@renderer/lib/ui/select';
+import { Spinner } from '@renderer/lib/ui/spinner';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';
+import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';
+import { AGENT_PROVIDERS, getProvider } from '@shared/core/providers/agent-provider-registry';
+
+type LoadableAgentRow = {
+ name: string;
+ dir: string;
+ switchAgentId: string;
+ apiEndpoint: string;
+ providerId: AgentProviderId | null;
+ providerSource: string;
+ alreadyAgent: boolean;
+ ownerName: string | null;
+ viewerIsOwner: boolean;
+ description: string | null;
+ source: 'server' | 'scan';
+ endpointMismatch: boolean;
+ blockedReason: string | null;
+};
+
+export const LOAD_AGENTS_QUERY_KEY = 'load-existing-agents';
+
+export function LoadExistingAgentsSection({
+ sshHost,
+ serverId,
+ initiallyOpen = false,
+}: {
+ sshHost: string;
+ serverId: string;
+ initiallyOpen?: boolean;
+}) {
+ const [isOpen, setIsOpen] = useState(initiallyOpen);
+ const [scanRequested, setScanRequested] = useState(false);
+ const queryClient = useQueryClient();
+ const showRemoveConfig = useShowModal('removeAgentConfigModal');
+
+ const discovery = useQuery({
+ queryKey: [LOAD_AGENTS_QUERY_KEY, sshHost, serverId],
+ queryFn: () => rpc.agents.discoverLoadableAgentsOnHost({ sshHost, serverId }),
+ enabled: isOpen && scanRequested,
+ });
+
+ const [manualAgents, setManualAgents] = useState<LoadableAgentRow[]>([]);
+ // Server URL for endpoint-mismatch copy; either discovery source reports it.
+ const [manualServerApiUrl, setManualServerApiUrl] = useState<string | null>(null);
+ const serverApiUrl = discovery.data?.serverApiUrl ?? manualServerApiUrl;
+
+ const agents: LoadableAgentRow[] = useMemo(() => {
+ const auto = discovery.data?.agents ?? [];
+ if (manualAgents.length === 0) return auto;
+ const seen = new Set(auto.map((a) => `${a.dir}\0${a.name}`));
+ return [...auto, ...manualAgents.filter((a) => !seen.has(`${a.dir}\0${a.name}`))];
+ }, [discovery.data, manualAgents]);
+
+ const [providerOverrides, setProviderOverrides] = useState<Record<string, AgentProviderId>>({});
+
+ const setProviderFor = useCallback((key: string, providerId: AgentProviderId) => {
+ setProviderOverrides((prev) => ({ ...prev, [key]: providerId }));
+ }, []);
+
+ // Selection state: keys are "dir\0name".
+ const [selected, setSelected] = useState<Set<string>>(new Set());
+ const [expanded, setExpanded] = useState<Set<string>>(new Set());
+
+ const toggleAgent = useCallback((key: string) => {
+ setSelected((prev) => {
+ const next = new Set(prev);
+ if (next.has(key)) next.delete(key);
+ else next.add(key);
+ return next;
+ });
+ }, []);
+
+ const toggleExpanded = useCallback((key: string) => {
+ setExpanded((prev) => {
+ const next = new Set(prev);
+ if (next.has(key)) next.delete(key);
+ else next.add(key);
+ return next;
+ });
+ }, []);
+
+ const selectableAgents = useMemo(() => agents.filter((a) => !a.blockedReason), [agents]);
+
+ const toggleAll = useCallback(() => {
+ if (selected.size === selectableAgents.length) {
+ setSelected(new Set());
+ } else {
+ setSelected(new Set(selectableAgents.map((a) => `${a.dir}\0${a.name}`)));
+ }
+ }, [selectableAgents, selected.size]);
+
+ const selectedByDir = useMemo(() => {
+ const byDir = new Map<
+ string,
+ Array<{ name: string; providerId: AgentProviderId; ownerName?: string | null }>
+ >();
+ for (const key of selected) {
+ const agent = agents.find((a) => `${a.dir}\0${a.name}` === key);
+ if (!agent) continue;
+ const pid = providerOverrides[key] ?? agent.providerId;
+ if (!pid) continue;
+ if (!byDir.has(agent.dir)) byDir.set(agent.dir, []);
+ byDir.get(agent.dir)!.push({ name: agent.name, providerId: pid, ownerName: agent.ownerName });
+ }
+ return byDir;
+ }, [selected, agents, providerOverrides]);
+
+ const allSelectedHaveProvider = useMemo(() => {
+ for (const key of selected) {
+ const agent = agents.find((a) => `${a.dir}\0${a.name}` === key);
+ if (!agent) continue;
+ if (!agent.providerId && !providerOverrides[key]) return false;
+ }
+ return true;
+ }, [selected, agents, providerOverrides]);
+
+ const canLoad = selected.size > 0 && allSelectedHaveProvider;
+
+ const loadMutation = useMutation({
+ mutationFn: async () => {
+ const results: string[] = [];
+ for (const [dir, dirAgents] of selectedByDir) {
+ const result = await rpc.agents.attachConfiguredAgents({
+ sshHost,
+ dir,
+ serverId,
+ agents: dirAgents,
+ });
+ if (result.success) {
+ results.push(...result.data.map((a: { name: string }) => a.name));
+ } else {
+ const e = result.error;
+ const msg =
+ 'message' in e
+ ? e.message
+ : e.type === 'switch-agent-not-on-server'
+ ? `Agent ${e.agentId} not found on server ${e.serverName}`
+ : `Not signed in to server ${e.serverName}`;
+ throw new Error(msg);
+ }
+ }
+ return results;
+ },
+ onSuccess: async (names) => {
+ toast({
+ title: `Loaded ${names.length} agent${names.length === 1 ? '' : 's'}`,
+ description: names.join(', '),
+ });
+ setSelected(new Set());
+
+ // Mark loaded agents as blocked immediately so the label appears without
+ // waiting for the SSH round trip that a full refetch requires.
+ const loaded = new Set(names);
+ queryClient.setQueryData(
+ [LOAD_AGENTS_QUERY_KEY, sshHost, serverId],
+ (prev: { agents: LoadableAgentRow[]; serverApiUrl: string } | undefined) => {
+ if (!prev) return prev;
+ return {
+ ...prev,
+ agents: prev.agents.map((a) =>
+ loaded.has(a.name)
+ ? { ...a, alreadyAgent: true, blockedReason: 'Already loaded in this Console' }
+ : a
+ ),
+ };
+ }
+ );
+ // Also update manual agents so both lists stay consistent.
+ setManualAgents((prev) =>
+ prev.map((a) =>
+ loaded.has(a.name)
+ ? { ...a, alreadyAgent: true, blockedReason: 'Already loaded in this Console' }
+ : a
+ )
+ );
+
+ void queryClient.invalidateQueries({ queryKey: [LOAD_AGENTS_QUERY_KEY, sshHost, serverId] });
+ },
+ onError: (error) => {
+ toast({
+ title: 'Failed to load agents',
+ description: failureText(error, 'Could not load the selected agents.'),
+ variant: 'destructive',
+ });
+ },
+ });
+
+ const removeMutation = useMutation({
+ mutationFn: async (agent: LoadableAgentRow) => {
+ const result = await rpc.agents.removeLoadableAgentConfig({
+ sshHost,
+ dir: agent.dir,
+ name: agent.name,
+ });
+ if (!result.removed) throw new Error('Config file not found on the host.');
+ return agent;
+ },
+ onSuccess: (agent) => {
+ toast({ title: 'Config deleted', description: `${agent.name} removed from ${agent.dir}` });
+ const key = `${agent.dir}\0${agent.name}`;
+ setManualAgents((prev) => prev.filter((a) => `${a.dir}\0${a.name}` !== key));
+ setSelected((prev) => {
+ const next = new Set(prev);
+ next.delete(key);
+ return next;
+ });
+ void queryClient.invalidateQueries({ queryKey: [LOAD_AGENTS_QUERY_KEY, sshHost, serverId] });
+ },
+ onError: (error) => {
+ toast({
+ title: 'Failed to delete config',
+ description: failureText(error, 'Could not delete the config file.'),
+ variant: 'destructive',
+ });
+ },
+ });
+
+ const confirmRemove = useCallback(
+ (agent: LoadableAgentRow) => {
+ showRemoveConfig({
+ agentName: agent.name,
+ dir: agent.dir,
+ sshHost,
+ onSuccess: () => removeMutation.mutate(agent),
+ });
+ },
+ [showRemoveConfig, sshHost, removeMutation]
+ );
+
+ const [manualDir, setManualDir] = useState('');
+ const manualScan = useMutation({
+ mutationFn: (dir: string) => rpc.agents.discoverLoadableAgentsInDir({ sshHost, dir, serverId }),
+ onSuccess: (found) => {
+ setManualServerApiUrl(found.serverApiUrl);
+ setManualAgents((prev) => {
+ const keys = new Set(prev.map((a) => `${a.dir}\0${a.name}`));
+ return [
+ ...prev,
+ ...found.agents.filter((a: LoadableAgentRow) => !keys.has(`${a.dir}\0${a.name}`)),
+ ];
+ });
+ setManualDir('');
+ },
+ });
+
+ const deepScan = useMutation({
+ mutationFn: () =>
+ rpc.agents.discoverLoadableAgentsOnHost({ sshHost, serverId, includeHomeScan: true }),
+ onSuccess: (result) => {
+ queryClient.setQueryData([LOAD_AGENTS_QUERY_KEY, sshHost, serverId], result);
+ },
+ });
+
+ const [deepScanProgress, setDeepScanProgress] = useState(0);
+ const deepScanStartRef = useRef(0);
+ useEffect(() => {
+ if (!deepScan.isPending) {
+ setDeepScanProgress(0);
+ return;
+ }
+ deepScanStartRef.current = Date.now();
+ const ESTIMATED_DURATION = 30_000;
+ const id = setInterval(() => {
+ const elapsed = Date.now() - deepScanStartRef.current;
+ setDeepScanProgress(Math.min(100, (elapsed / ESTIMATED_DURATION) * 100));
+ }, 200);
+ return () => clearInterval(id);
+ }, [deepScan.isPending]);
+
+ const providerOptions = AGENT_PROVIDERS.filter((p) => p.detectable !== false);
+
+ return (
+ <section className="pt-2">
+ <button
+ type="button"
+ className="flex w-full items-center gap-1 px-3 py-2 text-left"
+ onClick={() =>
+ setIsOpen((prev) => {
+ if (prev) setScanRequested(false);
+ return !prev;
+ })
+ }
+ >
+ {isOpen ? <ChevronDown className="size-4" /> : <ChevronRight className="size-4" />}
+ <Label className="cursor-pointer">Load existing agents</Label>
+ </button>
+
+ {isOpen && (
+ <div className="space-y-3 px-3 pb-2">
+ {!scanRequested ? (
+ <div className="flex items-center gap-2">
+ <Button size="sm" variant="outline" onClick={() => setScanRequested(true)}>
+ <ScanSearch className="size-4" /> Discover agents
+ </Button>
+ <span className="text-xs text-foreground-muted">
+ Check this host for agents to load
+ </span>
+ </div>
+ ) : discovery.isLoading ? (
+ <div className="flex items-center gap-2 text-sm text-foreground-muted">
+ <Spinner /> Checking registered agents on this host…
+ </div>
+ ) : deepScan.isPending ? (
+ <div className="space-y-2">
+ <div className="flex items-center justify-between text-sm text-foreground-muted">
+ <span>Walking home directory on {sshHost}…</span>
+ <Button size="sm" variant="ghost" onClick={() => deepScan.reset()}>
+ <X className="size-3" /> Cancel
+ </Button>
+ </div>
+ <Progress value={deepScanProgress} />
+ </div>
+ ) : discovery.isError ? (
+ <p className="text-xs text-destructive">
+ {failureText(discovery.error, 'Could not scan the host.')}
+ </p>
+ ) : agents.length === 0 ? (
+ <div className="space-y-1">
+ <p className="text-sm text-foreground-muted">
+ No registered agents found in this host's known directories. Scan a specific
+ directory below.
+ </p>
+ <Tooltip>
+ <TooltipTrigger>
+ <Button size="sm" variant="outline" onClick={() => deepScan.mutate()}>
+ <ScanSearch className="size-4" /> Deep scan
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ Scans the full filesystem on this host. May take a while on large VMs.
+ </TooltipContent>
+ </Tooltip>
+ </div>
+ ) : (
+ <>
+ <div className="flex items-center justify-between">
+ {selectableAgents.length > 0 && (
+ <button
+ type="button"
+ className="text-xs text-foreground-muted hover:text-foreground"
+ onClick={toggleAll}
+ >
+ {selected.size > 0 && selected.size === selectableAgents.length
+ ? 'Deselect all'
+ : 'Select all'}
+ </button>
+ )}
+ <div className="flex items-center gap-1">
+ <Tooltip>
+ <TooltipTrigger>
+ <Button size="sm" variant="outline" onClick={() => deepScan.mutate()}>
+ <ScanSearch className="size-3" /> Deep scan
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ Scans the full filesystem on this host. May take a while on large VMs.
+ </TooltipContent>
+ </Tooltip>
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={discovery.isFetching}
+ onClick={() =>
+ void queryClient.invalidateQueries({
+ queryKey: [LOAD_AGENTS_QUERY_KEY, sshHost, serverId],
+ })
+ }
+ >
+ <RefreshCw className={`size-3 ${discovery.isFetching ? 'animate-spin' : ''}`} />
+ Rescan
+ </Button>
+ </div>
+ </div>
+
+ <div className="divide-y divide-border rounded-md border">
+ {agents.map((agent) => {
+ const key = `${agent.dir}\0${agent.name}`;
+ const blocked = !!agent.blockedReason;
+ const needsProvider = !agent.providerId && !providerOverrides[key];
+ const isSelected = selected.has(key);
+ const isExpanded = expanded.has(key);
+
+ return (
+ <div key={key}>
+ <div className="flex items-center gap-3 px-3 py-2">
+ <Checkbox
+ checked={isSelected}
+ disabled={blocked}
+ onCheckedChange={() => toggleAgent(key)}
+ />
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2">
+ <span className="truncate text-sm font-medium">{agent.name}</span>
+ {agent.blockedReason && (
+ <span className="shrink-0 text-xs text-destructive">
+ {agent.blockedReason}
+ </span>
+ )}
+ </div>
+ <div className="flex items-center gap-2 text-xs text-foreground-muted">
+ <span className="truncate">{agent.dir}</span>
+ {agent.ownerName && <span>· by {agent.ownerName}</span>}
+ {agent.providerId && (
+ <span>
+ · {getProvider(agent.providerId)?.name ?? agent.providerId}
+ </span>
+ )}
+ </div>
+ {agent.endpointMismatch ? (
+ <p className="text-xs text-foreground-muted">
+ Registered against <code>{agent.apiEndpoint}</code>
+ {serverApiUrl && (
+ <>
+ ; this server is <code>{serverApiUrl}</code>
+ </>
+ )}
+ </p>
+ ) : (
+ !blocked &&
+ agent.ownerName && (
+ <p className="text-xs text-foreground-muted">
+ Session access: yes · rooms: policy admits only its owner
+ {agent.viewerIsOwner
+ ? ' (you)'
+ : `, ask ${agent.ownerName} to widen`}
+ </p>
+ )
+ )}
+ </div>
+ {!blocked && needsProvider && (
+ <Select
+ value={providerOverrides[key] ?? ''}
+ onValueChange={(v) => setProviderFor(key, v as AgentProviderId)}
+ >
+ <SelectTrigger className="w-36">
+ <SelectValue placeholder="Provider" />
+ </SelectTrigger>
+ <SelectContent>
+ {providerOptions.map((p) => (
+ <SelectItem key={p.id} value={p.id}>
+ {p.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ )}
+ <Button
+ size="sm"
+ variant="ghost"
+ className="shrink-0 px-2 text-foreground-muted hover:text-foreground"
+ aria-label={`${isExpanded ? 'Hide' : 'Show'} details for ${agent.name}`}
+ onClick={() => toggleExpanded(key)}
+ >
+ <Info className="size-3.5" />
+ </Button>
+ <Button
+ size="sm"
+ variant="ghost"
+ className="shrink-0 px-2 text-foreground-muted hover:text-destructive"
+ aria-label={`Delete ${agent.name}'s config from this host`}
+ disabled={agent.alreadyAgent || removeMutation.isPending}
+ title={
+ agent.alreadyAgent
+ ? 'Loaded in this Console — remove it from the agent itself'
+ : 'Delete this config file from the host'
+ }
+ onClick={() => confirmRemove(agent)}
+ >
+ <Trash2 className="size-3.5" />
+ </Button>
+ </div>
+ {isExpanded && (
+ <div className="space-y-1 border-t border-dashed border-border px-3 py-2 pl-10 text-xs">
+ {agent.description && (
+ <p className="text-foreground">{agent.description}</p>
+ )}
+ <dl className="grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5 text-foreground-muted">
+ <dt>Agent ID</dt>
+ <dd className="truncate font-mono">{agent.switchAgentId}</dd>
+ <dt>Endpoint</dt>
+ <dd className="truncate font-mono">{agent.apiEndpoint}</dd>
+ <dt>Directory</dt>
+ <dd className="truncate font-mono">{agent.dir}</dd>
+ <dt>Provider</dt>
+ <dd>
+ {agent.providerId
+ ? `${getProvider(agent.providerId)?.name ?? agent.providerId} (${agent.providerSource})`
+ : 'unknown — pick one to load'}
+ </dd>
+ {agent.ownerName && (
+ <>
+ <dt>Owner</dt>
+ <dd>
+ {agent.ownerName}
+ {agent.viewerIsOwner ? ' (you)' : ''}
+ </dd>
+ </>
+ )}
+ <dt>Found via</dt>
+ <dd>
+ {agent.source === 'server' ? 'server registration' : 'host scan'}
+ </dd>
+ </dl>
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ </>
+ )}
+
+ {/* Manual directory scan fallback */}
+ <div className="flex items-center gap-2">
+ <FolderSearch className="size-4 shrink-0 text-foreground-muted" />
+ <Input
+ value={manualDir}
+ placeholder="Scan a directory (absolute path)"
+ className="flex-1"
+ onChange={(e) => setManualDir(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' && manualDir.trim()) manualScan.mutate(manualDir.trim());
+ }}
+ />
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={!manualDir.trim() || manualScan.isPending}
+ onClick={() => manualScan.mutate(manualDir.trim())}
+ >
+ {manualScan.isPending ? <Spinner /> : 'Scan'}
+ </Button>
+ </div>
+ {manualScan.isError && (
+ <p className="text-xs text-destructive">
+ {failureText(manualScan.error, 'Could not scan the directory.')}
+ </p>
+ )}
+
+ {/* Load button */}
+ {agents.length > 0 && (
+ <div className="flex justify-end">
+ <Button
+ size="sm"
+ disabled={!canLoad || loadMutation.isPending}
+ onClick={() => loadMutation.mutate()}
+ >
+ {loadMutation.isPending ? (
+ <>
+ <Spinner /> Loading…
+ </>
+ ) : (
+ <>
+ <Download className="size-4" /> Load {selected.size} agent
+ {selected.size === 1 ? '' : 's'}
+ </>
+ )}
+ </Button>
+ </div>
+ )}
+ </div>
+ )}
+ </section>
+ );
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/remove-agent-config-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/remove-agent-config-modal.tsx
new file mode 100644
index 000000000..95eea0b11
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/remove-agent-config-modal.tsx
@@ -0,0 +1,57 @@
+import type { BaseModalProps } from '@renderer/lib/modal/modal-provider';
+import { Button } from '@renderer/lib/ui/button';
+import { ConfirmButton } from '@renderer/lib/ui/confirm-button';
+import {
+ DialogContentArea,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@renderer/lib/ui/dialog';
+
+export type RemoveAgentConfigModalArgs = {
+ /** The agent's name (also the config file's stem). */
+ agentName: string;
+ /** The working directory holding the config, for the confirmation copy. */
+ dir: string;
+ /** The host the directory lives on. */
+ sshHost: string;
+};
+
+export type RemoveAgentConfigModalResult = { confirmed: true };
+
+type Props = BaseModalProps<RemoveAgentConfigModalResult> & RemoveAgentConfigModalArgs;
+
+/**
+ * Confirm deleting an agent's on-disk config from a remote host — the cleanup
+ * action in "Load existing agents" (CHOO-2560). Host-file-only by design: the
+ * server registration and other Consoles are untouched, and the copy says so.
+ */
+export function RemoveAgentConfigModal({ agentName, dir, sshHost, onSuccess, onClose }: Props) {
+ return (
+ <>
+ <DialogHeader showCloseButton={false}>
+ <DialogTitle>Delete agent config from host</DialogTitle>
+ </DialogHeader>
+ <DialogContentArea className="flex flex-col gap-3 pt-0">
+ <p className="text-sm text-foreground-muted">
+ This deletes <span className="font-medium text-foreground">{agentName}</span>
+ {"'"}s config file (<code>.switch/agents/{agentName}.json</code>) in{' '}
+ <code className="break-all">{dir}</code> on{' '}
+ <span className="font-medium text-foreground">{sshHost}</span>.
+ </p>
+ <p className="text-xs text-foreground-muted">
+ The agent{"'"}s registration on the Switch server is not affected, and neither is any
+ Console already running it. The file{"'"}s API token cannot be recovered.
+ </p>
+ </DialogContentArea>
+ <DialogFooter>
+ <Button variant="outline" onClick={onClose}>
+ Cancel
+ </Button>
+ <ConfirmButton variant="destructive" onClick={() => onSuccess({ confirmed: true })}>
+ Delete config
+ </ConfirmButton>
+ </DialogFooter>
+ </>
+ );
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-host-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-host-view.tsx
index e4feda9b2..b8b34f509 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-host-view.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-host-view.tsx
@@ -31,9 +31,11 @@ import { Spinner } from '@renderer/lib/ui/spinner';
import { StatusBadge } from '@renderer/lib/ui/status-badge';
import { deriveHostStatus } from '@shared/core/remote-hosts/host-status';
import { isHostBlocked } from '@shared/core/remote-hosts/reachability';
+import { switchServersStore } from '../../switch-servers/switch-servers-store';
import { hostReachabilityStore } from '../host-reachability-store';
import { hostSetupStore } from '../host-setup-store';
import { HostUnreachablePanel } from '../host-unreachable-panel';
+import { LoadExistingAgentsSection } from '../load-existing-agents-section';
import { SetupDetailSheet, type SheetTarget } from '../setup/setup-detail-sheet';
import {
AgentTypeRowItem,
@@ -51,7 +53,7 @@ import {
useSkipSetupStep,
useUpdateSetupStep,
} from '../setup/use-host-setup';
-import { REMOTE_HOSTS_QUERY_KEY } from './remote-hosts-view';
+import { consumeJustAddedHost, REMOTE_HOSTS_QUERY_KEY } from './remote-hosts-view';
function useSshHost(): string {
return useParams('remoteHost').params.sshHost;
@@ -59,6 +61,7 @@ function useSshHost(): string {
export const RemoteHostMainPanel = observer(function RemoteHostMainPanel() {
const sshHost = useSshHost();
+ const [justAdded] = useState(() => consumeJustAddedHost(sshHost));
const { navigate } = useNavigate();
const hosts = useQuery({
@@ -100,6 +103,17 @@ export const RemoteHostMainPanel = observer(function RemoteHostMainPanel() {
startPrepare();
}, [blocked, plan.isLoading, startPrepare]);
+ // Resolve the Switch server for this host: prefer a managed server on this
+ // host, then the active server, then the first available. Read the
+ // observables outside useMemo so MobX tracks them and React sees them change.
+ const servers = switchServersStore.servers;
+ const activeServer = switchServersStore.activeServer;
+ const serverId = useMemo(() => {
+ const managed = servers.find((s) => s.sshHost === sshHost && s.managed);
+ if (managed) return managed.id;
+ return activeServer?.id ?? servers[0]?.id ?? null;
+ }, [sshHost, servers, activeServer]);
+
const status = deriveHostStatus(reachability, plan.data ?? null);
const { prerequisites, agentTypes } = useMemo(
() => groupPlanSteps(plan.data ?? null),
@@ -265,6 +279,14 @@ export const RemoteHostMainPanel = observer(function RemoteHostMainPanel() {
))}
</section>
)}
+
+ {serverId && (
+ <LoadExistingAgentsSection
+ sshHost={sshHost}
+ serverId={serverId}
+ initiallyOpen={justAdded}
+ />
+ )}
</div>
)}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-hosts-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-hosts-view.tsx
index dd3783789..95760bd76 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-hosts-view.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-hosts-view.tsx
@@ -35,6 +35,22 @@ import { useAllHostSetupPlans } from '../setup/use-host-setup';
export const REMOTE_HOSTS_QUERY_KEY = ['remote-hosts'];
+/**
+ * Volatile flag: the SSH host alias just added by the Add Host modal, consumed
+ * once by `remote-host-view.tsx` to auto-expand the Load Existing Agents
+ * section on the post-add-host page visit.
+ */
+export let justAddedHost: string | null = null;
+
+/** Consume the flag — returns the value and clears it. */
+export function consumeJustAddedHost(sshHost: string): boolean {
+ if (justAddedHost === sshHost) {
+ justAddedHost = null;
+ return true;
+ }
+ return false;
+}
+
type HostFilter = 'all' | 'ready' | 'attention';
type RemoteHost = { sshHost: string; name: string };
@@ -201,7 +217,8 @@ export const RemoteHostsSettingsPage = observer(function RemoteHostsSettingsPage
onboarded: sshHosts,
onAdded: (sshHost) => {
invalidate();
- openHost(sshHost);
+ justAddedHost = sshHost;
+ navigate('remoteHost', { sshHost });
},
})
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-agents-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-agents-view.tsx
index d8cd684d2..093dde3a5 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-agents-view.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-agents-view.tsx
@@ -123,6 +123,11 @@ const AgentCard = observer(function AgentCard({
{provider ? `${provider} · ` : ''}
{sshHost ?? 'this computer'}
</div>
+ {agent.ownerName && (
+ <div className="truncate text-xs text-foreground-tertiary-passive">
+ loaded · by {agent.ownerName}
+ </div>
+ )}
</div>
</div>
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/palette-agent-icon.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/palette-agent-icon.test.tsx
index 7bd3b8a25..59b5e5d75 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/palette-agent-icon.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/palette-agent-icon.test.tsx
@@ -36,6 +36,7 @@ const AGENT: Agent = {
serverId: SERVER_ID,
status: null,
autoApprove: false,
+ ownerName: null,
providerConfig: null,
createdAt: '2026-01-01T00:00:00.000Z',
updatedAt: '2026-01-01T00:00:00.000Z',
@@ -61,6 +62,7 @@ function remoteAgent(iconUrl: string | null): RemoteAgentSummary {
ownerId: null,
ownerName: null,
knownAgentType: 'claude-code',
+ knownAgentOptions: null,
addressingPolicy: null,
iconUrl,
createdAt: '2026-01-01T00:00:00.000Z',
diff --git a/console/apps/switch-console-desktop/src/shared/core/agents/agents.ts b/console/apps/switch-console-desktop/src/shared/core/agents/agents.ts
index 649a68c2e..58d073034 100644
--- a/console/apps/switch-console-desktop/src/shared/core/agents/agents.ts
+++ b/console/apps/switch-console-desktop/src/shared/core/agents/agents.ts
@@ -26,6 +26,9 @@ export type Agent = {
* "bypass permissions" flag. Defaults false for local agents and true for
* remote agents (seeded at onboarding); editable per agent. */
autoApprove: boolean;
+ /** The agent's owner on the Switch server, set when the agent was loaded from
+ * another install. Null for agents this Console created. */
+ ownerName: string | null;
/** Per-agent, provider-specific launch config (e.g. Codex model / effort /
* instructions). Null when unset. */
providerConfig: AgentProviderConfig | null;
@@ -47,6 +50,8 @@ export type CreateAgentParams = {
/** Seed for the per-agent bypass-permissions flag: false for local agents,
* true for remote agents. */
autoApprove: boolean;
+ /** The agent's owner on the Switch server, when loaded from another install. */
+ ownerName?: string | null;
/** Optional per-agent provider config set at creation. */
providerConfig?: AgentProviderConfig | null;
};
diff --git a/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts
index bd7840f5e..5ac0427ad 100644
--- a/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts
+++ b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts
@@ -184,6 +184,10 @@ export type RemoteAgentSummary = {
ownerId: string | null;
ownerName: string | null;
knownAgentType: string | null;
+ /** The agent's known-agent options, including `repo_dir` when the server
+ * recorded one. Null for agents registered before the field existed or when
+ * the server omits it. */
+ knownAgentOptions: Record<string, unknown> | null;
/** Who may address the agent, or null when it is open to everyone. On the
* summary as well as the detail, so "which of these agents answers only its
* owner" is one list read rather than a read per agent. Null also for a
@@ -713,6 +717,10 @@ export type ProvisionAgentResult =
* the Switch deployment at `endpoint` — another install's agent. Refused
* before minting, so nothing was created. */
| { kind: 'credentials-conflict'; endpoint: string }
+ /** The working directory already holds credentials for this name on the SAME
+ * server, but the agent is unknown to this install — a colleague's agent.
+ * Refused before minting to avoid destroying their token (CHOO-2560). */
+ | { kind: 'already-configured' }
| RegisterIdentityFailure;
/**
diff --git a/console/apps/switch-console-desktop/src/shared/events/appEvents.ts b/console/apps/switch-console-desktop/src/shared/events/appEvents.ts
index cae27d74f..de74bcc79 100644
--- a/console/apps/switch-console-desktop/src/shared/events/appEvents.ts
+++ b/console/apps/switch-console-desktop/src/shared/events/appEvents.ts
@@ -18,6 +18,17 @@ export const externalLinkOpenRequestedChannel = defineEvent<{ url: string }>(
'external-link:open-requested'
);
+/**
+ * An agent row was created, updated or deleted in the main process
+ * (main → renderer). Bridges the main-only `agentEvents` bus so renderer
+ * stores and queries can react to agent CRUD from any path — Add Agent,
+ * Load existing agents, Remove agent — without each call site having to
+ * remember a manual refetch (CHOO-2560).
+ */
+export const agentsChangedChannel = defineEvent<{ kind: 'created' | 'updated' | 'deleted' }>(
+ 'agents:changed'
+);
+
/**
* A mouse back/forward button pressed on Windows, where those buttons arrive as
* an `app-command` on the window rather than as a mouse event in the page.
diff --git a/console/docs/screenshots/load-existing-agents-expanded.png b/console/docs/screenshots/load-existing-agents-expanded.png
new file mode 100644
index 000000000..38753cfcf
Binary files /dev/null and b/console/docs/screenshots/load-existing-agents-expanded.png differ