Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
feat(switchdash): discover and onboard already-configured agents on a shared remote host (CHOO-1937) (#130)
Christian McDermottc9e083483dc9
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.test.tsindex b794aed8a..27779ebb2 100644--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.test.ts@@ -182,7 +182,10 @@ describe('RemoteSidecarLauncher', () => {// it mid-transfer dies on a SyntaxError.expect(puts).toHaveLength(1);expect(puts[0]!.local).toBe('/local/dist-sidecar/sidecar.mjs');- expect(puts[0]!.remote).toMatch(/^\.switchdash\/sidecar\.mjs\.\d+\.tmp$/);+ // A uuid, not a pid: the bundle is shared per directory while the deploy+ // lock is per agent, so two clients on different machines can upload+ // concurrently and a pid is not unique across them.+ expect(puts[0]!.remote).toMatch(/^\.switchdash\/sidecar\.mjs\.[0-9a-f-]{36}\.tmp$/);const rename = calls.find((c) => c.command === 'sh' && isBundleRename(c.args[1] ?? ''));expect(rename!.args[1]).toContain(`mv '${puts[0]!.remote}' '.switchdash/sidecar.mjs'`);const specWrite = calls.find((c) => c.command === 'sh' && isLaunchSpecWrite(c.args[1] ?? ''));diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.tsindex e03a16a7b..a9303b796 100644--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.ts@@ -1,4 +1,4 @@-import { createHash } from 'node:crypto';+import { createHash, randomUUID } from 'node:crypto';import { readFile } from 'node:fs/promises';import { exactTmuxTarget } from '@main/core/pty/tmux-session-name';import { quoteShellArg } from '@main/utils/shellEscape';@@ -15,8 +15,10 @@ import {sidecarWatchEnabledRelPath,} from '../../../../sidecar/sidecar-paths';import {+ compareSidecarVersions,MIN_SUPPORTED_SIDECAR_MAJOR,SIDECAR_CLIENT_MAJOR,+ SIDECAR_VERSION,sidecarMajor,} from '../../../../sidecar/sidecar-version';@@ -366,14 +368,33 @@ export class RemoteSidecarLauncher {* to load is observably half-written. A concurrent start would fail on a* SyntaxError. Renaming is atomic, so a reader sees the old bundle or the new* one.+ *+ * The temp name must be unique across *machines*, not just within one: the+ * deploy lock is per-agent while the bundle is shared per directory, so two+ * clients deploying for different agents in one directory hold different locks+ * and upload concurrently. A pid alone collides across hosts, and two streams+ * into one temp file rename a torn bundle into place (CHOO-1937).*/private async uploadBundle(): Promise<void> {- const tmpRel = `${SIDECAR_BUNDLE_REL_PATH}.${process.pid}.tmp`;- await this.host.putFile(this.bundlePath, tmpRel);- await this.host.exec('sh', [- '-c',- `mv ${quoteShellArg(tmpRel)} ${quoteShellArg(SIDECAR_BUNDLE_REL_PATH)}`,- ]);+ const tmpRel = `${SIDECAR_BUNDLE_REL_PATH}.${randomUUID()}.tmp`;+ try {+ await this.host.putFile(this.bundlePath, tmpRel);+ await this.host.exec('sh', [+ '-c',+ `mv ${quoteShellArg(tmpRel)} ${quoteShellArg(SIDECAR_BUNDLE_REL_PATH)}`,+ ]);+ } catch (error) {+ // A unique name is never reused, so a failed attempt can no longer be+ // cleaned up by the next one overwriting it. Remove it here instead of+ // accumulating fragments in a directory other clients deploy into too.+ await this.host.exec('sh', ['-c', `rm -f ${quoteShellArg(tmpRel)}`]).catch((cause: unknown) =>+ this.log.debug('RemoteSidecarLauncher: could not remove a failed bundle upload', {+ tmpRel,+ error: String(cause),+ })+ );+ throw error;+ }}/** Epoch of the sidecar currently running, or null if none/unreadable. */@@ -545,6 +566,8 @@ export class RemoteSidecarLauncher {* reserved for the cases that need it:* - incompatible protocol → must replace; we cannot talk to it at all.* - same build → reattach; there is nothing to gain.+ * - newer version → reattach; a newer switchdash deployed it, and replacing+ * it would be a downgrade.* - different build, no live sessions → upgrade, since nothing is disturbed.* - different build, live sessions → reattach and record that an upgrade is* pending, rather than interrupting work in flight for a build difference.@@ -564,6 +587,21 @@ export class RemoteSidecarLauncher {}if (ready.hash === localHash) return this.toEndpoint(ready);+ // A hash difference alone does not say which build is newer. On a host two+ // switchdash installs share, replacing on difference alone means each sees+ // the other's sidecar as an upgrade and they trade it back and forth+ // indefinitely. Ordering by version breaks the symmetry: only the newer+ // client replaces, and the older one settles for what is already there+ // (CHOO-1937).+ if (compareSidecarVersions(ready.version, SIDECAR_VERSION) > 0) {+ this.log.debug('RemoteSidecarLauncher: host runs a newer sidecar — leaving it in place', {+ sidecarTmuxName: this.sidecarTmuxName,+ runningVersion: ready.version,+ clientVersion: SIDECAR_VERSION,+ });+ return this.toEndpoint(ready);+ }+const liveSessions = await this.runningSessionCount();if (liveSessions > 0) {this.log.warn(diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/attach-configured-agents.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/attach-configured-agents.test.tsnew file mode 100644index 000000000..d244d7a20--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agents/attach-configured-agents.test.ts@@ -0,0 +1,200 @@+import type { PluginFs } from '@switchdash/core/agents/plugins';+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * A {@link PluginFs} that fails any write. Attaching adopts another install's+ * directory, so every write is a bug — this turns "should not write" into a+ * test failure at the point of the write rather than an assertion after it.+ */+function readOnlyFs(seed: Record<string, string>): PluginFs {+ const files = new Map<string, string>(Object.entries(seed));+ return {+ read: (p) => Promise.resolve(files.get(p) ?? null),+ write: (p) => Promise.reject(new Error(`attach wrote to the workspace: ${p}`)),+ delete: (p) => Promise.reject(new Error(`attach deleted from the workspace: ${p}`)),+ exists: (p) => Promise.resolve(files.has(p)),+ list: (dir) => {+ const prefix = `${dir}/`;+ const entries = new Set<string>();+ for (const p of files.keys()) {+ if (!p.startsWith(prefix)) continue;+ const rest = p.slice(prefix.length);+ const slash = rest.indexOf('/');+ entries.add(slash === -1 ? rest : rest.slice(0, slash));+ }+ return Promise.resolve([...entries]);+ },+ };+}++function creds(agentId: string, endpoint = 'https://switch.example.com') {+ return JSON.stringify({+ env: {+ SWITCH_API_ENDPOINT: endpoint,+ SWITCH_API_TOKEN: 'tok-secret',+ SWITCH_AGENT_ID: agentId,+ },+ });+}++const h = vi.hoisted(() => {+ class GatewayError extends Error {+ constructor(readonly kind: string) {+ super(kind);+ }+ }+ const state: {+ workspace: PluginFs | null;+ agentNames: string[];+ existsOnServer: boolean;+ existsThrows: Error | null;+ } = { workspace: null, agentNames: [], existsOnServer: true, existsThrows: null };+ return {+ state,+ GatewayError,+ warn: vi.fn(),+ createAgent: vi.fn(async (input: Record<string, unknown>) => ({ ...input })),+ agentExistsOnServer: vi.fn(async () => {+ if (h.state.existsThrows) throw h.state.existsThrows;+ return h.state.existsOnServer;+ }),+ openLocation: vi.fn(async () => {}),+ emit: vi.fn(),+ };+});++vi.mock('@main/core/locations/store', () => ({+ getLocationByHostDir: vi.fn(async () => ({ id: 'loc-1' })),+ ensureLocation: vi.fn(async () => ({ id: 'loc-1' })),+}));+vi.mock('./getAgents', () => ({+ getAgents: vi.fn(async () => h.state.agentNames.map((name) => ({ name }))),+}));+vi.mock('./agent-workspace-fs', () => ({+ resolveWorkspaceFsFor: vi.fn(async () => ({+ fs: h.state.workspace as PluginFs,+ homeFs: null,+ close: vi.fn(),+ })),+}));+vi.mock('@main/core/providers/plugin-registry', () => ({+ listPlugins: () => [{ metadata: { id: 'codex' }, behavior: {} }],+}));+vi.mock('@main/core/switch-servers/gateway-client', () => ({+ agentExistsOnServer: h.agentExistsOnServer,+ GatewayError: h.GatewayError,+}));+vi.mock('@main/core/switch-servers/servers-store', () => ({+ getServer: vi.fn(async () => ({+ id: 'srv-1',+ name: 'Switch',+ apiUrl: 'https://switch.example.com',+ })),+}));+vi.mock('./createAgent', () => ({ createAgent: h.createAgent }));+vi.mock('@main/core/locations/path-utils', () => ({ checkIsValidDirectory: () => true }));+vi.mock('@main/core/locations/location-manager', () => ({+ locationManager: { openLocation: h.openLocation },+}));+vi.mock('./setAgentAutoSession', () => ({+ reconcileAgentAutoSessionFromGateway: vi.fn(async () => {}),+}));+vi.mock('./agent-events', () => ({ agentEvents: { _emit: h.emit } }));+vi.mock('@main/lib/logger', () => ({ log: { info: vi.fn(), warn: h.warn, error: vi.fn() } }));++const { attachConfiguredAgents } = await import('./attach-configured-agents');++function params(agents: Array<{ name: string; providerId: 'codex' | 'claude' }>) {+ return { sshHost: 'vm-1', dir: '/repo', serverId: 'srv-1', agents };+}++describe('attachConfiguredAgents', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ h.state.agentNames = [];+ h.state.existsOnServer = true;+ h.state.existsThrows = null;+ h.state.workspace = readOnlyFs({ '.switch/agents/theirs.json': creds('sw-theirs') });+ });++ it('adopts the existing Switch identity instead of minting a new one', async () => {+ const result = await attachConfiguredAgents(params([{ name: 'theirs', providerId: 'codex' }]));++ expect(result.success).toBe(true);+ expect(h.createAgent).toHaveBeenCalledWith(+ expect.objectContaining({+ name: 'theirs',+ providerId: 'codex',+ switchAgentId: 'sw-theirs',+ apiEndpoint: 'https://switch.example.com',+ locationId: 'loc-1',+ })+ );+ });++ it('writes nothing to the working directory', async () => {+ // The workspace belongs to whichever install set the agent up. Any write+ // here rejects, so this passing means attach touched none of their state.+ await expect(+ attachConfiguredAgents(params([{ name: 'theirs', providerId: 'codex' }]))+ ).resolves.toMatchObject({ success: true });+ });++ it('fails loudly when the identity no longer exists on the server', async () => {+ // Minting a replacement here would create exactly the duplicate agent this+ // feature exists to avoid.+ h.state.existsOnServer = false;++ const result = await attachConfiguredAgents(params([{ name: 'theirs', providerId: 'codex' }]));++ expect(result).toMatchObject({+ success: false,+ error: { type: 'switch-agent-not-on-server', agentId: 'sw-theirs' },+ });+ expect(h.createAgent).not.toHaveBeenCalled();+ });++ it('reports an unauthenticated server rather than throwing', async () => {+ h.state.existsThrows = new h.GatewayError('unauthorized');++ expect(+ await attachConfiguredAgents(params([{ name: 'theirs', providerId: 'codex' }]))+ ).toMatchObject({ success: false, error: { type: 'switch-server-unauthenticated' } });+ expect(h.createAgent).not.toHaveBeenCalled();+ });++ it('refuses a name that is no longer configured in the directory', async () => {+ const result = await attachConfiguredAgents(params([{ name: 'ghost', providerId: 'codex' }]));++ expect(result.success).toBe(false);+ expect(h.createAgent).not.toHaveBeenCalled();+ });++ it('skips an agent this switchdash already has', async () => {+ h.state.agentNames = ['theirs'];++ const result = await attachConfiguredAgents(params([{ name: 'theirs', providerId: 'codex' }]));++ expect(result.success).toBe(false);+ expect(h.createAgent).not.toHaveBeenCalled();+ });++ it('keeps the directory endpoint and warns when it differs from the chosen server', async () => {+ // One Switch server can be reachable at two URLs. The launch path reads the+ // endpoint from the same file as the token, so the directory's value is what+ // the session will really use — surfaced, never corrected.+ h.state.workspace = readOnlyFs({+ '.switch/agents/theirs.json': creds('sw-theirs', 'https://switch.internal:8443'),+ });++ await attachConfiguredAgents(params([{ name: 'theirs', providerId: 'codex' }]));++ expect(h.createAgent).toHaveBeenCalledWith(+ expect.objectContaining({ apiEndpoint: 'https://switch.internal:8443' })+ );+ expect(h.warn).toHaveBeenCalledWith(+ expect.stringContaining('endpoint differs'),+ expect.anything()+ );+ });+});diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/attach-configured-agents.ts b/dash/apps/switchdash-desktop/src/main/core/agents/attach-configured-agents.tsnew file mode 100644index 000000000..eb4eddcea--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agents/attach-configured-agents.ts@@ -0,0 +1,177 @@+import { randomUUID } from 'node:crypto';+import { err, ok } from '@switchdash/shared';+import type { Result } from '@switchdash/shared';+import { locationManager } from '@main/core/locations/location-manager';+import { checkIsValidDirectory } from '@main/core/locations/path-utils';+import { ensureLocation } from '@main/core/locations/store';+import { agentExistsOnServer, GatewayError } from '@main/core/switch-servers/gateway-client';+import { getServer } from '@main/core/switch-servers/servers-store';+import { log } from '@main/lib/logger';+import type { Agent } from '@shared/core/agents/agents';+import type { OnboardAgentError } from '@shared/core/agents/onboarding';+import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';+import { basenameFromAnyPath } from '@shared/path-name';+import { agentEvents } from './agent-events';+import { createAgent } from './createAgent';+import { discoverConfiguredAgents } from './discover-configured-agents';+import { reconcileAgentAutoSessionFromGateway } from './setAgentAutoSession';++export type AttachConfiguredAgentsParams = {+ sshHost: string | null;+ dir: string;+ locationName?: string;+ /** The registered Switch server the discovered identities are verified against. */+ serverId: string;+ /**+ * The agents to attach. `providerId` is supplied by the caller rather than+ * 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 }>;+};++export type AttachConfiguredAgentsResult = Result<Agent[], OnboardAgentError>;++/** Compare endpoints ignoring a trailing slash, which is not a difference. */+function sameEndpoint(a: string, b: string): boolean {+ return a.replace(/\/+$/, '') === b.replace(/\/+$/, '');+}++/**+ * Adopt agents already configured in a working directory into this switchdash,+ * under the Switch identity they already have (CHOO-1937).+ *+ * This is the second half of shared-host onboarding: another install (or another+ * person) set the agent up here, and this one attaches to it rather than+ * creating a duplicate. The identity is read back from disk at attach time+ * rather than trusted from the caller, so a stale scan cannot mint a row+ * pointing at the wrong agent.+ *+ * **Writes nothing to the working directory.** No credentials, no definition, no+ * provider config — the directory is another install's state and this operation+ * treats it as read-only. That is possible because the API token is never needed+ * here: it stays where it already is, and the launch path reads it from disk when+ * a session spawns. This module deliberately imports no workspace writer, so the+ * guarantee is structural rather than a matter of care.+ *+ * An identity that no longer exists on the chosen server fails the attach loudly+ * instead of falling back to minting a fresh one — a silent mint is exactly the+ * duplicate this feature exists to prevent.+ */+export async function attachConfiguredAgents(+ params: AttachConfiguredAgentsParams+): Promise<AttachConfiguredAgentsResult> {+ if (params.sshHost === null && !checkIsValidDirectory(params.dir)) {+ return err({ type: 'invalid-directory', dir: params.dir, message: 'Invalid directory' });+ }+ if (params.agents.length === 0) {+ return err({+ type: 'invalid-directory',+ dir: params.dir,+ message: 'No agents selected to attach.',+ });+ }++ const server = await getServer(params.serverId);+ if (!server) throw new Error(`No Switch server with id ${params.serverId}`);++ const discovered = new Map(+ (await discoverConfiguredAgents({ sshHost: params.sshHost, dir: params.dir })).map((d) => [+ d.name,+ d,+ ])+ );++ const selected: Array<{ name: string; providerId: AgentProviderId }> = [];+ for (const requested of params.agents) {+ const found = discovered.get(requested.name);+ if (!found) {+ return err({+ type: 'invalid-directory',+ dir: params.dir,+ message: `No configured agent named "${requested.name}" in this directory. It may have been removed since the directory was scanned.`,+ });+ }+ // Already attached here — the scan marks these, so re-selecting one is a+ // stale-UI artefact rather than an error worth failing the whole batch for.+ if (!found.alreadyAgent) selected.push(requested);+ }+ if (selected.length === 0) {+ return err({+ type: 'invalid-directory',+ dir: params.dir,+ message: 'Every selected agent is already attached here.',+ });+ }++ const location = await ensureLocation({+ sshHost: params.sshHost,+ dir: params.dir,+ name: params.locationName ?? basenameFromAnyPath(params.dir) ?? params.dir,+ });++ const created: Agent[] = [];+ for (const { name, providerId } of selected) {+ const found = discovered.get(name);+ if (!found) continue;++ try {+ if (!(await agentExistsOnServer(server, found.switchAgentId))) {+ return err({+ type: 'switch-agent-not-on-server',+ dir: params.dir,+ serverId: server.id,+ serverName: server.name,+ agentId: found.switchAgentId,+ });+ }+ } catch (cause) {+ if (cause instanceof GatewayError && cause.kind === 'unauthorized') {+ return err({+ type: 'switch-server-unauthenticated',+ dir: params.dir,+ serverId: server.id,+ serverName: server.name,+ });+ }+ throw cause;+ }++ // The directory's endpoint wins over the chosen server's URL: it is what the+ // launch path will actually hand the session, since the token and endpoint+ // are read from the same on-disk file. A difference is legitimate (one Switch+ // server reachable at two URLs) so it is surfaced, not corrected — correcting+ // it would mean writing to another install's credentials.+ if (!sameEndpoint(found.apiEndpoint, server.apiUrl)) {+ log.warn('attachConfiguredAgents: directory endpoint differs from the chosen server', {+ name,+ dirEndpoint: found.apiEndpoint,+ serverEndpoint: server.apiUrl,+ serverId: server.id,+ });+ }++ const agent = await createAgent({+ id: randomUUID(),+ locationId: location.id,+ name,+ providerId,+ switchAgentId: found.switchAgentId,+ apiEndpoint: found.apiEndpoint,+ serverId: params.serverId,+ autoApprove: params.sshHost !== null,+ });+ created.push(agent);++ await reconcileAgentAutoSessionFromGateway(agent.id).catch((error) => {+ log.warn('attachConfiguredAgents: failed to reconcile auto_session', {+ agentId: agent.id,+ error: String(error),+ });+ });+ }++ await locationManager.openLocation(location);+ for (const agent of created) agentEvents._emit('agent:created', agent);+ return ok(created);+}diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/controller.ts b/dash/apps/switchdash-desktop/src/main/core/agents/controller.tsindex fc4c53cdc..1c2c6e858 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/controller.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/controller.ts@@ -7,9 +7,14 @@ import { createRPCController } from '@shared/lib/ipc/rpc';import { addAgent, type AddAgentParams } from './add-agent';import { readAgentDefinition, updateAgentDefinition } from './agent-definition';import { assignAgentServer } from './assignAgentServer';+import {+ attachConfiguredAgents,+ type AttachConfiguredAgentsParams,+} from './attach-configured-agents';import { createAgent } from './createAgent';import { getAgentDefinitionFields } from './definition-fields';import { deleteAgent, type DeleteAgentOptions } from './deleteAgent';+import { discoverConfiguredAgents } from './discover-configured-agents';import { discoverLocationAgents } from './discover-location-agents';import { getAgentById } from './getAgentById';import { getAgents } from './getAgents';@@ -40,6 +45,9 @@ export const agentsController = createRPCController({dir: string;providerId: AgentProviderId;}) => discoverLocationAgents(params),+ discoverConfiguredAgents: (params: { sshHost: string | null; dir: string }) =>+ discoverConfiguredAgents(params),+ attachConfiguredAgents: (params: AttachConfiguredAgentsParams) => attachConfiguredAgents(params),getAgents: (locationId?: string) => getAgents(locationId),getAgentById: (agentId: string) => getAgentById(agentId),renameAgent: (params: RenameAgentParams) => renameAgent(params),diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/discover-configured-agents.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/discover-configured-agents.test.tsnew file mode 100644index 000000000..1c85cc7f5--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agents/discover-configured-agents.test.ts@@ -0,0 +1,201 @@+import type { PluginFs } from '@switchdash/core/agents/plugins';+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * In-memory {@link PluginFs} with the real `list` semantics discovery depends on:+ * basenames of one directory's entries, and `[]` for a directory that does not+ * exist (never a throw).+ */+function fakeFs(seed: Record<string, string> = {}): PluginFs {+ const files = new Map<string, string>(Object.entries(seed));+ return {+ read: (p) => Promise.resolve(files.get(p) ?? null),+ write: (p, c) => {+ files.set(p, c);+ return Promise.resolve();+ },+ delete: (p) => {+ files.delete(p);+ return Promise.resolve();+ },+ exists: (p) => Promise.resolve(files.has(p)),+ list: (dir) => {+ const prefix = `${dir}/`;+ const entries = new Set<string>();+ for (const p of files.keys()) {+ if (!p.startsWith(prefix)) continue;+ const rest = p.slice(prefix.length);+ const slash = rest.indexOf('/');+ entries.add(slash === -1 ? rest : rest.slice(0, slash));+ }+ return Promise.resolve([...entries]);+ },+ };+}++function creds(agentId: string, endpoint = 'https://switch.example.com', token = 'tok-secret') {+ return `${JSON.stringify({+ permissions: { allow: ['mcp__plugin_switch-connector_switch'] },+ env: {+ SWITCH_API_ENDPOINT: endpoint,+ SWITCH_API_TOKEN: token,+ SWITCH_AGENT_ID: agentId,+ },+ })}\n`;+}++function launchSpec(providerId: string) {+ return JSON.stringify({ command: 'codex', args: [], env: {}, cwd: '/repo', providerId });+}++const h = vi.hoisted(() => {+ const state: {+ workspace: PluginFs | null;+ location: { id: string } | undefined;+ agentNames: string[];+ claudeDefinitions: Array<{ name: string; description: string | null }>;+ } = { workspace: null, location: { id: 'loc-1' }, agentNames: [], claudeDefinitions: [] };+ return { state, warn: vi.fn() };+});++vi.mock('@main/core/locations/store', () => ({+ getLocationByHostDir: vi.fn(async () => h.state.location),+}));+vi.mock('./getAgents', () => ({+ getAgents: vi.fn(async () => h.state.agentNames.map((name) => ({ name }))),+}));+vi.mock('./agent-workspace-fs', () => ({+ resolveWorkspaceFsFor: vi.fn(async () => ({+ fs: h.state.workspace as PluginFs,+ homeFs: null,+ close: vi.fn(),+ })),+}));+vi.mock('@main/core/providers/plugin-registry', () => ({+ listPlugins: () => [+ { metadata: { id: 'codex' }, behavior: {} },+ {+ metadata: { id: 'claude' },+ behavior: {+ repoAgents: { discoverDefinitions: async () => h.state.claudeDefinitions },+ },+ },+ ],+}));+vi.mock('@main/lib/logger', () => ({ log: { info: vi.fn(), warn: h.warn, error: vi.fn() } }));++const { discoverConfiguredAgents } = await import('./discover-configured-agents');++const scan = () => discoverConfiguredAgents({ sshHost: 'vm-1', dir: '/repo' });++describe('discoverConfiguredAgents', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ h.state.location = { id: 'loc-1' };+ h.state.agentNames = [];+ h.state.claudeDefinitions = [];+ h.state.workspace = fakeFs();+ });++ it('finds a Codex agent from credentials alone', async () => {+ // The gap this feature closes: Codex has no repo-agent definitions, so the+ // definition-based scan sees nothing. The provider-neutral credentials file+ // is written for every provider, so it finds the agent anyway.+ h.state.workspace = fakeFs({+ '.switch/agents/.gitignore': '*\n',+ '.switch/agents/codex-hoot.json': creds('sw-codex'),+ '.switchdash/agents/codex-hoot/agent-launch-spec.json': launchSpec('codex'),+ });++ expect(await scan()).toEqual([+ {+ name: 'codex-hoot',+ switchAgentId: 'sw-codex',+ apiEndpoint: 'https://switch.example.com',+ providerId: 'codex',+ providerSource: 'launch-spec',+ alreadyAgent: false,+ },+ ]);+ });++ it('never surfaces the API token', async () => {+ // Attaching must not need the secret: it stays on disk for the launch path.+ h.state.workspace = fakeFs({+ '.switch/agents/hoot.json': creds('sw-1', 'https://switch.example.com', 'tok-do-not-leak'),+ });++ expect(JSON.stringify(await scan())).not.toContain('tok-do-not-leak');+ });++ it('falls back to the owning provider definition, then to unknown', async () => {+ h.state.claudeDefinitions = [{ name: 'cc-hoot', description: null }];+ h.state.workspace = fakeFs({+ '.switch/agents/cc-hoot.json': creds('sw-cc'),+ '.switch/agents/mystery.json': creds('sw-my'),+ });++ const byName = new Map((await scan()).map((a) => [a.name, a]));+ expect(byName.get('cc-hoot')).toMatchObject({+ providerId: 'claude',+ providerSource: 'definition',+ });+ expect(byName.get('mystery')).toMatchObject({+ providerId: null,+ providerSource: 'unknown',+ });+ });++ it('prefers the launch spec over a definition, since it is what actually spawns', async () => {+ h.state.claudeDefinitions = [{ name: 'hoot', description: null }];+ h.state.workspace = fakeFs({+ '.switch/agents/hoot.json': creds('sw-1'),+ '.switchdash/agents/hoot/agent-launch-spec.json': launchSpec('codex'),+ });++ expect((await scan())[0]).toMatchObject({ providerId: 'codex', providerSource: 'launch-spec' });+ });++ it('marks agents this switchdash already has a row for', async () => {+ h.state.agentNames = ['mine'];+ h.state.workspace = fakeFs({+ '.switch/agents/mine.json': creds('sw-mine'),+ '.switch/agents/theirs.json': creds('sw-theirs'),+ });++ const byName = new Map((await scan()).map((a) => [a.name, a.alreadyAgent]));+ expect(byName.get('mine')).toBe(true);+ expect(byName.get('theirs')).toBe(false);+ });++ it('treats a directory with no credentials dir as having no agents', async () => {+ expect(await scan()).toEqual([]);+ });++ it('reports nothing for an unknown location rather than failing', async () => {+ h.state.location = undefined;+ h.state.workspace = fakeFs({ '.switch/agents/hoot.json': creds('sw-1') });++ expect((await scan())[0]).toMatchObject({ name: 'hoot', alreadyAgent: false });+ });++ it('skips unusable credentials files instead of inventing an identity', async () => {+ h.state.workspace = fakeFs({+ '.switch/agents/broken.json': '{ not json',+ '.switch/agents/no-id.json': JSON.stringify({ env: { SWITCH_API_ENDPOINT: 'https://x' } }),+ '.switch/agents/good.json': creds('sw-good'),+ });++ expect((await scan()).map((a) => a.name)).toEqual(['good']);+ expect(h.warn).toHaveBeenCalled();+ });++ it('ignores non-JSON entries such as the .gitignore', async () => {+ h.state.workspace = fakeFs({+ '.switch/agents/.gitignore': '*\n',+ '.switch/agents/hoot.json': creds('sw-1'),+ });++ expect((await scan()).map((a) => a.name)).toEqual(['hoot']);+ });+});diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/discover-configured-agents.ts b/dash/apps/switchdash-desktop/src/main/core/agents/discover-configured-agents.tsnew file mode 100644index 000000000..2ce096656--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agents/discover-configured-agents.ts@@ -0,0 +1,191 @@+import type { PluginFs } from '@switchdash/core/agents/plugins';+import { getLocationByHostDir } from '@main/core/locations/store';+import { listPlugins } from '@main/core/providers/plugin-registry';+import { log } from '@main/lib/logger';+import {+ isValidProviderId,+ type AgentProviderId,+} from '@shared/core/providers/agent-provider-registry';+import type { AgentLaunchSpec } from '../../../sidecar/agent-launch-spec';+import { sidecarLaunchSpecRelPath } from '../../../sidecar/sidecar-paths';+import { resolveWorkspaceFsFor } from './agent-workspace-fs';+import { getAgents } from './getAgents';+import { SWITCH_AGENTS_DIR_RELATIVE } from './switch-settings-paths';++/** How an agent's provider was inferred, so the UI can say whether to trust it. */+export type ProviderSource = 'launch-spec' | 'definition' | 'unknown';++/**+ * An agent already configured in a working directory, found by its+ * provider-neutral Switch credentials rather than by any provider's definition+ * format.+ */+export type DiscoveredConfiguredAgent = {+ /** The `.switch/agents/<name>.json` filename stem — the key every reader and+ * writer of the credentials uses, and the agent's name. */+ name: string;+ switchAgentId: string;+ apiEndpoint: string;+ /** Best-effort: null when nothing on disk names a provider. */+ providerId: AgentProviderId | null;+ providerSource: ProviderSource;+ /** Whether this switchdash already has a row for the name at this location. */+ alreadyAgent: boolean;+};++/**+ * The Switch identity in a credentials file, without its token.+ *+ * `SWITCH_API_TOKEN` is present in the file and is deliberately never read: an+ * attaching switchdash needs no secret, because the launch path reads the token+ * straight from disk at spawn time. Keeping it unread is what makes attaching to+ * another install's agent a non-destructive, credential-free operation.+ */+type CredentialIdentity = { switchAgentId: string; apiEndpoint: string };++function asNonEmptyString(value: unknown): string | null {+ if (typeof value !== 'string') return null;+ const trimmed = value.trim();+ return trimmed.length > 0 ? trimmed : null;+}++function parseCredentialIdentity(raw: string | null, name: string): CredentialIdentity | null {+ if (raw === null) return null;+ let env: Record<string, unknown> | undefined;+ try {+ env = (JSON.parse(raw) as { env?: Record<string, unknown> })?.env;+ } catch (error) {+ log.warn('discoverConfiguredAgents: unparseable credentials file', {+ name,+ error: error instanceof Error ? error.message : String(error),+ });+ return null;+ }+ if (!env) return null;++ const switchAgentId = asNonEmptyString(env.SWITCH_AGENT_ID);+ const apiEndpoint = asNonEmptyString(env.SWITCH_API_ENDPOINT);+ if (!switchAgentId || !apiEndpoint) return null;+ return { switchAgentId, apiEndpoint };+}++/**+ * The provider named by the agent's sidecar launch spec — what actually spawns+ * its sessions on a remote host, so the most authoritative signal available.+ * Absent for an agent that has never run remotely.+ */+async function providerFromLaunchSpec(+ workspaceFs: PluginFs,+ name: string+): Promise<AgentProviderId | null> {+ const raw = await workspaceFs.read(sidecarLaunchSpecRelPath(name));+ if (raw === null) return null;+ try {+ const spec = JSON.parse(raw) as Partial<AgentLaunchSpec>;+ return isValidProviderId(spec.providerId) ? spec.providerId : null;+ } catch (error) {+ log.warn('discoverConfiguredAgents: unparseable launch spec', {+ name,+ error: error instanceof Error ? error.message : String(error),+ });+ return null;+ }+}++/**+ * Definition names per provider, for the providers that have a definition+ * concept at all. Built once per scan: each provider answers with its own+ * discovery rather than this module hardcoding any provider's on-disk layout.+ */+async function definitionOwners(workspaceFs: PluginFs): Promise<Map<string, AgentProviderId>> {+ const owners = new Map<string, AgentProviderId>();+ for (const plugin of listPlugins()) {+ const behavior = plugin.behavior.repoAgents;+ if (!behavior) continue;+ try {+ for (const def of await behavior.discoverDefinitions(workspaceFs)) {+ if (!owners.has(def.name) && isValidProviderId(plugin.metadata.id)) {+ owners.set(def.name, plugin.metadata.id);+ }+ }+ } catch (error) {+ log.warn('discoverConfiguredAgents: provider definition scan failed', {+ providerId: plugin.metadata.id,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ }+ return owners;+}++/**+ * Read-only scan of a working directory for agents already configured there,+ * keyed on the provider-neutral `.switch/agents/<name>.json` credentials every+ * provider writes at create time (CHOO-1937).+ *+ * This is the counterpart to `discoverLocationAgents`, and answers a different+ * question. That one asks a provider which of *its* definitions in the directory+ * could become an agent — a Claude-only answer today, since Claude is the only+ * provider with a definition concept. This one asks which agents already *are*+ * configured here, whoever set them up and whichever provider runs them, so an+ * agent someone else onboarded on a shared host is visible to every switchdash+ * that can reach the directory.+ *+ * Deliberately pure disk IO: it does not verify the identities against a Switch+ * server. That check needs a server the caller has chosen and belongs to the+ * attach path, which fails loudly on a missing identity rather than papering+ * over it here.+ *+ * Works for local and remote (SSH) directories.+ */+export async function discoverConfiguredAgents(params: {+ sshHost: string | null;+ dir: string;+}): Promise<DiscoveredConfiguredAgent[]> {+ const location = await getLocationByHostDir(params.sshHost, params.dir);+ const existing = location+ ? new Set((await getAgents(location.id)).map((a) => a.name))+ : new Set<string>();++ const workspace = await resolveWorkspaceFsFor(params.sshHost, params.dir);+ try {+ const names = (await workspace.fs.list(SWITCH_AGENTS_DIR_RELATIVE))+ .filter((entry) => entry.endsWith('.json'))+ .map((entry) => entry.slice(0, -'.json'.length))+ .filter((name) => name.length > 0)+ .sort((a, b) => a.localeCompare(b));+ if (names.length === 0) return [];++ const owners = await definitionOwners(workspace.fs);++ const discovered: DiscoveredConfiguredAgent[] = [];+ for (const name of names) {+ const identity = parseCredentialIdentity(+ await workspace.fs.read(`${SWITCH_AGENTS_DIR_RELATIVE}/${name}.json`),+ name+ );+ if (!identity) continue;++ const fromSpec = await providerFromLaunchSpec(workspace.fs, name);+ const fromDefinition = owners.get(name) ?? null;+ const providerId = fromSpec ?? fromDefinition;+ const providerSource: ProviderSource = fromSpec+ ? 'launch-spec'+ : fromDefinition+ ? 'definition'+ : 'unknown';++ discovered.push({+ name,+ switchAgentId: identity.switchAgentId,+ apiEndpoint: identity.apiEndpoint,+ providerId,+ providerSource,+ alreadyAgent: existing.has(name),+ });+ }+ return discovered;+ } finally {+ workspace.close();+ }+}diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/reap-stale-sidecars.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/reap-stale-sidecars.test.tsnew file mode 100644index 000000000..90a9e8f8c--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agents/reap-stale-sidecars.test.ts@@ -0,0 +1,108 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { agentSidecarTmuxName } from '@main/core/agent-runtime/impl/remote-sidecar-launcher';+import type { Agent } from '@shared/core/agents/agents';++const h = vi.hoisted(() => {+ const state: { dbNames: string[]; hostListing: string | Error } = {+ dbNames: [],+ hostListing: '',+ };+ const reap = vi.fn<+ (host: unknown, repoDir: string, expected: readonly string[], log: unknown) => Promise<void>+ >(async () => {});+ return { state, reap, warn: vi.fn() };+});++vi.mock('@main/core/agent-runtime/impl/remote-sidecar-launcher', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ reapStaleAgentSidecars: h.reap,+}));+vi.mock('./getAgents', () => ({+ getAgents: vi.fn(async () => h.state.dbNames.map((name) => ({ name }))),+}));+vi.mock('@main/lib/logger', () => ({ log: { info: vi.fn(), warn: h.warn, error: vi.fn() } }));++const { reapStaleSidecarsForAgent } = await import('./reap-stale-sidecars');++const REPO = '/srv/repo';+const agent = { id: 'a-1', name: 'mine', locationId: 'loc-1' } as Agent;++function host() {+ return {+ exec: vi.fn(async () => {+ if (h.state.hostListing instanceof Error) throw h.state.hostListing;+ return { stdout: h.state.hostListing, stderr: '' };+ }),+ putFile: vi.fn(async () => {}),+ };+}++/** The expected-set the reaper was handed, as agent slugs rather than hashes. */+function expectedSlugs(candidates: string[]): string[] {+ const passed = new Set(h.reap.mock.calls[0]?.[2] ?? []);+ return candidates.filter((slug) => passed.has(agentSidecarTmuxName(REPO, slug)));+}++describe('reapStaleSidecarsForAgent', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ h.state.dbNames = ['mine'];+ h.state.hostListing = '';+ });++ it('spares a co-located agent this switchdash does not manage', async () => {+ // The shared-host case: someone else onboarded `theirs` in the same+ // directory. It is absent from this install's database, and reaping against+ // that alone would kill a sidecar doing real work for another person.+ h.state.hostListing = 'mine.json\ntheirs.json\n.gitignore\n';++ await reapStaleSidecarsForAgent(agent, host(), REPO);++ expect(expectedSlugs(['mine', 'theirs'])).toEqual(['mine', 'theirs']);+ });++ it('still reaps a generation the directory no longer has credentials for', async () => {+ // A rename deletes the old credentials file, so the host's view marks the+ // previous name reapable — which is the whole point of this function.+ h.state.hostListing = 'mine.json\n';++ await reapStaleSidecarsForAgent(agent, host(), REPO);++ expect(expectedSlugs(['mine', 'old-name'])).toEqual(['mine']);+ });++ it('always protects the invoking agent, even when the host lists nothing', async () => {+ h.state.dbNames = [];+ h.state.hostListing = '';++ await reapStaleSidecarsForAgent(agent, host(), REPO);++ expect(expectedSlugs(['mine'])).toEqual(['mine']);+ });++ it('falls back to the local view when the host cannot be listed', async () => {+ // Narrower is the safe direction: it can only spare a sidecar, never kill+ // an extra one.+ h.state.hostListing = new Error('ssh down');+ h.state.dbNames = ['mine', 'sibling'];++ await reapStaleSidecarsForAgent(agent, host(), REPO);++ expect(expectedSlugs(['mine', 'sibling'])).toEqual(['mine', 'sibling']);+ });++ it('ignores non-JSON entries in the credentials directory', async () => {+ h.state.hostListing = '.gitignore\nREADME\n';++ await reapStaleSidecarsForAgent(agent, host(), REPO);++ expect(expectedSlugs(['.gitignore', 'README', 'mine'])).toEqual(['mine']);+ });++ it('reads the credentials directory of the repo dir it was given', async () => {+ const h2 = host();+ await reapStaleSidecarsForAgent(agent, h2, REPO);++ expect(h2.exec).toHaveBeenCalledWith('ls', ['-1A', '/srv/repo/.switch/agents']);+ });+});diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/reap-stale-sidecars.ts b/dash/apps/switchdash-desktop/src/main/core/agents/reap-stale-sidecars.tsindex 1a24ce80b..33958ba5c 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/reap-stale-sidecars.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/reap-stale-sidecars.ts@@ -6,19 +6,58 @@ import {import { log } from '@main/lib/logger';import type { Agent } from '@shared/core/agents/agents';import { getAgents } from './getAgents';+import { SWITCH_AGENTS_DIR_RELATIVE } from './switch-settings-paths';++/**+ * Agent names configured in the directory according to the HOST — the stems of+ * the provider-neutral `.switch/agents/<name>.json` credentials every provider+ * writes.+ *+ * The local database only knows the agents *this* switchdash manages, which is+ * not the same set as the agents that legitimately run in a shared directory+ * (CHOO-1937). Reaping against the local set alone would kill the sidecar of an+ * agent another install onboarded here — a process this install has never heard+ * of but which is doing real work for someone else.+ *+ * Best-effort: a host that cannot be listed contributes nothing rather than+ * failing the launch this runs alongside. That is the safe direction — a+ * narrower expected-set can only spare a sidecar, never kill an extra one.+ */+async function hostConfiguredSlugs(host: SidecarHost, repoDir: string): Promise<string[]> {+ try {+ const { stdout } = await host.exec('ls', ['-1A', `${repoDir}/${SWITCH_AGENTS_DIR_RELATIVE}`]);+ return stdout+ .split('\n')+ .map((line) => line.trim())+ .filter((entry) => entry.endsWith('.json'))+ .map((entry) => entry.slice(0, -'.json'.length))+ .filter((name) => name.length > 0);+ } catch {+ return [];+ }+}/*** The sidecar tmux names that are legitimately running in an agent's directory:- * one per agent switchdash has at that location, since siblings sharing a- * directory each run their own sidecar (CHOO-1440).+ * one per agent at that location, since siblings sharing a directory each run+ * their own sidecar (CHOO-1440).*- * `agent` is always included, even if the location query somehow misses its row- * — reaping must never be able to kill the sidecar of the very agent it was- * invoked for.+ * Drawn from the local database *and* the host's own credentials directory, so+ * the set covers agents this switchdash does not manage. `agent` is always+ * included, even if both lookups somehow miss its row — reaping must never be+ * able to kill the sidecar of the very agent it was invoked for.*/-async function expectedSidecarNames(agent: Agent, repoDir: string): Promise<string[]> {+async function expectedSidecarNames(+ agent: Agent,+ host: SidecarHost,+ repoDir: string+): Promise<string[]> {const siblings = await getAgents(agent.locationId);- const slugs = new Set([agent.name ?? agent.id, ...siblings.map((a) => a.name ?? a.id)]);+ const slugs = new Set([+ agent.name ?? agent.id,+ ...siblings.map((a) => a.name ?? a.id),+ ...(await hostConfiguredSlugs(host, repoDir)),+ ]);return [...slugs].map((slug) => agentSidecarTmuxName(repoDir, slug));}@@ -29,6 +68,11 @@ async function expectedSidecarNames(agent: Agent, repoDir: string): Promise<stri* those survive: nothing else on the host ever looks at a sidecar whose name is* not the one it just computed.*+ * A rename deletes the old credentials file, and the storage migration deletes+ * the id-keyed one, so the host's own view still marks those generations+ * reapable — the directory's credentials are the record of which agents are+ * *currently* set up, not of every name ever used.+ ** Call this from paths that ensure a sidecar, not from read-only probes: it is* reconciliation, and a status read should not mutate the host.*@@ -42,7 +86,12 @@ export async function reapStaleSidecarsForAgent(repoDir: string): Promise<void> {try {- await reapStaleAgentSidecars(host, repoDir, await expectedSidecarNames(agent, repoDir), log);+ await reapStaleAgentSidecars(+ host,+ repoDir,+ await expectedSidecarNames(agent, host, repoDir),+ log+ );} catch (error) {log.warn('reapStaleSidecarsForAgent: failed to reconcile sidecars', {agentId: agent.id,diff --git a/dash/apps/switchdash-desktop/src/main/core/sidecar/controller.ts b/dash/apps/switchdash-desktop/src/main/core/sidecar/controller.tsindex bf28d455e..b833135a2 100644--- a/dash/apps/switchdash-desktop/src/main/core/sidecar/controller.ts+++ b/dash/apps/switchdash-desktop/src/main/core/sidecar/controller.ts@@ -65,7 +65,7 @@ async function readAndBroadcast(agentId: string): Promise<AgentSidecarStatus> {const full: AgentSidecarStatus = {agentId,running: status.running,- verdict: verdictFor(status, clientHash),+ verdict: verdictFor(status, clientHash, SIDECAR_VERSION),clientHash,clientVersion: SIDECAR_VERSION,deployedHash: status.hash,diff --git a/dash/apps/switchdash-desktop/src/main/core/sidecar/verdict.test.ts b/dash/apps/switchdash-desktop/src/main/core/sidecar/verdict.test.tsindex c49ed65b2..02218a65b 100644--- a/dash/apps/switchdash-desktop/src/main/core/sidecar/verdict.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/sidecar/verdict.test.ts@@ -3,42 +3,57 @@ import type { SidecarRunStatus } from '@main/core/agent-runtime/impl/remote-sideimport { verdictFor } from './verdict';const CLIENT = 'client-hash';+const CLIENT_VERSION = '1.7';const status = (over: Partial<SidecarRunStatus>): SidecarRunStatus => ({running: true,compatible: true,hash: CLIENT,- version: '1.0',+ version: CLIENT_VERSION,epoch: 1,pid: 100,liveSessions: 0,...over,});+const verdict = (over: Partial<SidecarRunStatus>) =>+ verdictFor(status(over), CLIENT, CLIENT_VERSION);+describe('verdictFor', () => {it('not-running when nothing is up', () => {- expect(verdictFor(status({ running: false }), CLIENT)).toBe('not-running');+ expect(verdict({ running: false })).toBe('not-running');});it('up-to-date when the host runs this exact build', () => {- expect(verdictFor(status({ hash: CLIENT }), CLIENT)).toBe('up-to-date');+ expect(verdict({ hash: CLIENT })).toBe('up-to-date');+ });++ it('upgrade-available when a different build of the same version is idle', () => {+ expect(verdict({ hash: 'other', liveSessions: 0 })).toBe('upgrade-available');});- it('upgrade-available when a different build is running and idle', () => {- expect(verdictFor(status({ hash: 'other', liveSessions: 0 }), CLIENT)).toBe(- 'upgrade-available'- );+ it('upgrade-available when the host runs an older version', () => {+ expect(verdict({ hash: 'other', version: '1.6' })).toBe('upgrade-available');});it('upgrade-pending when a different build is running but busy', () => {- expect(verdictFor(status({ hash: 'other', liveSessions: 3 }), CLIENT)).toBe('upgrade-pending');+ expect(verdict({ hash: 'other', liveSessions: 3 })).toBe('upgrade-pending');+ });++ it('newer-on-host rather than offering a downgrade', () => {+ // A newer switchdash deployed it. Offering "Update" here is an invitation to+ // downgrade, and on a shared host both installs would accept it in turn.+ expect(verdict({ hash: 'other', version: '1.8' })).toBe('newer-on-host');+ });++ it('newer-on-host outranks the live-session check', () => {+ // Busy or idle, there is still nothing this client should do about it.+ expect(verdict({ hash: 'other', version: '2.0', liveSessions: 4 })).toBe('newer-on-host');});it('incompatible outranks any build comparison', () => {// Even the same hash is moot if we cannot speak its protocol — though in// practice an incompatible sidecar is a different build anyway.- expect(verdictFor(status({ compatible: false, hash: 'other', liveSessions: 5 }), CLIENT)).toBe(- 'incompatible'- );+ expect(verdict({ compatible: false, hash: 'other', liveSessions: 5 })).toBe('incompatible');});});diff --git a/dash/apps/switchdash-desktop/src/main/core/sidecar/verdict.ts b/dash/apps/switchdash-desktop/src/main/core/sidecar/verdict.tsindex f8a8db385..390341bf6 100644--- a/dash/apps/switchdash-desktop/src/main/core/sidecar/verdict.ts+++ b/dash/apps/switchdash-desktop/src/main/core/sidecar/verdict.ts@@ -1,5 +1,6 @@import type { SidecarRunStatus } from '@main/core/agent-runtime/impl/remote-sidecar-launcher';import type { SidecarVerdict } from '@shared/events/sidecarEvents';+import { compareSidecarVersions } from '../../../sidecar/sidecar-version';/*** Turn a raw host status + this client's build into the client-vs-host verdict.@@ -7,10 +8,20 @@ import type { SidecarVerdict } from '@shared/events/sidecarEvents';* Compatibility (can I talk to it) is checked before the build comparison (is an* upgrade available), mirroring the launcher's deploy policy — a build that* differs is not a problem, only a protocol that does not fit is.+ *+ * A running sidecar newer than this client is reported as such rather than as an+ * upgrade, matching what the launcher will actually do with it. Offering+ * "Update" there would invite a downgrade, and on a host two installs share it+ * is an invitation each of them accepts in turn (CHOO-1937).*/-export function verdictFor(status: SidecarRunStatus, clientHash: string): SidecarVerdict {+export function verdictFor(+ status: SidecarRunStatus,+ clientHash: string,+ clientVersion: string+): SidecarVerdict {if (!status.running) return 'not-running';if (!status.compatible) return 'incompatible';if (status.hash === clientHash) return 'up-to-date';+ if (compareSidecarVersions(status.version, clientVersion) > 0) return 'newer-on-host';return status.liveSessions > 0 ? 'upgrade-pending' : 'upgrade-available';}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsxindex 98ecbcaf5..47a653791 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx@@ -42,6 +42,7 @@ import {} from '@renderer/lib/ui/select';import { log } from '@renderer/utils/logger';import type { AgentProviderConfig } from '@shared/core/agents/agent-provider-config';+import { getProvider } from '@shared/core/providers/agent-provider-registry';import type { ProvisionAgentResult } from '@shared/core/switch-servers/switch-servers';import { basenameFromAnyPath } from '@shared/path-name';import { AgentAdvancedConfig } from './agent-advanced-config';@@ -50,7 +51,11 @@ import { CodexAgentConfig } from './codex-agent-config';import { ConfigureAgentPanel } from './configure-agent-panel';import { PickExistingPanel } from './content';import { useConfigureAgentForm, usePickMode } from './modes';-import { OnboardExistingPanel } from './onboard-existing-panel';+import {+ type AdoptKind,+ OnboardExistingPanel,+ type OnboardableAgent,+} from './onboard-existing-panel';// switchdash adds a Switch *agent* by pointing at a local directory that the// switch-connector `configure` skill has set up (its `.claude/settings.local.json`@@ -214,12 +219,55 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLoc}),enabled: !!pickState.providerId && discoverDir.trim().length > 0,});+ // Agents already configured in the directory, found by their provider-neutral+ // Switch credentials rather than by any provider's definition format. This is+ // what an agent someone else set up on a shared host looks like, and the only+ // way a provider with no definition concept (Codex) is visible at all+ // (CHOO-1937). Provider-agnostic, so it does not wait on the type picker.+ const configuredQuery = useQuery({+ queryKey: ['discoverConfiguredAgents', discoverSshHost ?? 'local', discoverDir],+ queryFn: () =>+ rpc.agents.discoverConfiguredAgents({ sshHost: discoverSshHost, dir: discoverDir }),+ enabled: discoverDir.trim().length > 0,+ });+// Definitions that can join Switch and switchdash hasn't already onboarded — the// ones worth offering. Already-onboarded ones (on THIS client) are excluded so// the modal never offers to re-add a row it already has; ones registered on the// gateway by another client are still offered (imported, not re-minted). CHOO-1440.- const onboardableAgents = (discoverQuery.data ?? []).filter((a) => a.eligible && !a.alreadyAgent);+ const definitionAgents = (discoverQuery.data ?? []).filter((a) => a.eligible && !a.alreadyAgent);+ const definitionNames = new Set(definitionAgents.map((a) => a.name));+ // Credentials-only agents: those the definition scan does not already cover.+ // A definition WITH credentials is left to the onboard path, which reuses its+ // identity too — listing it twice would offer one agent as two rows.+ const attachableAgents = (configuredQuery.data ?? []).filter(+ (a) => !a.alreadyAgent && !definitionNames.has(a.name)+ );+ const onboardableAgents: OnboardableAgent[] = [+ ...definitionAgents.map((a) => ({+ name: a.name,+ description: a.description,+ kind: (a.registered ? 'import' : 'adopt') as AdoptKind,+ providerLabel: null,+ })),+ ...attachableAgents.map((a) => {+ const providerId = a.providerId ?? pickState.providerId ?? null;+ return {+ name: a.name,+ description: null,+ kind: 'attach' as AdoptKind,+ providerLabel: providerId ? (getProvider(providerId)?.name ?? providerId) : null,+ };+ }),+ ];const hasOnboardable = onboardableAgents.length > 0;+ /** Attachable rows keyed by name, with the provider resolved for submission. */+ const attachByName = new Map(+ attachableAgents.flatMap((a) => {+ const providerId = a.providerId ?? pickState.providerId ?? null;+ return providerId ? [[a.name, providerId] as const] : [];+ })+ );// Branch the flow when a directory has onboardable definitions: `createMode`// false shows the multi-select adopt list; true reveals the create form. When@@ -227,7 +275,14 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLoc// are the checked definitions to onboard (default: all).const [createMode, setCreateMode] = useState(false);const [selectedNames, setSelectedNames] = useState<Set<string>>(new Set());- const onboardableKey = onboardableAgents.map((a) => a.name).join('|');+ // Default-select only what can actually be submitted: an attach row whose+ // provider is unknown is disabled until a type is picked, and pre-checking it+ // would just block the button with no visible cause. Picking a type unblocks+ // the row, which changes this key and folds it into the selection.+ const onboardableKey = onboardableAgents+ .filter((a) => !(a.kind === 'attach' && a.providerLabel === null))+ .map((a) => a.name)+ .join('|');useEffect(() => {setSelectedNames(new Set(onboardableKey ? onboardableKey.split('|') : []));setCreateMode(false);@@ -249,7 +304,8 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLoc// form flashes up first and then flips to the onboard list when discovery lands// (CHOO-1440).const isDiscovering =- !!pickState.providerId && discoverDir.trim().length > 0 && discoverQuery.isPending;+ (!!pickState.providerId && discoverDir.trim().length > 0 && discoverQuery.isPending) ||+ (discoverDir.trim().length > 0 && configuredQuery.isPending);const isChecking =(isRemoteRun? shouldDetectRemote && remoteAgentQuery.isPending@@ -507,20 +563,51 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLocconst handleConfigure = () => createNewAgent(configureForm);const handleConfigureRemote = () => createNewAgent(remoteConfigureForm);- /** Onboard (or adopt) the selected agents already defined in the picked- * directory — importing those already registered on the gateway and minting a- * fresh identity for plain provider definitions. */+ /**+ * Bring in the selected agents. Definitions go through the onboard path+ * (importing a registered identity, minting one for a plain definition);+ * credentials-only agents go through the attach path, which adopts the+ * identity already on disk and writes nothing to the directory (CHOO-1937).+ */const handleOnboard = async () => {- if (!pickState.serverId || !pickState.providerId || selectedNames.size === 0) return;+ if (!pickState.serverId || selectedNames.size === 0) return;+ const attachSelected = [...selectedNames].flatMap((name) => {+ const providerId = attachByName.get(name);+ return providerId ? [{ name, providerId }] : [];+ });+ const onboardSelected = [...selectedNames].filter((name) => !attachByName.has(name));+ if (onboardSelected.length > 0 && !pickState.providerId) return;setSubmitState('creating');setCloseGuard(true);try {+ const locationIds: string[] = [];+ if (attachSelected.length > 0) {+ const attached = await rpc.agents.attachConfiguredAgents({+ sshHost: discoverSshHost,+ dir: discoverDir,+ serverId: pickState.serverId,+ agents: attachSelected,+ });+ if (!attached.success) {+ reportCreationError(attached.error);+ setCloseGuard(false);+ setSubmitState('idle');+ return;+ }+ locationIds.push(...attached.data.map((a) => a.locationId));+ }+ if (onboardSelected.length === 0) {+ await agentsStore.load();+ await getLocationManagerStore().reload();+ finishWith(locationIds[0]!);+ return;+ }const result = await rpc.agents.onboardLocationAgents({sshHost: discoverSshHost,dir: discoverDir,- providerId: pickState.providerId,+ providerId: pickState.providerId!,serverId: pickState.serverId,- names: [...selectedNames],+ names: onboardSelected,});if (!result.success) {reportCreationError(result.error);@@ -545,8 +632,15 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLoc}};+ // A definition still needs the picked agent type to run under; an attach row+ // carries its own (inferred from disk, or the picked one as a fallback).+ const selectionNeedsProviderPick = [...selectedNames].some((name) => !attachByName.has(name));const canOnboard =- hasOnboardable && selectedNames.size > 0 && !!pickState.serverId && submitState === 'idle';+ hasOnboardable &&+ selectedNames.size > 0 &&+ !!pickState.serverId &&+ (!selectionNeedsProviderPick || !!pickState.providerId) &&+ submitState === 'idle';const submitLabel = submitState === 'creating' ? 'Adding...' : 'Add Agent';return (@@ -572,9 +666,7 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLoconClick={() => void handleOnboard()}disabled={!canOnboard}>- {submitState === 'creating'- ? 'Onboarding...'- : `Onboard ${selectedNames.size} selected`}+ {submitState === 'creating' ? 'Adding...' : `Add ${selectedNames.size} selected`}</ConfirmButton>) : isMissingRemoteAgent ? (<ConfirmButtondiff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/onboard-existing-panel.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/onboard-existing-panel.tsxindex 870b75709..fab212bf6 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/onboard-existing-panel.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/onboard-existing-panel.tsx@@ -1,21 +1,43 @@import { Checkbox } from '@renderer/lib/ui/checkbox';-/** A discovered definition the modal can onboard. Structurally a subset of the- * main-process `DiscoveredLocationAgent`, kept local so the renderer does not- * import across the process boundary. */+/**+ * How an agent found in the directory will be brought into this switchdash.+ *+ * - `import` — a provider definition that already carries Switch credentials;+ * its identity is reused.+ * - `adopt` — a plain provider definition with no Switch setup; switchdash mints+ * an identity for it.+ * - `attach` — credentials found in the directory with no definition of ours to+ * go with them, which is what an agent set up by another switchdash (or for a+ * provider with no definition concept, such as Codex) looks like. Its identity+ * is reused and nothing in the directory is written (CHOO-1937).+ */+export type AdoptKind = 'import' | 'adopt' | 'attach';++/** A discovered agent the modal can bring in. Structurally a subset of the+ * main-process discovery types, kept local so the renderer does not import+ * across the process boundary. */export type OnboardableAgent = {name: string;description: string | null;- /** Already a Switch agent on disk (import its identity) vs a plain provider- * definition to adopt (mint a fresh identity). */- registered: boolean;+ kind: AdoptKind;+ /** For `attach`: the provider that will run it. Null when nothing on disk+ * names one and the modal has no provider picked to fall back on, in which+ * case the row cannot be selected. */+ providerLabel: string | null;+};++const BADGE: Record<AdoptKind, string> = {+ import: 'Switch agent · import',+ adopt: 'adopt as new',+ attach: 'configured here · attach',};/**- * Multi-select list of provider definitions found in a directory that aren't yet- * switchdash agents on this client — including ones already registered on the- * gateway by another client (imported, not re-minted). The user picks which to- * onboard, or switches to creating a brand-new agent (CHOO-1440).+ * Multi-select list of agents found in a directory that aren't yet switchdash+ * agents on this client — provider definitions (CHOO-1440) and agents another+ * install already configured here (CHOO-1937), in one list because the user is+ * answering one question: which of these should this switchdash manage.*/export function OnboardExistingPanel({agents,@@ -29,34 +51,52 @@ export function OnboardExistingPanel({return (<div className="flex flex-col gap-2 rounded-md border border-border bg-background-1 px-3 py-2.5 text-sm"><span className="text-foreground-muted">- {agents.length} agent{agents.length === 1 ? '' : 's'} defined in this directory{' '}- {agents.length === 1 ? "isn't" : "aren't"} in switchdash yet — pick which to onboard, or+ {agents.length} agent{agents.length === 1 ? '' : 's'} in this directory{' '}+ {agents.length === 1 ? "isn't" : "aren't"} in switchdash yet — pick which to bring in, orcreate a new one below.</span><div className="flex flex-col gap-0.5">- {agents.map((a) => (- <label- key={a.name}- className="flex cursor-pointer items-start gap-2 rounded px-1.5 py-1 hover:bg-background-2"- >- <Checkbox- checked={selected.has(a.name)}- onCheckedChange={(checked) => onToggle(a.name, checked === true)}- className="mt-0.5"- />- <div className="flex min-w-0 flex-col">- <div className="flex items-center gap-2">- <span className="font-mono text-xs text-foreground">{a.name}</span>- <span className="rounded bg-background-2 px-1 py-0.5 text-[10px] text-foreground-muted">- {a.registered ? 'Switch agent · import' : 'adopt as new'}- </span>+ {agents.map((a) => {+ const blocked = a.kind === 'attach' && a.providerLabel === null;+ return (+ <label+ key={a.name}+ className={`flex items-start gap-2 rounded px-1.5 py-1 ${+ blocked ? 'cursor-not-allowed opacity-60' : 'cursor-pointer hover:bg-background-2'+ }`}+ >+ <Checkbox+ checked={selected.has(a.name)}+ disabled={blocked}+ onCheckedChange={(checked) => onToggle(a.name, checked === true)}+ className="mt-0.5"+ />+ <div className="flex min-w-0 flex-col">+ <div className="flex items-center gap-2">+ <span className="font-mono text-xs text-foreground">{a.name}</span>+ <span className="rounded bg-background-2 px-1 py-0.5 text-[10px] text-foreground-muted">+ {BADGE[a.kind]}+ </span>+ {a.kind === 'attach' && a.providerLabel !== null && (+ <span className="rounded bg-background-2 px-1 py-0.5 text-[10px] text-foreground-muted">+ {a.providerLabel}+ </span>+ )}+ </div>+ {blocked ? (+ <span className="text-xs text-foreground-muted">+ Pick an agent type above to attach this one — the directory does not say which+ runs it.+ </span>+ ) : (+ a.description && (+ <span className="truncate text-xs text-foreground-muted">{a.description}</span>+ )+ )}</div>- {a.description && (- <span className="truncate text-xs text-foreground-muted">{a.description}</span>- )}- </div>- </label>- ))}+ </label>+ );+ })}</div></div>);diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/sidecar-settings-section.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/sidecar-settings-section.tsxindex 2b6466f90..009105aef 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/sidecar-settings-section.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/sidecar-settings-section.tsx@@ -38,6 +38,7 @@ const VERDICT_DISPLAY: Record<'up-to-date': { label: 'Up to date', variant: 'secondary', icon: CheckCircle2 },'upgrade-available': { label: 'Update available', variant: 'default', icon: RefreshCw },'upgrade-pending': { label: 'Update pending', variant: 'outline', icon: AlertTriangle },+ 'newer-on-host': { label: 'Newer on host', variant: 'secondary', icon: CheckCircle2 },incompatible: { label: 'Incompatible', variant: 'destructive', icon: AlertTriangle },'not-running': { label: 'Not running', variant: 'outline', icon: XCircle },};diff --git a/dash/apps/switchdash-desktop/src/shared/events/sidecarEvents.ts b/dash/apps/switchdash-desktop/src/shared/events/sidecarEvents.tsindex 77cea3d93..dc48ab97a 100644--- a/dash/apps/switchdash-desktop/src/shared/events/sidecarEvents.ts+++ b/dash/apps/switchdash-desktop/src/shared/events/sidecarEvents.ts@@ -10,6 +10,9 @@ import { defineEvent } from '@shared/lib/ipc/events';* (the sidecar is idle).* - `upgrade-pending` — a different build is running but has live sessions, so* the upgrade is deferred until it is idle rather than interrupting work.+ * - `newer-on-host` — a newer switchdash deployed the running sidecar. There is+ * nothing to offer: replacing it would be a downgrade, and on a shared host+ * two installs doing that to each other never converges.* - `incompatible` — the host runs a protocol this client cannot speak; it must* be replaced before this client can use it.*/@@ -18,6 +21,7 @@ export type SidecarVerdict =| 'up-to-date'| 'upgrade-available'| 'upgrade-pending'+ | 'newer-on-host'| 'incompatible';/** Full per-agent sidecar status for the UI. */diff --git a/dash/apps/switchdash-desktop/src/sidecar/sidecar-version.test.ts b/dash/apps/switchdash-desktop/src/sidecar/sidecar-version.test.tsnew file mode 100644index 000000000..40a7a13b4--- /dev/null+++ b/dash/apps/switchdash-desktop/src/sidecar/sidecar-version.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it } from 'vitest';+import { compareSidecarVersions, sidecarMajor, SIDECAR_VERSION } from './sidecar-version';++const older = (a: string | null, b: string | null) => compareSidecarVersions(a, b) < 0;+const newer = (a: string | null, b: string | null) => compareSidecarVersions(a, b) > 0;+const same = (a: string | null, b: string | null) => compareSidecarVersions(a, b) === 0;++describe('sidecarMajor', () => {+ it('reads the major, treating a missing or unparseable version as 0', () => {+ expect(sidecarMajor('2.4')).toBe(2);+ expect(sidecarMajor(null)).toBe(0);+ expect(sidecarMajor('nonsense')).toBe(0);+ });+});++describe('compareSidecarVersions', () => {+ it('orders by major first', () => {+ expect(older('1.9', '2.0')).toBe(true);+ expect(newer('2.0', '1.9')).toBe(true);+ });++ it('orders by minor within a major', () => {+ expect(older('1.6', '1.7')).toBe(true);+ expect(newer('1.10', '1.9')).toBe(true);+ expect(same('1.7', '1.7')).toBe(true);+ });++ it('treats a missing or unparseable version as the oldest', () => {+ // A sidecar predating the version field reports none, and must never look+ // newer than the client — that would make it un-upgradeable forever.+ expect(older(null, SIDECAR_VERSION)).toBe(true);+ expect(older('nonsense', SIDECAR_VERSION)).toBe(true);+ expect(same(null, '0.0')).toBe(true);+ });++ it('is antisymmetric, so two clients cannot each consider the other newer', () => {+ // The property the shared-host fix rests on: if A does not replace B, B must+ // be free to replace A, or the sidecar can never be upgraded at all.+ for (const [a, b] of [+ ['1.6', '1.7'],+ ['1.7', '1.7'],+ ['2.0', '1.9'],+ [null, '1.0'],+ ] as Array<[string | null, string | null]>) {+ // `|| 0` normalises -0, which `Object.is` distinguishes from 0.+ expect(Math.sign(compareSidecarVersions(a, b)) || 0).toBe(+ -Math.sign(compareSidecarVersions(b, a)) || 0+ );+ }+ });+});diff --git a/dash/apps/switchdash-desktop/src/sidecar/sidecar-version.ts b/dash/apps/switchdash-desktop/src/sidecar/sidecar-version.tsindex dd2298f12..374791413 100644--- a/dash/apps/switchdash-desktop/src/sidecar/sidecar-version.ts+++ b/dash/apps/switchdash-desktop/src/sidecar/sidecar-version.ts@@ -44,5 +44,35 @@ export function sidecarMajor(version: string | null): number {return Number.isFinite(major) ? major : 0;}+/** An `x.y` version as numbers; a missing or unparseable part reads as 0. */+function parseSidecarVersion(version: string | null): { major: number; minor: number } {+ if (!version) return { major: 0, minor: 0 };+ const [rawMajor, rawMinor] = version.split('.');+ const major = Number.parseInt(rawMajor ?? '', 10);+ const minor = Number.parseInt(rawMinor ?? '', 10);+ return {+ major: Number.isFinite(major) ? major : 0,+ minor: Number.isFinite(minor) ? minor : 0,+ };+}++/**+ * Order two `x.y` versions: negative when `a` is older, 0 when equal, positive+ * when `a` is newer.+ *+ * This is the ONE machine decision the minor takes part in, and it is a+ * tie-breaker rather than a build check. "Is this the same build" stays on the+ * content hash, for the reasons above; this only answers "is the sidecar already+ * on the host newer than what I ship", so a client never replaces a sidecar+ * deployed by a newer switchdash. Without that ordering, two installs on+ * different releases sharing a host each see the other's build as an upgrade and+ * replace it in turn, forever (CHOO-1937).+ */+export function compareSidecarVersions(a: string | null, b: string | null): number {+ const left = parseSidecarVersion(a);+ const right = parseSidecarVersion(b);+ return left.major - right.major || left.minor - right.minor;+}+/** This client's own major, for compatibility comparisons. */export const SIDECAR_CLIENT_MAJOR = sidecarMajor(SIDECAR_VERSION);