Skip to content

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

feat(console): Move all sets up the SSH hosts it needs, and shows progress per machine (#675)

Louis Amaudruz7be78bdc6275
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 90f687c2b..a8895d17c 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
@@ -57,6 +57,9 @@ type World = {
roomsMidTurn: string[];
untellable: string[];
lookup: TargetLookup;
+ /** What the machine looks like once `enable` has turned it on; null leaves it as it was. */
+ lookupAfterEnable: TargetLookup | null;
+ enableFails: boolean;
eligibility: { management: boolean; owner: string | null; ownedByMe: boolean };
stoppedByHand: boolean;
controllerRunning: boolean[];
@@ -81,7 +84,14 @@ function deps(): AgentMigrationDeps {
definitions: {
build: async () => BUILT,
},
- targets: { resolve: async () => world.lookup },
+ targets: {
+ resolve: async () => world.lookup,
+ enable: async (agent) => {
+ world.calls.push(`enable ${agent.sshHost ?? 'this computer'}`);
+ if (world.enableFails) throw new Error('ssh: connect to host gpu-1: Connection refused');
+ world.lookup = world.lookupAfterEnable ?? world.lookup;
+ },
+ },
management: {
eligibility: async () => world.eligibility,
adopt: async (workspaceId, switchAgentId, body) => {
@@ -180,6 +190,7 @@ function deps(): AgentMigrationDeps {
},
pollMs: 1_000,
controllerStopWaitMs: 8_000,
+ machineReadyWaitMs: 5_000,
};
}
@@ -197,6 +208,8 @@ beforeEach(() => {
canEnable: false,
controller: { controllerId: CONTROLLER, state: 'running' },
},
+ lookupAfterEnable: null,
+ enableFails: false,
eligibility: { management: true, owner: 'Ada', ownedByMe: true },
stoppedByHand: false,
controllerRunning: [false],
@@ -293,6 +306,7 @@ describe('moving an agent onto its controller', () => {
const service = new AgentMigrationService({
...deps(),
targets: {
+ ...deps().targets,
resolve: async () => {
throw new Error('ssh: connect to host build-box port 22: Connection refused');
},
@@ -639,32 +653,78 @@ describe('moving every agent of a workspace', () => {
});
const scope = { kind: 'workspace', serverId: 'server-1', workspaceId: WORKSPACE } as const;
- it('takes the agents on SSH hosts too, not another workspace’s, and says when it is complete', async () => {
+ it('takes the agents on SSH hosts too, not another workspace’s, and counts them per machine', async () => {
const migration = service();
- expect(await migration.moveAllProgress(scope)).toEqual({
- managed: [],
- remaining: [
- { name: 'builder', reason: null },
- { name: 'trainer', reason: null },
- ],
- });
+ const before = await migration.moveAllProgress(scope);
+ expect(before.machines.map((m) => [m.name, m.managed, m.total])).toEqual([
+ ['This computer', 0, 1],
+ ['gpu-1', 0, 1],
+ ]);
const moved = await migration.moveAll(scope);
expect(moved.moved.map((agent) => agent.name)).toEqual(['builder', 'trainer']);
- expect(await migration.moveAllProgress(scope)).toEqual({
- managed: ['builder', 'trainer'],
- remaining: [],
- });
+ const after = await migration.moveAllProgress(scope);
+ expect(after.machines.every((m) => m.managed === m.total)).toBe(true);
const back = await migration.stopManagingAll(scope);
expect(back.moved.map((agent) => agent.name)).toEqual(['builder', 'trainer']);
});
- it('counts an agent that cannot move as remaining, with the reason', async () => {
+ it('names the commonest reason a machine’s agents cannot move, once per machine', async () => {
world.eligibility = { management: true, owner: 'Grace', ownedByMe: false };
const progress = await service().moveAllProgress(scope);
- expect(progress.managed).toEqual([]);
- expect(progress.remaining[0]).toMatchObject({
- name: 'builder',
+ expect(progress.machines[0]).toMatchObject({
+ name: 'This computer',
+ managed: 0,
+ blocked: 1,
reason: expect.stringMatching(/owner/),
+ setUpOnMove: false,
});
});
+
+ it('sets up a host that is not a machine yet, then moves its agents', async () => {
+ const ready = world.lookup;
+ world.lookup = {
+ ...ready,
+ target: null,
+ blocker: 'Make gpu-1 a machine first.',
+ canEnable: true,
+ };
+ world.lookupAfterEnable = ready;
+ const migration = service();
+ expect((await migration.moveAllProgress(scope)).machines.map((m) => m.setUpOnMove)).toEqual([
+ true,
+ true,
+ ]);
+ const moved = await migration.moveAll(scope);
+ expect(world.calls.filter((call) => call.startsWith('enable'))).toEqual([
+ 'enable this computer',
+ ]);
+ expect(moved.moved.map((agent) => agent.name)).toEqual(['builder', 'trainer']);
+ });
+
+ it('reports a host that cannot be set up once for its agents, and moves the rest', async () => {
+ world.lookup = {
+ ...world.lookup,
+ target: null,
+ blocker: 'Make it a machine first.',
+ canEnable: true,
+ };
+ world.enableFails = true;
+ const moved = await service().moveAll(scope);
+ expect(moved.moved).toEqual([]);
+ expect(moved.skipped.map((agent) => agent.reason)).toEqual([
+ expect.stringMatching(/^this computer could not be made a machine: ssh: connect/),
+ expect.stringMatching(/^gpu-1 could not be made a machine: ssh: connect/),
+ ]);
+ });
+
+ it('gives up waiting for a machine that never becomes ready, saying so', async () => {
+ world.lookup = {
+ ...world.lookup,
+ target: null,
+ blocker: 'Not reached Switch yet.',
+ canEnable: true,
+ };
+ const moved = await service().moveAll(scope);
+ expect(moved.skipped[0]?.reason).toMatch(/is not ready for agents yet: Not reached Switch yet/);
+ });
});
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 acbaf4bb7..4d675fc0d 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
@@ -6,6 +6,7 @@ import type {
MigrationOperation,
MigrationStage,
MigrationTarget,
+ MoveAllMachine,
MoveAllProgress,
MoveAllResult,
MoveToManagedResult,
@@ -136,7 +137,14 @@ export type AgentMigrationDeps = {
definitions: {
build(agent: MigrationAgent): Promise<BuiltDefinition>;
};
- targets: { resolve(agent: MigrationAgent): Promise<TargetLookup> };
+ targets: {
+ resolve(agent: MigrationAgent): Promise<TargetLookup>;
+ /**
+ * Turns the agent's machine on to run managed agents (this computer's
+ * controller, or an SSH host's), as its own toggle does.
+ */
+ enable(agent: MigrationAgent): Promise<void>;
+ };
management: MigrationManagementPort;
machine: MigrationMachinePort;
credentials: MigrationCredentialsPort;
@@ -149,6 +157,8 @@ export type AgentMigrationDeps = {
pollMs: number;
/** How long a return waits for the controller to stop the agent. */
controllerStopWaitMs: number;
+ /** How long "Move all" waits for a machine it turned on to take agents. */
+ machineReadyWaitMs: number;
};
/** A move refused before anything changed, for a reason a person can act on. */
@@ -173,6 +183,16 @@ export type MoveScope =
/** Every agent of a workspace, on this computer and on every SSH host. */
| { kind: 'workspace'; serverId: string; workspaceId: string };
+/** Agents grouped by the machine they run on: this computer first, then each SSH host by name. */
+function groupByMachine(agents: MigrationAgent[]): MigrationAgent[][] {
+ const groups = new Map<string, MigrationAgent[]>();
+ for (const agent of agents) {
+ const key = agent.sshHost ?? '';
+ groups.set(key, [...(groups.get(key) ?? []), agent]);
+ }
+ return [...groups.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([, group]) => group);
+}
+
function agentInScope(agent: MigrationAgent, scope: MoveScope): boolean {
switch (scope.kind) {
case 'this-computer':
@@ -289,36 +309,84 @@ export class AgentMigrationService {
}
/**
- * Moves every agent that can move, on this computer for a server or on an
- * SSH host, one at a time. Agents that cannot move are skipped with the
- * reason; one that fails does not stop the rest.
+ * Moves every agent that can move, on this computer for a server, on an SSH
+ * host, or across a workspace, one machine at a time. A machine that is not
+ * running managed agents yet is turned on first, as its own toggle would,
+ * then its agents move once it can take them. Agents that cannot move are
+ * skipped with the reason; one that fails does not stop the rest.
*/
async moveAll(scope: MoveScope): Promise<MoveAllResult> {
const result: MoveAllResult = { moved: [], skipped: [], failed: [] };
const agents = (await this.deps.agents.list()).filter((agent) => agentInScope(agent, scope));
- for (const agent of agents) {
- const state = await this.state(agent.id).catch((error: unknown) => ({
- error: message(error),
- }));
- if ('error' in state) {
- result.failed.push({ agentId: agent.id, name: agent.name, message: state.error });
- continue;
- }
- if (state.runner === 'managed') continue;
- if (state.blocker) {
- result.skipped.push({ agentId: agent.id, name: agent.name, reason: state.blocker });
- continue;
- }
- try {
- await this.moveToManaged(agent.id);
- result.moved.push({ agentId: agent.id, name: agent.name });
- } catch (error) {
- result.failed.push({ agentId: agent.id, name: agent.name, message: message(error) });
+ for (const group of groupByMachine(agents)) {
+ const setUp = await this.setUpMachine(group);
+ for (const agent of group) {
+ if (setUp) {
+ if (!(await this.isManaged(agent)))
+ result.skipped.push({ agentId: agent.id, name: agent.name, reason: setUp });
+ continue;
+ }
+ const state = await this.state(agent.id).catch((error: unknown) => ({
+ error: message(error),
+ }));
+ if ('error' in state) {
+ result.failed.push({ agentId: agent.id, name: agent.name, message: state.error });
+ continue;
+ }
+ if (state.runner === 'managed') continue;
+ if (state.blocker) {
+ result.skipped.push({ agentId: agent.id, name: agent.name, reason: state.blocker });
+ continue;
+ }
+ try {
+ await this.moveToManaged(agent.id);
+ result.moved.push({ agentId: agent.id, name: agent.name });
+ } catch (error) {
+ result.failed.push({ agentId: agent.id, name: agent.name, message: message(error) });
+ }
}
}
return result;
}
+ private async isManaged(agent: MigrationAgent): Promise<boolean> {
+ return (await this.deps.store.forIdentity(agent.id, agent.switchAgentId)) !== null;
+ }
+
+ /**
+ * Turns on the machine a group of agents runs on when one of them is waiting
+ * for exactly that, and waits until it can take agents. Null when there was
+ * nothing to do or it is ready; otherwise why the group cannot move.
+ */
+ private async setUpMachine(group: MigrationAgent[]): Promise<string | null> {
+ const waiting = [];
+ for (const agent of group) {
+ if (await this.isManaged(agent)) continue;
+ const state = await this.state(agent.id).catch(() => null);
+ if (state?.runner === 'console' && state.canEnableTarget) waiting.push(agent);
+ }
+ const first = waiting[0];
+ if (!first) return null;
+ const where = first.sshHost ?? 'this computer';
+ this.deps.log.info('Turning a machine on to move its agents', { machine: where });
+ try {
+ await this.deps.targets.enable(first);
+ } catch (error) {
+ return `${where} could not be made a machine: ${message(error)}`;
+ }
+ const deadline = this.deps.now() + this.deps.machineReadyWaitMs;
+ for (;;) {
+ const lookup = await this.deps.targets.resolve(first).catch((error: unknown) => ({
+ target: null,
+ blocker: message(error),
+ }));
+ if (lookup.target) return null;
+ if (this.deps.now() >= deadline)
+ return `${where} was made a machine, but is not ready for agents yet: ${lookup.blocker ?? 'it has not reached Switch'}. Run Move all again once it shows Running.`;
+ await this.deps.sleep(this.deps.pollMs);
+ }
+ }
+
/**
* Brings back every agent this Console moved onto one machine, one at a
* time; one that fails does not stop the rest. `moved` lists the ones that
@@ -351,26 +419,47 @@ export class AgentMigrationService {
}
/**
- * How far moving every agent in scope has got: the ones managed now, and
- * the ones Console still runs, with what keeps each from moving (null when
- * nothing does and it just has not been moved). Complete when none remain.
+ * How far moving every agent in scope has got, per machine: how many are
+ * managed, how many are moving now, and why the rest cannot move, if
+ * anything stops them other than not having been moved yet.
*/
async moveAllProgress(scope: MoveScope): Promise<MoveAllProgress> {
- const progress: MoveAllProgress = { managed: [], remaining: [] };
- for (const agent of await this.deps.agents.list()) {
- if (!agentInScope(agent, scope)) continue;
- try {
- const state = await this.state(agent.id);
- if (state.runner === 'managed') progress.managed.push(agent.name);
- else progress.remaining.push({ name: agent.name, reason: state.blocker });
- } catch (error) {
- progress.remaining.push({
- name: agent.name,
- reason: `Its state cannot be read: ${message(error)}`,
- });
+ const machines: MoveAllMachine[] = [];
+ const agents = (await this.deps.agents.list()).filter((agent) => agentInScope(agent, scope));
+ for (const group of groupByMachine(agents)) {
+ const machine: MoveAllMachine = {
+ kind: group[0]!.sshHost === null ? 'this-computer' : 'ssh-host',
+ name: group[0]!.sshHost ?? 'This computer',
+ total: group.length,
+ managed: 0,
+ moving: 0,
+ blocked: 0,
+ reason: null,
+ setUpOnMove: false,
+ };
+ const reasons = new Map<string, number>();
+ for (const agent of group) {
+ let state: AgentMigrationState;
+ try {
+ state = await this.state(agent.id);
+ } catch (error) {
+ const reason = `An agent's state cannot be read: ${message(error)}`;
+ reasons.set(reason, (reasons.get(reason) ?? 0) + 1);
+ machine.blocked++;
+ continue;
+ }
+ if (state.operation) machine.moving++;
+ if (state.runner === 'managed') machine.managed++;
+ else if (state.canEnableTarget) machine.setUpOnMove = true;
+ else if (state.blocker) {
+ machine.blocked++;
+ reasons.set(state.blocker, (reasons.get(state.blocker) ?? 0) + 1);
+ }
}
+ machine.reason = [...reasons.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? null;
+ machines.push(machine);
}
- return progress;
+ return { machines };
}
// ── State ──────────────────────────────────────────────────────────────────
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration.ts b/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration.ts
index 8b1f4df0d..3d74f36e6 100644
--- a/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration.ts
@@ -522,6 +522,13 @@ export const agentMigrationService = new AgentMigrationService({
workspaceId: agent.workspaceId,
sshHost: agent.sshHost,
}),
+ enable: async (agent) => {
+ if (!agent.serverId || !agent.workspaceId)
+ throw new Error(`${agent.name} is not on a Switch workspace.`);
+ if (agent.sshHost)
+ await hostControllerService.enable(agent.sshHost, agent.serverId, agent.workspaceId);
+ else await embeddedControllerService.enable(agent.serverId, agent.workspaceId);
+ },
},
management,
machine,
@@ -543,4 +550,5 @@ export const agentMigrationService = new AgentMigrationService({
sleep: (ms) => delay(ms),
pollMs: 2_000,
controllerStopWaitMs: 60_000,
+ machineReadyWaitMs: 180_000,
});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/agent-migration/agent-migration-presentation.test.ts b/console/apps/switch-console-desktop/src/renderer/features/agent-migration/agent-migration-presentation.test.ts
index c9c1ff915..4433e6caf 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/agent-migration/agent-migration-presentation.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/agent-migration/agent-migration-presentation.test.ts
@@ -3,6 +3,8 @@ import type { AgentMigrationState } from '@shared/core/agent-migration/agent-mig
import {
migrationAction,
migrationSummary,
+ moveAllMachineState,
+ moveAllOutcome,
moveAllState,
moveAllSummary,
operationLabel,
@@ -191,32 +193,79 @@ describe('a Move all', () => {
});
});
-describe('whether moving every agent is complete', () => {
- it('is complete once every agent is managed', () => {
- expect(moveAllState({ managed: ['a', 'b'], remaining: [] })).toMatchObject({
- tone: 'ok',
- label: 'Complete',
- detail: 'All 2 agents are managed.',
- });
- });
+const MACHINE = {
+ kind: 'ssh-host' as const,
+ name: 'dev-vm',
+ total: 18,
+ managed: 0,
+ moving: 0,
+ blocked: 0,
+ reason: null,
+ setUpOnMove: false,
+};
- it('is not complete while some still run in Console, and counts the ones that cannot move', () => {
+describe('whether moving every agent is complete', () => {
+ it('adds the machines up, and is complete once every agent is managed', () => {
expect(
moveAllState({
- managed: ['a'],
- remaining: [
- { name: 'b', reason: null },
- { name: 'c', reason: 'Its SSH host is not a machine.' },
+ machines: [
+ { ...MACHINE, managed: 18 },
+ { ...MACHINE, name: 'This computer', kind: 'this-computer', total: 6, managed: 6 },
],
})
- ).toMatchObject({
- tone: 'warn',
+ ).toEqual({ tone: 'ok', label: 'Complete', managed: 24, total: 24 });
+ });
+
+ it('is moving while any machine moves, and not complete otherwise', () => {
+ expect(moveAllState({ machines: [{ ...MACHINE, moving: 1 }] }).label).toBe('Moving…');
+ expect(moveAllState({ machines: [{ ...MACHINE, managed: 3 }] })).toMatchObject({
label: 'Not complete',
- detail: '1 of 3 moved. One cannot move yet:',
+ managed: 3,
+ total: 18,
+ });
+ expect(moveAllState({ machines: [] }).label).toBe('Nothing to move');
+ });
+});
+
+describe('one machine in Move all', () => {
+ it('says a host that is not a machine yet is set up by Move all, not that its agents cannot move', () => {
+ expect(moveAllMachineState({ ...MACHINE, setUpOnMove: true })).toEqual({
+ tone: 'neutral',
+ label: 'Not a machine yet',
+ note: 'Move all sets dev-vm up as a machine, then moves its agents.',
+ });
+ });
+
+ it('gives one reason for a blocked machine, and none once it is done', () => {
+ expect(
+ moveAllMachineState({ ...MACHINE, blocked: 18, reason: 'The server is unreachable.' })
+ ).toEqual({ tone: 'warn', label: 'Blocked', note: 'The server is unreachable.' });
+ expect(moveAllMachineState({ ...MACHINE, managed: 10, blocked: 2, reason: 'x' }).label).toBe(
+ '2 blocked'
+ );
+ expect(moveAllMachineState({ ...MACHINE, managed: 18 })).toEqual({
+ tone: 'ok',
+ label: 'Done',
+ note: null,
});
});
+});
- it('has nothing to move when Console runs no agents for the workspace', () => {
- expect(moveAllState({ managed: [], remaining: [] }).label).toBe('Nothing to move');
+describe('what Move all did', () => {
+ it('counts the moves and names the first few failures', () => {
+ const failed = Array.from({ length: 5 }, (_, index) => ({
+ agentId: `a${index}`,
+ name: `agent-${index}`,
+ message: 'controller offline',
+ }));
+ expect(
+ moveAllOutcome({ moved: [{ agentId: 'm', name: 'mover' }], skipped: [], failed }, 'Moved')
+ ).toEqual([
+ 'Moved 1 agent.',
+ 'agent-0: controller offline',
+ 'agent-1: controller offline',
+ 'agent-2: controller offline',
+ "2 more failed; see the agents' pages.",
+ ]);
});
});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/agent-migration/agent-migration-presentation.ts b/console/apps/switch-console-desktop/src/renderer/features/agent-migration/agent-migration-presentation.ts
index 9ebf80041..dc5dc76cc 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/agent-migration/agent-migration-presentation.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/agent-migration/agent-migration-presentation.ts
@@ -2,6 +2,7 @@ import type {
AgentMigrationState,
MigrationOperation,
MigrationTarget,
+ MoveAllMachine,
MoveAllProgress,
MoveAllResult,
} from '@shared/core/agent-migration/agent-migration';
@@ -114,31 +115,57 @@ export function moveAllSummary(result: MoveAllResult, verb: 'Moved' | 'Brought b
return lines;
}
-/** Whether "Move all" is complete: every agent in scope managed. */
+/** Whether "Move all" is complete across the machines: every agent managed. */
export function moveAllState(progress: MoveAllProgress): {
tone: MigrationTone;
label: string;
- detail: string;
+ managed: number;
+ total: number;
} {
- const total = progress.managed.length + progress.remaining.length;
- if (total === 0)
+ const total = progress.machines.reduce((sum, machine) => sum + machine.total, 0);
+ const managed = progress.machines.reduce((sum, machine) => sum + machine.managed, 0);
+ const moving = progress.machines.some((machine) => machine.moving > 0);
+ if (total === 0) return { tone: 'neutral', label: 'Nothing to move', managed, total };
+ if (moving) return { tone: 'busy', label: 'Moving…', managed, total };
+ if (managed === total) return { tone: 'ok', label: 'Complete', managed, total };
+ return { tone: 'warn', label: 'Not complete', managed, total };
+}
+
+/** Where one machine stands, and the one line said under it, if any. */
+export function moveAllMachineState(machine: MoveAllMachine): {
+ tone: MigrationTone;
+ label: string;
+ note: string | null;
+} {
+ if (machine.moving > 0) return { tone: 'busy', label: `Moving ${machine.moving}…`, note: null };
+ if (machine.managed === machine.total) return { tone: 'ok', label: 'Done', note: null };
+ if (machine.setUpOnMove)
return {
tone: 'neutral',
- label: 'Nothing to move',
- detail: 'This Console runs no agents for this workspace.',
+ label: 'Not a machine yet',
+ note:
+ machine.kind === 'ssh-host'
+ ? `Move all sets ${machine.name} up as a machine, then moves its agents.`
+ : 'Move all turns this computer on as a machine, then moves its agents.',
};
- if (progress.remaining.length === 0)
+ if (machine.blocked > 0)
return {
- tone: 'ok',
- label: 'Complete',
- detail: total === 1 ? 'The agent is managed.' : `All ${total} agents are managed.`,
+ tone: 'warn',
+ label:
+ machine.blocked === machine.total - machine.managed
+ ? 'Blocked'
+ : `${machine.blocked} blocked`,
+ note: machine.reason,
};
- const blocked = progress.remaining.filter((agent) => agent.reason !== null).length;
- return {
- tone: 'warn',
- label: 'Not complete',
- detail:
- `${progress.managed.length} of ${total} moved.` +
- (blocked ? ` ${blocked === 1 ? 'One cannot' : `${blocked} cannot`} move yet:` : ''),
- };
+ return { tone: 'neutral', label: 'Ready', note: null };
+}
+
+/** What a "Move all" or "Bring all back" did: a count, and each failure, the first few named. */
+export function moveAllOutcome(result: MoveAllResult, verb: 'Moved' | 'Brought back'): string[] {
+ const count = result.moved.length;
+ const lines = [count ? `${verb} ${count} agent${count === 1 ? '' : 's'}.` : `${verb} no agents.`];
+ const failures = [...result.failed.map((agent) => `${agent.name}: ${agent.message}`)];
+ for (const line of failures.slice(0, 3)) lines.push(line);
+ if (failures.length > 3) lines.push(`${failures.length - 3} more failed; see the agents' pages.`);
+ return lines;
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/agent-migration/move-all-agents.tsx b/console/apps/switch-console-desktop/src/renderer/features/agent-migration/move-all-agents.tsx
new file mode 100644
index 000000000..b2e637ab8
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/agent-migration/move-all-agents.tsx
@@ -0,0 +1,198 @@
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
+import { CircleCheck, Monitor, Server } from 'lucide-react';
+import { useState } from 'react';
+import { InfoTooltip } from '@renderer/features/settings/components/InfoTooltip';
+import { failureText } from '@renderer/lib/errors/describe-failure';
+import { rpc } from '@renderer/lib/ipc';
+import { Button } from '@renderer/lib/ui/button';
+import { StatusBadge, type StatusTone } from '@renderer/lib/ui/status-badge';
+import { cn } from '@renderer/utils/utils';
+import { MOVE_RULE, type MoveAllMachine } from '@shared/core/agent-migration/agent-migration';
+import {
+ type MigrationTone,
+ moveAllMachineState,
+ moveAllOutcome,
+ moveAllState,
+} from './agent-migration-presentation';
+
+const TONE: Record<MigrationTone, StatusTone> = {
+ neutral: 'neutral',
+ busy: 'info',
+ ok: 'success',
+ warn: 'warning',
+ error: 'danger',
+};
+
+const BAR: Record<MigrationTone, string> = {
+ neutral: 'bg-foreground-info',
+ busy: 'bg-foreground-info',
+ ok: 'bg-foreground-success',
+ warn: 'bg-foreground-warning',
+ error: 'bg-foreground-destructive',
+};
+
+/** How often progress is read again: every 2 s while agents move, so the counters climb as they do. */
+const IDLE_REFRESH_MS = 10_000;
+const MOVING_REFRESH_MS = 2_000;
+
+/**
+ * Moving every agent this Console runs for a workspace onto managed machines
+ * at once, and how far that has got: one row per machine, this computer and
+ * each SSH host, with a counter, rather than one per agent. Each agent can
+ * still be moved on its own page.
+ */
+export function MoveAllAgents({
+ serverId,
+ workspaceId,
+}: {
+ serverId: string;
+ workspaceId: string;
+}) {
+ const queryClient = useQueryClient();
+ const scope = { serverId, workspaceId };
+ const [outcome, setOutcome] = useState<string[] | null>(null);
+ const settle = (lines: string[]) => {
+ setOutcome(lines);
+ void queryClient.invalidateQueries({ queryKey: ['agent-migration'] });
+ void queryClient.invalidateQueries({ queryKey: ['embedded-controller', serverId] });
+ void queryClient.invalidateQueries({ queryKey: ['host-controller'] });
+ };
+ const moveAll = useMutation({
+ mutationFn: () => rpc.agentMigration.moveAllInWorkspace(scope),
+ onMutate: () => setOutcome(null),
+ onSuccess: (result) => settle(moveAllOutcome(result, 'Moved')),
+ });
+ const bringBack = useMutation({
+ mutationFn: () => rpc.agentMigration.stopManagingAllInWorkspace(scope),
+ onMutate: () => setOutcome(null),
+ onSuccess: (result) => settle(moveAllOutcome(result, 'Brought back')),
+ });
+ const working = moveAll.isPending || bringBack.isPending;
+ const progress = useQuery({
+ queryKey: ['agent-migration', 'workspace', serverId, workspaceId],
+ queryFn: () => rpc.agentMigration.moveAllProgressInWorkspace(scope),
+ refetchInterval: working ? MOVING_REFRESH_MS : IDLE_REFRESH_MS,
+ });
+ const failure = moveAll.error ?? bringBack.error ?? progress.error;
+ const machines = progress.data?.machines ?? [];
+ const overall = progress.data ? moveAllState(progress.data) : null;
+ const everyoneMoved = overall !== null && overall.managed === overall.total;
+
+ return (
+ <div className="space-y-3 rounded-lg border border-border p-3">
+ <div className="flex items-start justify-between gap-3">
+ <div className="min-w-0 space-y-0.5">
+ <p className="flex items-center gap-1.5 text-sm text-foreground">
+ Move all agents to managed
+ <InfoTooltip label="What moving does" content={MOVE_RULE} />
+ </p>
+ <p className="text-xs text-foreground-muted">
+ Every agent this Console runs for this workspace, on this computer and on your SSH
+ hosts. A host that is not a machine yet is set up first.
+ </p>
+ </div>
+ {overall && (
+ <div className="flex shrink-0 items-center gap-2">
+ {overall.total > 0 && (
+ <span className="text-xs text-foreground-muted tabular-nums">
+ {overall.managed}/{overall.total}
+ </span>
+ )}
+ <StatusBadge tone={TONE[overall.tone]}>{overall.label}</StatusBadge>
+ </div>
+ )}
+ </div>
+
+ {machines.length > 0 && (
+ <ul className="divide-y divide-border overflow-hidden rounded-md border border-border">
+ {machines.map((machine) => (
+ <MachineRow key={machine.name} machine={machine} />
+ ))}
+ </ul>
+ )}
+ {!progress.data && !progress.error && (
+ <p className="text-xs text-foreground-muted">Loading…</p>
+ )}
+
+ <div className="flex flex-wrap items-center gap-2">
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={working || !progress.data || everyoneMoved}
+ onClick={() => moveAll.mutate()}
+ >
+ {moveAll.isPending ? 'Moving…' : 'Move all'}
+ </Button>
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={working || !overall?.managed}
+ onClick={() => bringBack.mutate()}
+ >
+ {bringBack.isPending ? 'Bringing back…' : 'Bring all back'}
+ </Button>
+ {outcome && <span className="min-w-0 text-xs text-foreground-muted">{outcome[0]}</span>}
+ </div>
+ {outcome && outcome.length > 1 && (
+ <ul className="space-y-0.5 text-xs text-foreground-error">
+ {outcome.slice(1).map((line) => (
+ <li key={line} className="truncate" title={line}>
+ {line}
+ </li>
+ ))}
+ </ul>
+ )}
+ {failure && (
+ <p className="text-xs text-foreground-error">
+ {failureText(failure, 'That did not work.')}
+ </p>
+ )}
+ </div>
+ );
+}
+
+function MachineRow({ machine }: { machine: MoveAllMachine }) {
+ const state = moveAllMachineState(machine);
+ const Icon = machine.kind === 'this-computer' ? Monitor : Server;
+ const share = machine.total ? (machine.managed / machine.total) * 100 : 0;
+ return (
+ <li className="space-y-1.5 px-3 py-2.5">
+ <div className="flex items-center gap-2.5">
+ <Icon className="size-4 shrink-0 text-foreground-muted" />
+ <span className="min-w-0 flex-1 truncate text-sm text-foreground">{machine.name}</span>
+ <span className="shrink-0 text-xs text-foreground-muted tabular-nums">
+ {machine.managed}/{machine.total}
+ </span>
+ {state.tone === 'ok' ? (
+ <CircleCheck className="size-4 shrink-0 text-foreground-success" aria-label="Done" />
+ ) : (
+ <StatusBadge tone={TONE[state.tone]} className="shrink-0">
+ {state.label}
+ </StatusBadge>
+ )}
+ </div>
+ <div
+ className="h-1 w-full overflow-hidden rounded-full bg-border"
+ role="progressbar"
+ aria-label={`${machine.name}: ${machine.managed} of ${machine.total} moved`}
+ aria-valuemin={0}
+ aria-valuemax={machine.total}
+ aria-valuenow={machine.managed}
+ >
+ <div
+ className={cn(
+ 'h-full rounded-full transition-all duration-500',
+ BAR[state.tone],
+ state.tone === 'busy' && 'animate-pulse'
+ )}
+ style={{ width: `${share}%` }}
+ />
+ </div>
+ {state.note && (
+ <p className="truncate pl-6.5 text-xs text-foreground-muted" title={state.note}>
+ {state.note}
+ </p>
+ )}
+ </li>
+ );
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/this-computer-machine-card.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/this-computer-machine-card.tsx
index cf22c861e..227bd9289 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/this-computer-machine-card.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/this-computer-machine-card.tsx
@@ -2,10 +2,7 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Computer, ExternalLink, Pencil, RefreshCw, TriangleAlert } from 'lucide-react';
import { observer } from 'mobx-react-lite';
import { useEffect, useState } from 'react';
-import {
- moveAllState,
- moveAllSummary,
-} from '@renderer/features/agent-migration/agent-migration-presentation';
+import { MoveAllAgents } from '@renderer/features/agent-migration/move-all-agents';
import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { failureText } from '@renderer/lib/errors/describe-failure';
import { useStateBoundFailure } from '@renderer/lib/hooks/use-state-bound-failure';
@@ -26,7 +23,6 @@ import { Label } from '@renderer/lib/ui/label';
import { StatusBadge, type StatusTone } from '@renderer/lib/ui/status-badge';
import { Switch } from '@renderer/lib/ui/switch';
import { Textarea } from '@renderer/lib/ui/textarea';
-import { MOVE_RULE } from '@shared/core/agent-migration/agent-migration';
import {
type EmbeddedControllerOverview,
MAX_MACHINE_DESCRIPTION,
@@ -424,99 +420,3 @@ function MachineDetails({
</div>
);
}
-
-/**
- * Moving every agent this Console runs for the workspace, on this computer
- * and on its SSH hosts, onto their machines all at once ("Move all"), or
- * bringing them all back, and whether that is complete. Each agent can also
- * be moved on its own page.
- */
-function MoveAllAgents({ serverId, workspaceId }: { serverId: string; workspaceId: string }) {
- const queryClient = useQueryClient();
- const scope = { serverId, workspaceId };
- const progressKey = ['agent-migration', 'workspace', serverId, workspaceId];
- const progress = useQuery({
- queryKey: progressKey,
- queryFn: () => rpc.agentMigration.moveAllProgressInWorkspace(scope),
- refetchInterval: REFRESH_MS,
- });
- const [outcome, setOutcome] = useState<string[] | null>(null);
- const settle = (lines: string[]) => {
- setOutcome(lines);
- void queryClient.invalidateQueries({ queryKey: overviewKey(serverId) });
- void queryClient.invalidateQueries({ queryKey: ['agent-migration'] });
- };
- const moveAll = useMutation({
- mutationFn: () => rpc.agentMigration.moveAllInWorkspace(scope),
- onSuccess: (result) => settle(moveAllSummary(result, 'Moved')),
- });
- const bringBack = useMutation({
- mutationFn: () => rpc.agentMigration.stopManagingAllInWorkspace(scope),
- onSuccess: (result) => settle(moveAllSummary(result, 'Brought back')),
- });
- const working = moveAll.isPending || bringBack.isPending;
- const failure = moveAll.error ?? bringBack.error ?? progress.error;
- const state = progress.data ? moveAllState(progress.data) : null;
- return (
- <div className="space-y-2 rounded-lg border border-border px-3 py-2">
- <div className="flex items-center justify-between gap-3">
- <p className="text-sm text-foreground">Move all agents to managed</p>
- {state && (
- <StatusBadge tone={TONE[state.tone]} className="shrink-0">
- {state.label}
- </StatusBadge>
- )}
- </div>
- <p className="text-xs text-foreground-muted">
- Move every agent this Console runs for this workspace, on this computer and on your SSH
- hosts, onto that computer’s machine, so Switch manages them. An agent on an SSH host needs
- the host turned on as a machine first. {MOVE_RULE} Agents that cannot move are left as they
- are, with the reason.
- </p>
- {state?.detail && <p className="text-xs text-foreground-muted">{state.detail}</p>}
- {progress.data && (
- <ul className="space-y-0.5 text-xs text-foreground-muted">
- {progress.data.remaining.flatMap((agent) =>
- agent.reason === null
- ? []
- : [
- <li key={agent.name}>
- {agent.name}: {agent.reason}
- </li>,
- ]
- )}
- </ul>
- )}
- <div className="flex flex-wrap items-center gap-2">
- <Button
- variant="outline"
- size="sm"
- disabled={working || progress.data?.remaining.length === 0}
- onClick={() => moveAll.mutate()}
- >
- {moveAll.isPending ? 'Moving…' : 'Move all'}
- </Button>
- <Button
- variant="ghost"
- size="sm"
- disabled={working || !progress.data?.managed.length}
- onClick={() => bringBack.mutate()}
- >
- {bringBack.isPending ? 'Bringing back…' : 'Bring all back'}
- </Button>
- </div>
- {outcome && (
- <ul className="space-y-0.5 text-xs text-foreground-muted">
- {outcome.map((line) => (
- <li key={line}>{line}</li>
- ))}
- </ul>
- )}
- {failure && (
- <p className="text-xs text-foreground-error">
- {failureText(failure, 'That did not work.')}
- </p>
- )}
- </div>
- );
-}
diff --git a/console/apps/switch-console-desktop/src/shared/core/agent-migration/agent-migration.ts b/console/apps/switch-console-desktop/src/shared/core/agent-migration/agent-migration.ts
index 4cef459c8..ac6a60641 100644
--- a/console/apps/switch-console-desktop/src/shared/core/agent-migration/agent-migration.ts
+++ b/console/apps/switch-console-desktop/src/shared/core/agent-migration/agent-migration.ts
@@ -96,12 +96,25 @@ export type MoveAllResult = {
failed: { agentId: string; name: string; message: string }[];
};
-/** How far "Move all" has got; see `AgentMigrationService.moveAllProgress`. */
-export type MoveAllProgress = {
- managed: string[];
- remaining: { name: string; reason: string | null }[];
+/** One machine's agents in "Move all"; see `AgentMigrationService.moveAllProgress`. */
+export type MoveAllMachine = {
+ kind: 'this-computer' | 'ssh-host';
+ /** "This computer", or the SSH host's name. */
+ name: string;
+ total: number;
+ managed: number;
+ /** Moving, or coming back, right now. */
+ moving: number;
+ /** Not managed, and kept from moving by something other than the machine not being set up. */
+ blocked: number;
+ /** The commonest reason among the blocked ones; null when none is. */
+ reason: string | null;
+ /** The machine is not running managed agents yet, and "Move all" turns it on. */
+ setUpOnMove: boolean;
};
+export type MoveAllProgress = { machines: MoveAllMachine[] };
+
export type AgentMigrationEvent = {
agentId: string;
runner: AgentRunner;