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 every agent to managed automatically, without a transition UI (#699)

Louis Amaudruz6eb0bdd482d4
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 a8895d17c..0df85a2b5 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
@@ -70,6 +70,8 @@ type World = {
releaseOutcome: 'released' | 'already_gone';
managedView: { controllerId: string | null; desiredState: 'running' | 'stopped' } | null;
clock: number;
+ /** The lookup for one agent; `lookup` for every agent when unset. */
+ lookupFor: ((agent: MigrationAgent) => TargetLookup) | null;
};
let world: World;
@@ -85,7 +87,7 @@ function deps(): AgentMigrationDeps {
build: async () => BUILT,
},
targets: {
- resolve: async () => world.lookup,
+ resolve: async (agent) => (world.lookupFor ? world.lookupFor(agent) : 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');
@@ -191,6 +193,7 @@ function deps(): AgentMigrationDeps {
pollMs: 1_000,
controllerStopWaitMs: 8_000,
machineReadyWaitMs: 5_000,
+ unmanageableRecheckMs: 60_000,
};
}
@@ -220,6 +223,7 @@ beforeEach(() => {
releaseOutcome: 'released',
managedView: { controllerId: CONTROLLER, desiredState: 'running' },
clock: 0,
+ lookupFor: null,
};
});
@@ -385,7 +389,6 @@ describe('moving an agent on an SSH host', () => {
},
],
});
- expect(await service.movedOnto({ kind: 'ssh-host', sshHost: 'gpu-1' })).toEqual(['builder']);
});
});
@@ -595,37 +598,7 @@ describe('what keeps an agent from moving', () => {
});
});
-describe('moving every agent on a machine', () => {
- it('moves the ones that can, and says why the others did not', async () => {
- const service = new AgentMigrationService(deps());
- const moved = await service.moveAll({ kind: 'this-computer', serverId: 'server-1' });
- expect(moved).toEqual({
- moved: [{ agentId: PARENT.id, name: 'builder' }],
- skipped: [],
- failed: [],
- });
- expect(await service.movedOnto({ kind: 'this-computer', serverId: 'server-1' })).toEqual([
- 'builder',
- ]);
- const back = await service.stopManagingAll({ kind: 'this-computer', serverId: 'server-1' });
- expect(back.moved).toEqual([{ agentId: PARENT.id, name: 'builder' }]);
- });
-
- it('skips an agent that cannot move', async () => {
- world.eligibility = { management: true, owner: 'Grace', ownedByMe: false };
- const result = await new AgentMigrationService(deps()).moveAll({
- kind: 'this-computer',
- serverId: 'server-1',
- });
- expect(result.moved).toEqual([]);
- expect(result.skipped[0]).toMatchObject({
- name: 'builder',
- reason: expect.stringMatching(/owner/),
- });
- });
-});
-
-describe('moving every agent of a workspace', () => {
+describe('moving every agent automatically', () => {
const REMOTE: MigrationAgent = {
...PARENT,
id: 'agent-2',
@@ -634,15 +607,26 @@ describe('moving every agent of a workspace', () => {
sshHost: 'gpu-1',
dir: '/srv/trainer',
};
- const ELSEWHERE: MigrationAgent = {
+ const OTHER_SERVER: MigrationAgent = {
...PARENT,
id: 'agent-3',
name: 'other',
switchAgentId: 'switch-3',
+ serverId: 'server-2',
workspaceId: 'workspace-2',
+ sshHost: 'gpu-1',
+ dir: '/srv/other',
};
- const all = [PARENT, REMOTE, ELSEWHERE];
- const service = () =>
+ const UNLINKED: MigrationAgent = {
+ ...PARENT,
+ id: 'agent-4',
+ name: 'loose',
+ switchAgentId: null,
+ workspaceId: null,
+ serverId: null,
+ };
+ let all: MigrationAgent[];
+ const service = (overrides: Partial<AgentMigrationDeps> = {}) =>
new AgentMigrationService({
...deps(),
agents: {
@@ -650,81 +634,144 @@ describe('moving every agent of a workspace', () => {
get: async (agentId) => all.find((agent) => agent.id === agentId) ?? null,
list: async () => all,
},
+ ...overrides,
});
- const scope = { kind: 'workspace', serverId: 'server-1', workspaceId: WORKSPACE } as const;
+ const adopted = () =>
+ world.calls.filter((call) => call.startsWith('adopt')).map((call) => call.split(' ')[1]);
+
+ beforeEach(() => {
+ all = [PARENT, REMOTE, OTHER_SERVER, UNLINKED];
+ world.lookupFor = (agent) =>
+ agent.workspaceId === 'workspace-2'
+ ? {
+ ...world.lookup,
+ target: world.lookup.target && { ...world.lookup.target, workspaceId: 'workspace-2' },
+ }
+ : world.lookup;
+ });
- it('takes the agents on SSH hosts too, not another workspace’s, and counts them per machine', async () => {
+ it('moves every linked agent, on every machine and server, and leaves unlinked ones', async () => {
const migration = service();
- 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']);
- 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']);
+ await migration.migrateEverything();
+ expect(adopted()).toEqual(['switch-1', 'switch-2', 'switch-3']);
+ expect(migration.migrationProblems()).toEqual([]);
+ });
+
+ it('cuts a running turn rather than waiting for it', async () => {
+ world.roomsMidTurn = ['room-a'];
+ await service().migrateEverything();
+ expect(world.calls).toContain('tell room-a');
+ expect(adopted()).toHaveLength(3);
});
- 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.machines[0]).toMatchObject({
- name: 'This computer',
- managed: 0,
- blocked: 1,
- reason: expect.stringMatching(/owner/),
- setUpOnMove: false,
+ it('does not move an agent twice', async () => {
+ const migration = service();
+ await migration.migrateEverything();
+ world.calls = [];
+ await migration.migrateEverything();
+ expect(adopted()).toEqual([]);
+ });
+
+ it.each([
+ ['someone else owns', { management: true, owner: 'Grace', ownedByMe: false }],
+ [
+ 'is on a server without agent management',
+ { management: false, owner: null, ownedByMe: false },
+ ],
+ ])(
+ 'leaves an agent that %s alone, without reporting it, and asks again later',
+ async (_what, eligibility) => {
+ world.eligibility = eligibility;
+ let asked = 0;
+ const base = deps().management;
+ const migration = service({
+ management: {
+ ...base,
+ eligibility: async (...args) => {
+ asked++;
+ return base.eligibility(...args);
+ },
+ },
+ });
+ await migration.migrateEverything();
+ expect(adopted()).toEqual([]);
+ expect(migration.migrationProblems()).toEqual([]);
+ expect(asked).toBe(3);
+ await migration.migrateEverything();
+ expect(asked).toBe(3);
+ world.clock += 60_000;
+ await migration.migrateEverything();
+ expect(asked).toBe(6);
+ }
+ );
+
+ it('skips an agent when Switch cannot be asked, without reporting it', async () => {
+ const migration = service({
+ management: {
+ ...deps().management,
+ eligibility: async () => {
+ throw new Error('Dev VM’s Switch stack is not running.');
+ },
+ },
});
+ await migration.migrateEverything();
+ expect(adopted()).toEqual([]);
+ expect(migration.migrationProblems()).toEqual([]);
});
- it('sets up a host that is not a machine yet, then moves its agents', async () => {
+ it('sets up each machine once per server, then moves its agents', async () => {
const ready = world.lookup;
- world.lookup = {
- ...ready,
- target: null,
- blocker: 'Make gpu-1 a machine first.',
- canEnable: true,
- };
+ world.lookup = { ...ready, target: null, blocker: 'Not a machine yet.', 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);
+ await service().migrateEverything();
expect(world.calls.filter((call) => call.startsWith('enable'))).toEqual([
'enable this computer',
]);
- expect(moved.moved.map((agent) => agent.name)).toEqual(['builder', 'trainer']);
+ expect(adopted()).toHaveLength(3);
});
- it('reports a host that cannot be set up once for its agents, and moves the rest', async () => {
+ it('reports the agents of a machine that cannot be set up, and clears them once they move', async () => {
world.lookup = {
...world.lookup,
target: null,
- blocker: 'Make it a machine first.',
+ blocker: 'Not a machine yet.',
canEnable: true,
};
+ const ready = { ...world.lookup, target: TARGET, blocker: null, canEnable: false };
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/),
+ const migration = service();
+ await migration.migrateEverything();
+ expect(migration.migrationProblems()).toEqual([
+ {
+ agentId: PARENT.id,
+ name: 'builder',
+ machine: 'this computer',
+ message: expect.stringMatching(
+ /^this computer could not be set up to run managed agents: ssh/
+ ),
+ },
+ expect.objectContaining({ name: 'trainer', machine: 'gpu-1' }),
+ expect.objectContaining({ name: 'other', machine: 'gpu-1' }),
]);
+ world.enableFails = false;
+ world.lookupAfterEnable = ready;
+ await migration.migrateEverything();
+ expect(migration.migrationProblems()).toEqual([]);
});
- 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/);
+ it('reports a move that fails, and keeps moving the rest', async () => {
+ world.failAdoptOn = 'switch-2';
+ const migration = service();
+ await migration.migrateEverything();
+ expect(migration.migrationProblems()).toEqual([
+ expect.objectContaining({ name: 'trainer', message: 'controller_offline' }),
+ ]);
+ expect(adopted()).toEqual(['switch-1', 'switch-2', 'switch-3']);
+ });
+
+ it('runs one pass at a time', async () => {
+ const migration = service();
+ await Promise.all([migration.migrateEverything(), migration.migrateEverything()]);
+ expect(adopted()).toEqual(['switch-1', 'switch-2', 'switch-3']);
});
});
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 4d675fc0d..ab7f0f75a 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
@@ -1,14 +1,13 @@
import type {
AgentMigrationEvent,
AgentMigrationState,
+ AgentRunner,
ManagedActual,
ManagedMachine,
+ MigrationProblem,
MigrationOperation,
MigrationStage,
MigrationTarget,
- MoveAllMachine,
- MoveAllProgress,
- MoveAllResult,
MoveToManagedResult,
} from '@shared/core/agent-migration/agent-migration';
import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';
@@ -157,8 +156,10 @@ 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. */
+ /** How long a pass waits for a machine it set up to take agents. */
machineReadyWaitMs: number;
+ /** How long an agent found someone else's, or on a server without agent management, is not asked about again. */
+ unmanageableRecheckMs: number;
};
/** A move refused before anything changed, for a reason a person can act on. */
@@ -177,49 +178,22 @@ type Moving = {
stoppedByHand: boolean;
};
-export type MoveScope =
- | { kind: 'this-computer'; serverId: string }
- | { kind: 'ssh-host'; sshHost: string }
- /** 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[][] {
+/**
+ * Agents grouped by the controller they move onto: one per machine and server,
+ * this computer first, then each SSH host by name.
+ */
+function groupByController(agents: MigrationAgent[]): MigrationAgent[][] {
const groups = new Map<string, MigrationAgent[]>();
for (const agent of agents) {
- const key = agent.sshHost ?? '';
+ const key = JSON.stringify([agent.sshHost ?? '', agent.serverId ?? '']);
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':
- return agent.sshHost === null && agent.serverId === scope.serverId;
- case 'ssh-host':
- return agent.sshHost === scope.sshHost;
- case 'workspace':
- return agent.serverId === scope.serverId && agent.workspaceId === scope.workspaceId;
- }
-}
-
-/** Whether a moved agent is in scope; `agent` is its Console agent, null when that is gone. */
-function recordInScope(
- record: ManagedAgentRecord,
- agent: MigrationAgent | null,
- scope: MoveScope
-): boolean {
- switch (scope.kind) {
- case 'this-computer':
- return (
- record.placement.kind === 'this-computer' && record.placement.serverId === scope.serverId
- );
- case 'ssh-host':
- return record.placement.kind === 'ssh-host' && record.placement.sshHost === scope.sshHost;
- case 'workspace':
- return agent !== null && agentInScope(agent, scope);
- }
+ const order = (agent: MigrationAgent) => [agent.sshHost ?? '', agent.serverId ?? ''] as const;
+ return [...groups.values()].sort((a, b) => {
+ const [hostA, serverA] = order(a[0]!);
+ const [hostB, serverB] = order(b[0]!);
+ return hostA === hostB ? serverA.localeCompare(serverB) : hostA.localeCompare(hostB);
+ });
}
/**
@@ -276,6 +250,10 @@ function message(error: unknown): string {
*/
export class AgentMigrationService {
private readonly operations = new Map<string, MigrationOperation>();
+ private readonly problems = new Map<string, MigrationProblem>();
+ /** Agents found someone else's, or on a server without agent management, until when. */
+ private readonly unmanageableUntil = new Map<string, number>();
+ private migrating: Promise<void> | null = null;
constructor(private readonly deps: AgentMigrationDeps) {}
@@ -287,6 +265,12 @@ export class AgentMigrationService {
return this.consoleState(agent, operation);
}
+ /** Who runs the agent: this Console, or a controller it was moved onto. */
+ async runner(agentId: string): Promise<AgentRunner> {
+ const agent = await this.requireAgent(agentId);
+ return (await this.isManaged(agent)) ? 'managed' : 'console';
+ }
+
async moveToManaged(agentId: string): Promise<MoveToManagedResult> {
let untold: MoveToManagedResult['untold'] = [];
await this.exclusive(agentId, 'moving', async () => {
@@ -308,45 +292,105 @@ export class AgentMigrationService {
});
}
+ /** Why each agent the last automatic passes could not move did not, by agent. */
+ migrationProblems(): MigrationProblem[] {
+ return [...this.problems.values()];
+ }
+
/**
- * 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.
+ * Moves every agent this Console runs that can be managed: linked to a
+ * server with agent management, and owned by the signed-in user. A machine
+ * that is not running managed agents yet is set up first. Turns running are
+ * cut. Agents someone else owns, or on a server without agent management,
+ * are left as they are; any other reason an agent did not move is kept as a
+ * problem until a later pass moves it. One pass runs at a time; a call
+ * during one waits for it.
*/
- 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 group of groupByMachine(agents)) {
+ migrateEverything(): Promise<void> {
+ this.migrating ??= this.migrateOnce().finally(() => {
+ this.migrating = null;
+ });
+ return this.migrating;
+ }
+
+ /** Forgets that an agent could not be managed, so the next pass asks Switch again. */
+ recheck(agentId: string): void {
+ this.unmanageableUntil.delete(agentId);
+ }
+
+ private async migrateOnce(): Promise<void> {
+ const agents = await this.deps.agents.list();
+ const present = new Set(agents.map((agent) => agent.id));
+ for (const agentId of this.problems.keys())
+ if (!present.has(agentId)) this.problems.delete(agentId);
+ const candidates: MigrationAgent[] = [];
+ for (const agent of agents) {
+ if (
+ !agent.switchAgentId ||
+ !agent.workspaceId ||
+ !agent.serverId ||
+ (await this.isManaged(agent))
+ ) {
+ this.problems.delete(agent.id);
+ continue;
+ }
+ if ((this.unmanageableUntil.get(agent.id) ?? 0) > this.deps.now()) continue;
+ 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 an agent can be managed', {
+ agentId: agent.id,
+ error: message(error),
+ });
+ continue;
+ }
+ if (!eligibility.management || !eligibility.ownedByMe) {
+ this.unmanageableUntil.set(agent.id, this.deps.now() + this.deps.unmanageableRecheckMs);
+ this.problems.delete(agent.id);
+ continue;
+ }
+ candidates.push(agent);
+ }
+ for (const group of groupByController(candidates)) {
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 });
+ this.problem(agent, setUp);
continue;
}
try {
- await this.moveToManaged(agent.id);
- result.moved.push({ agentId: agent.id, name: agent.name });
+ const state = await this.state(agent.id);
+ if (state.runner === 'console') {
+ if (state.blocker) {
+ this.problem(agent, state.blocker);
+ continue;
+ }
+ await this.moveToManaged(agent.id);
+ this.deps.log.info('Moved an agent to managed', { agentId: agent.id });
+ }
+ this.problems.delete(agent.id);
} catch (error) {
- result.failed.push({ agentId: agent.id, name: agent.name, message: message(error) });
+ this.problem(agent, message(error));
}
}
}
- return result;
+ }
+
+ private problem(agent: MigrationAgent, why: string): void {
+ this.deps.log.warn('An agent could not be moved to managed', {
+ agentId: agent.id,
+ error: why,
+ });
+ this.problems.set(agent.id, {
+ agentId: agent.id,
+ name: agent.name,
+ machine: agent.sshHost ?? 'this computer',
+ message: why,
+ });
}
private async isManaged(agent: MigrationAgent): Promise<boolean> {
@@ -354,9 +398,9 @@ export class AgentMigrationService {
}
/**
- * 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.
+ * Sets up the machine a group of agents moves onto 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 = [];
@@ -368,11 +412,11 @@ export class AgentMigrationService {
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 });
+ this.deps.log.info('Setting a machine up 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)}`;
+ return `${where} could not be set up to run managed agents: ${message(error)}`;
}
const deadline = this.deps.now() + this.deps.machineReadyWaitMs;
for (;;) {
@@ -382,86 +426,11 @@ export class AgentMigrationService {
}));
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.`;
+ return `${where} was set up to run managed agents, but is not ready for them yet: ${lookup.blocker ?? 'it has not reached Switch'}.`;
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
- * came back.
- */
- async stopManagingAll(scope: MoveScope): Promise<MoveAllResult> {
- const result: MoveAllResult = { moved: [], skipped: [], failed: [] };
- for (const record of await this.deps.store.list()) {
- const agent = await this.deps.agents.get(record.agentId);
- if (!recordInScope(record, agent, scope)) continue;
- const name = agent?.name ?? record.agentId;
- try {
- await this.stopManaging(record.agentId);
- result.moved.push({ agentId: record.agentId, name });
- } catch (error) {
- result.failed.push({ agentId: record.agentId, name, message: message(error) });
- }
- }
- return result;
- }
-
- /** The agents this Console moved onto one machine, by name. */
- async movedOnto(scope: MoveScope): Promise<string[]> {
- const names: string[] = [];
- for (const record of await this.deps.store.list()) {
- const agent = await this.deps.agents.get(record.agentId);
- if (recordInScope(record, agent, scope)) names.push(agent?.name ?? record.agentId);
- }
- return names;
- }
-
- /**
- * 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 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 { machines };
- }
-
// ── State ──────────────────────────────────────────────────────────────────
private async consoleState(
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 3d74f36e6..a4d59e5ea 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
@@ -551,4 +551,32 @@ export const agentMigrationService = new AgentMigrationService({
pollMs: 2_000,
controllerStopWaitMs: 60_000,
machineReadyWaitMs: 180_000,
+ unmanageableRecheckMs: 15 * 60_000,
});
+
+const AUTO_MIGRATION_INTERVAL_MS = 60_000;
+let autoMigrationTimer: NodeJS.Timeout | null = null;
+
+function migrateEverythingLogged(): void {
+ agentMigrationService.migrateEverything().catch((error: unknown) => {
+ log.error('The automatic move to managed agents failed', {
+ event: 'agent_migration',
+ error: error instanceof Error ? error.message : String(error),
+ });
+ });
+}
+
+/**
+ * Moves every agent that can be managed onto a controller, now and then every
+ * minute, so agents created, linked or brought online later move too.
+ */
+export function startAutoMigration(): void {
+ if (autoMigrationTimer) return;
+ migrateEverythingLogged();
+ autoMigrationTimer = setInterval(migrateEverythingLogged, AUTO_MIGRATION_INTERVAL_MS);
+}
+
+export function stopAutoMigration(): void {
+ if (autoMigrationTimer) clearInterval(autoMigrationTimer);
+ autoMigrationTimer = null;
+}
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-migration/controller.ts b/console/apps/switch-console-desktop/src/main/core/agent-migration/controller.ts
index 7dc1f040d..4a884ea8d 100644
--- a/console/apps/switch-console-desktop/src/main/core/agent-migration/controller.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agent-migration/controller.ts
@@ -1,8 +1,6 @@
import type {
- AgentMigrationState,
- MoveAllProgress,
- MoveAllResult,
- MoveToManagedResult,
+ AgentRunner,
+ MigrationProblem,
NewAgentMachine,
} from '@shared/core/agent-migration/agent-migration';
import { createRPCController } from '@shared/lib/ipc/rpc';
@@ -10,31 +8,19 @@ import { agentMigrationService } from './agent-migration';
import { newManagedAgentService } from './new-managed-agent';
import type { AddManagedAgentParams, AddManagedAgentResult } from './new-managed-agent-service';
-/** "Move to managed" and "Stop managing" for the agents Console runs, and new agents created managed. */
+/** The automatic move of the agents Console runs onto controllers, and new agents created managed. */
export const agentMigrationController = createRPCController({
- getState: (agentId: string): Promise<AgentMigrationState> => agentMigrationService.state(agentId),
+ /** Who runs the agent: this Console, or a controller it was moved onto. */
+ getRunner: (agentId: string): Promise<AgentRunner> => agentMigrationService.runner(agentId),
- moveToManaged: (agentId: string): Promise<MoveToManagedResult> =>
- agentMigrationService.moveToManaged(agentId),
+ /** Why the agents the automatic move could not move did not. */
+ getProblems: (): MigrationProblem[] => agentMigrationService.migrationProblems(),
- stopManaging: (agentId: string): Promise<void> => agentMigrationService.stopManaging(agentId),
-
- /** Moves every agent of a workspace that can move, on this computer and on every SSH host. */
- moveAllInWorkspace: (scope: { serverId: string; workspaceId: string }): Promise<MoveAllResult> =>
- agentMigrationService.moveAll({ kind: 'workspace', ...scope }),
-
- stopManagingAllInWorkspace: (scope: {
- serverId: string;
- workspaceId: string;
- }): Promise<MoveAllResult> =>
- agentMigrationService.stopManagingAll({ kind: 'workspace', ...scope }),
-
- /** How far moving every agent of a workspace has got. */
- moveAllProgressInWorkspace: (scope: {
- serverId: string;
- workspaceId: string;
- }): Promise<MoveAllProgress> =>
- agentMigrationService.moveAllProgress({ kind: 'workspace', ...scope }),
+ /** Runs the automatic move again now, asking Switch afresh about the agent. */
+ retry: (agentId: string): Promise<void> => {
+ agentMigrationService.recheck(agentId);
+ return agentMigrationService.migrateEverything();
+ },
/** Whether a new agent on this machine (an SSH host, or this computer) runs as a managed agent. */
newAgentMachine: (params: {
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-migration/managed-agents-store.ts b/console/apps/switch-console-desktop/src/main/core/agent-migration/managed-agents-store.ts
index 0e5c95cc7..756972f32 100644
--- a/console/apps/switch-console-desktop/src/main/core/agent-migration/managed-agents-store.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agent-migration/managed-agents-store.ts
@@ -131,9 +131,7 @@ export async function managedRecordFor(
/** Thrown where Console would start the watcher of an agent a controller runs. */
export class AgentManagedByControllerError extends Error {
constructor(name: string) {
- super(
- `${name} runs on a managed machine now, so Console does not run it. Use Stop managing on the agent to bring it back to this Console.`
- );
+ super(`${name} runs on a managed machine now: Switch runs it there, not this Console.`);
this.name = 'AgentManagedByControllerError';
}
}
diff --git a/console/apps/switch-console-desktop/src/main/core/embedded-controller/embedded-controller-service.test.ts b/console/apps/switch-console-desktop/src/main/core/embedded-controller/embedded-controller-service.test.ts
index 65999fd29..9e11321d7 100644
--- a/console/apps/switch-console-desktop/src/main/core/embedded-controller/embedded-controller-service.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/embedded-controller/embedded-controller-service.test.ts
@@ -383,7 +383,7 @@ describe('EmbeddedControllerService', () => {
const refused = running.disable(SERVER);
await expect(refused).rejects.toBeInstanceOf(MovedAgentsHereError);
await expect(refused).rejects.toThrow(
- 'This computer runs builder for this Console. Bring them back with Stop managing (or Bring all back) before turning it off.'
+ 'This computer runs builder as managed agents for this Console. Delete those agents before turning it off.'
);
expect(management.revoke).not.toHaveBeenCalled();
expect(calls[0]!.child.signals).toEqual([]);
diff --git a/console/apps/switch-console-desktop/src/main/core/embedded-controller/embedded-controller-service.ts b/console/apps/switch-console-desktop/src/main/core/embedded-controller/embedded-controller-service.ts
index ba2d7c141..0ad6399e6 100644
--- a/console/apps/switch-console-desktop/src/main/core/embedded-controller/embedded-controller-service.ts
+++ b/console/apps/switch-console-desktop/src/main/core/embedded-controller/embedded-controller-service.ts
@@ -255,7 +255,7 @@ export class EmbeddedControllerService {
const moved = await this.deps.movedAgents(serverId);
if (moved.length)
throw new MovedAgentsHereError(
- `This computer runs ${moved.join(', ')} for this Console. Bring them back with Stop managing (or Bring all back) before turning it off.`,
+ `This computer runs ${moved.join(', ')} as managed agents for this Console. Delete those agents before turning it off.`,
moved
);
await this.turnOff(serverId);
diff --git a/console/apps/switch-console-desktop/src/main/core/host-controllers/controller.ts b/console/apps/switch-console-desktop/src/main/core/host-controllers/controller.ts
index 567abd0d6..1d83b2d18 100644
--- a/console/apps/switch-console-desktop/src/main/core/host-controllers/controller.ts
+++ b/console/apps/switch-console-desktop/src/main/core/host-controllers/controller.ts
@@ -1,5 +1,3 @@
-import { agentMigrationService } from '@main/core/agent-migration/agent-migration';
-import type { MoveAllResult } from '@shared/core/agent-migration/agent-migration';
import type { HostControllerOverview } from '@shared/core/host-controllers/host-controllers';
import { createRPCController } from '@shared/lib/ipc/rpc';
import { hostControllerService } from './host-controllers';
@@ -25,10 +23,4 @@ export const hostControllersController = createRPCController({
disable: (params: { sshHost: string; serverId: string }): Promise<void> =>
hostControllerService.disable(params.sshHost, params.serverId, { force: false }),
-
- moveAll: (sshHost: string): Promise<MoveAllResult> =>
- agentMigrationService.moveAll({ kind: 'ssh-host', sshHost }),
-
- stopManagingAll: (sshHost: string): Promise<MoveAllResult> =>
- agentMigrationService.stopManagingAll({ kind: 'ssh-host', sshHost }),
});
diff --git a/console/apps/switch-console-desktop/src/main/core/host-controllers/host-controller-service.test.ts b/console/apps/switch-console-desktop/src/main/core/host-controllers/host-controller-service.test.ts
index f5358fd52..63b60f850 100644
--- a/console/apps/switch-console-desktop/src/main/core/host-controllers/host-controller-service.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/host-controllers/host-controller-service.test.ts
@@ -378,7 +378,7 @@ describe('removing the host as a machine', () => {
const refused = service.forgetHost(HOST);
await expect(refused).rejects.toBeInstanceOf(MovedAgentsHereError);
await expect(refused).rejects.toThrow(
- 'build-box runs builder for this Console, so it cannot be removed yet. Bring the agents back first'
+ 'build-box runs builder as managed agents for this Console, so it cannot be removed yet. Delete those agents first.'
);
await expect(refused).rejects.toMatchObject({ agents: ['builder'] });
expect(calls).toEqual([]);
diff --git a/console/apps/switch-console-desktop/src/main/core/host-controllers/host-controller-service.ts b/console/apps/switch-console-desktop/src/main/core/host-controllers/host-controller-service.ts
index 191294bfe..91c7253cc 100644
--- a/console/apps/switch-console-desktop/src/main/core/host-controllers/host-controller-service.ts
+++ b/console/apps/switch-console-desktop/src/main/core/host-controllers/host-controller-service.ts
@@ -311,7 +311,7 @@ export class HostControllerService {
const moved = await this.deps.movedAgents(sshHost, serverId);
if (moved.length)
throw new MovedAgentsHereError(
- `${sshHost} runs ${moved.join(', ')} for this Console. Bring them back with Stop managing (or Bring all back) before turning it off.`,
+ `${sshHost} runs ${moved.join(', ')} as managed agents for this Console. Delete those agents before turning it off.`,
moved
);
await this.exclusive(sshHost, serverId, async () => {
@@ -398,7 +398,7 @@ export class HostControllerService {
moved.push(...(await this.deps.movedAgents(sshHost, record.serverId)));
if (moved.length)
throw new MovedAgentsHereError(
- `${sshHost} runs ${moved.join(', ')} for this Console, so it cannot be removed yet. Bring the agents back first: Bring all back on the host’s page, or Stop managing on each agent.`,
+ `${sshHost} runs ${moved.join(', ')} as managed agents for this Console, so it cannot be removed yet. Delete those agents first.`,
moved
);
for (const record of records) await this.disable(sshHost, record.serverId, { force: true });
diff --git a/console/apps/switch-console-desktop/src/main/index.ts b/console/apps/switch-console-desktop/src/main/index.ts
index f02947cee..5fd66ec96 100644
--- a/console/apps/switch-console-desktop/src/main/index.ts
+++ b/console/apps/switch-console-desktop/src/main/index.ts
@@ -10,6 +10,7 @@ import { flushPendingDeeplink, setupDeeplinks } from './app/deeplinks';
import { setupApplicationMenu } from './app/menu';
import { APP_ORIGIN, registerAppScheme, setupAppProtocol } from './app/protocol';
import { createMainWindow, getMainWindow } from './app/window';
+import { startAutoMigration, stopAutoMigration } from './core/agent-migration/agent-migration';
import { bridgeAgentEventsToRenderer } from './core/agents/agent-events-renderer-bridge';
import { setAgentStorageMigrationReady } from './core/agents/agent-storage-migration-ready';
import { migrateAgentStorage } from './core/agents/migrate-agent-storage';
@@ -251,6 +252,8 @@ void app.whenReady().then(async () => {
} catch (e) {
log.error('Failed to start the embedded agents controllers at startup:', e);
}
+ // After the controllers: moving an agent onto this computer's controller needs it running.
+ startAutoMigration();
});
// A laptop waking from sleep usually has stale (frozen) SSH sockets to remote
@@ -285,6 +288,7 @@ app.on('before-quit', (event) => {
event.preventDefault();
logAppExit('before-quit');
controlService.dispose();
+ stopAutoMigration();
stopResourceSampler();
localServerService.dispose();
remoteServerService.dispose();
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
deleted file mode 100644
index 4433e6caf..000000000
--- a/console/apps/switch-console-desktop/src/renderer/features/agent-migration/agent-migration-presentation.test.ts
+++ /dev/null
@@ -1,271 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import type { AgentMigrationState } from '@shared/core/agent-migration/agent-migration';
-import {
- migrationAction,
- migrationSummary,
- moveAllMachineState,
- moveAllOutcome,
- moveAllState,
- moveAllSummary,
- operationLabel,
- targetName,
-} from './agent-migration-presentation';
-
-const CONSOLE: AgentMigrationState = {
- agentId: 'agent-1',
- runner: 'console',
- operation: null,
- target: { kind: 'this-computer', serverId: 'server-1', machineName: 'build-box' },
- blocker: null,
- canEnableTarget: false,
- notCarried: [],
- managed: null,
-};
-
-const MANAGED: AgentMigrationState = {
- ...CONSOLE,
- runner: 'managed',
- managed: {
- controllerId: 'controller-1',
- movedAt: '2026-10-01T00:00:00Z',
- machine: { kind: 'running' },
- desiredState: 'running',
- actual: { process: 'running', attached: true, reason: null, detail: null },
- unreadable: null,
- },
-};
-
-describe('where an agent runs', () => {
- it('names the machine', () => {
- expect(targetName(CONSOLE.target)).toBe('this computer (build-box)');
- expect(
- targetName({ kind: 'ssh-host', sshHost: 'gpu-1', serverId: 'server-1', machineName: null })
- ).toBe('gpu-1');
- expect(targetName(null)).toBe('a managed machine');
- });
-
- it('reads as run by this Console before a move', () => {
- expect(migrationSummary(CONSOLE)).toEqual({
- label: 'Run by this Console',
- tone: 'neutral',
- detail: null,
- });
- });
-
- it('says what its controller reports once moved', () => {
- expect(migrationSummary(MANAGED)).toMatchObject({ label: 'Managed', tone: 'ok' });
- expect(
- migrationSummary({
- ...MANAGED,
- managed: {
- ...MANAGED.managed!,
- actual: {
- process: 'failed',
- attached: false,
- reason: 'provider_login_missing',
- detail: 'Sign in to Claude Code.',
- },
- },
- })
- ).toEqual({
- label: 'Managed, failed',
- tone: 'error',
- detail:
- 'this computer (build-box): failed (provider login missing) — Sign in to Claude Code.',
- });
- expect(
- migrationSummary({ ...MANAGED, managed: { ...MANAGED.managed!, actual: null } }).tone
- ).toBe('busy');
- expect(
- migrationSummary({
- ...MANAGED,
- managed: { ...MANAGED.managed!, unreadable: 'Switch no longer manages this agent.' },
- })
- ).toMatchObject({ tone: 'warn', detail: 'Switch no longer manages this agent.' });
- });
-
- it('reads as not running while its machine’s controller is stopped, whatever it last reported', () => {
- const reason = 'gpu-1’s controller is not running. Start it again from the host’s page.';
- expect(
- migrationSummary({
- ...MANAGED,
- managed: { ...MANAGED.managed!, machine: { kind: 'stopped', reason } },
- })
- ).toEqual({ label: 'Managed, not running', tone: 'warn', detail: reason });
- expect(
- migrationSummary({
- ...MANAGED,
- managed: {
- ...MANAGED.managed!,
- machine: {
- kind: 'unknown',
- reason: 'Console cannot tell whether gpu-1’s controller runs.',
- },
- },
- })
- ).toEqual({
- label: 'Managed',
- tone: 'warn',
- detail: 'Console cannot tell whether gpu-1’s controller runs.',
- });
- });
-
- it('says its machine was removed, and that Stop managing brings it back, once the controller is gone', () => {
- const stranded: AgentMigrationState = {
- ...MANAGED,
- target: { kind: 'this-computer', serverId: 'server-1', machineName: null },
- managed: { ...MANAGED.managed!, machine: { kind: 'removed' } },
- };
- expect(migrationSummary(stranded)).toEqual({
- label: 'Machine removed',
- tone: 'error',
- detail:
- 'The machine it was moved onto, this computer, was removed from Switch, so nothing runs this agent now. Stop managing brings it back to this Console.',
- });
- expect(migrationAction(stranded)).toEqual({
- kind: 'return',
- label: 'Stop managing',
- disabledReason: null,
- });
- });
-
- it('shows a move in flight', () => {
- const telling: AgentMigrationState = {
- ...CONSOLE,
- operation: { kind: 'moving', stage: 'telling-rooms' },
- };
- expect(migrationSummary(telling)).toEqual({
- label: 'Moving…',
- tone: 'busy',
- detail: 'Telling the rooms it was working in that it is moving…',
- });
- expect(operationLabel({ kind: 'returning', stage: 'waiting-for-controller' })).toBe(
- 'Waiting for the machine to stop it…'
- );
- });
-});
-
-describe('the action offered', () => {
- it('is Move to managed, disabled with the reason it cannot run', () => {
- expect(migrationAction(CONSOLE)).toEqual({
- kind: 'move',
- label: 'Move to managed',
- disabledReason: null,
- });
- expect(migrationAction({ ...CONSOLE, blocker: 'Turn it on first.' })?.disabledReason).toBe(
- 'Turn it on first.'
- );
- });
-
- it('is Stop managing once moved', () => {
- expect(migrationAction(MANAGED).label).toBe('Stop managing');
- });
-
- it('is held while a move is in flight', () => {
- expect(
- migrationAction({
- ...CONSOLE,
- operation: { kind: 'moving', stage: 'adopting' },
- })?.disabledReason
- ).toBe('Working…');
- });
-});
-
-describe('a Move all', () => {
- it('says what moved, what was skipped and what failed', () => {
- expect(
- moveAllSummary(
- {
- moved: [{ agentId: 'a', name: 'builder' }],
- skipped: [{ agentId: 'b', name: 'reviewer', reason: 'Only its owner can move it.' }],
- failed: [{ agentId: 'c', name: 'tester', message: 'controller offline' }],
- },
- 'Moved'
- )
- ).toEqual([
- 'Moved builder.',
- 'reviewer did not move: Only its owner can move it.',
- 'tester failed: controller offline',
- ]);
- expect(moveAllSummary({ moved: [], skipped: [], failed: [] }, 'Brought back')).toEqual([
- 'Brought back no agents.',
- ]);
- });
-});
-
-const MACHINE = {
- kind: 'ssh-host' as const,
- name: 'dev-vm',
- total: 18,
- managed: 0,
- moving: 0,
- blocked: 0,
- reason: null,
- setUpOnMove: false,
-};
-
-describe('whether moving every agent is complete', () => {
- it('adds the machines up, and is complete once every agent is managed', () => {
- expect(
- moveAllState({
- machines: [
- { ...MACHINE, managed: 18 },
- { ...MACHINE, name: 'This computer', kind: 'this-computer', total: 6, managed: 6 },
- ],
- })
- ).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',
- 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,
- });
- });
-});
-
-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
deleted file mode 100644
index dc5dc76cc..000000000
--- a/console/apps/switch-console-desktop/src/renderer/features/agent-migration/agent-migration-presentation.ts
+++ /dev/null
@@ -1,171 +0,0 @@
-import type {
- AgentMigrationState,
- MigrationOperation,
- MigrationTarget,
- MoveAllMachine,
- MoveAllProgress,
- MoveAllResult,
-} from '@shared/core/agent-migration/agent-migration';
-
-export type MigrationTone = 'neutral' | 'busy' | 'ok' | 'warn' | 'error';
-
-/** The machine, said for a person. */
-export function targetName(target: MigrationTarget | null): string {
- if (!target) return 'a managed machine';
- if (target.kind === 'this-computer')
- return target.machineName ? `this computer (${target.machineName})` : 'this computer';
- return target.machineName ? `${target.sshHost} (${target.machineName})` : target.sshHost;
-}
-
-/** What a move or a return in flight is doing now. */
-export function operationLabel(operation: MigrationOperation): string {
- const moving = operation.kind === 'moving';
- switch (operation.stage) {
- case 'checking':
- return moving ? 'Checking it can move…' : 'Checking it can come back…';
- case 'telling-rooms':
- return 'Telling the rooms it was working in that it is moving…';
- case 'adopting':
- return 'Placing it on the machine…';
- case 'stopping-console-watcher':
- return 'Stopping this Console’s watcher…';
- case 'releasing':
- return moving ? 'Starting it on the machine…' : 'Asking Switch to stop managing it…';
- case 'waiting-for-controller':
- return 'Waiting for the machine to stop it…';
- case 'restoring-console-watcher':
- return 'Starting this Console’s watcher…';
- }
-}
-
-export type MigrationSummary = { label: string; tone: MigrationTone; detail: string | null };
-
-/** One line about where the agent runs, and how that is going. */
-export function migrationSummary(state: AgentMigrationState): MigrationSummary {
- if (state.operation)
- return {
- label: state.operation.kind === 'moving' ? 'Moving…' : 'Coming back…',
- tone: 'busy',
- detail: operationLabel(state.operation),
- };
- if (state.runner === 'console')
- return { label: 'Run by this Console', tone: 'neutral', detail: null };
- const where = targetName(state.target);
- const managed = state.managed;
- if (!managed) return { label: 'Managed', tone: 'ok', detail: `Runs on ${where}.` };
- if (managed.machine.kind === 'removed')
- return {
- label: 'Machine removed',
- tone: 'error',
- detail: `The machine it was moved onto, ${where}, was removed from Switch, so nothing runs this agent now. Stop managing brings it back to this Console.`,
- };
- if (managed.unreadable) return { label: 'Managed', tone: 'warn', detail: managed.unreadable };
- if (managed.machine.kind === 'stopped' && managed.desiredState !== 'stopped')
- return { label: 'Managed, not running', tone: 'warn', detail: managed.machine.reason };
- if (managed.machine.kind === 'unknown')
- return { label: 'Managed', tone: 'warn', detail: managed.machine.reason };
- if (managed.desiredState === 'stopped')
- return { label: 'Managed, stopped', tone: 'neutral', detail: `Placed on ${where}, stopped.` };
- const actual = managed.actual;
- if (!actual)
- return { label: 'Managed', tone: 'busy', detail: `Runs on ${where}; it has not reported yet.` };
- const reason = actual.reason ? ` (${actual.reason.replaceAll('_', ' ')})` : '';
- if (actual.process === 'failed' || actual.process === 'crashed')
- return {
- label: 'Managed, failed',
- tone: 'error',
- detail: `${where}: ${actual.process}${reason}${actual.detail ? ` — ${actual.detail}` : ''}`,
- };
- if (actual.process === 'running')
- return actual.attached
- ? { label: 'Managed', tone: 'ok', detail: `Runs on ${where}.` }
- : {
- label: 'Managed',
- tone: 'warn',
- detail: `Runs on ${where}, but its events are not reaching it yet.`,
- };
- return { label: 'Managed', tone: 'busy', detail: `${where}: ${actual.process}${reason}` };
-}
-
-export type MigrationAction = {
- kind: 'move' | 'return';
- label: string;
- /** Why it cannot run now, or null when it can. */
- disabledReason: string | null;
-};
-
-/** The one action offered for the agent: move it, or bring it back. */
-export function migrationAction(state: AgentMigrationState): MigrationAction {
- const busy = state.operation ? 'Working…' : null;
- if (state.runner === 'managed')
- return { kind: 'return', label: 'Stop managing', disabledReason: busy ?? state.blocker };
- return { kind: 'move', label: 'Move to managed', disabledReason: busy ?? state.blocker };
-}
-
-/** What a "Move all" or "Bring all back" did, for a person. */
-export function moveAllSummary(result: MoveAllResult, verb: 'Moved' | 'Brought back'): string[] {
- const lines: string[] = [];
- lines.push(
- result.moved.length
- ? `${verb} ${result.moved.map((agent) => agent.name).join(', ')}.`
- : `${verb} no agents.`
- );
- for (const agent of result.skipped) lines.push(`${agent.name} did not move: ${agent.reason}`);
- for (const agent of result.failed) lines.push(`${agent.name} failed: ${agent.message}`);
- return lines;
-}
-
-/** Whether "Move all" is complete across the machines: every agent managed. */
-export function moveAllState(progress: MoveAllProgress): {
- tone: MigrationTone;
- label: string;
- managed: number;
- total: number;
-} {
- 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: '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 (machine.blocked > 0)
- return {
- tone: 'warn',
- label:
- machine.blocked === machine.total - machine.managed
- ? 'Blocked'
- : `${machine.blocked} blocked`,
- note: machine.reason,
- };
- 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/managed-agent-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/agent-migration/managed-agent-section.tsx
deleted file mode 100644
index 08967b7de..000000000
--- a/console/apps/switch-console-desktop/src/renderer/features/agent-migration/managed-agent-section.tsx
+++ /dev/null
@@ -1,239 +0,0 @@
-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
-import { ArrowRightLeft, Server, TriangleAlert } from 'lucide-react';
-import { useEffect, useState } from 'react';
-import { agentsStore } from '@renderer/features/locations/stores/agents-store';
-import { failureText } from '@renderer/lib/errors/describe-failure';
-import { events, rpc } from '@renderer/lib/ipc';
-import { Button } from '@renderer/lib/ui/button';
-import {
- Dialog,
- DialogClose,
- DialogContent,
- DialogContentArea,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from '@renderer/lib/ui/dialog';
-import { StatusBadge, type StatusTone } from '@renderer/lib/ui/status-badge';
-import { type AgentMigrationState, MOVE_RULE } from '@shared/core/agent-migration/agent-migration';
-import { agentMigrationChannel } from '@shared/events/agentMigrationEvents';
-import {
- migrationAction,
- migrationSummary,
- type MigrationTone,
- targetName,
-} from './agent-migration-presentation';
-
-const TONE: Record<MigrationTone, StatusTone> = {
- neutral: 'neutral',
- busy: 'info',
- ok: 'success',
- warn: 'warning',
- error: 'danger',
-};
-
-const REFRESH_MS = 10_000;
-
-export function migrationStateKey(agentId: string): readonly unknown[] {
- return ['agent-migration', agentId];
-}
-
-/** Where the agent runs (this Console, or a managed machine), kept fresh. */
-export function useAgentMigrationState(agentId: string) {
- const queryClient = useQueryClient();
- const query = useQuery({
- queryKey: migrationStateKey(agentId),
- queryFn: () => rpc.agentMigration.getState(agentId),
- refetchInterval: REFRESH_MS,
- });
- useEffect(
- () =>
- events.on(agentMigrationChannel, (event) => {
- if (event.agentId !== agentId) return;
- queryClient.setQueryData<AgentMigrationState>(migrationStateKey(agentId), (current) =>
- current ? { ...current, runner: event.runner, operation: event.operation } : current
- );
- if (!event.operation)
- void queryClient.invalidateQueries({ queryKey: migrationStateKey(agentId) });
- }),
- [agentId, queryClient]
- );
- return query;
-}
-
-/**
- * "Move to managed" and "Stop managing" for one agent: hands the agent to
- * Switch's agent management, which runs it on a machine's controller, and
- * brings it back to this Console.
- */
-export function ManagedAgentSection({
- agentId,
- onReturned,
-}: {
- agentId: string;
- /** Called once the agent is back with this Console; null when the page already shows it. */
- onReturned: (() => void) | null;
-}) {
- const queryClient = useQueryClient();
- const query = useAgentMigrationState(agentId);
- const [confirming, setConfirming] = useState<'move' | 'return' | null>(null);
- const refresh = () => {
- void queryClient.invalidateQueries({ queryKey: migrationStateKey(agentId) });
- void queryClient.invalidateQueries({ queryKey: ['shared-host', agentId] });
- };
- const move = useMutation({
- mutationFn: () => rpc.agentMigration.moveToManaged(agentId),
- onSettled: refresh,
- });
- const giveBack = useMutation({
- mutationFn: () => rpc.agentMigration.stopManaging(agentId),
- onSuccess: () => onReturned?.(),
- onSettled: refresh,
- });
- const enable = useMutation({
- mutationFn: () => {
- const agent = agentsStore.agentById(agentId);
- const target = query.data?.target;
- if (!agent?.workspaceId || !target) throw new Error('Open the agent’s workspace first.');
- return target.kind === 'this-computer'
- ? rpc.embeddedController.enable({
- serverId: target.serverId,
- workspaceId: agent.workspaceId,
- })
- : rpc.hostControllers.enable({
- sshHost: target.sshHost,
- serverId: target.serverId,
- workspaceId: agent.workspaceId,
- });
- },
- onSettled: refresh,
- });
-
- const state = query.data;
- if (!state)
- return (
- <p className="text-sm text-foreground-muted">
- {query.error
- ? failureText(query.error, 'Could not tell where this agent runs.')
- : 'Checking where this agent runs…'}
- </p>
- );
-
- const summary = migrationSummary(state);
- const action = migrationAction(state);
- const where = targetName(state.target);
- const failure = move.error ?? giveBack.error ?? enable.error;
- const untold = move.data?.untold ?? [];
-
- return (
- <div className="flex flex-col gap-3 rounded-md border border-border p-3">
- <div className="flex flex-wrap items-center gap-2 text-sm">
- <Server className="size-4 text-foreground-muted" />
- <span className="font-medium">Managed by Switch</span>
- <StatusBadge tone={TONE[summary.tone]} className="ml-auto">
- {summary.label}
- </StatusBadge>
- </div>
- {summary.detail && <p className="text-sm text-foreground-muted">{summary.detail}</p>}
- {state.runner === 'console' && !state.operation && (
- <p className="text-sm text-foreground-muted">
- Move to managed hands this agent to Switch’s agent management, which runs it on {where}{' '}
- instead of this Console. {MOVE_RULE}
- </p>
- )}
- {state.runner === 'managed' &&
- !state.operation &&
- state.managed?.machine.kind !== 'removed' && (
- <p className="text-sm text-foreground-muted">
- This Console does not run it while it is managed: its room watcher here is off and its
- sessions run on the machine. Stop managing brings it back. {MOVE_RULE}
- </p>
- )}
- {untold.length > 0 && (
- <p role="alert" className="text-sm text-foreground-muted">
- Moved. {untold.length === 1 ? 'One room' : `${untold.length} rooms`} where it was working
- could not be told the request was cut off: {untold.map((room) => room.reason).join('; ')}
- </p>
- )}
- {state.blocker && !state.operation && (
- <p role="alert" className="text-sm text-foreground-muted">
- {state.blocker}
- </p>
- )}
- {failure && (
- <p role="alert" className="text-sm break-words text-destructive">
- {failureText(failure, 'That did not work.')}
- </p>
- )}
- <div className="flex flex-wrap items-center gap-2">
- <Button
- variant="outline"
- size="sm"
- disabled={action.disabledReason !== null || move.isPending || giveBack.isPending}
- onClick={() => {
- move.reset();
- giveBack.reset();
- setConfirming(action.kind);
- }}
- >
- <ArrowRightLeft className="size-3.5" /> {action.label}
- </Button>
- {state.canEnableTarget && state.target && (
- <Button
- variant="outline"
- size="sm"
- disabled={enable.isPending}
- onClick={() => enable.mutate()}
- >
- {state.target.kind === 'this-computer'
- ? 'Run managed agents on this computer'
- : `Run managed agents on ${state.target.sshHost}`}
- </Button>
- )}
- </div>
-
- <Dialog open={confirming !== null} onOpenChange={(open) => !open && setConfirming(null)}>
- <DialogContent>
- <DialogHeader>
- <TriangleAlert className="size-4 text-amber-500" />
- <DialogTitle>
- {confirming === 'move' ? `Move it to ${where}?` : 'Bring it back to this Console?'}
- </DialogTitle>
- </DialogHeader>
- <DialogContentArea>
- <DialogDescription>
- {confirming === 'move'
- ? `Switch’s agent management will run this agent on ${where}, and this Console stops running it. ${MOVE_RULE}`
- : `Switch stops managing this agent, the machine stops it, and this Console runs it again. ${MOVE_RULE}`}
- </DialogDescription>
- {confirming === 'move' && state.notCarried.length > 0 && (
- <div className="mt-3 space-y-1 text-sm">
- <p className="font-medium">Not carried over to the managed agent:</p>
- <ul className="list-disc space-y-1 pl-5 text-foreground-muted">
- {state.notCarried.map((line) => (
- <li key={line}>{line}</li>
- ))}
- </ul>
- </div>
- )}
- </DialogContentArea>
- <DialogFooter>
- <DialogClose render={<Button variant="outline" size="sm" />}>Cancel</DialogClose>
- <Button
- size="sm"
- onClick={() => {
- const kind = confirming;
- setConfirming(null);
- if (kind === 'move') move.mutate();
- else giveBack.mutate();
- }}
- >
- {confirming === 'move' ? 'Move to managed' : 'Stop managing'}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- </div>
- );
-}
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
deleted file mode 100644
index b2e637ab8..000000000
--- a/console/apps/switch-console-desktop/src/renderer/features/agent-migration/move-all-agents.tsx
+++ /dev/null
@@ -1,198 +0,0 @@
-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/locations/components/settings-view/sidecar-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sidecar-panel.tsx
index 177c945e6..3c95f7f69 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sidecar-panel.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sidecar-panel.tsx
@@ -1,14 +1,12 @@
-import { useQuery } from '@tanstack/react-query';
+import { useQuery, useQueryClient } from '@tanstack/react-query';
import { observer } from 'mobx-react-lite';
-import {
- ManagedAgentSection,
- useAgentMigrationState,
-} from '@renderer/features/agent-migration/managed-agent-section';
+import { useEffect } from 'react';
import { SectionLabel } from '@renderer/features/locations/components/main-panel/agent-page-section';
import { SidecarSettingsSection } from '@renderer/features/locations/components/settings-view/sections/sidecar-settings-section';
-import { rpc } from '@renderer/lib/ipc';
+import { events, rpc } from '@renderer/lib/ipc';
import { useParams } from '@renderer/lib/layout/navigation-provider';
import { Spinner } from '@renderer/lib/ui/spinner';
+import { agentMigrationChannel } from '@shared/events/agentMigrationEvents';
export const SidecarPanel = observer(function SidecarPanel() {
const {
@@ -37,15 +35,35 @@ export const SidecarPanel = observer(function SidecarPanel() {
return (
<section className="flex flex-col gap-4">
<SectionLabel>Room watcher</SectionLabel>
- <ManagedAgentSection agentId={agent.id} onReturned={null} />
<ConsoleWatcher agentId={agent.id} />
</section>
);
});
-/** This Console's own watcher for the agent, which a managed agent does not have. */
+/**
+ * This Console's own watcher for the agent. A managed agent has none: Switch
+ * runs it on a machine's agents controller.
+ */
function ConsoleWatcher({ agentId }: { agentId: string }) {
- const migration = useAgentMigrationState(agentId);
- if (migration.data?.runner === 'managed') return null;
+ const queryClient = useQueryClient();
+ const runner = useQuery({
+ queryKey: ['agent-runner', agentId],
+ queryFn: () => rpc.agentMigration.getRunner(agentId),
+ });
+ useEffect(
+ () =>
+ events.on(agentMigrationChannel, (event) => {
+ if (event.agentId === agentId)
+ queryClient.setQueryData(['agent-runner', agentId], event.runner);
+ }),
+ [agentId, queryClient]
+ );
+ if (runner.data === 'managed')
+ return (
+ <p className="text-sm text-foreground-muted">
+ Switch runs this agent on a machine’s agents controller, so this Console does not watch its
+ rooms.
+ </p>
+ );
return <SidecarSettingsSection agentId={agentId} />;
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-page.tsx b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-page.tsx
index 58b8f9366..968c28c8a 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-page.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-page.tsx
@@ -1,8 +1,6 @@
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { Plus } from 'lucide-react';
-import { observer } from 'mobx-react-lite';
import { useMemo, useState } from 'react';
-import { ManagedAgentSection } from '@renderer/features/agent-migration/managed-agent-section';
import { LocalDirectorySelector } from '@renderer/features/locations/components/add-agent-modal/local-directory-selector';
import type {
FormState,
@@ -25,11 +23,9 @@ import {
import { AutoApproveRow } from '@renderer/features/locations/components/settings-view/sections/auto-approve-settings-section';
import { CanManageAgentsRow } from '@renderer/features/locations/components/settings-view/sections/can-manage-agents-settings-section';
import { SettingRow } from '@renderer/features/locations/components/settings-view/sections/setting-row';
-import { agentsStore } from '@renderer/features/locations/stores/agents-store';
import { AgentIconPicker } from '@renderer/lib/components/agent-icon-picker';
import { failureText } from '@renderer/lib/errors/describe-failure';
import { rpc } from '@renderer/lib/ipc';
-import { useNavigate } from '@renderer/lib/layout/navigation-provider';
import { useShowModal } from '@renderer/lib/modal/modal-provider';
import { workspaceAgentsQueryKey } from '@renderer/lib/stores/use-workspace-agents';
import { Badge } from '@renderer/lib/ui/badge';
@@ -354,8 +350,6 @@ function ManagedAgentPageContent({ agent }: { agent: ManagedAgentView }) {
Sessions of agents on a machine are not listed here yet.
</p>
</section>
-
- <MovedFromConsole agent={agent} />
</div>
</div>
{error && (
@@ -424,27 +418,3 @@ function WithReason({ reason, children }: { reason: string; children: React.Reac
</TooltipProvider>
);
}
-
-/**
- * An agent moved to managed from this Console still has its entry here, which
- * is what bringing it back needs: "Stop managing" lives with it.
- */
-const MovedFromConsole = observer(function MovedFromConsole({
- agent,
-}: {
- agent: ManagedAgentView;
-}) {
- const { navigate } = useNavigate();
- const local = agentsStore
- .agentsOnServer(agent.serverId)
- .find((candidate) => candidate.switchAgentId === agent.agentId);
- if (!local) return null;
- return (
- <ManagedAgentSection
- agentId={local.id}
- onReturned={() =>
- navigate('location', { locationId: local.locationId, agentName: local.name })
- }
- />
- );
-});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/host-machine-card.tsx b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/host-machine-card.tsx
deleted file mode 100644
index 5291f4d98..000000000
--- a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/host-machine-card.tsx
+++ /dev/null
@@ -1,320 +0,0 @@
-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
-import { RefreshCw, Server, TriangleAlert } from 'lucide-react';
-import { useEffect, useState } from 'react';
-import { moveAllSummary } from '@renderer/features/agent-migration/agent-migration-presentation';
-import { failureText } from '@renderer/lib/errors/describe-failure';
-import { useStateBoundFailure } from '@renderer/lib/hooks/use-state-bound-failure';
-import { events, rpc } from '@renderer/lib/ipc';
-import { Button } from '@renderer/lib/ui/button';
-import {
- Dialog,
- DialogClose,
- DialogContent,
- DialogContentArea,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from '@renderer/lib/ui/dialog';
-import { StatusBadge, type StatusTone } from '@renderer/lib/ui/status-badge';
-import { Switch } from '@renderer/lib/ui/switch';
-import { MOVE_RULE } from '@shared/core/agent-migration/agent-migration';
-import type { HostControllerOverview } from '@shared/core/host-controllers/host-controllers';
-import { hostControllerStateChannel } from '@shared/events/hostControllerEvents';
-import {
- canRestartHost,
- failureAlreadyShown,
- hostAgentActual,
- type HostMachineTone,
- hostMachineStatus,
- hostStateKey,
- hostToggleBlocker,
- hostUnknownToServer,
- supervisionNote,
-} from './host-machine';
-
-const REFRESH_MS = 15_000;
-
-const TONE: Record<HostMachineTone, StatusTone> = {
- neutral: 'neutral',
- busy: 'info',
- ok: 'success',
- warn: 'warning',
- error: 'danger',
-};
-
-function overviewKey(sshHost: string, serverId: string): readonly unknown[] {
- return ['host-controller', sshHost, serverId];
-}
-
-/**
- * "This host as a machine": the agents controller Console installs and runs on
- * an SSH host for a Switch server, the managed agents placed there, and moving
- * this Console's agents on the host onto it.
- */
-export function HostMachineCard({
- sshHost,
- serverId,
- workspaceId,
-}: {
- sshHost: string;
- serverId: string;
- workspaceId: string | null;
-}) {
- const queryClient = useQueryClient();
- const key = overviewKey(sshHost, serverId);
- const [confirmingOff, setConfirmingOff] = useState(false);
- const [outcome, setOutcome] = useState<string[] | null>(null);
- const query = useQuery({
- queryKey: [...key, workspaceId],
- queryFn: () => rpc.hostControllers.getOverview({ sshHost, serverId, workspaceId }),
- refetchInterval: REFRESH_MS,
- });
- useEffect(
- () =>
- events.on(hostControllerStateChannel, (event) => {
- if (event.sshHost !== sshHost || event.serverId !== serverId) return;
- void queryClient.invalidateQueries({ queryKey: overviewKey(sshHost, serverId) });
- }),
- [queryClient, sshHost, serverId]
- );
- const refresh = async () => {
- await Promise.all([
- queryClient.invalidateQueries({ queryKey: key }),
- queryClient.invalidateQueries({ queryKey: ['agent-migration'] }),
- ]);
- };
- const failed = useStateBoundFailure(query.data ? hostStateKey(query.data) : null);
- const handlers = {
- onSuccess: async () => {
- failed.clear();
- await refresh();
- },
- onError: async (error: Error) => {
- await refresh();
- const fresh = queryClient.getQueryData<HostControllerOverview>([...key, workspaceId]);
- failed.fail(error, fresh ? hostStateKey(fresh) : null);
- },
- };
- const enable = useMutation({
- mutationFn: () => {
- if (!workspaceId) throw new Error('Open a workspace on this server first.');
- return rpc.hostControllers.enable({ sshHost, serverId, workspaceId });
- },
- ...handlers,
- });
- const disable = useMutation({
- mutationFn: () => rpc.hostControllers.disable({ sshHost, serverId }),
- ...handlers,
- });
- const restart = useMutation({
- mutationFn: () => rpc.hostControllers.restart({ sshHost, serverId }),
- ...handlers,
- });
- const enrollAgain = useMutation({
- mutationFn: () => rpc.hostControllers.enrollAgain({ sshHost, serverId }),
- ...handlers,
- });
- const moveAll = useMutation({
- mutationFn: () => rpc.hostControllers.moveAll(sshHost),
- ...handlers,
- onSuccess: async (result) => {
- setOutcome(moveAllSummary(result, 'Moved'));
- await handlers.onSuccess();
- },
- });
- const bringBack = useMutation({
- mutationFn: () => rpc.hostControllers.stopManagingAll(sshHost),
- ...handlers,
- onSuccess: async (result) => {
- setOutcome(moveAllSummary(result, 'Brought back'));
- await handlers.onSuccess();
- },
- });
-
- const overview = query.data;
- if (!overview)
- return (
- <section className="rounded-lg border border-border p-4">
- <Heading />
- <p className="mt-2 text-xs text-foreground-muted">
- {query.error ? failureText(query.error, 'Could not read the host’s state.') : 'Loading…'}
- </p>
- </section>
- );
-
- const status = hostMachineStatus(overview);
- const blocker = hostToggleBlocker(overview);
- const checked = overview.enrollment !== null || overview.phase.kind === 'installing';
- const note = supervisionNote(overview);
- const running = overview.enrollment !== null && overview.process?.kind === 'running';
- const failure =
- failed.failure && !failureAlreadyShown(overview, failed.failure.message)
- ? failed.failure
- : null;
- const moving = moveAll.isPending || bringBack.isPending;
-
- return (
- <section className="space-y-3 rounded-lg border border-border p-4">
- <div className="flex items-start justify-between gap-3">
- <Heading />
- <div className="flex shrink-0 items-center gap-2">
- <StatusBadge tone={TONE[status.tone]}>{status.label}</StatusBadge>
- <Switch
- aria-label="Run managed agents on this host"
- checked={checked}
- disabled={blocker !== null}
- onCheckedChange={(next) => {
- failed.clear();
- if (next) enable.mutate();
- else setConfirmingOff(true);
- }}
- />
- </div>
- </div>
- {blocker && blocker !== 'Working…' && (
- <p className="text-xs text-foreground-muted">{blocker}</p>
- )}
- {status.detail && (
- <p
- className={`text-xs break-words whitespace-pre-wrap ${status.tone === 'error' ? 'text-foreground-error' : 'text-foreground-muted'}`}
- >
- {status.detail}
- </p>
- )}
- {note && <p className="text-xs text-foreground-muted">{note}</p>}
- {failure && (
- <p className="text-xs break-words text-foreground-error">
- {failureText(failure, 'That did not work.')}
- </p>
- )}
- {hostUnknownToServer(overview) && (
- <Button
- variant="outline"
- size="sm"
- disabled={enrollAgain.isPending}
- onClick={() => enrollAgain.mutate()}
- >
- <RefreshCw className="size-4" /> {enrollAgain.isPending ? 'Enrolling…' : 'Enroll again'}
- </Button>
- )}
- {canRestartHost(overview) && !hostUnknownToServer(overview) && (
- <Button
- variant="outline"
- size="sm"
- disabled={restart.isPending}
- onClick={() => restart.mutate()}
- >
- <RefreshCw className="size-4" /> Start again
- </Button>
- )}
-
- {overview.remote?.kind === 'ok' && overview.enrollment && (
- <ul className="divide-y divide-border rounded-lg border border-border">
- {overview.remote.agents.length === 0 && (
- <li className="px-3 py-2 text-xs text-foreground-muted">
- No managed agents are placed on this host yet.
- </li>
- )}
- {overview.remote.agents.map((agent) => {
- const actual = hostAgentActual(overview, agent);
- return (
- <li key={agent.agentId} className="flex items-center justify-between gap-3 px-3 py-2">
- <div className="min-w-0">
- <p className="truncate text-sm text-foreground">
- {agent.displayName ?? agent.name}
- </p>
- <p className="truncate text-xs text-foreground-muted">
- {agent.provider} · wanted {agent.desiredState}
- {actual.detail ? ` · ${actual.detail}` : ''}
- </p>
- </div>
- <StatusBadge tone={TONE[actual.tone]} className="shrink-0">
- {actual.label}
- </StatusBadge>
- </li>
- );
- })}
- </ul>
- )}
-
- {running && (
- <div className="space-y-2 rounded-lg border border-border px-3 py-2">
- <p className="text-sm text-foreground">Agents this Console runs on this host</p>
- <p className="text-xs text-foreground-muted">
- Move them onto the host’s controller, so Switch manages them. {MOVE_RULE}
- </p>
- {overview.movedAgents.length > 0 && (
- <p className="text-xs text-foreground-muted">
- Moved here: {overview.movedAgents.join(', ')}.
- </p>
- )}
- <div className="flex flex-wrap gap-2">
- <Button variant="outline" size="sm" disabled={moving} onClick={() => moveAll.mutate()}>
- {moveAll.isPending ? 'Moving…' : 'Move all'}
- </Button>
- <Button
- variant="ghost"
- size="sm"
- disabled={moving || overview.movedAgents.length === 0}
- 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>
- )}
- </div>
- )}
-
- <Dialog open={confirmingOff} onOpenChange={setConfirmingOff}>
- <DialogContent>
- <DialogHeader>
- <TriangleAlert className="size-4 text-amber-500" />
- <DialogTitle>Stop running managed agents on {sshHost}?</DialogTitle>
- </DialogHeader>
- <DialogContentArea>
- <DialogDescription>
- This removes the host from Switch as a machine, stops the managed agents placed on it
- and removes the controller’s identity from the host. The agents stay defined in
- Switch, and can be placed on another machine.
- </DialogDescription>
- </DialogContentArea>
- <DialogFooter>
- <DialogClose render={<Button variant="outline" size="sm" />}>Cancel</DialogClose>
- <Button
- variant="destructive"
- size="sm"
- onClick={() => {
- setConfirmingOff(false);
- disable.mutate();
- }}
- >
- Remove this host
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- </section>
- );
-}
-
-function Heading() {
- return (
- <div className="flex min-w-0 items-start gap-2">
- <Server className="mt-0.5 size-4 shrink-0 text-foreground-muted" />
- <div className="min-w-0 space-y-0.5">
- <h3 className="text-sm font-medium text-foreground">This host as a machine</h3>
- <p className="text-xs text-foreground-muted">
- Run managed agents on this host: Console installs Switch’s agents controller here, and
- Switch can place agents on it. It keeps running when Console is closed.
- </p>
- </div>
- </div>
- );
-}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/host-machine.test.ts b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/host-machine.test.ts
deleted file mode 100644
index ffe1d43bf..000000000
--- a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/host-machine.test.ts
+++ /dev/null
@@ -1,243 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import type { PlacedManagedAgent } from '@shared/core/embedded-controller/embedded-controller';
-import type { HostControllerOverview } from '@shared/core/host-controllers/host-controllers';
-import {
- canRestartHost,
- failureAlreadyShown,
- hostAgentActual,
- hostMachineStatus,
- hostStateKey,
- hostToggleBlocker,
- hostUnknownToServer,
- supervisionNote,
-} from './host-machine';
-
-const OFF: HostControllerOverview = {
- sshHost: 'build-box',
- serverId: 'server-1',
- enrollment: null,
- phase: { kind: 'off' },
- process: null,
- remote: { kind: 'ok', controller: null, agents: [] },
- movedAgents: [],
-};
-
-const ON: HostControllerOverview = {
- ...OFF,
- enrollment: {
- controllerId: 'controller-1',
- name: 'build-box.internal',
- workspaceId: 'workspace-1',
- supervision: 'systemd',
- enrolledAt: '2026-10-01T00:00:00Z',
- },
- process: { kind: 'running' },
- remote: { kind: 'ok', controller: { state: 'online', lastSeenAt: null }, agents: [] },
-};
-
-describe('the state of a host as a machine', () => {
- it('is off until it is set up, saying why a set-up failed', () => {
- expect(hostMachineStatus(OFF)).toEqual({ label: 'Off', tone: 'neutral', detail: null });
- expect(
- hostMachineStatus({ ...OFF, phase: { kind: 'error', message: 'Node 20 is too old.' } })
- ).toEqual({ label: 'Off', tone: 'error', detail: 'Node 20 is too old.' });
- expect(
- hostMachineStatus({ ...OFF, phase: { kind: 'installing', step: 'Enrolling the host…' } })
- ).toEqual({ label: 'Setting up…', tone: 'busy', detail: 'Enrolling the host…' });
- });
-
- it('says Switch no longer knows the host when it is enrolled but not listed, whatever its process does', () => {
- const unknown = { ...ON, remote: { kind: 'ok' as const, controller: null, agents: [] } };
- expect(hostUnknownToServer(unknown)).toBe(true);
- expect(hostMachineStatus(unknown)).toMatchObject({
- label: 'Unknown to Switch',
- tone: 'error',
- detail: expect.stringContaining('Switch no longer knows build-box as a machine'),
- });
- const stopped = {
- ...unknown,
- process: { kind: 'stopped' as const, state: 'exited', code: 1, log: '' },
- };
- expect(hostMachineStatus(stopped).label).toBe('Unknown to Switch');
- expect(hostMachineStatus({ ...unknown, movedAgents: ['jack'] }).detail).toContain('jack');
- expect(hostUnknownToServer(OFF)).toBe(false);
- expect(hostUnknownToServer(ON)).toBe(false);
- });
-
- it('is running when the host runs it and Switch sees it', () => {
- expect(hostMachineStatus(ON)).toEqual({ label: 'Running', tone: 'ok', detail: null });
- });
-
- it('says why it is not running, with the last thing it logged', () => {
- const status = hostMachineStatus({
- ...ON,
- process: { kind: 'stopped', state: 'exited', code: 2, log: 'bad bundle' },
- });
- expect(status).toMatchObject({ label: 'Stopped', tone: 'error' });
- expect(status.detail).toContain('configuration error');
- expect(status.detail).toContain('bad bundle');
- expect(
- hostMachineStatus({ ...ON, process: { kind: 'stopped', state: 'exited', code: 3, log: '' } })
- .label
- ).toBe('Removed');
- });
-
- it('says a controller whose process went away is not running, never that it is', () => {
- const rebooted: HostControllerOverview = {
- ...ON,
- enrollment: { ...ON.enrollment!, supervision: 'detached' },
- process: {
- kind: 'stopped',
- state: 'gone',
- code: null,
- log: 'INFO Started agent {"agentId":"agent-1"}',
- },
- };
- const status = hostMachineStatus(rebooted);
- expect(status).toMatchObject({ label: 'Stopped', tone: 'error' });
- expect(status.detail).toBe(
- 'The controller is not running. Its process is gone without saying why: the host may have restarted, or the process was killed.\n' +
- 'The last lines it logged:\nINFO Started agent {"agentId":"agent-1"}'
- );
- expect(canRestartHost(rebooted)).toBe(true);
- for (const state of ['running', 'restarting', 'active'])
- expect(
- hostMachineStatus({ ...ON, process: { kind: 'stopped', state, code: null, log: '' } })
- .detail
- ).not.toMatch(/It is running|reports it running|reports it active/);
- });
-
- it('says what the supervisor reports for the other ways it stops', () => {
- const detail = (state: string, code: number | null = null) =>
- hostMachineStatus({ ...ON, process: { kind: 'stopped', state, code, log: '' } }).detail;
- expect(detail('stopped')).toBe('The controller is not running. It was stopped.');
- expect(detail('never-started')).toBe(
- 'The controller is not running. It has not been started on this host.'
- );
- expect(detail('exited', 0)).toBe('The controller is not running. It exited with code 0.');
- expect(detail('failed', 1)).toBe(
- 'The controller is not running. systemd reports that it failed.'
- );
- });
-
- it('does not claim to know when the host cannot be asked', () => {
- expect(
- hostMachineStatus({ ...ON, process: { kind: 'unknown', reason: 'unreachable' } })
- ).toEqual({
- label: 'Unknown',
- tone: 'warn',
- detail: 'Console cannot tell whether the controller runs: unreachable',
- });
- });
-
- it('is disconnected while the controller has not reached Switch', () => {
- expect(
- hostMachineStatus({
- ...ON,
- remote: { kind: 'ok', controller: { state: 'unknown', lastSeenAt: null }, agents: [] },
- })
- ).toMatchObject({ label: 'Disconnected', tone: 'warn' });
- });
-
- it('says how it is kept running', () => {
- expect(supervisionNote(ON)).toContain('systemd');
- expect(
- supervisionNote({ ...ON, enrollment: { ...ON.enrollment!, supervision: 'detached' } })
- ).toContain('Start again');
- expect(supervisionNote(OFF)).toBeNull();
- });
-});
-
-describe('the toggle', () => {
- it('needs a server with agent management to turn on', () => {
- expect(hostToggleBlocker(OFF)).toBeNull();
- expect(hostToggleBlocker({ ...OFF, remote: { kind: 'unavailable' } })).toMatch(
- /agent management/
- );
- expect(hostToggleBlocker({ ...OFF, remote: null })).toMatch(/workspace/);
- });
-
- it('needs the agents moved from this Console back before turning off', () => {
- expect(hostToggleBlocker(ON)).toBeNull();
- expect(hostToggleBlocker({ ...ON, movedAgents: ['builder'] })).toMatch(/builder/);
- });
-
- it('is held while setting up or removing', () => {
- expect(hostToggleBlocker({ ...ON, phase: { kind: 'removing' } })).toBe('Working…');
- });
-});
-
-describe('starting it again', () => {
- it('is offered for a stopped controller, but not a revoked one', () => {
- expect(canRestartHost(ON)).toBe(false);
- expect(
- canRestartHost({ ...ON, process: { kind: 'stopped', state: 'exited', code: 1, log: '' } })
- ).toBe(true);
- expect(
- canRestartHost({ ...ON, process: { kind: 'stopped', state: 'exited', code: 3, log: '' } })
- ).toBe(false);
- });
-});
-
-describe('the managed agents placed on the host', () => {
- const AGENT: PlacedManagedAgent = {
- agentId: 'agent-1',
- name: 'builder',
- displayName: null,
- provider: 'claude',
- desiredState: 'running',
- actual: { process: 'running', attached: true, reason: null, detail: 'pid 4242' },
- };
-
- it('read as the controller reports them while it runs', () => {
- expect(hostAgentActual(ON, AGENT)).toEqual({
- label: 'running',
- tone: 'ok',
- detail: 'pid 4242',
- });
- });
-
- it('read as not running while the controller is stopped, whatever they last reported', () => {
- const stopped: HostControllerOverview = {
- ...ON,
- process: { kind: 'stopped', state: 'gone', code: null, log: '' },
- };
- expect(hostAgentActual(stopped, AGENT)).toEqual({
- label: 'not running',
- tone: 'warn',
- detail: 'the controller is not running',
- });
- expect(hostAgentActual(stopped, { ...AGENT, desiredState: 'stopped' }).tone).toBe('neutral');
- });
-
- it('read as unknown while Console cannot tell whether the controller runs', () => {
- expect(
- hostAgentActual({ ...ON, process: { kind: 'unknown', reason: 'unreachable' } }, AGENT)
- ).toMatchObject({ label: 'unknown', tone: 'warn' });
- });
-});
-
-describe('a failure shown on the card', () => {
- it('outlives a re-read of the same state, not a change of it', () => {
- const refusedIn = hostStateKey({ ...ON, movedAgents: ['builder'] });
- expect(hostStateKey({ ...ON, movedAgents: ['builder'] })).toBe(refusedIn);
- expect(hostStateKey(ON)).not.toBe(refusedIn);
- expect(
- hostStateKey({
- ...ON,
- movedAgents: ['builder'],
- process: { kind: 'stopped', state: 'gone', code: null, log: '' },
- })
- ).not.toBe(refusedIn);
- });
-
- it('is not repeated when the status line already shows it', () => {
- const failed: HostControllerOverview = {
- ...ON,
- phase: { kind: 'error', message: 'build-box runs Node 20.11.0.' },
- };
- expect(failureAlreadyShown(failed, 'build-box runs Node 20.11.0.')).toBe(true);
- expect(failureAlreadyShown(failed, 'Switch is down.')).toBe(false);
- expect(failureAlreadyShown(ON, 'build-box runs Node 20.11.0.')).toBe(false);
- });
-});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/host-machine.ts b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/host-machine.ts
deleted file mode 100644
index f788ef0f1..000000000
--- a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/host-machine.ts
+++ /dev/null
@@ -1,214 +0,0 @@
-import { agentActual } from '@renderer/features/switch-servers/this-computer-machine';
-import type { PlacedManagedAgent } from '@shared/core/embedded-controller/embedded-controller';
-import type {
- HostControllerOverview,
- HostControllerProcess,
-} from '@shared/core/host-controllers/host-controllers';
-
-export type HostMachineTone = 'neutral' | 'busy' | 'ok' | 'warn' | 'error';
-
-export type HostMachineStatus = { label: string; tone: HostMachineTone; detail: string | null };
-
-type StoppedProcess = Extract<HostControllerProcess, { kind: 'stopped' }>;
-
-/**
- * Why a stopped controller is not running. The supervisor's word for its
- * state is never repeated as is: a process the host reports stopped is not
- * running, whatever word was left behind.
- */
-function stoppedReason(process: StoppedProcess): string {
- if (process.code === 3) return 'Switch removed this host as a machine.';
- if (process.code === 2) return 'It stopped on a configuration error.';
- if (process.code === 4) return 'Another copy of this controller took over.';
- switch (process.state) {
- case 'never-started':
- return 'It has not been started on this host.';
- case 'stopped':
- return 'It was stopped.';
- case 'exited':
- return process.code === null ? 'It exited.' : `It exited with code ${process.code}.`;
- case 'failed':
- return 'systemd reports that it failed.';
- case 'inactive':
- return 'systemd reports it inactive.';
- case 'gone':
- case 'running':
- case 'restarting':
- case 'active':
- case 'activating':
- case 'reloading':
- return 'Its process is gone without saying why: the host may have restarted, or the process was killed.';
- default:
- return `Its supervisor reports it ${process.state}.`;
- }
-}
-
-/** One line of state for "This host as a machine". */
-export function hostMachineStatus(overview: HostControllerOverview): HostMachineStatus {
- const { phase, enrollment, process, remote } = overview;
- if (phase.kind === 'installing')
- return { label: 'Setting up…', tone: 'busy', detail: phase.step };
- if (phase.kind === 'removing')
- return {
- label: 'Turning off…',
- tone: 'busy',
- detail: 'Removing the host from Switch and stopping its managed agents.',
- };
- if (!enrollment) {
- if (phase.kind === 'error') return { label: 'Off', tone: 'error', detail: phase.message };
- return { label: 'Off', tone: 'neutral', detail: null };
- }
- const failed = phase.kind === 'error' ? phase.message : null;
- if (hostUnknownToServer(overview)) {
- const why = `Switch no longer knows ${overview.sshHost} as a machine (its data was reset or restored, or the machine was deleted), so its controller cannot sign in. Enroll it again.`;
- return {
- label: 'Unknown to Switch',
- tone: 'error',
- detail: overview.movedAgents.length
- ? `${why} ${overview.movedAgents.join(', ')}, moved here from this Console, then need Stop managing, and can be moved again.`
- : why,
- };
- }
- if (process?.kind === 'unknown')
- return {
- label: 'Unknown',
- tone: 'warn',
- detail: `Console cannot tell whether the controller runs: ${process.reason}`,
- };
- if (process?.kind === 'stopped')
- return {
- label: process.code === 3 ? 'Removed' : 'Stopped',
- tone: 'error',
- detail: [
- failed,
- `The controller is not running. ${stoppedReason(process)}`,
- process.log ? `The last lines it logged:\n${process.log}` : null,
- ]
- .filter(Boolean)
- .join('\n'),
- };
- if (remote?.kind === 'error')
- return {
- label: 'Running',
- tone: 'warn',
- detail: `The controller runs, but Switch could not be asked how it sees it: ${remote.message}`,
- };
- if (remote?.kind === 'unavailable')
- return {
- label: 'Disconnected',
- tone: 'warn',
- detail: 'This server no longer has agent management turned on.',
- };
- const state = remote?.kind === 'ok' ? (remote.controller?.state ?? null) : null;
- if (remote?.kind === 'ok' && state !== 'online')
- return {
- label: state === 'revoked' ? 'Removed' : 'Disconnected',
- tone: state === 'revoked' ? 'error' : 'warn',
- detail:
- state === 'revoked'
- ? 'Switch has removed this host; its controller is stopping its agents.'
- : 'The controller runs but has not reached Switch recently. It keeps trying.',
- };
- return { label: 'Running', tone: failed ? 'warn' : 'ok', detail: failed };
-}
-
-/** How the controller is kept running, said for a person. */
-export function supervisionNote(overview: HostControllerOverview): string | null {
- const supervision = overview.enrollment?.supervision;
- if (supervision === 'systemd')
- return 'A systemd user unit keeps it running, also after the host restarts.';
- if (supervision === 'detached')
- return 'A background process keeps it running while the host is up (this host has no lingering systemd user session). After the host restarts, press Start again.';
- return null;
-}
-
-/**
- * Why the toggle cannot be moved now, or null when it can. Turning it on needs
- * a workspace and a server with agent management; turning it off needs the
- * agents moved from this Console brought back first.
- */
-export function hostToggleBlocker(overview: HostControllerOverview): string | null {
- const { phase, enrollment, remote } = overview;
- if (phase.kind === 'installing' || phase.kind === 'removing') return 'Working…';
- if (enrollment) {
- if (overview.movedAgents.length)
- return `Bring back ${overview.movedAgents.join(', ')} before turning it off.`;
- return null;
- }
- if (remote === null) return 'Open a workspace on this server to add the host to it.';
- if (remote.kind === 'unavailable')
- return 'This server does not have agent management turned on, so it cannot place agents on machines.';
- if (remote.kind === 'error') return `Switch could not be asked: ${remote.message}`;
- return null;
-}
-
-/** Start again is offered when the controller is enrolled and not running. */
-export function canRestartHost(overview: HostControllerOverview): boolean {
- return (
- overview.enrollment !== null &&
- overview.phase.kind !== 'installing' &&
- overview.phase.kind !== 'removing' &&
- overview.process?.kind === 'stopped' &&
- overview.process.code !== 3
- );
-}
-
-export type HostAgentActual = { label: string; tone: HostMachineTone; detail: string | null };
-
-/**
- * What a managed agent placed on the host is doing. The controller's last
- * report holds only while the controller runs: with it stopped, or with
- * Console unable to tell, nothing on the host runs the agent, whatever it
- * reported before.
- */
-export function hostAgentActual(
- overview: HostControllerOverview,
- agent: PlacedManagedAgent
-): HostAgentActual {
- const process = overview.process;
- if (process?.kind === 'stopped')
- return {
- label: 'not running',
- tone: agent.desiredState === 'running' ? 'warn' : 'neutral',
- detail: 'the controller is not running',
- };
- if (process?.kind === 'unknown')
- return {
- label: 'unknown',
- tone: 'warn',
- detail: 'Console cannot tell whether the controller runs',
- };
- return { ...agentActual(agent), detail: agent.actual?.detail ?? null };
-}
-
-/**
- * What the card's state is, for telling whether a failure shown on it still
- * describes it: the phase, the enrollment, whether the controller runs (and
- * how it stopped) and the agents moved here.
- */
-export function hostStateKey(overview: HostControllerOverview): string {
- const { process } = overview;
- return JSON.stringify([
- overview.phase.kind,
- overview.enrollment?.controllerId ?? null,
- process?.kind ?? null,
- process?.kind === 'stopped' ? process.code : null,
- overview.movedAgents,
- ]);
-}
-
-/** Whether a failed action's message is already on the card, as the failure Console keeps for the host. */
-export function failureAlreadyShown(overview: HostControllerOverview, message: string): boolean {
- return overview.phase.kind === 'error' && overview.phase.message.trim() === message.trim();
-}
-
-/** Switch answered, and does not list the machine this host is enrolled as. */
-export function hostUnknownToServer(overview: HostControllerOverview): boolean {
- return (
- overview.enrollment !== null &&
- overview.phase.kind !== 'installing' &&
- overview.phase.kind !== 'removing' &&
- overview.remote?.kind === 'ok' &&
- overview.remote.controller === null
- );
-}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/remove-host-failure.test.ts b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/remove-host-failure.test.ts
index 40c5a39aa..5af9e963e 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/remove-host-failure.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/remove-host-failure.test.ts
@@ -13,7 +13,7 @@ function rpcError(code: string, message: string): RpcError {
describe('a host removal that did not happen', () => {
it('says why it was refused, with the way out, when agents moved there still run on it', () => {
const message =
- 'build-box runs builder for this Console, so it cannot be removed yet. Bring the agents back first: Bring all back on the host’s page, or Stop managing on each agent.';
+ 'build-box runs builder as managed agents for this Console, so it cannot be removed yet. Delete those agents first.';
expect(removeHostFailureToast('Build Box', rpcError('MovedAgentsHereError', message))).toEqual({
title: 'Build Box was not removed',
description: message,
diff --git a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-host-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-host-view.tsx
index 4499fe5ec..271f4b5d3 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-host-view.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-host-view.tsx
@@ -38,7 +38,6 @@ import { deriveHostStatus } from '@shared/core/remote-hosts/host-status';
import { isHostBlocked } from '@shared/core/remote-hosts/reachability';
import { switchServersStore } from '../../switch-servers/switch-servers-store';
import { workspacesStore } from '../../workspaces/workspaces-store';
-import { HostMachineCard } from '../host-machine-card';
import { hostReachabilityStore } from '../host-reachability-store';
import { hostSetupStore } from '../host-setup-store';
import { HostUnreachablePanel } from '../host-unreachable-panel';
@@ -317,16 +316,6 @@ export const RemoteHostMainPanel = observer(function RemoteHostMainPanel() {
</section>
)}
- {serverId && (
- <div className="pt-4">
- <HostMachineCard
- sshHost={sshHost}
- serverId={serverId}
- workspaceId={workspaceId}
- />
- </div>
- )}
-
{serverId && workspaceId && (
<LoadExistingAgentsSection
sshHost={sshHost}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-item.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-item.tsx
index d24335c5d..b46e0a3aa 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-item.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-item.tsx
@@ -45,6 +45,7 @@ import {
} from '@shared/core/switch-rooms/connection-health';
import { type AgentPresence, SidebarAgentRow } from './agent-row';
import { DiscoveryFailureIndicator } from './discovery-failure-indicator';
+import { MigrationProblemIndicator } from './migration-problem-indicator';
import { SidebarItemMiniButton } from './sidebar-primitives';
import { agentExpandKey } from './sidebar-store';
@@ -154,6 +155,7 @@ export const SidebarAgentItem = observer(function SidebarAgentItem({
agentId={agent.providerId ?? null}
/>
<DiscoveryFailureIndicator agentId={agent.id} label={label} />
+ <MigrationProblemIndicator agentId={agent.id} label={label} />
{agent.providerId && (
<ProviderIssueIndicator
providerId={agent.providerId}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/migration-problem-indicator.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/migration-problem-indicator.tsx
new file mode 100644
index 000000000..a56ae855c
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/migration-problem-indicator.tsx
@@ -0,0 +1,63 @@
+import { useMutation, useQuery } from '@tanstack/react-query';
+import { TriangleAlert } from 'lucide-react';
+import { describeFailure } from '@renderer/lib/errors/describe-failure';
+import { useToast } from '@renderer/lib/hooks/use-toast';
+import { rpc } from '@renderer/lib/ipc';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';
+import { SidebarItemMiniButton } from './sidebar-primitives';
+
+/** Why the agents the automatic move to managed could not move did not, polled once and shared. */
+function useMigrationProblems() {
+ return useQuery({
+ queryKey: ['agent-migration-problems'],
+ queryFn: () => rpc.agentMigration.getProblems(),
+ refetchInterval: 5000,
+ });
+}
+
+/**
+ * A warning on an agent Console could not move to managed, which tries again
+ * when clicked. Nothing shows while moves go through: it is only something to
+ * look at when one did not.
+ */
+export function MigrationProblemIndicator({ agentId, label }: { agentId: string; label: string }) {
+ const { toast } = useToast();
+ const query = useMigrationProblems();
+ const retry = useMutation({
+ mutationFn: () => rpc.agentMigration.retry(agentId),
+ onSettled: () => query.refetch(),
+ onError: (error) => {
+ const { headline, detail } = describeFailure(error, `Could not move ${label} again.`);
+ toast({ title: headline, description: detail ?? undefined, variant: 'destructive' });
+ },
+ });
+ const problem = query.data?.find((entry) => entry.agentId === agentId);
+ if (!problem) return null;
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <SidebarItemMiniButton
+ type="button"
+ aria-label={`Could not move ${label} to a managed machine. Retry`}
+ disabled={retry.isPending}
+ onClick={(event) => {
+ event.stopPropagation();
+ retry.mutate();
+ }}
+ >
+ <TriangleAlert className="h-3.5 w-3.5 shrink-0 text-foreground-warning" />
+ </SidebarItemMiniButton>
+ }
+ />
+ <TooltipContent className="max-w-xs">
+ <p>
+ {retry.isPending
+ ? 'Moving this agent to a managed machine…'
+ : `Couldn’t move this agent to a managed machine on ${problem.machine}. Click to retry.`}
+ </p>
+ <p className="mt-1 text-foreground-muted">{problem.message}</p>
+ </TooltipContent>
+ </Tooltip>
+ );
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-agent-row.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-agent-row.tsx
index f47062843..a9c3b4361 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-agent-row.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-agent-row.tsx
@@ -26,6 +26,7 @@ import { cn } from '@renderer/utils/utils';
import type { Agent } from '@shared/core/agents/agents';
import { AgentStatusSlot } from './agent-status-slot';
import { DiscoveryFailureIndicator } from './discovery-failure-indicator';
+import { MigrationProblemIndicator } from './migration-problem-indicator';
import { SidebarItemMiniButton, SidebarMenuAction, SidebarMenuRow } from './sidebar-primitives';
import { depthIndent, roomAgentGroupKey } from './sidebar-store';
@@ -147,6 +148,7 @@ export const RoomAgentRow = observer(function RoomAgentRow({
/>
<AgentConnectionIndicator agent={agent} />
<DiscoveryFailureIndicator agentId={agent.id} label={label} />
+ <MigrationProblemIndicator agentId={agent.id} label={label} />
{agent.providerId && (
<ProviderIssueIndicator
providerId={agent.providerId}
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
deleted file mode 100644
index 68933ff9e..000000000
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/this-computer-machine-card.tsx
+++ /dev/null
@@ -1,438 +0,0 @@
-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 { 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';
-import { events, rpc } from '@renderer/lib/ipc';
-import { Button } from '@renderer/lib/ui/button';
-import {
- Dialog,
- DialogClose,
- DialogContent,
- DialogContentArea,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from '@renderer/lib/ui/dialog';
-import { Input } from '@renderer/lib/ui/input';
-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 {
- type EmbeddedControllerOverview,
- MAX_MACHINE_DESCRIPTION,
- MAX_MACHINE_NAME,
- type MachineDetailsChange,
-} from '@shared/core/embedded-controller/embedded-controller';
-import { embeddedControllerStateChannel } from '@shared/events/embeddedControllerEvents';
-import { switchServersStore } from './switch-servers-store';
-import {
- canStartAgain,
- machineStateKey,
- machineStatus,
- type MachineStatusTone,
- toggleBlocker,
- toggleChecked,
- unknownToServer,
-} from './this-computer-machine';
-
-/** How often the card re-reads the server while it is on screen. */
-const REFRESH_MS = 10_000;
-const CONNECTING_REFRESH_MS = 1_000;
-
-const TONE: Record<MachineStatusTone, StatusTone> = {
- neutral: 'neutral',
- busy: 'info',
- ok: 'success',
- warn: 'warning',
- error: 'danger',
-};
-
-const card = 'rounded-lg border border-border bg-card p-4';
-
-function overviewKey(serverId: string): readonly unknown[] {
- return ['embedded-controller', serverId];
-}
-
-/**
- * "This computer as a machine": whether this Console runs the managed agents
- * the server places on this computer, how that is going, and which agents
- * they are. Agents created in Console itself are not affected either way.
- */
-export const ThisComputerMachineCard = observer(function ThisComputerMachineCard({
- serverId,
- signedIn,
-}: {
- serverId: string;
- signedIn: boolean;
-}) {
- const queryClient = useQueryClient();
- const workspaceId = workspacesStore.idOnServerInScope(serverId);
- const server = switchServersStore.servers.find((candidate) => candidate.id === serverId);
- const [confirmingOff, setConfirmingOff] = useState(false);
-
- const overviewQuery = useQuery({
- queryKey: [...overviewKey(serverId), workspaceId],
- queryFn: () => rpc.embeddedController.getOverview({ serverId, workspaceId }),
- // Every second while the controller runs but Switch does not list it online yet.
- refetchInterval: (query) => {
- const data = query.state.data;
- const reaching =
- data?.phase.kind === 'running' &&
- data.remote?.kind === 'ok' &&
- data.remote.controller?.state !== 'online';
- return reaching ? CONNECTING_REFRESH_MS : REFRESH_MS;
- },
- });
-
- useEffect(
- () =>
- events.on(embeddedControllerStateChannel, (event) => {
- if (event.serverId !== serverId) return;
- void queryClient.invalidateQueries({ queryKey: overviewKey(serverId) });
- }),
- [queryClient, serverId]
- );
-
- const refresh = () => queryClient.invalidateQueries({ queryKey: overviewKey(serverId) });
- const failed = useStateBoundFailure(
- overviewQuery.data ? machineStateKey(overviewQuery.data) : null
- );
- const handlers = {
- onSuccess: async () => {
- failed.clear();
- await refresh();
- },
- onError: async (error: Error) => {
- await refresh();
- const fresh = queryClient.getQueryData<EmbeddedControllerOverview>([
- ...overviewKey(serverId),
- workspaceId,
- ]);
- failed.fail(error, fresh ? machineStateKey(fresh) : null);
- },
- };
- const enable = useMutation({
- mutationFn: () => {
- if (!workspaceId) throw new Error('Open a workspace on this server first.');
- return rpc.embeddedController.enable({ serverId, workspaceId });
- },
- ...handlers,
- });
- const disable = useMutation({
- mutationFn: () => rpc.embeddedController.disable(serverId),
- ...handlers,
- });
- const startAgain = useMutation({
- mutationFn: () => rpc.embeddedController.restart(serverId),
- ...handlers,
- });
- const dismiss = useMutation({
- mutationFn: () => rpc.embeddedController.dismissRemoved(serverId),
- ...handlers,
- });
- const enrollAgain = useMutation({
- mutationFn: () => rpc.embeddedController.enrollAgain(serverId),
- ...handlers,
- });
-
- const overview = overviewQuery.data;
- // Nothing to say on a server this computer has nothing to do with and is not
- // signed in to: the sign-in form is the page's subject then.
- if (!overview) {
- if (!signedIn) return null;
- return (
- <section className={card}>
- <Heading />
- <p className="mt-2 text-xs text-foreground-muted">
- {overviewQuery.error
- ? failureText(overviewQuery.error, 'Could not read this computer’s state.')
- : 'Loading…'}
- </p>
- </section>
- );
- }
- if (!signedIn && !overview.enrollment && overview.phase.kind === 'off') return null;
-
- const status = machineStatus(overview, Date.now());
- const blocker = toggleBlocker(overview);
- const checked = toggleChecked(overview);
- const failure = failed.failure;
-
- return (
- <section className={`${card} space-y-3`}>
- <div className="flex items-start justify-between gap-3">
- <Heading />
- <div className="flex shrink-0 items-center gap-2">
- <StatusBadge tone={TONE[status.tone]}>{status.label}</StatusBadge>
- <Switch
- aria-label="Run managed agents on this computer"
- checked={checked}
- disabled={blocker !== null}
- onCheckedChange={(next) => {
- failed.clear();
- if (next) enable.mutate();
- else setConfirmingOff(true);
- }}
- />
- </div>
- </div>
-
- {blocker && blocker !== 'Working…' && (
- <p className="text-xs text-foreground-muted">{blocker}</p>
- )}
- {status.detail && (
- <p
- className={
- status.tone === 'error'
- ? 'text-xs text-foreground-error'
- : 'text-xs text-foreground-muted'
- }
- >
- {status.detail}
- </p>
- )}
- {failure && (
- <p className="text-xs text-foreground-error">
- {failureText(failure, 'That did not work.')}
- </p>
- )}
-
- <div className="flex flex-wrap items-center gap-2">
- {canStartAgain(overview) && (
- <Button
- variant="outline"
- size="sm"
- disabled={startAgain.isPending}
- onClick={() => startAgain.mutate()}
- >
- <RefreshCw className="size-4" />
- Start again
- </Button>
- )}
- {unknownToServer(overview) && (
- <Button
- variant="outline"
- size="sm"
- disabled={enrollAgain.isPending}
- onClick={() => enrollAgain.mutate()}
- >
- <RefreshCw className="size-4" />
- {enrollAgain.isPending ? 'Enrolling…' : 'Enroll again'}
- </Button>
- )}
- {overview.phase.kind === 'removed' && (
- <Button
- variant="outline"
- size="sm"
- disabled={dismiss.isPending}
- onClick={() => dismiss.mutate()}
- >
- Dismiss
- </Button>
- )}
- {server && (overview.enrollment || overview.remote?.kind === 'ok') && (
- <Button
- variant="ghost"
- size="sm"
- onClick={() =>
- void rpc.switchServers.openGatewayPage({
- serverId,
- url: `${server.gatewayUrl.replace(/\/+$/, '')}/machines`,
- })
- }
- >
- <ExternalLink className="size-4" />
- Machines
- </Button>
- )}
- </div>
-
- {overview.enrollment && (
- <MachineDetails serverId={serverId} overview={overview} onSaved={refresh} />
- )}
-
- {overview.enrollment && overview.phase.kind === 'running' && workspaceId && (
- <MoveAllAgents serverId={serverId} workspaceId={workspaceId} />
- )}
-
- <Dialog open={confirmingOff} onOpenChange={setConfirmingOff}>
- <DialogContent>
- <DialogHeader>
- <TriangleAlert className="size-4 text-amber-500" />
- <DialogTitle>Stop running managed agents on this computer?</DialogTitle>
- </DialogHeader>
- <DialogContentArea>
- <DialogDescription>
- This removes {overview.enrollment?.name ?? 'this computer'} from Switch as a machine
- and stops the managed agents placed on it. They stay defined in Switch, and can be
- moved to another machine. Agents this Console runs itself are not affected; any moved
- here from this Console have to be brought back first.
- </DialogDescription>
- </DialogContentArea>
- <DialogFooter>
- <DialogClose render={<Button variant="outline" size="sm" />}>Cancel</DialogClose>
- <Button
- variant="destructive"
- size="sm"
- onClick={() => {
- setConfirmingOff(false);
- disable.mutate();
- }}
- >
- Remove this computer
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- </section>
- );
-});
-
-function Heading() {
- return (
- <div className="flex min-w-0 items-start gap-2">
- <Computer className="mt-0.5 size-4 shrink-0 text-foreground-muted" />
- <div className="min-w-0 space-y-0.5">
- <h3 className="text-sm font-medium text-foreground">This computer as a machine</h3>
- <p className="text-xs text-foreground-muted">
- Run managed agents on this computer: Switch can place agents here, and this Console runs
- them while it is open.
- </p>
- </div>
- </div>
- );
-}
-
-/**
- * This computer's name and description as a machine on the server, which its
- * owner sees on the Machines page and agents allowed to manage agents read
- * when they pick a machine, with an edit action.
- */
-function MachineDetails({
- serverId,
- overview,
- onSaved,
-}: {
- serverId: string;
- overview: EmbeddedControllerOverview;
- onSaved: () => void;
-}) {
- const [editing, setEditing] = useState(false);
- const [name, setName] = useState('');
- const [description, setDescription] = useState('');
- const save = useMutation({
- mutationFn: (changes: MachineDetailsChange) =>
- rpc.embeddedController.updateDetails({ serverId, changes }),
- onSuccess: () => setEditing(false),
- onSettled: onSaved,
- });
-
- const remote = overview.remote;
- const controller = remote?.kind === 'ok' ? remote.controller : null;
- if (!controller || controller.state === 'revoked') return null;
-
- const trimmedName = name.trim();
- const trimmedDescription = description.trim();
- const nameProblem = !trimmedName
- ? 'A machine needs a name.'
- : trimmedName.length > MAX_MACHINE_NAME
- ? `At most ${MAX_MACHINE_NAME} characters.`
- : null;
- const descriptionProblem =
- trimmedDescription.length > MAX_MACHINE_DESCRIPTION
- ? `At most ${MAX_MACHINE_DESCRIPTION} characters.`
- : null;
- const changes: MachineDetailsChange = {
- ...(trimmedName !== controller.name ? { name: trimmedName } : {}),
- ...(trimmedDescription !== (controller.description ?? '')
- ? { description: trimmedDescription || null }
- : {}),
- };
-
- return (
- <div className="flex items-start justify-between gap-3">
- <div className="min-w-0">
- <p className="truncate text-sm text-foreground">{controller.name}</p>
- <p className="truncate text-xs text-foreground-muted">
- {controller.description ?? 'No description'}
- </p>
- </div>
- <Button
- variant="ghost"
- size="sm"
- aria-label="Rename or describe this computer"
- onClick={() => {
- setName(controller.name);
- setDescription(controller.description ?? '');
- save.reset();
- setEditing(true);
- }}
- >
- <Pencil className="size-4" />
- Edit
- </Button>
- <Dialog open={editing} onOpenChange={setEditing}>
- <DialogContent>
- <DialogHeader>
- <DialogTitle>This computer as a machine</DialogTitle>
- </DialogHeader>
- <DialogContentArea className="gap-3">
- <DialogDescription>
- The name and description your Machines page shows, and that agents you allow to manage
- agents see when they pick a machine.
- </DialogDescription>
- <div className="space-y-1">
- <Label htmlFor="machine-name">Name</Label>
- <Input
- id="machine-name"
- value={name}
- aria-invalid={nameProblem !== null}
- onChange={(event) => setName(event.target.value)}
- />
- {nameProblem && <p className="text-xs text-foreground-error">{nameProblem}</p>}
- </div>
- <div className="space-y-1">
- <Label htmlFor="machine-description">Description</Label>
- <Textarea
- id="machine-description"
- value={description}
- placeholder="What this computer is for"
- aria-invalid={descriptionProblem !== null}
- onChange={(event) => setDescription(event.target.value)}
- />
- {descriptionProblem && (
- <p className="text-xs text-foreground-error">{descriptionProblem}</p>
- )}
- </div>
- {save.error && (
- <p className="text-xs text-foreground-error">
- {failureText(save.error, 'Could not save.')}
- </p>
- )}
- </DialogContentArea>
- <DialogFooter>
- <DialogClose render={<Button variant="outline" size="sm" />}>Cancel</DialogClose>
- <Button
- size="sm"
- disabled={
- save.isPending ||
- nameProblem !== null ||
- descriptionProblem !== null ||
- Object.keys(changes).length === 0
- }
- onClick={() => save.mutate(changes)}
- >
- Save
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- </div>
- );
-}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/this-computer-machine.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/this-computer-machine.test.ts
deleted file mode 100644
index a605c7cfe..000000000
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/this-computer-machine.test.ts
+++ /dev/null
@@ -1,236 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import type {
- EmbeddedControllerOverview,
- EmbeddedControllerPhase,
- EmbeddedControllerRemote,
-} from '@shared/core/embedded-controller/embedded-controller';
-import {
- agentActual,
- canStartAgain,
- machineStateKey,
- machineStatus,
- toggleBlocker,
- toggleChecked,
- unknownToServer,
-} from './this-computer-machine';
-
-const ENROLLMENT = {
- controllerId: 'controller-1',
- name: 'build-box',
- workspaceId: 'workspace-1',
- enrolledAt: '2026-01-01T00:00:00Z',
-};
-
-function overview(
- phase: EmbeddedControllerPhase,
- remote: EmbeddedControllerRemote | null,
- enrolled = true
-): EmbeddedControllerOverview {
- return {
- serverId: 'server-1',
- unsupportedReason: null,
- enrollment: enrolled ? ENROLLMENT : null,
- phase,
- remote,
- movedAgents: [],
- };
-}
-
-const ok = (
- state: 'online' | 'offline' | 'unknown' | 'revoked' | null
-): EmbeddedControllerRemote => ({
- kind: 'ok',
- controller: state ? { name: 'box', description: null, state, lastSeenAt: null } : null,
- agents: [],
-});
-const running: EmbeddedControllerPhase = { kind: 'running', since: '2026-01-01T00:00:00Z' };
-/** Well past the connecting grace for `running`. */
-const LATER = Date.parse('2026-01-01T01:00:00Z');
-
-describe('machineStatus', () => {
- it('says running only while the server sees the controller online', () => {
- expect(machineStatus(overview(running, ok('online')), LATER).label).toBe('Running');
- expect(machineStatus(overview(running, ok('unknown')), LATER)).toMatchObject({
- label: 'Disconnected',
- tone: 'warn',
- });
- expect(machineStatus(overview(running, ok('revoked')), LATER).label).toBe('Removed');
- expect(machineStatus(overview(running, { kind: 'unavailable' }), LATER).label).toBe(
- 'Disconnected'
- );
- expect(
- machineStatus(overview(running, { kind: 'error', message: 'offline' }), LATER)
- ).toMatchObject({
- label: 'Running',
- tone: 'warn',
- });
- });
-
- it('says Switch no longer knows the computer when it is enrolled but not listed, and offers to enroll again', () => {
- const unknown = overview(running, ok(null));
- expect(unknownToServer(unknown)).toBe(true);
- expect(machineStatus(unknown, LATER)).toMatchObject({
- label: 'Unknown to Switch',
- tone: 'error',
- detail: expect.stringContaining('Enroll it again.'),
- });
- const withMoved = { ...unknown, movedAgents: ['jack'] };
- expect(machineStatus(withMoved, LATER).detail).toContain('jack, moved here from this Console');
- expect(unknownToServer(overview(running, ok('offline')))).toBe(false);
- expect(unknownToServer(overview(running, { kind: 'error', message: 'down' }))).toBe(false);
- expect(unknownToServer(overview({ kind: 'off' }, ok(null), false))).toBe(false);
- });
-
- it('says connecting, not disconnected, in the first minute after the controller starts', () => {
- const justStarted = Date.parse(running.since) + 5_000;
- expect(machineStatus(overview(running, ok('unknown')), justStarted)).toMatchObject({
- label: 'Connecting…',
- tone: 'busy',
- });
- expect(machineStatus(overview(running, ok('online')), justStarted).label).toBe('Running');
- });
-
- it('names every other phase, with the reason where there is one', () => {
- expect(machineStatus(overview({ kind: 'off' }, ok(null), false), LATER).label).toBe('Off');
- expect(machineStatus(overview({ kind: 'enrolling' }, null, false), LATER).tone).toBe('busy');
- expect(
- machineStatus(
- overview(
- {
- kind: 'restarting',
- attempt: 2,
- retryAt: '2026-01-01T00:00:02Z',
- lastExit: 'exit code 1',
- },
- ok('unknown')
- ),
- LATER
- )
- ).toMatchObject({ label: 'Disconnected', detail: expect.stringContaining('exit code 1') });
- expect(machineStatus(overview({ kind: 'removed', at: 'x' }, null, false), LATER)).toMatchObject(
- {
- label: 'Removed',
- detail: expect.stringContaining('This computer was removed from Switch.'),
- }
- );
- expect(machineStatus(overview({ kind: 'taken_over', at: 'x' }, null), LATER).detail).toMatch(
- /took over/
- );
- expect(machineStatus(overview({ kind: 'error', message: 'boom' }, null), LATER)).toEqual({
- label: 'Error',
- tone: 'error',
- detail: 'boom',
- });
- });
-});
-
-describe('toggle', () => {
- it('blocks turning on where the controller cannot run or the server cannot place agents', () => {
- const off = { kind: 'off' } as const;
- expect(toggleBlocker(overview(off, ok(null), false))).toBeNull();
- expect(
- toggleBlocker({
- ...overview(off, ok(null), false),
- unsupportedReason: 'Needs macOS or Linux.',
- })
- ).toBe('Needs macOS or Linux.');
- expect(toggleBlocker(overview(off, { kind: 'unavailable' }, false))).toMatch(
- /agent management turned on/
- );
- expect(toggleBlocker(overview(off, null, false))).toMatch(/Open a workspace/);
- expect(toggleBlocker(overview({ kind: 'enrolling' }, null, false))).toBe('Working…');
- });
-
- it('lets an enrolled computer be turned off, unless something is in flight or agents were moved here', () => {
- expect(toggleBlocker(overview(running, { kind: 'unavailable' }))).toBeNull();
- expect(toggleBlocker({ ...overview(running, ok('online')), movedAgents: ['builder'] })).toBe(
- 'Bring back builder before turning it off: they were moved here from this Console.'
- );
- expect(toggleBlocker(overview({ kind: 'stopping' }, ok('online')))).toBe('Working…');
- expect(toggleChecked(overview(running, ok('online')))).toBe(true);
- expect(toggleChecked(overview({ kind: 'enrolling' }, null, false))).toBe(true);
- expect(toggleChecked(overview({ kind: 'removed', at: 'x' }, null, false))).toBe(false);
- });
-
- it('offers to start again only after a takeover or an error', () => {
- expect(canStartAgain(overview({ kind: 'taken_over', at: 'x' }, null))).toBe(true);
- expect(canStartAgain(overview({ kind: 'error', message: 'm' }, null))).toBe(true);
- expect(canStartAgain(overview(running, null))).toBe(false);
- expect(canStartAgain(overview({ kind: 'error', message: 'm' }, null, false))).toBe(false);
- });
-});
-
-describe('a removed computer with agents still moved onto it', () => {
- it('says nothing runs them, and how to bring them back', () => {
- expect(
- machineStatus(
- {
- ...overview({ kind: 'removed', at: 'x' }, null, false),
- movedAgents: ['builder'],
- },
- LATER
- ).detail
- ).toMatch(
- /Nothing runs builder, moved here from this Console, now: bring them back with Stop managing\.$/
- );
- });
-});
-
-describe('machineStateKey', () => {
- it('stays the same across reads of the same state', () => {
- expect(machineStateKey(overview(running, ok('online')))).toBe(
- machineStateKey(overview(running, ok('unknown')))
- );
- });
-
- it('changes with the phase, the enrollment or the agents moved here', () => {
- const base = machineStateKey({ ...overview(running, ok('online')), movedAgents: ['builder'] });
- expect(machineStateKey(overview(running, ok('online')))).not.toBe(base);
- expect(
- machineStateKey({
- ...overview({ kind: 'removed', at: 'x' }, null, false),
- movedAgents: ['builder'],
- })
- ).not.toBe(base);
- });
-});
-
-describe('agentActual', () => {
- const base = {
- agentId: 'a',
- name: 'scout',
- displayName: null,
- provider: 'claude',
- desiredState: 'running' as const,
- };
-
- it('reads the last report: process, attachment and reason', () => {
- expect(agentActual({ ...base, actual: null })).toEqual({
- label: 'Not reported yet',
- tone: 'neutral',
- });
- expect(
- agentActual({
- ...base,
- actual: { process: 'running', attached: true, reason: null, detail: null },
- })
- ).toEqual({ label: 'running', tone: 'ok' });
- expect(
- agentActual({
- ...base,
- actual: { process: 'running', attached: false, reason: null, detail: null },
- })
- ).toEqual({ label: 'running, not attached', tone: 'warn' });
- expect(
- agentActual({
- ...base,
- actual: {
- process: 'failed',
- attached: false,
- reason: 'provider_login_missing',
- detail: 'x',
- },
- })
- ).toEqual({ label: 'failed (provider login missing)', tone: 'error' });
- });
-});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/this-computer-machine.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/this-computer-machine.ts
deleted file mode 100644
index 7b5d78766..000000000
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/this-computer-machine.ts
+++ /dev/null
@@ -1,188 +0,0 @@
-import type {
- EmbeddedControllerOverview,
- PlacedManagedAgent,
-} from '@shared/core/embedded-controller/embedded-controller';
-
-export type MachineStatusTone = 'neutral' | 'busy' | 'ok' | 'warn' | 'error';
-
-/** One line of state for "This computer as a machine": off, enrolling, running, disconnected, removed or error. */
-export type MachineStatus = {
- label: string;
- tone: MachineStatusTone;
- detail: string | null;
-};
-
-const REMOVED_DETAIL =
- 'This computer was removed from Switch. Its managed agents were stopped. Turn it on again to add it back as a new machine.';
-
-function clock(iso: string): string {
- return new Date(iso).toLocaleTimeString([], {
- hour: '2-digit',
- minute: '2-digit',
- second: '2-digit',
- });
-}
-
-/** How long after starting a controller that has not reached Switch reads as connecting, not disconnected. */
-export const CONNECTING_GRACE_MS = 60_000;
-
-/** What the card says when Switch does not list the machine this computer is enrolled as. */
-function unknownStatus(overview: EmbeddedControllerOverview): MachineStatus {
- const why =
- 'Switch no longer knows this computer as a machine (its data was reset or restored, or the machine was deleted), so its controller cannot sign in. Enroll it again.';
- return {
- label: 'Unknown to Switch',
- tone: 'error',
- detail: overview.movedAgents.length
- ? `${why} ${overview.movedAgents.join(', ')}, moved here from this Console, then need Stop managing, and can be moved again.`
- : why,
- };
-}
-
-export function machineStatus(overview: EmbeddedControllerOverview, nowMs: number): MachineStatus {
- if (unknownToServer(overview)) return unknownStatus(overview);
- const { phase, remote } = overview;
- switch (phase.kind) {
- case 'off':
- return { label: 'Off', tone: 'neutral', detail: null };
- case 'enrolling':
- return { label: 'Adding this computer…', tone: 'busy', detail: null };
- case 'stopping':
- return {
- label: 'Turning off…',
- tone: 'busy',
- detail: 'Removing this computer from Switch and stopping its managed agents.',
- };
- case 'removed':
- return {
- label: 'Removed',
- tone: 'error',
- detail: overview.movedAgents.length
- ? `${REMOVED_DETAIL} Nothing runs ${overview.movedAgents.join(', ')}, moved here from this Console, now: bring them back with Stop managing.`
- : REMOVED_DETAIL,
- };
- case 'taken_over':
- return {
- label: 'Error',
- tone: 'error',
- detail:
- 'Another copy of this computer’s controller connected to Switch and took over, so this one stopped. Start it again only once that copy has stopped, or the two take turns.',
- };
- case 'error':
- return { label: 'Error', tone: 'error', detail: phase.message };
- case 'restarting':
- return {
- label: 'Disconnected',
- tone: 'warn',
- detail: `The controller stopped (${phase.lastExit}). Starting it again at ${clock(phase.retryAt)}.`,
- };
- case 'running': {
- if (remote?.kind === 'error')
- return {
- label: 'Running',
- tone: 'warn',
- detail: `The controller is running, but Switch could not be asked how it sees it: ${remote.message}`,
- };
- if (remote?.kind === 'unavailable')
- return {
- label: 'Disconnected',
- tone: 'warn',
- detail: 'This server no longer has agent management turned on.',
- };
- if (remote?.kind !== 'ok') return { label: 'Running', tone: 'ok', detail: null };
- const state = remote.controller?.state ?? null;
- if (state === 'online') return { label: 'Running', tone: 'ok', detail: null };
- if (state === 'revoked')
- return {
- label: 'Removed',
- tone: 'error',
- detail: 'Switch has removed this computer; its controller is stopping its agents.',
- };
- if (nowMs - Date.parse(phase.since) < CONNECTING_GRACE_MS)
- return {
- label: 'Connecting…',
- tone: 'busy',
- detail: 'The controller has started and is connecting to Switch.',
- };
- return {
- label: 'Disconnected',
- tone: 'warn',
- detail: 'The controller is running but has not reached Switch recently. It keeps trying.',
- };
- }
- }
-}
-
-/**
- * Why the toggle cannot be moved now, or null when it can. Turning it on needs
- * a computer that can run the controller, a workspace to enroll in and a
- * server with agent management; turning it off needs the agents moved from
- * this Console brought back first.
- */
-export function toggleBlocker(overview: EmbeddedControllerOverview): string | null {
- const { phase, enrollment, remote } = overview;
- if (phase.kind === 'enrolling' || phase.kind === 'stopping') return 'Working…';
- if (enrollment) {
- if (overview.movedAgents.length)
- return `Bring back ${overview.movedAgents.join(', ')} before turning it off: they were moved here from this Console.`;
- return null;
- }
- if (overview.unsupportedReason) return overview.unsupportedReason;
- if (remote === null) return 'Open a workspace on this server to add this computer to it.';
- if (remote.kind === 'unavailable')
- return 'This server does not have agent management turned on, so it cannot place agents on machines.';
- if (remote.kind === 'error') return `Switch could not be asked: ${remote.message}`;
- return null;
-}
-
-/** The toggle reads on while enrolled, or while enrolling. */
-export function toggleChecked(overview: EmbeddedControllerOverview): boolean {
- return overview.enrollment !== null || overview.phase.kind === 'enrolling';
-}
-
-/** What a placed agent is doing, as its controller last reported it. */
-export function agentActual(agent: PlacedManagedAgent): { label: string; tone: MachineStatusTone } {
- const actual = agent.actual;
- if (!actual) return { label: 'Not reported yet', tone: 'neutral' };
- const reason = actual.reason ? ` (${actual.reason.replaceAll('_', ' ')})` : '';
- const tone: MachineStatusTone =
- actual.process === 'failed' || actual.process === 'crashed'
- ? 'error'
- : actual.process === 'running'
- ? actual.attached
- ? 'ok'
- : 'warn'
- : 'neutral';
- const attached = actual.process === 'running' && !actual.attached ? ', not attached' : '';
- return { label: `${actual.process}${attached}${reason}`, tone };
-}
-
-/** Restart is offered for the states the controller is not restarted from on its own. */
-export function canStartAgain(overview: EmbeddedControllerOverview): boolean {
- return (
- overview.enrollment !== null &&
- (overview.phase.kind === 'taken_over' || overview.phase.kind === 'error')
- );
-}
-
-/**
- * What the card's state is, for telling whether a failure shown on it still
- * describes it: the phase, the enrollment and the agents moved here.
- */
-export function machineStateKey(overview: EmbeddedControllerOverview): string {
- return JSON.stringify([
- overview.phase.kind,
- overview.enrollment?.controllerId ?? null,
- overview.movedAgents,
- ]);
-}
-
-/** Switch answered, and does not list the machine this computer is enrolled as. */
-export function unknownToServer(overview: EmbeddedControllerOverview): boolean {
- return (
- overview.enrollment !== null &&
- overview.remote?.kind === 'ok' &&
- overview.remote.controller === null &&
- (overview.phase.kind === 'running' || overview.phase.kind === 'restarting')
- );
-}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/view.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/view.tsx
index 5bae9e983..9f256d71c 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/view.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/view.tsx
@@ -64,7 +64,6 @@ import { isSwitchCloudServer } from './switch-cloud-store';
import { switchRoomsStore } from './switch-rooms-store';
import { switchServersStore } from './switch-servers-store';
import { TelemetryConsentNotice } from './TelemetryConsentNotice';
-import { ThisComputerMachineCard } from './this-computer-machine-card';
import { loadSwitchCloudOrigin, managedCloudServerId } from './use-cloud-launches';
import { myIdentitiesQueryKey } from './use-my-identities';
import { VersionDriftNotice } from './VersionDriftNotice';
@@ -375,7 +374,6 @@ const ServerMainPanel = observer(function ServerMainPanel() {
{connected && <ServerStatTiles serverId={serverId} />}
{connected && <MessagingAppsCard serverId={serverId} />}
- <ThisComputerMachineCard serverId={serverId} signedIn={connected} />
</>
)}
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/errors/describe-failure.test.ts b/console/apps/switch-console-desktop/src/renderer/lib/errors/describe-failure.test.ts
index 7c7545bb9..9036f324e 100644
--- a/console/apps/switch-console-desktop/src/renderer/lib/errors/describe-failure.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/lib/errors/describe-failure.test.ts
@@ -127,7 +127,7 @@ describe('describeFailure', () => {
it('passes a refusal to remove a machine running moved agents straight through', () => {
const message =
- 'build-box runs builder for this Console, so it cannot be removed yet. Bring the agents back first: Bring all back on the host’s page, or Stop managing on each agent.';
+ 'build-box runs builder as managed agents for this Console, so it cannot be removed yet. Delete those agents first.';
expect(describeFailure(rpcError('MovedAgentsHereError', message), 'Could not remove.')).toEqual(
{ headline: message, detail: null }
);
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/managed-agent-page.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/managed-agent-page.test.tsx
index 6c717d635..7e6b51b62 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/managed-agent-page.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/managed-agent-page.test.tsx
@@ -44,12 +44,6 @@ vi.mock(
() => ({ CanManageAgentsRow: () => <div>Can manage agents</div> })
);
vi.mock('@renderer/lib/components/agent-icon-picker', () => ({ AgentIconPicker: () => null }));
-vi.mock('@renderer/features/agent-migration/managed-agent-section', () => ({
- ManagedAgentSection: () => null,
-}));
-vi.mock('@renderer/features/locations/stores/agents-store', () => ({
- agentsStore: { agentsOnServer: () => [] },
-}));
vi.mock('@renderer/lib/modal/modal-provider', () => ({ useShowModal: () => vi.fn() }));
import { ManagedAgentPage } from '@renderer/features/managed-agents/managed-agent-page';
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/server-view-shared.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/server-view-shared.test.tsx
index af5a2e299..d46dbdb5d 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/server-view-shared.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/server-view-shared.test.tsx
@@ -37,10 +37,6 @@ vi.mock('@tanstack/react-query', async (importOriginal) => ({
...(await importOriginal<typeof ReactQuery>()),
useQueryClient: () => ({ invalidateQueries: () => Promise.resolve() }),
}));
-// This computer as a machine has its own tests; here it is only a card on the page.
-vi.mock('@renderer/features/switch-servers/this-computer-machine-card', () => ({
- ThisComputerMachineCard: () => null,
-}));
vi.mock('@renderer/features/settings/use-app-settings-key', () => ({
useAppSettingsKey: () => ({ value: { enabled: state.consent } }),
}));
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 ac6a60641..19865719e 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
@@ -89,32 +89,15 @@ export type AgentMigrationState = {
/** A move that went through. `untold` lists the rooms where a turn was cut that could not be told so, and why. */
export type MoveToManagedResult = { untold: { roomId: string; reason: string }[] };
-/** One agent of a "Move all" that did not move, and why. */
-export type MoveAllResult = {
- moved: { agentId: string; name: string }[];
- skipped: { agentId: string; name: string; reason: string }[];
- failed: { agentId: string; name: string; message: string }[];
-};
-
-/** 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. */
+/** An agent the automatic move to managed could not move, and why. */
+export type MigrationProblem = {
+ agentId: string;
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;
+ /** "this computer", or the SSH host's name. */
+ machine: string;
+ message: string;
};
-export type MoveAllProgress = { machines: MoveAllMachine[] };
-
export type AgentMigrationEvent = {
agentId: string;
runner: AgentRunner;