Skip to content

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

fix(console): remove the Console agent a deleted managed agent was moved from (#974)

Louis Amaudruzf765f3af144b
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration-service.test.ts b/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration-service.test.ts
index dc8c36a6e..ac16b52f6 100644
--- a/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration-service.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration-service.test.ts
@@ -1006,6 +1006,73 @@ describe('moving every agent automatically', () => {
expect(migration.migrationProblems()[0]?.message).toMatch(/^Could not move trainer/);
});
+ it('removes a moved agent once its server has deleted it', async () => {
+ all = [PARENT];
+ const migration = service();
+ await migration.migrateEverything();
+ expect(adopted()).toEqual(['switch-1']);
+ world.calls = [];
+ world.eligibility = { management: true, owner: null, ownedByMe: false, gone: true };
+ await migration.migrateEverything();
+ expect(world.calls).toEqual([`forget ${PARENT.id}`]);
+ });
+
+ it('asks whether a moved agent still exists at most once per heal interval', async () => {
+ all = [PARENT];
+ let asked = 0;
+ const base = deps().management;
+ const migration = service({
+ management: {
+ ...base,
+ eligibility: async (workspaceId, switchAgentId) => {
+ asked++;
+ return base.eligibility(workspaceId, switchAgentId);
+ },
+ },
+ });
+ await migration.migrateEverything();
+ asked = 0;
+ await migration.migrateEverything();
+ expect(asked).toBe(1);
+ world.eligibility = { management: true, owner: null, ownedByMe: false, gone: true };
+ await migration.migrateEverything();
+ expect(asked).toBe(1);
+ expect(world.calls).not.toContain(`forget ${PARENT.id}`);
+ world.clock += 5_000;
+ await migration.migrateEverything();
+ expect(asked).toBe(2);
+ expect(world.calls).toContain(`forget ${PARENT.id}`);
+ });
+
+ it('keeps a moved agent when Switch cannot be asked whether it still exists', async () => {
+ all = [PARENT];
+ let failing = false;
+ const base = deps().management;
+ const migration = service({
+ management: {
+ ...base,
+ eligibility: async (workspaceId, switchAgentId) => {
+ if (failing) throw new Error('HTTP 502');
+ return base.eligibility(workspaceId, switchAgentId);
+ },
+ },
+ });
+ await migration.migrateEverything();
+ failing = true;
+ world.calls = [];
+ await migration.migrateEverything();
+ expect(world.calls).not.toContain(`forget ${PARENT.id}`);
+ expect(world.records.has(PARENT.id)).toBe(true);
+ expect(migration.migrationProblems()).toEqual([]);
+ });
+
+ it('removes the Console agents linked to a Switch agent deleted on their server', async () => {
+ const SAME_ID_ELSEWHERE: MigrationAgent = { ...OTHER_SERVER, switchAgentId: 'switch-2' };
+ all = [PARENT, REMOTE, SAME_ID_ELSEWHERE];
+ await service().forgetDeleted('server-1', 'switch-2');
+ expect(world.calls).toEqual([`forget ${REMOTE.id}`]);
+ });
+
it('runs one pass at a time', async () => {
const migration = service();
await Promise.all([migration.migrateEverything(), migration.migrateEverything()]);
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration-service.ts b/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration-service.ts
index 18327d5be..6e35cb673 100644
--- a/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration-service.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration-service.ts
@@ -354,6 +354,16 @@ export class AgentMigrationService {
});
}
+ /**
+ * Removes the Console agents linked to a Switch agent just deleted on its
+ * server, rather than leaving them under Legacy until a pass finds it gone.
+ */
+ async forgetDeleted(serverId: string, switchAgentId: string): Promise<void> {
+ for (const agent of await this.deps.agents.list())
+ if (agent.serverId === serverId && agent.switchAgentId === switchAgentId)
+ await this.forgetGone(agent, `gone:${agent.id}`, this.deps.now());
+ }
+
/** Why each agent the last automatic passes could not move did not, by agent. */
migrationProblems(): MigrationProblem[] {
return [...this.problems.values()];
@@ -441,6 +451,10 @@ export class AgentMigrationService {
if (await this.isManaged(agent)) {
this.leftAlone.delete(agent.id);
this.unasked.delete(agent.id);
+ if (await this.deletedOnServer(agent, now)) {
+ await this.forgetGone(agent, `gone:${agent.id}`, now);
+ continue;
+ }
candidates.push(agent);
continue;
}
@@ -466,21 +480,7 @@ export class AgentMigrationService {
if (eligibility.gone) {
// Deleted on its server: there is nothing to move it to and no way back,
// and listing it here (and under Legacy) only keeps asking about it.
- this.deps.log.warn('Removing an agent its server no longer has', {
- agentId: agent.id,
- switchAgentId: agent.switchAgentId,
- });
- try {
- await this.deps.agents.forget(agent.id);
- } catch (error) {
- this.deps.log.error('Could not remove an agent its server no longer has', {
- agentId: agent.id,
- error: message(error),
- });
- this.backOff(`ask:${agent.id}`, now);
- }
- this.leftAlone.delete(agent.id);
- this.problems.delete(agent.id);
+ await this.forgetGone(agent, `ask:${agent.id}`, now);
continue;
}
if (!eligibility.management || !eligibility.ownedByMe) {
@@ -923,6 +923,50 @@ export class AgentMigrationService {
return (await this.deps.store.forIdentity(agent.id, agent.switchAgentId)) !== null;
}
+ /**
+ * Whether a moved agent's server has deleted it, asked at most once every
+ * `healIntervalMs`. Deleting a managed agent deletes it on its server only,
+ * so the Console row it was moved from would otherwise stay, under Legacy.
+ */
+ private async deletedOnServer(agent: MigrationAgent, now: number): Promise<boolean> {
+ const key = `gone:${agent.id}`;
+ if (!agent.workspaceId || !agent.switchAgentId) return false;
+ if (this.operations.has(agent.id) || !this.due(key, now)) return false;
+ let eligibility: Awaited<ReturnType<MigrationManagementPort['eligibility']>>;
+ try {
+ eligibility = await this.deps.management.eligibility(agent.workspaceId, agent.switchAgentId);
+ } catch (error) {
+ this.deps.log.warn('Switch could not be asked whether a moved agent still exists', {
+ agentId: agent.id,
+ error: message(error),
+ });
+ this.backOff(key, now);
+ return false;
+ }
+ if (eligibility.gone) return true;
+ this.backOff(key, now, this.deps.healIntervalMs);
+ return false;
+ }
+
+ private async forgetGone(agent: MigrationAgent, retryKey: string, now: number): Promise<void> {
+ this.deps.log.warn('Removing an agent its server no longer has', {
+ agentId: agent.id,
+ switchAgentId: agent.switchAgentId,
+ });
+ try {
+ await this.deps.agents.forget(agent.id);
+ this.retryAt.delete(retryKey);
+ } catch (error) {
+ this.deps.log.error('Could not remove an agent its server no longer has', {
+ agentId: agent.id,
+ error: message(error),
+ });
+ this.backOff(retryKey, now);
+ }
+ this.leftAlone.delete(agent.id);
+ this.problems.delete(agent.id);
+ }
+
// ── State ──────────────────────────────────────────────────────────────────
private async consoleState(
diff --git a/console/apps/switch-console-desktop/src/main/core/managed-agents/controller.ts b/console/apps/switch-console-desktop/src/main/core/managed-agents/controller.ts
index 14c3bd9a1..b01f7609d 100644
--- a/console/apps/switch-console-desktop/src/main/core/managed-agents/controller.ts
+++ b/console/apps/switch-console-desktop/src/main/core/managed-agents/controller.ts
@@ -5,6 +5,7 @@ import {
sealProviderLogin,
vertexLoginCredential,
} from '@switch-console/agent-providers';
+import { agentMigrationService } from '@main/core/agent-migration/agent-migration';
import { embeddedControllerService } from '@main/core/embedded-controller/embedded-controllers';
import { hostControllerService } from '@main/core/host-controllers/host-controllers';
import {
@@ -30,6 +31,7 @@ import {
} from '@main/core/switch-servers/local-provider-sign-in';
import { withReachableServerWorkspaceSession } from '@main/core/workspaces/workspace-session';
import { requireWorkspaceForServer } from '@main/core/workspaces/workspaces-store';
+import { log } from '@main/lib/logger';
import type {
AdvancedConfigField,
ManagedAgentChanges,
@@ -238,11 +240,23 @@ export const managedAgentsController = createRPCController({
/** Deletes the agent: its machine stops it, and it is gone from Switch.
* One call: Switch stops managing an agent it deletes, while stopping
- * managing it first would leave the agent behind if the delete then failed. */
- remove: (params: { serverId: string; agentId: string }): Promise<void> =>
- withReachableServerWorkspaceSession(params.serverId, (server) =>
+ * managing it first would leave the agent behind if the delete then failed.
+ * An agent this Console moved to managed also loses the Console row it was
+ * moved from; a failure there is left to the next automatic pass. */
+ remove: async (params: { serverId: string; agentId: string }): Promise<void> => {
+ await withReachableServerWorkspaceSession(params.serverId, (server) =>
deleteAgent(server, params.agentId)
- ),
+ );
+ await agentMigrationService
+ .forgetDeleted(params.serverId, params.agentId)
+ .catch((error: unknown) => {
+ log.error('Could not remove the Console agent a deleted managed agent was moved from', {
+ serverId: params.serverId,
+ agentId: params.agentId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ });
+ },
});
function definitionBody(changes: ManagedAgentChanges['definition']): Record<string, unknown> {
diff --git a/console/apps/switch-console-desktop/src/main/core/managed-agents/give-machine-login.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-agents/give-machine-login.test.ts
index 7436700a2..49c9cb163 100644
--- a/console/apps/switch-console-desktop/src/main/core/managed-agents/give-machine-login.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/managed-agents/give-machine-login.test.ts
@@ -20,6 +20,8 @@ const mocks = vi.hoisted(() => ({
readLocalProviderSignIn: vi.fn(),
}));
+vi.mock('@main/core/agent-migration/agent-migration', () => ({ agentMigrationService: {} }));
+vi.mock('@main/lib/logger', () => ({ log: { warn: vi.fn(), error: vi.fn(), info: vi.fn() } }));
vi.mock('@main/core/embedded-controller/embedded-controllers', () => ({
embeddedControllerService: {},
}));