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
Remove a location with its last agent; stop probing unused hosts
raullopez-sandbox970e96bd9cc1
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.tsindex f36c77d61..7684d5c16 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@@ -39,9 +39,18 @@ const h = vi.hoisted(() => {discardControllerState: vi.fn(async () => {}),deleteRow: vi.fn(async () => {}),stopRemoteWatcher: vi.fn(async () => {}),+ deleteLocationIfUnused: vi.fn(async () => {}),+ releaseHostIfUnused: vi.fn(async () => {}),};});+vi.mock('@main/core/locations/store', () => ({+ deleteLocationIfUnused: h.deleteLocationIfUnused,+}));+vi.mock('@main/core/remote-hosts/production-host-reachability', () => ({+ releaseHostIfUnused: h.releaseHostIfUnused,+}));+// Console runs every agent here; none was moved to a managed machine.vi.mock('@main/core/agent-migration/managed-agents-store', () => ({managedRecordFor: vi.fn(async () => null),@@ -59,7 +68,7 @@ vi.mock('./agent-workdir-fs', () => ({resolveWorkdirFsFor: vi.fn(async () => ({ fs: h.state.fs, close: vi.fn() })),}));vi.mock('./agent-location', () => ({- getAgentLocation: vi.fn(async () => ({ sshHost: h.state.sshHost, dir: '/repo' })),+ getAgentLocation: vi.fn(async () => ({ id: 'loc', sshHost: h.state.sshHost, dir: '/repo' })),}));vi.mock('./getAgentById', () => ({ getAgentById: vi.fn(async () => h.state.agent) }));vi.mock('./remove-switch-settings', () => ({@@ -139,6 +148,37 @@ describe('deleteAgent', () => {h.state.sshHost = null;});+ it('releases the location and its host once the agent row is gone', async () => {+ h.state.sshHost = 'example-host';+ h.deleteRow.mockImplementationOnce(async () => {+ expect(h.deleteLocationIfUnused).not.toHaveBeenCalled();+ });++ await deleteAgent('agent-1', {+ deleteInSwitch: false,+ removeProvisionedFiles: false,+ trigger: 'user',+ });++ expect(h.deleteLocationIfUnused).toHaveBeenCalledWith('loc');+ expect(h.releaseHostIfUnused).toHaveBeenCalledWith('example-host');+ });++ it('does not report the delete as failed when releasing the location fails', async () => {+ h.deleteLocationIfUnused.mockRejectedValueOnce(new Error('db busy'));++ await deleteAgent('agent-1', {+ deleteInSwitch: false,+ removeProvisionedFiles: false,+ trigger: 'user',+ });++ expect(h.trackEvent).toHaveBeenCalledWith(+ 'agent_removed',+ expect.objectContaining({ outcome: 'success' })+ );+ });+it('removes the per-agent credentials for a provider with no repo-agent definitions', async () => {// The write is unconditional for every provider, so the teardown must be too:// a provider without `removeLocal` would otherwise leave a live token on diskdiff --git a/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.ts b/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.tsindex c848a6054..22e1beab0 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@@ -1,6 +1,8 @@import { eq } from 'drizzle-orm';import { forgetManagedAgent } from '@main/core/agent-migration/managed-agents-store';+import { deleteLocationIfUnused } from '@main/core/locations/store';import { getPlugin } from '@main/core/providers/plugin-registry';+import { releaseHostIfUnused } from '@main/core/remote-hosts/production-host-reachability';import { discardControllerState } from '@main/core/sdk-host/agent-host';import { sessionHooks } from '@main/core/sessions/session-hooks';import { setControllerStopped } from '@main/core/switch-rooms/auto-session-store';@@ -200,8 +202,9 @@ async function removeProvisionedFiles(agent: Agent, location: Location): Promise* 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.+ * The agent's location row goes with its last agent (its directory never+ * does); a location other agents still use is kept. A remote host nothing+ * uses any more stops being probed.*/export async function deleteAgent(agentId: string, options: DeleteAgentOptions): Promise<void> {const agent = await getAgentById(agentId);@@ -310,4 +313,19 @@ async function removeAgent(// notice it left.for (const row of sessionRows) sessionHooks._emit('session:deleted', row.id);agentEvents._emit('agent:deleted', agentId);++ if (location) await releaseLocationIfUnused(location);+}++/** Housekeeping after the agent is gone: a failure here must not report the delete as failed. */+async function releaseLocationIfUnused(location: Location): Promise<void> {+ try {+ await deleteLocationIfUnused(location.id);+ if (location.sshHost) await releaseHostIfUnused(location.sshHost);+ } catch (error) {+ log.warn('deleteAgent: failed to release the unused location', {+ locationId: location.id,+ error: String(error),+ });+ }}diff --git a/console/apps/switch-console-desktop/src/main/core/locations/store.db.test.ts b/console/apps/switch-console-desktop/src/main/core/locations/store.db.test.tsnew file mode 100644index 000000000..9f53061cf--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/locations/store.db.test.ts@@ -0,0 +1,45 @@+import { openFixture } from '@tooling/utils/db';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { AppDb } from '@main/db/client';+import { agents, locations } from '@main/db/schema';+import { deleteLocationIfUnused, getLocationById } from './store';++const mocks = vi.hoisted(() => ({ db: undefined as AppDb | undefined }));++vi.mock('@main/db/client', () => ({+ get db() {+ if (!mocks.db) throw new Error('Test database not initialized');+ return mocks.db;+ },+}));++describe('deleteLocationIfUnused', () => {+ let fixture: Awaited<ReturnType<typeof openFixture>>;++ beforeEach(async () => {+ fixture = await openFixture('empty');+ mocks.db = fixture.db;+ await fixture.db.insert(locations).values([+ { id: 'shared', name: 'shared', sshHost: 'example-host', dir: '/srv/shared' },+ { id: 'empty', name: 'empty', sshHost: 'example-host', dir: '/srv/empty' },+ ]);+ await fixture.db+ .insert(agents)+ .values({ id: 'agent-1', locationId: 'shared', name: 'agent-1', providerId: 'claude' });+ });++ afterEach(() => {+ fixture.close();+ mocks.db = undefined;+ });++ it('deletes a location once its last agent is gone', async () => {+ await deleteLocationIfUnused('empty');+ expect(await getLocationById('empty')).toBeUndefined();+ });++ it('keeps a location another agent still uses', async () => {+ await deleteLocationIfUnused('shared');+ expect(await getLocationById('shared')).toBeDefined();+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/locations/store.ts b/console/apps/switch-console-desktop/src/main/core/locations/store.tsindex 640bc40c5..02a79e87f 100644--- a/console/apps/switch-console-desktop/src/main/core/locations/store.ts+++ b/console/apps/switch-console-desktop/src/main/core/locations/store.ts@@ -1,7 +1,7 @@import { randomUUID } from 'node:crypto';-import { and, desc, eq } from 'drizzle-orm';+import { and, desc, eq, notExists } from 'drizzle-orm';import { db } from '@main/db/client';-import { locations, type LocationRow } from '@main/db/schema';+import { agents, locations, type LocationRow } from '@main/db/schema';import type { Location } from '@shared/core/locations/locations';function rowToLocation(row: LocationRow): Location {@@ -61,3 +61,17 @@ export async function ensureLocation(params: {.returning();return rowToLocation(row!);}++/** Delete a location row once no agent uses it. Never touches the directory itself. */+export async function deleteLocationIfUnused(locationId: string): Promise<void> {+ await db+ .delete(locations)+ .where(+ and(+ eq(locations.id, locationId),+ notExists(+ db.select({ id: agents.id }).from(agents).where(eq(agents.locationId, locationId))+ )+ )+ );+}diff --git a/console/apps/switch-console-desktop/src/main/core/remote-hosts/controller.ts b/console/apps/switch-console-desktop/src/main/core/remote-hosts/controller.tsindex 9c3bcbe0f..eb91ce6e9 100644--- a/console/apps/switch-console-desktop/src/main/core/remote-hosts/controller.ts+++ b/console/apps/switch-console-desktop/src/main/core/remote-hosts/controller.ts@@ -5,8 +5,7 @@ import { hostBlockedReason, type HostReachability } from '@shared/core/remote-hoimport type { HostSetupPlan } from '@shared/core/remote-hosts/setup';import { createRPCController } from '@shared/lib/ipc/rpc';import { listSshConfigHosts } from './list-ssh-config-hosts';-import { hostReachabilityService } from './production-host-reachability';-import { deletePersistedReachability } from './reachability-store';+import { hostReachabilityService, releaseHostIfUnused } from './production-host-reachability';import {discardSetupPlan,ensureSetupPlan,@@ -94,7 +93,7 @@ export const remoteHostsController = createRPCController({await hostControllerService.forgetHost(sshHost);await removeRemoteHost(sshHost);await discardSetupPlan(sshHost);- await deletePersistedReachability(sshHost);+ await releaseHostIfUnused(sshHost);evictRemoteDependencyManager(sshHost);} catch (error) {trackEvent('host_removed', { outcome: 'failure' });diff --git a/console/apps/switch-console-desktop/src/main/core/remote-hosts/host-reachability-service.test.ts b/console/apps/switch-console-desktop/src/main/core/remote-hosts/host-reachability-service.test.tsindex 1f3d86836..b3dc96991 100644--- a/console/apps/switch-console-desktop/src/main/core/remote-hosts/host-reachability-service.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/remote-hosts/host-reachability-service.test.ts@@ -4,10 +4,18 @@ import {HostUnreachableError,} from '@shared/core/remote-hosts/reachability';import { HostReachabilityService, probeDelayFor } from './host-reachability-service';+import {+ deletePersistedReachability,+ listPersistedReachability,+ listSshHostsInUse,+ savePersistedReachability,+} from './reachability-store';vi.mock('./reachability-store', () => ({listPersistedReachability: vi.fn(async () => []),+ listSshHostsInUse: vi.fn(async () => new Set<string>()),savePersistedReachability: vi.fn(async () => {}),+ deletePersistedReachability: vi.fn(async () => {}),hydrate: (record: unknown) => ({...(record as object),nextProbeAt: null,@@ -192,4 +200,44 @@ describe('HostReachabilityService', () => {expect(probe).toHaveBeenCalledWith('vm');});++ it('prunes saved records for hosts nothing uses and never probes them', async () => {+ const record = {+ status: 'unreachable' as const,+ lastError: 'Connection lost before handshake',+ lastCheckedAt: null,+ lastReachableAt: null,+ consecutiveFailures: 6,+ };+ vi.mocked(listPersistedReachability).mockResolvedValueOnce([+ { ...record, sshHost: 'example-gone' },+ { ...record, sshHost: 'example-used' },+ ]);+ vi.mocked(listSshHostsInUse).mockResolvedValueOnce(new Set(['example-used']));+ const { service: svc, timers } = makeService(async () => {});++ await svc.initialize();++ expect(deletePersistedReachability).toHaveBeenCalledExactlyOnceWith('example-gone');+ expect(svc.getAll().map((r) => r.sshHost)).toEqual(['example-used']);+ expect(timers).toHaveLength(1);+ });++ it('forgets a host so an in-flight probe neither re-saves nor reschedules it', async () => {+ let fail!: (error: Error) => void;+ const { service: svc, timers } = makeService(+ () => new Promise<void>((_resolve, reject) => (fail = reject))+ );++ const probing = svc.checkNow('example-gone');+ await svc.forget('example-gone');+ fail(new Error('Connection lost before handshake'));+ await probing;+ await settle();++ expect(deletePersistedReachability).toHaveBeenCalledWith('example-gone');+ expect(savePersistedReachability).not.toHaveBeenCalled();+ expect(timers).toHaveLength(0);+ expect(svc.getAll()).toEqual([]);+ });});diff --git a/console/apps/switch-console-desktop/src/main/core/remote-hosts/host-reachability-service.ts b/console/apps/switch-console-desktop/src/main/core/remote-hosts/host-reachability-service.tsindex 971aead58..7aff8bab0 100644--- a/console/apps/switch-console-desktop/src/main/core/remote-hosts/host-reachability-service.ts+++ b/console/apps/switch-console-desktop/src/main/core/remote-hosts/host-reachability-service.ts@@ -8,8 +8,10 @@ import {} from '@shared/core/remote-hosts/reachability';import type { SshConnectionEvent } from '@shared/core/ssh/sshEvents';import {+ deletePersistedReachability,hydrate,listPersistedReachability,+ listSshHostsInUse,savePersistedReachability,type PersistedHostReachability,} from './reachability-store';@@ -91,13 +93,24 @@ export class HostReachabilityService extends EventEmitter {/*** Load persisted state so the app boots knowing which hosts were down. Hosts* that were unreachable at shutdown get a probe scheduled rather than being- * hammered by every consumer at once on startup.+ * hammered by every consumer at once on startup. Records for hosts nothing+ * uses any more are deleted instead, so a forgotten host is never dialled.*/async initialize(): Promise<void> {if (this.loaded) return;this.loaded = true;- const persisted = await listPersistedReachability();+ const [persisted, inUse] = await Promise.all([+ listPersistedReachability(),+ listSshHostsInUse(),+ ]);for (const record of persisted) {+ if (!inUse.has(record.sshHost)) {+ await deletePersistedReachability(record.sshHost);+ this.deps.log.info('HostReachabilityService: pruned reachability of unused host', {+ sshHost: record.sshHost,+ });+ continue;+ }const reachability = hydrate(record);this.hosts.set(record.sshHost, { reachability });if (isHostBlocked(reachability) && reachability.status !== 'suspended') {@@ -164,7 +177,9 @@ export class HostReachabilityService extends EventEmitter {lastError: message,consecutiveFailures: entry.reachability.consecutiveFailures + 1,}).then(() => {- if (status === 'unreachable') this.scheduleProbe(sshHost);+ if (status === 'unreachable' && this.hosts.get(sshHost) === entry) {+ this.scheduleProbe(sshHost);+ }});}@@ -182,12 +197,14 @@ export class HostReachabilityService extends EventEmitter {this.setProbing(sshHost, true);try {await this.deps.probe(sshHost);+ if (this.hosts.get(sshHost) !== entry) return entry.reachability;return await this.transition(sshHost, {status: 'reachable',lastError: null,consecutiveFailures: 0,});} catch (error) {+ if (this.hosts.get(sshHost) !== entry) return entry.reachability;const message = error instanceof Error ? error.message : String(error);const status: HostReachabilityStatus = this.deps.isAuthError(error)? 'suspended'@@ -195,13 +212,15 @@ export class HostReachabilityService extends EventEmitter {const next = await this.transition(sshHost, {status,lastError: message,- consecutiveFailures: this.entry(sshHost).reachability.consecutiveFailures + 1,+ consecutiveFailures: entry.reachability.consecutiveFailures + 1,});- if (status === 'unreachable') this.scheduleProbe(sshHost);+ if (status === 'unreachable' && this.hosts.get(sshHost) === entry) {+ this.scheduleProbe(sshHost);+ }return next;} finally {- this.entry(sshHost).inFlight = undefined;- this.setProbing(sshHost, false);+ entry.inFlight = undefined;+ if (this.hosts.get(sshHost) === entry) this.setProbing(sshHost, false);}})();@@ -239,6 +258,17 @@ export class HostReachabilityService extends EventEmitter {}}+ /**+ * Stop tracking a host nothing uses any more: cancel its probe and delete its+ * persisted record. A probe already in flight settles without saving it back.+ */+ async forget(sshHost: string): Promise<void> {+ const entry = this.hosts.get(sshHost);+ if (entry) this.cancelProbe(entry);+ this.hosts.delete(sshHost);+ await deletePersistedReachability(sshHost);+ }+/** Stop all timers (app shutdown / tests). */dispose(): void {for (const entry of this.hosts.values()) this.cancelProbe(entry);diff --git a/console/apps/switch-console-desktop/src/main/core/remote-hosts/production-host-reachability.ts b/console/apps/switch-console-desktop/src/main/core/remote-hosts/production-host-reachability.tsindex d0a91e6d5..52f6559c7 100644--- a/console/apps/switch-console-desktop/src/main/core/remote-hosts/production-host-reachability.ts+++ b/console/apps/switch-console-desktop/src/main/core/remote-hosts/production-host-reachability.ts@@ -1,11 +1,13 @@import { SshExecutionContext } from '@main/core/execution-context/ssh-execution-context';import { sshConnectionIdForHost } from '@main/core/locations/location-transport';import { forceSshReconnect } from '@main/core/ssh/connect/connect-agent-ssh';+import { sshConnectionManager } from '@main/core/ssh/lifecycle/production-ssh-connection-manager';import { SshAuthError } from '@main/core/ssh/lifecycle/ssh-connection-manager';import { events } from '@main/lib/events';import { log } from '@main/lib/logger';import { hostReachabilityEventChannel } from '@shared/core/remote-hosts/reachability';import { HostReachabilityService } from './host-reachability-service';+import { listSshHostsInUse } from './reachability-store';/*** The reachability probe: rebuild the host's transport and run a trivial@@ -24,3 +26,13 @@ export const hostReachabilityService = new HostReachabilityService({publish: (reachability) => events.emit(hostReachabilityEventChannel, reachability),log,});++/**+ * Once nothing uses a host, stop probing it, drop its saved reachability and+ * close its pooled connection so nothing goes on redialling it.+ */+export async function releaseHostIfUnused(sshHost: string): Promise<void> {+ if ((await listSshHostsInUse()).has(sshHost)) return;+ await hostReachabilityService.forget(sshHost);+ await sshConnectionManager.disconnect(sshConnectionIdForHost(sshHost));+}diff --git a/console/apps/switch-console-desktop/src/main/core/remote-hosts/reachability-store.db.test.ts b/console/apps/switch-console-desktop/src/main/core/remote-hosts/reachability-store.db.test.tsnew file mode 100644index 000000000..d80a1df98--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/remote-hosts/reachability-store.db.test.ts@@ -0,0 +1,59 @@+import { openFixture } from '@tooling/utils/db';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { AppDb } from '@main/db/client';+import {+ agents,+ locations,+ remoteHosts,+ remoteHostSetupPlans,+ switchServers,+} from '@main/db/schema';+import { listSshHostsInUse } from './reachability-store';++const mocks = vi.hoisted(() => ({ db: undefined as AppDb | undefined }));++vi.mock('@main/db/client', () => ({+ get db() {+ if (!mocks.db) throw new Error('Test database not initialized');+ return mocks.db;+ },+}));++describe('listSshHostsInUse', () => {+ let fixture: Awaited<ReturnType<typeof openFixture>>;++ beforeEach(async () => {+ fixture = await openFixture('empty');+ mocks.db = fixture.db;+ });++ afterEach(() => {+ fixture.close();+ mocks.db = undefined;+ });++ it('counts onboarded, mid-setup, server and agent hosts, not an agentless location', async () => {+ await fixture.db.insert(remoteHosts).values({ sshHost: 'example-onboarded', name: 'x' });+ await fixture.db.insert(remoteHostSetupPlans).values({ sshHost: 'example-setup', steps: '[]' });+ await fixture.db.insert(switchServers).values([+ { id: 'srv', name: 'srv', url: 'https://srv.example.com', sshHost: 'example-server' },+ { id: 'ext', name: 'ext', url: 'https://ext.example.com' },+ ]);+ await fixture.db.insert(locations).values([+ { id: 'used', name: 'used', sshHost: 'example-agent', dir: '/srv/a' },+ { id: 'orphan', name: 'orphan', sshHost: 'example-orphan', dir: '/srv/b' },+ { id: 'local', name: 'local', sshHost: '', dir: '/tmp/local' },+ ]);+ await fixture.db.insert(agents).values([+ { id: 'a1', locationId: 'used', name: 'a1', providerId: 'claude' },+ { id: 'a2', locationId: 'local', name: 'a2', providerId: 'claude' },+ ]);++ expect([...(await listSshHostsInUse())].sort()).toEqual([+ 'example-agent',+ 'example-onboarded',+ 'example-server',+ 'example-setup',+ ]);+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/remote-hosts/reachability-store.ts b/console/apps/switch-console-desktop/src/main/core/remote-hosts/reachability-store.tsindex ec036736c..94f8cc68f 100644--- a/console/apps/switch-console-desktop/src/main/core/remote-hosts/reachability-store.ts+++ b/console/apps/switch-console-desktop/src/main/core/remote-hosts/reachability-store.ts@@ -1,6 +1,14 @@-import { eq } from 'drizzle-orm';+import { eq, isNotNull } from 'drizzle-orm';import { db } from '@main/db/client';-import { remoteHostReachability, type RemoteHostReachabilityRow } from '@main/db/schema';+import {+ agents,+ locations,+ remoteHostReachability,+ type RemoteHostReachabilityRow,+ remoteHosts,+ remoteHostSetupPlans,+ switchServers,+} from '@main/db/schema';import {type HostReachability,type HostReachabilityStatus,@@ -67,6 +75,26 @@ export async function deletePersistedReachability(sshHost: string): Promise<voidawait db.delete(remoteHostReachability).where(eq(remoteHostReachability.sshHost, sshHost));}+/**+ * SSH hosts something still needs reached: onboarded, mid-setup, running a+ * managed server, or holding a location with at least one agent.+ */+export async function listSshHostsInUse(): Promise<Set<string>> {+ const rows = await Promise.all([+ db.select({ sshHost: remoteHosts.sshHost }).from(remoteHosts),+ db.select({ sshHost: remoteHostSetupPlans.sshHost }).from(remoteHostSetupPlans),+ db+ .select({ sshHost: switchServers.sshHost })+ .from(switchServers)+ .where(isNotNull(switchServers.sshHost)),+ db+ .selectDistinct({ sshHost: locations.sshHost })+ .from(locations)+ .innerJoin(agents, eq(agents.locationId, locations.id)),+ ]);+ return new Set(rows.flat().flatMap((row) => (row.sshHost ? [row.sshHost] : [])));+}+/** A persisted record widened back to the full live shape (no probe scheduled yet). */export function hydrate(record: PersistedHostReachability): HostReachability {return { ...record, nextProbeAt: null, probing: false };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.tsindex c2252b1a7..cc38190e7 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@@ -70,8 +70,9 @@ export class LocationManagerStore {}private async _doLoad(): Promise<void> {- // Only surface locations that still have at least one agent — a location- // with no agents lingers in the DB (kept for reuse) but has no sidebar row.+ // Only surface locations that still have at least one agent. Removing a+ // location's last agent deletes its row; this also hides any row left+ // agentless by an older version.const [rawLocations, agents] = await Promise.all([rpc.locations.getLocations(),rpc.agents.getAgents(),@@ -289,8 +290,8 @@ export class LocationManagerStore {/*** Remove every agent at a location (the sidebar's "Remove Agent" action). The- * location row is kept in the DB for reuse; it simply drops out of the sidebar- * once it has no agents.+ * main process deletes the location row with its last agent; files on disk+ * stay.*/async removeLocation(locationId: string): Promise<void> {const snapshot = this.locations.get(locationId);