Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
Console: devices pages, add-machine dialog, new agent from a machine (WIP)
Massimo Cairofe24e532a76d
diff --git a/console/apps/switch-console-desktop/src/main/core/embedded-controller/management-port.test.ts b/console/apps/switch-console-desktop/src/main/core/embedded-controller/management-port.test.tsindex b45cb2590..2bc0f52b3 100644--- a/console/apps/switch-console-desktop/src/main/core/embedded-controller/management-port.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/embedded-controller/management-port.test.ts@@ -70,6 +70,12 @@ describe('placedOn', () => {workspacesDir: null,os: null,sealingKey: null,+ platform: null,+ version: null,+ connection: null,+ release: null,+ report: null,+ createdAt: null,},],[diff --git a/console/apps/switch-console-desktop/src/main/core/managed-agents/controller.ts b/console/apps/switch-console-desktop/src/main/core/managed-agents/controller.tsindex e9bff4e4e..247013c9b 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-agents/controller.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-agents/controller.ts@@ -17,6 +17,9 @@ import {fetchManagementControllers,GatewayError,giveMachineLogin,+ issueMachineEnrollment,+ recheckMachineProvider,+ type ManagementController,managementErrorMessage,setManagedAgentDesiredState,updateManagedAgent,@@ -32,21 +35,35 @@ import {import { withReachableServerWorkspaceSession } from '@main/core/workspaces/workspace-session';import { requireWorkspaceForServer } from '@main/core/workspaces/workspaces-store';import { log } from '@main/lib/logger';+import type { MachineEnrollment } from '@shared/core/managed-agents/machine-enrollment';import type {AdvancedConfigField,ManagedAgentChanges,ManagedAgentView,MachineLoginInput,+ MachineDetail,MachineLoginOutcome,ManagedMachine,OwnedMachine,ThisComputerReport,} from '@shared/core/managed-agents/managed-agents';import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';+import { isLoopbackUrl } from '@shared/core/switch-servers/loopback';+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';import { createRPCController } from '@shared/lib/ipc/rpc';-import { ownedMachines, preferredFirst, thisComputerReport } from './owned-machines';+import {+ type LocalControllers,+ machineDetails,+ ownedMachines,+ preferredFirst,+ thisComputerReport,+} from './owned-machines';-async function machinesOn(serverId: string): Promise<OwnedMachine[] | null> {+/** The owner's controllers on a server, as `view` makes them; null without agent management. */+async function controllersOn<T>(+ serverId: string,+ view: (controllers: ManagementController[], local: LocalControllers) => T+): Promise<T | null> {const [thisComputer, hosts] = await Promise.all([embeddedControllerService.enrolledControllerId(serverId),hostControllerService.recordsOn(serverId),@@ -59,13 +76,17 @@ async function machinesOn(serverId: string): Promise<OwnedMachine[] | null> {if (error instanceof AgentManagementUnavailableError) return null;throw error;}- return ownedMachines(controllers, {+ return view(controllers, {thisComputer,sshHosts: hosts.map(({ controllerId, sshHost }) => ({ controllerId, sshHost })),});});}+function machinesOn(serverId: string): Promise<OwnedMachine[] | null> {+ return controllersOn(serverId, ownedMachines);+}+/*** The signed-in user's managed agents on a server, as the server holds them:* every one, whatever machine it runs on. Console keeps no copy.@@ -134,6 +155,14 @@ export const managedAgentsController = createRPCController({*/machines: (serverId: string): Promise<OwnedMachine[] | null> => machinesOn(serverId),+ /**+ * Every one of the owner's machines on a server, revoked ones included, with+ * all each last reported, for the Machines page. Null when the server does+ * not run agent management.+ */+ machineDetails: (serverId: string): Promise<MachineDetail[] | null> =>+ controllersOn(serverId, machineDetails),+/*** This computer's providers as its controller last reported them to a* server it runs for, `preferServerId` (the one Console is on now) first@@ -186,28 +215,56 @@ export const managedAgentsController = createRPCController({return { operationId };}),+ /**+ * A one-time code to enroll a new machine with, and the address it enrolls+ * against: the one the server names, else the one Console reaches it at.+ * `loopback` says that address only works on this computer.+ */+ machineEnrollment: (serverId: string): Promise<MachineEnrollment> =>+ withReachableServerWorkspaceSession(serverId, async (server) => {+ const issued = await issueMachineEnrollment(server);+ const serverUrl = issued.serverUrl ?? server.url;+ return {+ code: issued.code,+ expiresAt: issued.expiresAt,+ serverUrl,+ loopback: isLoopbackUrl(serverUrl),+ };+ }),+/** How the machine took up a login given to it, by the operation `giveMachineLogin` answered. */machineLoginOutcome: (params: {serverId: string;machineId: string;operationId: string;}): Promise<MachineLoginOutcome> =>- withReachableServerWorkspaceSession(params.serverId, async (server) => {- const operation = await fetchMachineOperation(server, params.machineId, params.operationId);- if (!operation) return { state: 'pending' };- if (operation.state === 'succeeded') return { state: 'succeeded' };- if (operation.state === 'pending' || operation.state === 'claimed')- return { state: 'pending' };- return {- state: 'failed',- code: operation.error?.code ?? operation.state,- message:- operation.error?.message ??- (operation.state === 'expired'- ? 'The machine did not take the login up in time; is it online?'- : `The machine did not take the login up (${operation.state}).`),- };- }),+ withReachableServerWorkspaceSession(params.serverId, (server) =>+ machineOperationOutcome(server, params.machineId, params.operationId, 'take the login up')+ ),++ /**+ * Has one of the owner's machines check a provider's install and sign-in+ * again. Answers the operation; `machineRecheckOutcome` says how it went,+ * and the machine's next report carries what it found.+ */+ recheckMachineProvider: (params: {+ serverId: string;+ machineId: string;+ provider: AgentProviderId;+ }): Promise<{ operationId: string }> =>+ withReachableServerWorkspaceSession(params.serverId, (server) =>+ recheckMachineProvider(server, params.machineId, params.provider)+ ),++ /** How a recheck went, by the operation `recheckMachineProvider` answered. */+ machineRecheckOutcome: (params: {+ serverId: string;+ machineId: string;+ operationId: string;+ }): Promise<MachineLoginOutcome> =>+ withReachableServerWorkspaceSession(params.serverId, (server) =>+ machineOperationOutcome(server, params.machineId, params.operationId, 'check the provider')+ ),/** Each provider's advanced configuration fields, keyed by provider, as the server checks a definition against them. */advancedConfigSchema: (serverId: string): Promise<Record<string, AdvancedConfigField[]>> =>@@ -322,3 +379,29 @@ async function loginToGive();return { kind: 'auth-json', credential };}++/**+ * Where one of a machine's operations stands: still pending, done, or why it+ * failed. `what` finishes "The machine did not …" for the failures the+ * server gives no words for.+ */+async function machineOperationOutcome(+ server: SwitchServer,+ machineId: string,+ operationId: string,+ what: string+): Promise<MachineLoginOutcome> {+ const operation = await fetchMachineOperation(server, machineId, operationId);+ if (!operation) return { state: 'pending' };+ if (operation.state === 'succeeded') return { state: 'succeeded' };+ if (operation.state === 'pending' || operation.state === 'claimed') return { state: 'pending' };+ return {+ state: 'failed',+ code: operation.error?.code ?? operation.state,+ message:+ operation.error?.message ??+ (operation.state === 'expired'+ ? `The machine did not ${what} in time; is it online?`+ : `The machine did not ${what} (${operation.state}).`),+ };+}diff --git a/console/apps/switch-console-desktop/src/main/core/managed-agents/owned-machines.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-agents/owned-machines.test.tsindex 09562f190..f6ce13534 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-agents/owned-machines.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-agents/owned-machines.test.ts@@ -20,6 +20,12 @@ function controller(patch: Partial<ManagementController> & { id: string }): ManaworkspacesDir: null,os: null,sealingKey: null,+ platform: null,+ version: null,+ connection: null,+ release: null,+ report: null,+ createdAt: null,...patch,};}diff --git a/console/apps/switch-console-desktop/src/main/core/managed-agents/owned-machines.ts b/console/apps/switch-console-desktop/src/main/core/managed-agents/owned-machines.tsindex 533151f5c..1f354b7ad 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-agents/owned-machines.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-agents/owned-machines.ts@@ -2,6 +2,8 @@ import type { ControllerProviderReport } from '@main/core/switch-servers/controlimport type { ManagementController } from '@main/core/switch-servers/gateway-client';import {isCloudMachine,+ type MachineDetail,+ type MachineLocal,type MachineProvider,type OwnedMachine,type ThisComputerReport,@@ -35,6 +37,27 @@ export function machineProvider(report: ControllerProviderReport): MachineProvid};}+function machineLocal(controller: ManagementController, local: LocalControllers): MachineLocal {+ if (controller.id === local.thisComputer) return { kind: 'this-computer' };+ const sshHost = local.sshHosts.find((host) => host.controllerId === controller.id)?.sshHost;+ return sshHost ? { kind: 'ssh-host', sshHost } : null;+}++function ownedMachine(controller: ManagementController, local: LocalControllers): OwnedMachine {+ return {+ id: controller.id,+ name: controller.name,+ kind: controller.kind,+ state: controller.state,+ providers: controller.providers.map(machineProvider),+ acceptsLogins: controller.sealingKey !== null,+ cloud: isCloudMachine(controller),+ workspacesDir: controller.workspacesDir,+ os: controller.os,+ local: machineLocal(controller, local),+ };+}+/** The owner's machines an agent can be placed on: every controller but the revoked ones. */export function ownedMachines(controllers: ManagementController[],@@ -42,26 +65,41 @@ export function ownedMachines(): OwnedMachine[] {return controllers.filter((controller) => controller.state !== 'revoked')- .map((controller): OwnedMachine => {- const sshHost = local.sshHosts.find((host) => host.controllerId === controller.id)?.sshHost;- return {- id: controller.id,- name: controller.name,- kind: controller.kind,- state: controller.state,- providers: controller.providers.map(machineProvider),- acceptsLogins: controller.sealingKey !== null,- cloud: isCloudMachine(controller),- workspacesDir: controller.workspacesDir,- os: controller.os,- local:- controller.id === local.thisComputer- ? { kind: 'this-computer' }- : sshHost- ? { kind: 'ssh-host', sshHost }- : null,- };- });+ .map((controller) => ownedMachine(controller, local));+}++/** Every one of the owner's machines, revoked ones included, with all each last reported. */+export function machineDetails(+ controllers: ManagementController[],+ local: LocalControllers+): MachineDetail[] {+ return controllers.map((controller): MachineDetail => {+ const report = controller.report;+ return {+ ...ownedMachine(controller, local),+ description: controller.description,+ providers: controller.providers.map((entry) => {+ const check = report?.providerChecks.find((c) => c.provider === entry.provider);+ return {+ ...machineProvider(entry),+ version: check?.version ?? null,+ checkedAt: check?.checkedAt ?? null,+ };+ }),+ platform: controller.platform,+ version: controller.version,+ connection: controller.connection,+ release: controller.release,+ updatedBy: report?.updatedBy ?? null,+ update: report?.update ?? null,+ resources: report?.resources ?? null,+ agents: report?.agents ?? [],+ lastSeenAt: controller.lastSeenAt,+ observedAt: report?.observedAt ?? null,+ createdAt: controller.createdAt,+ revokedAt: controller.revokedAt,+ };+ });}/**diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.tsindex 30f414d4d..a52927c47 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts@@ -122,6 +122,7 @@ const {updateManagementController,fetchManagementControllers,giveMachineLogin,+ recheckMachineProvider,fetchMachineOperation,fetchAgentManagementAccess,updateCanManageAgents,@@ -3308,6 +3309,92 @@ describe('agent management calls', () => {expect(JSON.parse(String(init.body))).toEqual({ name: 'laptop', description: null });});+ it('reads what a machine last reported, and tolerates a report missing parts', async () => {+ fetchMock.mockImplementation(async () =>+ respond(200, [+ {+ id: 'controller-1',+ name: 'box',+ description: null,+ kind: 'daemon',+ state: 'offline',+ last_seen_at: '2026-10-01T10:30:00Z',+ revoked_at: null,+ platform: { os: 'linux', arch: 'x64', os_version: '6.8' },+ version: '1.0.0',+ release: { wanted: '1.1.0', running: '1.0.0', current: false },+ connection: {+ connected_at: '2026-10-01T10:00:00Z',+ disconnected_at: '2026-10-01T11:00:00Z',+ disconnect_reason: 'socket_closed',+ },+ created_at: '2026-09-01T00:00:00Z',+ status: {+ observed_at: '2026-10-01T10:30:00Z',+ controller: { version: '1.0.0', updated_by: 'self' },+ machine: { disk_free_bytes: 10, disk_total_bytes: 100, sessions_running: 1 },+ update: { target: '1.1.0', state: 'waiting_idle' },+ providers: [+ {+ provider: 'claude',+ installed: true,+ auth: 'ok',+ version: '2.1.0',+ checked_at: '2026-10-01T10:29:00Z',+ },+ ],+ agents: [+ { agent_id: 'a1', process: 'running', attached: true, sessions: { active: 2 } },+ { process: 'running' },+ ],+ },+ },+ {+ id: 'controller-2',+ name: 'new',+ description: null,+ kind: 'daemon',+ state: 'unknown',+ last_seen_at: null,+ revoked_at: null,+ },+ ])+ );+ const [reported, fresh] = await fetchManagementControllers(SERVER);+ expect(reported?.platform).toEqual({ os: 'linux', arch: 'x64', osVersion: '6.8' });+ expect(reported?.connection?.disconnectReason).toBe('socket_closed');+ expect(reported?.release?.current).toBe(false);+ expect(reported?.report).toEqual({+ observedAt: '2026-10-01T10:30:00Z',+ updatedBy: 'self',+ update: { target: '1.1.0', state: 'waiting_idle', problem: null },+ resources: {+ diskFreeBytes: 10,+ diskTotalBytes: 100,+ memFreeBytes: 0,+ memTotalBytes: 0,+ sessionsRunning: 1,+ sessionsMax: 0,+ },+ providerChecks: [{ provider: 'claude', version: '2.1.0', checkedAt: '2026-10-01T10:29:00Z' }],+ agents: [+ {+ agentId: 'a1',+ process: 'running',+ attached: true,+ activeSessions: 2,+ restarts10m: 0,+ since: null,+ reason: null,+ detail: null,+ },+ ],+ });+ expect(fresh?.report).toBeNull();+ expect(fresh?.connection).toBeNull();+ expect(fresh?.version).toBeNull();+ });+it('reads the key a machine takes logins sealed to, and gives it one', async () => {fetchMock.mockImplementation(async () =>respond(200, [@@ -3393,6 +3480,23 @@ describe('agent management calls', () => {);});+ it('asks a machine to recheck one provider as a provider.recheck operation', async () => {+ fetchMock.mockImplementation(async () =>+ respond(201, { id: 'op-3', kind: 'provider.recheck', state: 'pending' })+ );+ expect(await recheckMachineProvider(SERVER, 'controller-1', 'codex')).toEqual({+ operationId: 'op-3',+ });+ const [url, init] = fetchMock.mock.calls.at(-1) as unknown as [string, RequestInit];+ expect(url).toBe('https://switch.example.com/gateway/management/operations');+ expect(init.method).toBe('POST');+ expect(JSON.parse(String(init.body))).toEqual({+ controller_id: 'controller-1',+ kind: 'provider.recheck',+ params: { provider: 'codex' },+ });+ });+it("reads each machine's providers from its last status report, and invents none", async () => {const controller = {name: 'box',diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.tsindex 4af95c1dd..36e6a0571 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts@@ -4028,6 +4028,59 @@ export type ManagementController = {* its controller has none (it keeps no key, or predates sealed logins).*/sealingKey: { key: string; keyId: string } | null;+ /** Its platform as it last reported; null when not known. */+ platform: { os: string; arch: string; osVersion: string } | null;+ /** The controller version it last reported; null before it has. */+ version: string | null;+ /** Its connection as Switch last recorded it: the current one, or the last; null when it never connected. */+ connection: ControllerConnection | null;+ /** The release Switch tells it to run; null when it is told none, as for one Console updates. */+ release: { wanted: string; running: string | null; current: boolean } | null;+ /** The rest of its last status report; null before it has reported. */+ report: ControllerReport | null;+ /** When it enrolled; null from a server that does not say. */+ createdAt: string | null;+};++export type ControllerConnection = {+ connectedAt: string;+ /** Null while it is connected. */+ disconnectedAt: string | null;+ /** Null while it is connected; else a reason code such as `socket_closed` or `heartbeat_lapsed`. */+ disconnectReason: string | null;+};++/** What a controller's last status report says beyond its providers. */+export type ControllerReport = {+ observedAt: string | null;+ /** Who moves it onto another release; null from a controller that does not say. */+ updatedBy: 'self' | 'console' | null;+ /** Why it does not run the release Switch names yet; null when it does or does not say. */+ update: { target: string; state: string; problem: string | null } | null;+ /** The machine's resources; null when the report carries none. */+ resources: {+ diskFreeBytes: number;+ diskTotalBytes: number;+ memFreeBytes: number;+ memTotalBytes: number;+ sessionsRunning: number;+ sessionsMax: number;+ } | null;+ /** Each provider's version and when it was last checked, beside `providers`. */+ providerChecks: { provider: string; version: string | null; checkedAt: string | null }[];+ /** Each agent it runs, as it last saw it. */+ agents: ControllerAgentReport[];+};++export type ControllerAgentReport = {+ agentId: string;+ process: string;+ attached: boolean;+ activeSessions: number;+ restarts10m: number;+ since: string | null;+ reason: string | null;+ detail: string | null;};/** A managed agent as the owner's list shows it. */@@ -4086,8 +4139,16 @@ type ManagementControllerJson = {revoked_at: string | null;status?: unknown;workspaces_dir?: string | null;- platform?: { os: string } | null;+ platform?: { os: string; arch?: string; os_version?: string } | null;public_key?: { alg: string; key: string; key_id: string } | null;+ version?: string | null;+ connection?: {+ connected_at: string;+ disconnected_at: string | null;+ disconnect_reason: string | null;+ } | null;+ release?: { wanted: string; running: string | null; current: boolean } | null;+ created_at?: string;};type ManagedAgentJson = {@@ -4145,14 +4206,27 @@ export async function enrollConsoleController(/*** A one-time code a headless controller enrolls with* (`POST /gateway/management/enrollment-codes`): single use, valid for ten- * minutes. A secret until it is spent.+ * minutes. A secret until it is spent. `serverUrl` is the agent bridge's public+ * origin as the server names it; null when it names none.*/-export async function issueEnrollmentCode(server: SwitchServer): Promise<string> {+export async function issueMachineEnrollment(+ server: SwitchServer+): Promise<{ code: string; expiresAt: string; serverUrl: string | null }> {const res = await managementFetch(server, '/enrollment-codes', {authenticated: true,method: 'POST',});- return ((await res.json()) as { code: string }).code;+ const json = (await res.json()) as {+ code: string;+ expires_at: string;+ server_url: string | null;+ };+ return { code: json.code, expiresAt: json.expires_at, serverUrl: json.server_url ?? null };+}++/** Just the code of a fresh enrollment, for a controller Console enrolls itself. */+export async function issueEnrollmentCode(server: SwitchServer): Promise<string> {+ return (await issueMachineEnrollment(server)).code;}/** The signed-in user's controllers (`GET /gateway/management/controllers`). */@@ -4175,6 +4249,24 @@ export async function fetchManagementControllers(json.public_key?.alg === 'X25519'? { key: json.public_key.key, keyId: json.public_key.key_id }: null,+ platform: json.platform+ ? {+ os: json.platform.os,+ arch: json.platform.arch ?? '',+ osVersion: json.platform.os_version ?? '',+ }+ : null,+ version: json.version ?? null,+ connection: json.connection+ ? {+ connectedAt: json.connection.connected_at,+ disconnectedAt: json.connection.disconnected_at,+ disconnectReason: json.connection.disconnect_reason,+ }+ : null,+ release: json.release ?? null,+ report: controllerReport(json.status),+ createdAt: json.created_at ?? null,}));}@@ -4216,6 +4308,25 @@ export async function withdrawMachineLogin();}+/**+ * Has a machine check one provider's install and sign-in again+ * (`POST /operations`, kind `provider.recheck`). Answers the operation; the+ * machine's next status report carries what it found.+ */+export async function recheckMachineProvider(+ server: SwitchServer,+ controllerId: string,+ provider: string+): Promise<{ operationId: string }> {+ const res = await managementFetch(server, '/operations', {+ method: 'POST',+ authenticated: true,+ body: { controller_id: controllerId, kind: 'provider.recheck', params: { provider } },+ });+ const body = (await res.json()) as { id: string };+ return { operationId: body.id };+}+/** One of a machine's operations as its owner sees it, by id; null when the server lists none by it. */export async function fetchMachineOperation(server: SwitchServer,@@ -4241,6 +4352,84 @@ export async function fetchMachineOperation(return { state: found.state, error: found.result?.error ?? null };}+function jsonRecord(value: unknown): Record<string, unknown> | null {+ return value && typeof value === 'object' && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : null;+}++function jsonText(value: unknown): string | null {+ return typeof value === 'string' && value ? value : null;+}++function jsonCount(value: unknown): number {+ return typeof value === 'number' && Number.isFinite(value) ? value : 0;+}++/**+ * The parts of a controller's last status report beyond its providers, read+ * defensively: the report is the controller's own JSON, stored as it sent it,+ * so an older controller can leave any part out. Null before it has reported.+ */+function controllerReport(status: unknown): ControllerReport | null {+ const report = jsonRecord(status);+ if (!report) return null;+ const controller = jsonRecord(report.controller);+ const machine = jsonRecord(report.machine);+ const update = jsonRecord(report.update);+ const updatedBy = controller?.updated_by;+ return {+ observedAt: jsonText(report.observed_at),+ updatedBy: updatedBy === 'self' || updatedBy === 'console' ? updatedBy : null,+ update:+ update && typeof update.target === 'string' && typeof update.state === 'string'+ ? { target: update.target, state: update.state, problem: jsonText(update.problem) }+ : null,+ resources: machine+ ? {+ diskFreeBytes: jsonCount(machine.disk_free_bytes),+ diskTotalBytes: jsonCount(machine.disk_total_bytes),+ memFreeBytes: jsonCount(machine.mem_free_bytes),+ memTotalBytes: jsonCount(machine.mem_total_bytes),+ sessionsRunning: jsonCount(machine.sessions_running),+ sessionsMax: jsonCount(machine.sessions_max),+ }+ : null,+ providerChecks: (Array.isArray(report.providers) ? report.providers : []).flatMap(+ (entry: unknown) => {+ const provider = jsonRecord(entry);+ if (!provider || typeof provider.provider !== 'string') return [];+ return [+ {+ provider: provider.provider,+ version: jsonText(provider.version),+ checkedAt: jsonText(provider.checked_at),+ },+ ];+ }+ ),+ agents: (Array.isArray(report.agents) ? report.agents : []).flatMap(+ (entry: unknown): ControllerAgentReport[] => {+ const agent = jsonRecord(entry);+ if (!agent || typeof agent.agent_id !== 'string' || typeof agent.process !== 'string')+ return [];+ return [+ {+ agentId: agent.agent_id,+ process: agent.process,+ attached: agent.attached === true,+ activeSessions: jsonCount(jsonRecord(agent.sessions)?.active),+ restarts10m: jsonCount(agent.restarts_10m),+ since: jsonText(agent.since),+ reason: jsonText(agent.reason),+ detail: jsonText(agent.detail),+ },+ ];+ }+ ),+ };+}+/*** The providers in a controller's last status report. An entry that does not* say which provider it is, or whether it is installed, is left out; a logindiff --git a/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts b/console/apps/switch-console-desktop/src/renderer/app/modal-registry.tsindex 546efd536..e89f0effe 100644--- a/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts+++ b/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts@@ -12,6 +12,7 @@ import { DisconnectServiceDialog } from '@renderer/features/connectors/disconnecimport { AddAgentModal } from '@renderer/features/locations/components/add-agent-modal/add-agent-modal';import { DeleteAgentModal } from '@renderer/features/locations/components/delete-agent-modal';import { ResetAgentModal } from '@renderer/features/locations/components/reset-agent-modal';+import { AddMachineModal } from '@renderer/features/machines/add-machine-modal';import { AddHostModal } from '@renderer/features/remote-hosts/add-host-modal';import { RemoveAgentConfigModal } from '@renderer/features/remote-hosts/remove-agent-config-modal';import { CreateSessionModal } from '@renderer/features/sessions/create-session-modal/create-session-modal';@@ -70,6 +71,7 @@ export const modalRegistry = {commandPaletteModal: createModal(CommandPaletteModal, { size: 'md' }),sessionModal: createModal(CreateSessionModal, { dismissOnOutsideClick: false }),addAgentModal: createModal(AddAgentModal, { size: 'lg', dismissOnOutsideClick: false }),+ addMachineModal: createModal(AddMachineModal, { size: 'lg' }),saveTemplateModal: createModal(SaveTemplateModal, { size: 'sm', dismissOnOutsideClick: false }),confirmActionModal: createModal(ConfirmActionDialog, { size: 'xs' }),deleteAgentModal: createModal(DeleteAgentModal, { size: 'sm' }),diff --git a/console/apps/switch-console-desktop/src/renderer/app/view-registry.ts b/console/apps/switch-console-desktop/src/renderer/app/view-registry.tsindex b09e4c96e..7ba81fe77 100644--- a/console/apps/switch-console-desktop/src/renderer/app/view-registry.ts+++ b/console/apps/switch-console-desktop/src/renderer/app/view-registry.ts@@ -4,6 +4,8 @@ import { adminView } from '@renderer/features/admin/admin-view';import { chatView } from '@renderer/features/chats/chat-view';import { connectorsView } from '@renderer/features/connectors/connectors-view';import { locationView } from '@renderer/features/locations/view';+import { machineView } from '@renderer/features/machines/machine-view';+import { machinesView } from '@renderer/features/machines/machines-view';import { managedAgentView } from '@renderer/features/managed-agents/managed-agent-view';import { remoteHostView } from '@renderer/features/remote-hosts/views/remote-host-view';import { remoteHostsView } from '@renderer/features/remote-hosts/views/remote-hosts-view';@@ -38,6 +40,8 @@ export const views = {server: serverView,managedServer: managedServerView,serverAgents: serverAgentsView,+ machines: machinesView,+ machine: machineView,connectors: connectorsView,serverRooms: serverRoomsView,remoteHosts: remoteHostsView,diff --git a/console/apps/switch-console-desktop/src/renderer/features/deeplinks/open-console-link.ts b/console/apps/switch-console-desktop/src/renderer/features/deeplinks/open-console-link.tsindex a5043c2ad..69f2d9727 100644--- a/console/apps/switch-console-desktop/src/renderer/features/deeplinks/open-console-link.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/deeplinks/open-console-link.ts@@ -85,7 +85,7 @@ async function openOnServer(serverId: string, link: ConsoleLink): Promise<void>return;case 'agents/new':navigation.navigate('serverAgents', { serverId });- showModal('addAgentModal', { entryPoint: 'link' });+ showModal('addAgentModal', { entryPoint: 'link', machineId: null });return;case 'agent':await openAgent(serverId, link.id!, link.tab);diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsxindex 36757d147..33580033b 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx@@ -1,6 +1,7 @@import type { BaseModalProps } from '@renderer/lib/modal/modal-provider';import type { UiEntryPoint } from '@shared/core/telemetry/reporting';import { NewAgentForm } from './new-agent-form';+import { machineRunLocation } from './server-run-locations';export type AddLocationModalProps = BaseModalProps<void> & {/**@@ -9,16 +10,18 @@ export type AddLocationModalProps = BaseModalProps<void> & {* under the same heading as the ones that did not.*/entryPoint: UiEntryPoint;+ /** The machine the agent goes on, picked already: null to start on this computer. */+ machineId: string | null;};-export function AddAgentModal({ onClose, entryPoint }: AddLocationModalProps) {+export function AddAgentModal({ onClose, entryPoint, machineId }: AddLocationModalProps) {return (<NewAgentFormonClose={onClose}onBack={null}entryPoint={entryPoint}serverId={null}- initialRunLocation="local"+ initialRunLocation={machineId ? machineRunLocation(machineId) : 'local'}/>);}diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/new-agent-form.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/new-agent-form.tsxindex e0c1d76d6..1389b21ad 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/new-agent-form.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/new-agent-form.tsx@@ -79,6 +79,7 @@ import {machineLabel,machineRunLocation,machineRunLocations,+ type MachineRunLocation,sshHostIsMachine,thisComputerIsMachine,} from './server-run-locations';@@ -88,7 +89,8 @@ export type NewAgentFormProps = {onBack: (() => void) | null;entryPoint: UiEntryPoint;serverId: string | null;- initialRunLocation: 'local' | 'cloud';+ /** Where the agent runs at first: this computer, Switch cloud, or one of the server's machines. */+ initialRunLocation: 'local' | 'cloud' | MachineRunLocation;};/** Sentinel `runHost` value meaning "run on this machine" (no remote host). */@@ -300,7 +302,9 @@ export const NewAgentForm = observer(function NewAgentForm({if (runHost === 'cloud') return;const id = machineIdOf(runHost);if (!serverMachines) {- if (id !== null) setRunHost(LOCAL_RUN_LOCATION);+ // A machine picked before the list arrives keeps its place until the list says otherwise.+ if (id !== null && (!askForMachines || machinesQuery.isFetched))+ setRunHost(LOCAL_RUN_LOCATION);return;}if (id !== null) {@@ -309,7 +313,7 @@ export const NewAgentForm = observer(function NewAgentForm({}const enrolled = machineFor(runHost, serverMachines);if (enrolled) setRunHost(machineRunLocation(enrolled.id));- }, [serverMachines, runHost]);+ }, [serverMachines, runHost, askForMachines, machinesQuery.isFetched]);// Everything chosen below the run location belongs to the machine it was// chosen on, so changing machines clears it.diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/server-run-locations.ts b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/server-run-locations.tsindex 9c948ee14..15e5618da 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/server-run-locations.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/server-run-locations.ts@@ -2,8 +2,11 @@ import type { OwnedMachine } from '@shared/core/managed-agents/managed-agents';const MACHINE_PREFIX = 'machine:';+/** A run location naming one of the server's machines. */+export type MachineRunLocation = `machine:${string}`;+/** The run location value for one of the server's machines. */-export function machineRunLocation(machineId: string): string {+export function machineRunLocation(machineId: string): MachineRunLocation {return `${MACHINE_PREFIX}${machineId}`;}diff --git a/console/apps/switch-console-desktop/src/renderer/features/machines/add-machine-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/machines/add-machine-modal.tsxnew file mode 100644index 000000000..a17b58542--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/machines/add-machine-modal.tsx@@ -0,0 +1,157 @@+import { useQuery } from '@tanstack/react-query';+import { useState } from 'react';+import { CopyButton } from '@renderer/features/admin/copy-button';+import { failureText } from '@renderer/lib/errors/describe-failure';+import { rpc } from '@renderer/lib/ipc';+import type { BaseModalProps } from '@renderer/lib/modal/modal-provider';+import { Button } from '@renderer/lib/ui/button';+import {+ DialogContentArea,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@renderer/lib/ui/dialog';+import { Field, FieldGroup, FieldLabel } from '@renderer/lib/ui/field';+import { Input } from '@renderer/lib/ui/input';+import { Spinner } from '@renderer/lib/ui/spinner';+import {+ enrollCommand,+ installCommand,+ MAX_MACHINE_DESCRIPTION,+ MAX_MACHINE_NAME,+} from '@shared/core/managed-agents/machine-enrollment';++type Props = BaseModalProps<void> & { serverId: string };++/**+ * How to add a machine: run the agents controller on it and enroll it with a+ * one-time code, issued when the dialog opens. The code is shown once:+ * closing discards it, and opening again issues a new one. The optional name+ * and description go into the commands, so the machine enrolls with them.+ */+export function AddMachineModal({ serverId, onClose }: Props) {+ const [name, setName] = useState('');+ const [description, setDescription] = useState('');+ // A fresh code each time the dialog opens, never one from the cache.+ const [opening] = useState(() => crypto.randomUUID());+ const enrollment = useQuery({+ queryKey: ['machine-enrollment', serverId, opening],+ queryFn: () => rpc.managedAgents.machineEnrollment(serverId),+ staleTime: Infinity,+ gcTime: 0,+ retry: false,+ });+ const nameTooLong = name.trim().length > MAX_MACHINE_NAME;+ const descriptionTooLong = description.trim().length > MAX_MACHINE_DESCRIPTION;+ const issued = enrollment.data;+ const machine = { name, description };++ return (+ <>+ <DialogHeader>+ <DialogTitle>Add a machine</DialogTitle>+ </DialogHeader>+ <DialogContentArea className="space-y-4 pt-0">+ <DialogDescription>+ Run the agents controller on the computer that should run your agents: a laptop, your own+ VM or a server. Enroll it once with the code below, and it runs whatever agents you place+ on it. It needs Linux or macOS with Node 22.13 or later, and the CLI of each provider your+ agents use, signed in as the user the controller runs as.+ </DialogDescription>+ {enrollment.error ? (+ <p role="alert" className="text-sm text-destructive">+ {failureText(enrollment.error, 'Could not issue an enrollment code.')}+ </p>+ ) : !issued ? (+ <Spinner />+ ) : (+ <>+ <FieldGroup>+ <Field>+ <FieldLabel>Name (optional)</FieldLabel>+ <Input+ value={name}+ onChange={(e) => setName(e.target.value)}+ placeholder="Defaults to the machine's host name"+ />+ {nameTooLong && (+ <p className="mt-1 text-xs text-destructive">+ At most {MAX_MACHINE_NAME} characters.+ </p>+ )}+ </Field>+ <Field>+ <FieldLabel>Description (optional)</FieldLabel>+ <Input+ value={description}+ onChange={(e) => setDescription(e.target.value)}+ placeholder="What it is for, such as the build box in the office"+ />+ {descriptionTooLong && (+ <p className="mt-1 text-xs text-destructive">+ At most {MAX_MACHINE_DESCRIPTION} characters.+ </p>+ )}+ </Field>+ </FieldGroup>++ {issued.loopback && (+ <p className="rounded-md border border-border bg-background-1 px-3 py-2 text-xs text-foreground-muted">+ This server is at {issued.serverUrl}, which only this computer can reach. Another+ machine needs an address it can reach Switch at: change <code>--server</code> to+ that.+ </p>+ )}++ {nameTooLong || descriptionTooLong ? (+ <p className="text-sm text-foreground-muted">+ Shorten the name or description to see the commands.+ </p>+ ) : (+ <>+ <CommandBlock+ title="Install, enroll and start"+ command={installCommand(issued.serverUrl, issued.code, machine)}+ note="Installs the newest controller with npm, enrolls the machine, and runs the controller as a service of your user."+ />+ <CommandBlock+ title="Already installed"+ command={enrollCommand(issued.serverUrl, issued.code, machine)}+ note="Then start it with switch-agent-controller install-service."+ />+ </>+ )}++ <p className="text-xs text-foreground-muted">+ The code is single use and valid until{' '}+ {new Date(issued.expiresAt).toLocaleTimeString()}. The machine shows up in Your+ Machines once its controller reports; if it does not, run{' '}+ <code>switch-agent-controller doctor</code> on it. A computer you reach over SSH can+ also join without this: create an agent on it, and Switch Console sets its controller+ up.+ </p>+ </>+ )}+ </DialogContentArea>+ <DialogFooter>+ <Button onClick={onClose}>Done</Button>+ </DialogFooter>+ </>+ );+}++function CommandBlock({ title, command, note }: { title: string; command: string; note: string }) {+ return (+ <div>+ <h4 className="mb-1 text-sm font-medium text-foreground">{title}</h4>+ <div className="flex items-start gap-1 rounded-md bg-background-1 px-3 py-2">+ <code className="min-w-0 flex-1 font-mono text-xs break-all text-foreground select-all">+ {command}+ </code>+ <CopyButton value={command} />+ </div>+ <p className="mt-1 text-xs text-foreground-muted">{note}</p>+ </div>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/machines/collapsible-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/machines/collapsible-section.tsxnew file mode 100644index 000000000..ebafe6749--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/machines/collapsible-section.tsx@@ -0,0 +1,46 @@+import { ChevronRightIcon } from 'lucide-react';+import { type ReactNode, useId, useState } from 'react';+import { cn } from '@renderer/utils/utils';++/**+ * A section of a machine's page that folds away under its title, with the+ * caret beside the title as the chat's thinking line has it.+ */+export function CollapsibleSection({+ title,+ defaultOpen,+ children,+}: {+ title: string;+ /** Whether it starts open. */+ defaultOpen: boolean;+ children: ReactNode;+}) {+ const [open, setOpen] = useState(defaultOpen);+ const contentId = useId();+ return (+ <section>+ <h3 className="text-[11.5px] text-[#8A8A8A]">+ <button+ type="button"+ aria-expanded={open}+ aria-controls={contentId}+ onClick={() => setOpen((shown) => !shown)}+ className="focus-visible:ring-ring -mx-1 inline-flex cursor-pointer items-center gap-1 rounded px-1 transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:outline-none"+ >+ {title}+ <ChevronRightIcon+ aria-hidden+ className={cn(+ 'size-3 shrink-0 transition-transform motion-reduce:transition-none',+ open && 'rotate-90'+ )}+ />+ </button>+ </h3>+ <div id={contentId} hidden={!open}>+ {children}+ </div>+ </section>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/machines/machine-details.tsx b/console/apps/switch-console-desktop/src/renderer/features/machines/machine-details.tsxnew file mode 100644index 000000000..946c4ac61--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/machines/machine-details.tsx@@ -0,0 +1,295 @@+import { Plus } from 'lucide-react';+import { CopyButton } from '@renderer/features/admin/copy-button';+import {+ managedAgentLabel,+ managedAgentState,+} from '@renderer/features/managed-agents/managed-agent-state';+import type { ManagedTone } from '@renderer/features/switch-servers/managed-server-state';+import { MessageBox, SectionLabel } from '@renderer/features/switch-servers/server-page-ui';+import { agoLabel, sinceLabel } from '@renderer/features/switch-servers/server-times';+import { AgentAvatar } from '@renderer/lib/components/agent-avatar';+import { useNavigate } from '@renderer/lib/layout/navigation-provider';+import { useShowModal } from '@renderer/lib/modal/modal-provider';+import { Button } from '@renderer/lib/ui/button';+import { formatBytes } from '@renderer/utils/formatBytes';+import { cn } from '@renderer/utils/utils';+import type { MachineDetail, ManagedAgentView } from '@shared/core/managed-agents/managed-agents';+import { providerDisplayName } from '@shared/core/providers/agent-provider-registry';+import { CollapsibleSection } from './collapsible-section';+import { MachineIcon, TONE_DOT, TonePill } from './machine-marks';+import { MachineProviders } from './machine-providers';+import {+ controllerRelease,+ lastContact,+ machineConnection,+ machineKindLabel,+ machineNotices,+ type MachineTone,+ platformLabel,+ resourceLabel,+ sessionsLabel,+} from './machine-state';++/** A notice's box, in the server page's hues. */+const NOTICE_TONE: Record<MachineTone, ManagedTone> = {+ ok: 'running',+ warning: 'attention',+ problem: 'failed',+ idle: 'stopped',+};++const STATE_TEXT: Record<MachineTone, string> = {+ ok: 'text-foreground',+ warning: 'text-foreground-warning',+ problem: 'text-foreground-error',+ idle: 'text-[var(--fg-dim)]',+};++const AGENT_TONE: Record<ReturnType<typeof managedAgentState>['tone'], MachineTone> = {+ ok: 'ok',+ busy: 'warning',+ idle: 'idle',+ problem: 'problem',+};++const PROCESS_TONE: Record<string, MachineTone> = {+ running: 'ok',+ starting: 'warning',+ pending: 'warning',+ restarting: 'warning',+ crashed: 'problem',+ failed: 'problem',+};++/**+ * One machine's page: what it is and whether it is connected, anything that+ * needs doing about it, what it last reported, and the agents on it. Built+ * from the local server's status page pieces, the other page about one+ * computer.+ */+export function MachineDetails({+ serverId,+ machine,+ placed,+}: {+ serverId: string;+ machine: MachineDetail;+ /** The managed agents placed on it. */+ placed: ManagedAgentView[];+}) {+ const connection = machineConnection(machine);+ const platform = platformLabel(machine.platform);+ const notices = machineNotices(machine);+ const removed = machine.state === 'revoked';+ const showAddAgentModal = useShowModal('addAgentModal');++ return (+ <div className="space-y-[18px]">+ <header className="flex items-center gap-3">+ <MachineIcon machine={machine} className="rounded-[10px] border-0 bg-[var(--fill)]" />+ <div className="min-w-0 flex-1">+ <div className="flex min-w-0 items-center gap-2">+ <h2 className="truncate font-mono text-[17px] font-semibold text-foreground">+ {machine.name}+ </h2>+ <TonePill tone={connection.tone} label={connection.label} title={connection.title} />+ </div>+ <p className="truncate text-[13px] text-[var(--fg-dim)]">+ {[machineKindLabel(machine), platform].filter(Boolean).join(' · ')}+ </p>+ </div>+ {!removed && (+ <Button+ size="sm"+ variant="outline"+ // The new agent form lists an offline machine but cannot place an agent on it.+ disabled={machine.state !== 'online'}+ title={+ machine.state === 'online' ? undefined : 'It can take a new agent once it is online.'+ }+ onClick={() => showAddAgentModal({ entryPoint: 'machine_page', machineId: machine.id })}+ >+ <Plus className="size-4" />+ New agent+ </Button>+ )}+ </header>++ {machine.description && (+ <p className="text-[13px] whitespace-pre-line text-foreground">{machine.description}</p>+ )}++ {notices.map((notice) => (+ <MessageBox key={notice.key} tone={NOTICE_TONE[notice.tone]} title={notice.title}>+ <p>{notice.body}</p>+ </MessageBox>+ ))}++ <DetailsSection machine={machine} />+ {!removed && <MachineProviders serverId={serverId} machine={machine} />}+ {!removed && <AgentsSection machine={machine} placed={placed} />}+ </div>+ );+}++/**+ * The agents on the machine: those placed on it, each opening its page, and+ * any others it reports running, which this person cannot open.+ */+function AgentsSection({+ machine,+ placed,+}: {+ machine: MachineDetail;+ placed: ManagedAgentView[];+}) {+ const { navigate } = useNavigate();+ const unlisted = machine.agents.filter(+ (report) => !placed.some((agent) => agent.agentId === report.agentId)+ );+ const count = placed.length + unlisted.length;+ return (+ <CollapsibleSection title={count === 0 ? 'Agents' : `Agents · ${count}`} defaultOpen>+ <div className="mt-1">+ {count === 0 && (+ <p className="py-[9px] text-[13px] text-[var(--fg-dim)]">No agents placed on it.</p>+ )}+ {placed.map((agent) => {+ const label = managedAgentLabel(agent);+ const state = managedAgentState(agent);+ const tone = AGENT_TONE[state.tone];+ const sessions =+ machine.agents.find((report) => report.agentId === agent.agentId)?.activeSessions ?? 0;+ return (+ <button+ key={agent.agentId}+ type="button"+ onClick={() =>+ navigate('managedAgent', {+ serverId: agent.serverId,+ agentId: agent.agentId,+ name: label,+ })+ }+ className="-mx-2 flex w-[calc(100%+1rem)] cursor-pointer items-center gap-2.5 rounded-md border-b-[0.5px] border-[var(--hair-soft)] px-2 py-[7px] text-left text-[13px] transition-colors hover:bg-[var(--sel-soft)]"+ >+ <AgentAvatar+ name={label}+ iconUrl={agent.iconUrl}+ serverId={agent.serverId}+ size={20}+ />+ <span className="min-w-0 flex-1 truncate text-foreground">{label}</span>+ <span className="shrink-0 text-[var(--fg-dim)]">+ {providerDisplayName(agent.definition.provider) ?? agent.definition.provider}+ {sessions > 0 && ` · ${sessions} ${sessions === 1 ? 'session' : 'sessions'}`}+ </span>+ <StateText tone={tone} label={state.label} title={state.detail ?? undefined} />+ </button>+ );+ })}+ {unlisted.map((report) => (+ <div+ key={report.agentId}+ className="flex items-center gap-2.5 border-b-[0.5px] border-[var(--hair-soft)] py-[7px] text-[13px]"+ title="Runs here, but is not one of the agents you can open."+ >+ <span className="min-w-0 flex-1 truncate font-mono text-[11.5px] text-[var(--fg-dim)]">+ {report.agentId}+ </span>+ <StateText+ tone={PROCESS_TONE[report.process] ?? 'idle'}+ label={report.process}+ title={[report.reason, report.detail].filter(Boolean).join(': ') || undefined}+ />+ </div>+ ))}+ </div>+ </CollapsibleSection>+ );+}++function StateText({ tone, label, title }: { tone: MachineTone; label: string; title?: string }) {+ return (+ <span+ title={title}+ className={cn('flex w-24 shrink-0 items-center justify-end gap-1.5', STATE_TEXT[tone])}+ >+ <span aria-hidden className={cn('size-1.5 shrink-0 rounded-full', TONE_DOT[tone])} />+ <span className="truncate">{label}</span>+ </span>+ );+}++/**+ * What the machine last reported about itself, and when it was added and last+ * heard from: the short facts in a grid, then its workspaces folder, the one+ * value too long for one.+ */+function DetailsSection({ machine }: { machine: MachineDetail }) {+ const now = new Date();+ const release = controllerRelease(machine);+ const contact = lastContact(machine, now);+ const resources = machine.resources;+ const memory = resources+ ? resourceLabel(resources.memFreeBytes, resources.memTotalBytes, formatBytes)+ : null;+ const disk = resources+ ? resourceLabel(resources.diskFreeBytes, resources.diskTotalBytes, formatBytes)+ : null;+ const removed = machine.state === 'revoked';++ return (+ <>+ {/* Label above value, so each sits next to its own: these values are+ short, and across a full-width row the eye loses which is which. */}+ <dl className="grid grid-cols-[repeat(auto-fill,minmax(180px,1fr))] gap-x-6 gap-y-4">+ <Fact label="Controller">+ <span title={release.title}>+ {machine.version ?? 'Not reported'}+ {release.badge+ ? ` · ${release.badge.label.toLowerCase()}`+ : machine.release?.current+ ? ' · up to date'+ : ''}+ </span>+ </Fact>+ {removed ? (+ machine.revokedAt && <Fact label="Removed">{sinceLabel(machine.revokedAt, now)}</Fact>+ ) : machine.state === 'online' && machine.connection ? (+ <Fact label="Connected since">{sinceLabel(machine.connection.connectedAt, now)}</Fact>+ ) : (+ <Fact label="Last seen">{contact ? agoLabel(contact, now) : 'Never'}</Fact>+ )}+ {!removed && resources && (+ <>+ <Fact label="Sessions running">{sessionsLabel(resources)}</Fact>+ {memory && <Fact label="Memory">{memory}</Fact>}+ {disk && <Fact label="Disk">{disk}</Fact>}+ </>+ )}+ {machine.createdAt && <Fact label="Added">{sinceLabel(machine.createdAt, now)}</Fact>}+ </dl>+ {machine.workspacesDir && (+ <section>+ <SectionLabel>Workspaces folder</SectionLabel>+ <div className="mt-1 flex items-start gap-1">+ <code className="min-w-0 pt-px font-[Menlo,ui-monospace,monospace] text-[11.5px] break-all text-foreground">+ {machine.workspacesDir}+ </code>+ <CopyButton value={machine.workspacesDir} />+ </div>+ </section>+ )}+ </>+ );+}++function Fact({ label, children }: { label: string; children: React.ReactNode }) {+ return (+ <div className="min-w-0">+ <dt className="text-[11.5px] text-[var(--fg-dim)]">{label}</dt>+ <dd className="mt-0.5 truncate text-[13px] text-foreground">{children}</dd>+ </div>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/machines/machine-marks.tsx b/console/apps/switch-console-desktop/src/renderer/features/machines/machine-marks.tsxnew file mode 100644index 000000000..3cf3f933b--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/machines/machine-marks.tsx@@ -0,0 +1,71 @@+import { Cloud, Laptop, Monitor, Server } from 'lucide-react';+import { cn } from '@renderer/utils/utils';+import type { MachineDetail } from '@shared/core/managed-agents/managed-agents';+import type { MachineTone } from './machine-state';++export const TONE_DOT: Record<MachineTone, string> = {+ ok: 'bg-green-500',+ warning: 'bg-amber-500',+ problem: 'bg-red-500',+ idle: 'bg-foreground-muted',+};++const PILL: Record<MachineTone, string> = {+ ok: 'bg-background-success text-foreground-success',+ warning: 'bg-background-warning text-foreground-warning',+ problem: 'bg-background-error text-foreground-error',+ idle: 'bg-background-tertiary text-foreground-muted',+};++export function TonePill({+ tone,+ label,+ title,+ dot = true,+}: {+ tone: MachineTone;+ label: string;+ title?: string;+ dot?: boolean;+}) {+ return (+ <span+ title={title}+ className={cn(+ 'inline-flex h-5 shrink-0 items-center gap-1.5 rounded-full px-2 text-[11px] whitespace-nowrap',+ PILL[tone]+ )}+ >+ {dot && <span aria-hidden className={cn('size-1.5 rounded-full', TONE_DOT[tone])} />}+ {label}+ </span>+ );+}++/** What kind of machine it is, as an icon: this computer, a cloud machine, a Console, or a server. */+export function MachineIcon({+ machine,+ className,+}: {+ machine: MachineDetail;+ className?: string;+}) {+ const Icon =+ machine.local?.kind === 'this-computer'+ ? Laptop+ : machine.cloud+ ? Cloud+ : machine.kind === 'console'+ ? Monitor+ : Server;+ return (+ <span+ className={cn(+ 'flex size-9 shrink-0 items-center justify-center rounded-lg border border-border bg-background',+ className+ )}+ >+ <Icon className="size-4 text-foreground-muted" />+ </span>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/machines/machine-providers.tsx b/console/apps/switch-console-desktop/src/renderer/features/machines/machine-providers.tsxnew file mode 100644index 000000000..281a21450--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/machines/machine-providers.tsx@@ -0,0 +1,219 @@+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';+import { KeyRound, RefreshCw } from 'lucide-react';+import { useEffect, useState } from 'react';+import {+ GiveMachineLogin,+ loginKindsFor,+} from '@renderer/features/locations/components/add-agent-modal/give-machine-login';+import { MANAGED_AGENTS_KEY } from '@renderer/features/managed-agents/use-managed-agents';+import {+ ProviderStatusRow,+ ReportedProviderLine,+} from '@renderer/lib/components/provider-status-row';+import { failureText } from '@renderer/lib/errors/describe-failure';+import { rpc } from '@renderer/lib/ipc';+import { useNavigate } from '@renderer/lib/layout/navigation-provider';+import { Button } from '@renderer/lib/ui/button';+import type {+ MachineDetail,+ MachineProviderDetail,+} from '@shared/core/managed-agents/managed-agents';+import {+ isValidProviderId,+ providerDisplayName,+} from '@shared/core/providers/agent-provider-registry';+import { CollapsibleSection } from './collapsible-section';++/** How often a recheck is asked about while the machine works on it. */+const RECHECK_POLL_MS = 1_500;++/**+ * The providers a machine reported, installed ones first, each in the row+ * Settings → Agent providers uses for this computer. What Switch can do from+ * here is ask the machine to check one again and give it a login; installing+ * a provider still happens on the machine, which the section says.+ */+export function MachineProviders({+ serverId,+ machine,+}: {+ serverId: string;+ machine: MachineDetail;+}) {+ const { navigate } = useNavigate();+ const installed = machine.providers.filter((p) => p.problem !== 'not installed');+ const missing = machine.providers.filter((p) => p.problem === 'not installed');+ const thisComputer = machine.local?.kind === 'this-computer';++ // Folded at first: a provider that cannot run agents is already raised in a+ // notice above the details, so the list is reference.+ return (+ <CollapsibleSection title="Providers" defaultOpen={false}>+ {machine.providers.length === 0 ? (+ <p className="py-[9px] text-[13px] text-[var(--fg-dim)]">Not reported yet.</p>+ ) : (+ <div className="-mx-3 mt-1">+ {[...installed, ...missing].map((provider) => (+ <MachineProviderRow+ key={provider.provider}+ serverId={serverId}+ machine={machine}+ provider={provider}+ />+ ))}+ </div>+ )}+ {missing.length > 0 &&+ (thisComputer ? (+ <p className="mt-1 text-[13px] text-[var(--fg-dim)]">+ Install providers on this computer from{' '}+ <button+ type="button"+ className="cursor-pointer text-foreground underline-offset-2 hover:underline"+ onClick={() => navigate('settings', { tab: 'clis-models' })}+ >+ Settings → Agent providers+ </button>+ .+ </p>+ ) : (+ <p className="mt-1 text-[13px] text-[var(--fg-dim)]">+ Switch cannot install a provider on {machine.name}: install its CLI there, then recheck+ it here.+ </p>+ ))}+ </CollapsibleSection>+ );+}++function MachineProviderRow({+ serverId,+ machine,+ provider,+}: {+ serverId: string;+ machine: MachineDetail;+ provider: MachineProviderDetail;+}) {+ const queryClient = useQueryClient();+ const [operationId, setOperationId] = useState<string | null>(null);+ const [giving, setGiving] = useState(false);+ const known = isValidProviderId(provider.provider) ? provider.provider : null;+ const name = providerDisplayName(provider.provider) ?? provider.provider;+ const installed = provider.problem !== 'not installed';+ const online = machine.state === 'online';++ const recheck = useMutation({+ mutationFn: (id: NonNullable<typeof known>) =>+ rpc.managedAgents.recheckMachineProvider({+ serverId,+ machineId: machine.id,+ provider: id,+ }),+ onSuccess: ({ operationId: id }) => setOperationId(id),+ });+ const outcome = useQuery({+ queryKey: [MANAGED_AGENTS_KEY, serverId, 'machine-recheck', operationId],+ queryFn: () =>+ rpc.managedAgents.machineRecheckOutcome({+ serverId,+ machineId: machine.id,+ operationId: operationId!,+ }),+ enabled: operationId !== null,+ refetchInterval: (query) =>+ query.state.data?.state === 'pending' || query.state.data === undefined+ ? RECHECK_POLL_MS+ : false,+ });+ const result = outcome.data;+ const done = result !== undefined && result.state !== 'pending';+ // What the machine found arrives with its report: read it now rather than at the next poll.+ useEffect(() => {+ if (done) void queryClient.invalidateQueries({ queryKey: [MANAGED_AGENTS_KEY, serverId] });+ }, [done, queryClient, serverId]);+ const checking = recheck.isPending || (operationId !== null && !done);++ const canGive =+ known !== null &&+ installed &&+ !provider.ready &&+ online &&+ machine.acceptsLogins &&+ loginKindsFor(known).length > 0;++ const failure = recheck.error+ ? failureText(recheck.error, `Could not ask ${machine.name} to check ${name}.`)+ : result?.state === 'failed'+ ? result.message+ : null;++ return (+ <div>+ <ProviderStatusRow+ providerId={provider.provider}+ name={name}+ meta={provider.version ?? undefined}+ installed={installed}+ status={+ <span+ title={+ [+ provider.detail,+ provider.checkedAt+ ? `Checked ${new Date(provider.checkedAt).toLocaleString()}`+ : null,+ ]+ .filter(Boolean)+ .join(' · ') || undefined+ }+ >+ <ReportedProviderLine reported={provider} checking={checking} />+ </span>+ }+ actions={+ <>+ {canGive && (+ <Button+ size="sm"+ variant="ghost"+ aria-pressed={giving}+ onClick={() => setGiving((open) => !open)}+ >+ <KeyRound className="size-3.5" />+ Give login+ </Button>+ )}+ {known !== null && installed && online && (+ <Button+ size="sm"+ variant="ghost"+ disabled={checking}+ onClick={() => recheck.mutate(known)}+ aria-label={`Recheck ${name} on ${machine.name}`}+ >+ <RefreshCw className={checking ? 'size-3.5 animate-spin' : 'size-3.5'} />+ Recheck+ </Button>+ )}+ </>+ }+ />+ {failure && (+ <p role="alert" className="px-3 pb-2 text-xs text-foreground-error">+ {failure}+ </p>+ )}+ {giving && known !== null && (+ <div className="px-3 pb-3">+ <GiveMachineLogin+ serverId={serverId}+ machine={machine}+ provider={known}+ onClose={() => setGiving(false)}+ />+ </div>+ )}+ </div>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/machines/machine-state.test.ts b/console/apps/switch-console-desktop/src/renderer/features/machines/machine-state.test.tsnew file mode 100644index 000000000..fd99fb55a--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/machines/machine-state.test.ts@@ -0,0 +1,257 @@+import { describe, expect, it } from 'vitest';+import type { MachineDetail } from '@shared/core/managed-agents/managed-agents';+import {+ arrangeMachines,+ controllerRelease,+ filterMachines,+ lastContact,+ machineConnection,+ machineNotices,+ machineSummary,+ platformLabel,+ sessionsLabel,+} from './machine-state';++function machine(patch: Partial<MachineDetail> & { id: string }): MachineDetail {+ return {+ name: patch.id,+ kind: 'daemon',+ state: 'online',+ providers: [],+ acceptsLogins: false,+ cloud: false,+ workspacesDir: null,+ os: null,+ local: null,+ description: null,+ platform: null,+ version: null,+ connection: {+ connectedAt: '2026-10-01T10:00:00Z',+ disconnectedAt: null,+ disconnectReason: null,+ },+ release: null,+ updatedBy: null,+ update: null,+ resources: null,+ agents: [],+ lastSeenAt: null,+ observedAt: null,+ createdAt: null,+ revokedAt: null,+ ...patch,+ };+}++describe('machineConnection', () => {+ it('says why an offline machine went', () => {+ const shown = machineConnection(+ machine({+ id: 'm',+ state: 'offline',+ connection: {+ connectedAt: '2026-10-01T10:00:00Z',+ disconnectedAt: '2026-10-01T11:00:00Z',+ disconnectReason: 'heartbeat_lapsed',+ },+ })+ );+ expect(shown.label).toBe('Offline');+ expect(shown.tone).toBe('problem');+ expect(shown.title).toContain('its connection stopped responding');+ });++ it('tells a machine that never connected from one that went', () => {+ expect(machineConnection(machine({ id: 'm', state: 'unknown', connection: null })).label).toBe(+ 'Never connected'+ );+ });+});++describe('controllerRelease', () => {+ it('flags nothing for a machine Console updates', () => {+ expect(controllerRelease(machine({ id: 'm', kind: 'console' }))).toEqual({+ title: 'Updates with Switch Console, which runs it.',+ badge: null,+ });+ });++ it('says a controller waiting for its sessions to end will update when idle', () => {+ const shown = controllerRelease(+ machine({+ id: 'm',+ version: '1.0.0',+ release: { wanted: '1.1.0', running: '1.0.0', current: false },+ update: { target: '1.1.0', state: 'waiting_idle', problem: null },+ })+ );+ expect(shown.badge).toEqual({ label: 'Updating when idle', tone: 'warning' });+ });++ it('calls a controller behind when it says nothing about the release', () => {+ const shown = controllerRelease(+ machine({ id: 'm', release: { wanted: '1.1.0', running: '1.0.0', current: false } })+ );+ expect(shown.badge?.label).toBe('Behind');+ });+});++describe('lastContact', () => {+ it('is the latest of what Switch heard while the machine is offline', () => {+ expect(+ lastContact(+ machine({+ id: 'm',+ state: 'offline',+ lastSeenAt: '2026-10-01T10:30:00Z',+ connection: {+ connectedAt: '2026-10-01T10:00:00Z',+ disconnectedAt: '2026-10-01T11:00:00Z',+ disconnectReason: null,+ },+ }),+ new Date('2026-10-02T00:00:00Z')+ )+ ).toBe('2026-10-01T11:00:00Z');+ });+});++describe('platformLabel', () => {+ it('names the operating system the way people do', () => {+ expect(platformLabel({ os: 'macos', arch: 'arm64', osVersion: '15.1' })).toBe(+ 'macOS 15.1 · arm64'+ );+ expect(platformLabel(null)).toBeNull();+ });+});++describe('arrangeMachines', () => {+ it('puts this computer first, connected machines next, and removed ones apart', () => {+ const { live, removed } = arrangeMachines([+ machine({ id: 'b-offline', state: 'offline' }),+ machine({ id: 'a-online' }),+ machine({ id: 'gone', state: 'revoked' }),+ machine({ id: 'z-laptop', local: { kind: 'this-computer' } }),+ ]);+ expect(live.map((m) => m.id)).toEqual(['z-laptop', 'a-online', 'b-offline']);+ expect(removed.map((m) => m.id)).toEqual(['gone']);+ });+});++describe('filterMachines', () => {+ const machines = [+ machine({ id: 'm1', name: 'build-box', description: 'The GPU one' }),+ machine({ id: 'm2', name: 'laptop', local: { kind: 'this-computer' } }),+ ];++ it('keeps them all for an empty query', () => {+ expect(filterMachines(machines, ' ')).toEqual(machines);+ });++ it('matches the name, the description and the kind, ignoring case', () => {+ expect(filterMachines(machines, 'BUILD').map((m) => m.id)).toEqual(['m1']);+ expect(filterMachines(machines, 'gpu').map((m) => m.id)).toEqual(['m1']);+ expect(filterMachines(machines, 'this computer').map((m) => m.id)).toEqual(['m2']);+ });+});++describe('machineSummary', () => {+ it('says what it is, its OS and how many agents it runs', () => {+ expect(+ machineSummary(+ machine({+ id: 'm1',+ local: { kind: 'this-computer' },+ platform: { os: 'darwin', osVersion: '25.6.0', arch: 'arm64' },+ }),+ 2+ )+ ).toBe('This computer · macOS · 2 agents');+ });++ it('leaves out an OS it never reported and names an empty machine in words', () => {+ expect(machineSummary(machine({ id: 'm1' }), 0)).toBe('Agents controller · No agents');+ });+});++describe('machineNotices', () => {+ it('has nothing to say about a healthy machine', () => {+ expect(machineNotices(machine({ id: 'm' }))).toEqual([]);+ });++ it('says a machine is offline, and why', () => {+ const [notice] = machineNotices(+ machine({+ id: 'm',+ state: 'offline',+ connection: {+ connectedAt: '2026-10-01T10:00:00Z',+ disconnectedAt: '2026-10-01T11:00:00Z',+ disconnectReason: 'heartbeat_lapsed',+ },+ })+ );+ expect(notice).toMatchObject({ key: 'connection', tone: 'problem', title: 'Offline' });+ expect(notice!.body).toContain('its connection stopped responding');+ });++ it('says only that a removed machine is removed', () => {+ const notices = machineNotices(+ machine({+ id: 'm',+ state: 'revoked',+ revokedAt: '2026-10-02T10:00:00Z',+ release: { wanted: '1.1.0', running: '1.0.0', current: false },+ })+ );+ expect(notices.map((n) => n.title)).toEqual(['Removed']);+ });++ it('flags a controller behind its release and providers that cannot run', () => {+ const notices = machineNotices(+ machine({+ id: 'm',+ release: { wanted: '1.1.0', running: '1.0.0', current: false },+ providers: [+ {+ provider: 'acme',+ ready: false,+ problem: 'login expired',+ detail: null,+ version: null,+ checkedAt: null,+ },+ {+ provider: 'other',+ ready: false,+ problem: 'not installed',+ detail: null,+ version: null,+ checkedAt: null,+ },+ ],+ })+ );+ expect(notices.map((n) => n.key)).toEqual(['release', 'providers']);+ expect(notices[1]!.body).toBe('acme: login expired');+ });+});++describe('sessionsLabel', () => {+ const resources = {+ diskFreeBytes: 1,+ diskTotalBytes: 2,+ memFreeBytes: 1,+ memTotalBytes: 2,+ sessionsRunning: 1,+ };++ it('shows the limit when there is one', () => {+ expect(sessionsLabel({ ...resources, sessionsMax: 4 })).toBe('1 of 4');+ });++ it('shows only the count when the controller enforces no limit', () => {+ expect(sessionsLabel({ ...resources, sessionsMax: 0 })).toBe('1');+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/machines/machine-state.ts b/console/apps/switch-console-desktop/src/renderer/features/machines/machine-state.tsnew file mode 100644index 000000000..f13fdd0e1--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/machines/machine-state.ts@@ -0,0 +1,271 @@+import type { MachineDetail } from '@shared/core/managed-agents/managed-agents';+import { providerDisplayName } from '@shared/core/providers/agent-provider-registry';++export type MachineTone = 'ok' | 'warning' | 'problem' | 'idle';++/** A short label with its tone, and the sentence behind it for its hover title. */+export type MachineBadge = { label: string; tone: MachineTone; title: string };++const DISCONNECT_REASON: Record<string, string> = {+ socket_closed: 'its controller stopped or lost its connection',+ heartbeat_lapsed: 'its connection stopped responding',+ server_shutdown: 'the Switch server it was connected to restarted',+ server_lost: 'the Switch server it was connected to stopped responding',+ taken_over: 'another instance of its controller took over',+ revoked: 'it was removed',+};++function when(iso: string): string {+ const date = new Date(iso);+ return Number.isNaN(date.getTime()) ? iso : date.toLocaleString();+}++/** Whether the machine is connected, with when it connected or when and why it stopped. */+export function machineConnection(machine: MachineDetail): MachineBadge {+ const connection = machine.connection;+ if (machine.state === 'revoked')+ return {+ label: 'Removed',+ tone: 'idle',+ title: machine.revokedAt ? `Removed from Switch ${when(machine.revokedAt)}.` : 'Removed.',+ };+ if (machine.state === 'unknown' || connection === null)+ return {+ label: 'Never connected',+ tone: 'idle',+ title: 'Has never connected to Switch. It does once its controller is started.',+ };+ if (machine.state === 'online')+ return {+ label: 'Online',+ tone: 'ok',+ title: `Connected since ${when(connection.connectedAt)}.`,+ };+ const why = connection.disconnectReason+ ? (DISCONNECT_REASON[connection.disconnectReason] ?? connection.disconnectReason)+ : null;+ const at = connection.disconnectedAt ? ` ${when(connection.disconnectedAt)}` : '';+ return { label: 'Offline', tone: 'problem', title: `Disconnected${at}${why ? `: ${why}` : ''}.` };+}++/**+ * The last time Switch heard from the machine at all: now while it is+ * connected, else the latest of its status report, its connecting and its+ * going.+ */+export function lastContact(machine: MachineDetail, now: Date): string | null {+ if (machine.state === 'online') return now.toISOString();+ const times = [+ machine.lastSeenAt,+ machine.connection?.connectedAt,+ machine.connection?.disconnectedAt,+ ]+ .filter((time): time is string => typeof time === 'string')+ .sort((a, b) => Date.parse(b) - Date.parse(a));+ return times[0] ?? null;+}++/** What the machine is to this person: this computer, an SSH host of theirs, or how it runs. */+export function machineKindLabel(machine: MachineDetail): string {+ if (machine.local?.kind === 'this-computer') return 'This computer';+ if (machine.local?.kind === 'ssh-host') return `SSH host · ${machine.local.sshHost}`;+ if (machine.cloud) return 'Switch cloud';+ if (machine.kind === 'console') return 'Switch Console';+ return 'Agents controller';+}++const OS_NAMES: Record<string, string> = {+ macos: 'macOS',+ darwin: 'macOS',+ linux: 'Linux',+ windows: 'Windows',+ win32: 'Windows',+};++/** Its operating system, version and architecture, as it reported them; null when it did not. */+export function platformLabel(platform: MachineDetail['platform']): string | null {+ if (!platform) return null;+ const os = OS_NAMES[platform.os.toLowerCase()] ?? platform.os;+ return [platform.osVersion ? `${os} ${platform.osVersion}` : os, platform.arch]+ .filter(Boolean)+ .join(' · ');+}++/**+ * Where the controller stands against the release Switch names for it: on it,+ * updated with Console, or behind and why. Null badge when there is nothing+ * to flag.+ */+export function controllerRelease(machine: MachineDetail): {+ title: string;+ badge: { label: string; tone: MachineTone } | null;+} {+ const release = machine.release;+ if (release === null || release.current)+ return {+ title:+ release !== null+ ? `Runs ${release.wanted}, the release Switch names.`+ : machine.kind === 'console' || machine.updatedBy === 'console'+ ? 'Updates with Switch Console, which runs it.'+ : 'Switch names no controller release for this machine.',+ badge: null,+ };+ const names = `Runs ${machine.version ?? 'an unknown version'}; Switch names ${release.wanted}.`;+ const update = machine.update;+ if (machine.state !== 'online' || !update || update.target !== release.wanted)+ return {+ title: `${names} ${+ machine.state === 'online'+ ? 'It has said nothing about moving to it: a controller older than self-update never does, and needs reinstalling once.'+ : 'It moves to it once it is connected again.'+ }`,+ badge: { label: 'Behind', tone: 'warning' },+ };+ if (update.state === 'waiting_idle')+ return {+ title: `${names} It moves to it once no session is running on it.`,+ badge: { label: 'Updating when idle', tone: 'warning' },+ };+ if (update.state === 'restart_needed')+ return {+ title: `${names} ${update.problem ?? 'It installed it; restart it to run it.'}`,+ badge: { label: 'Restart needed', tone: 'warning' },+ };+ return {+ title: `${names} ${update.problem ?? 'It did not say why.'}`,+ badge: { label: 'Update failed', tone: 'problem' },+ };+}++const KIND_ORDER: Record<string, number> = { 'this-computer': 0, 'ssh-host': 1 };+const STATE_ORDER: Record<MachineDetail['state'], number> = {+ online: 0,+ offline: 1,+ unknown: 2,+ revoked: 3,+};++/**+ * The machines in the order the page lists them, the removed ones apart: this+ * computer first, then its SSH hosts, then the rest, each by whether it is+ * connected and then by name.+ */+export function arrangeMachines(machines: MachineDetail[]): {+ live: MachineDetail[];+ removed: MachineDetail[];+} {+ const rank = (machine: MachineDetail) => KIND_ORDER[machine.local?.kind ?? ''] ?? 2;+ const sorted = [...machines].sort(+ (a, b) =>+ rank(a) - rank(b) ||+ STATE_ORDER[a.state] - STATE_ORDER[b.state] ||+ a.name.localeCompare(b.name)+ );+ return {+ live: sorted.filter((machine) => machine.state !== 'revoked'),+ removed: sorted+ .filter((machine) => machine.state === 'revoked')+ .sort((a, b) => (b.revokedAt ?? '').localeCompare(a.revokedAt ?? '')),+ };+}++/** How full a resource is, as "X free of Y", or null when the machine reported none of it. */+export function resourceLabel(+ free: number,+ total: number,+ format: (bytes: number) => string+): string | null {+ if (total <= 0) return null;+ return `${format(free)} free of ${format(total)}`;+}++/**+ * The machines whose name, description or kind contains `query`, ignoring+ * case. An empty query keeps them all.+ */+export function filterMachines(machines: MachineDetail[], query: string): MachineDetail[] {+ const needle = query.trim().toLowerCase();+ if (needle === '') return machines;+ return machines.filter((machine) =>+ [machine.name, machine.description, machineKindLabel(machine)].some((text) =>+ text?.toLowerCase().includes(needle)+ )+ );+}++/**+ * One line saying what the machine is and what it runs, for its row in the+ * list: its kind, its operating system and how many agents are on it.+ */+export function machineSummary(machine: MachineDetail, agentCount: number): string {+ const os = machine.platform+ ? (OS_NAMES[machine.platform.os.toLowerCase()] ?? machine.platform.os)+ : null;+ const agents =+ agentCount === 0 ? 'No agents' : `${agentCount} ${agentCount === 1 ? 'agent' : 'agents'}`;+ return [machineKindLabel(machine), os, agents].filter(Boolean).join(' · ');+}++/** Something about the machine to act on or wait for, shown above its details. */+export type MachineNotice = { key: string; tone: MachineTone; title: string; body: string };++/**+ * What needs saying before the details: that it is offline, removed or never+ * connected, that its controller is behind the release Switch names, and+ * which installed providers cannot run an agent. None for a healthy machine.+ */+export function machineNotices(machine: MachineDetail): MachineNotice[] {+ const connection = machineConnection(machine);+ if (machine.state === 'revoked')+ return [+ {+ key: 'connection',+ tone: 'idle',+ title: 'Removed',+ body: `${connection.title} It no longer runs agents and cannot reconnect.`,+ },+ ];+ const notices: MachineNotice[] = [];+ if (machine.state === 'offline')+ notices.push({+ key: 'connection',+ tone: 'problem',+ title: 'Offline',+ body: `${connection.title} The agents placed on it do not run until it is back.`,+ });+ else if (machine.state === 'unknown' || machine.connection === null)+ notices.push({+ key: 'connection',+ tone: 'idle',+ title: 'Not connected yet',+ body: connection.title,+ });+ const release = controllerRelease(machine);+ if (release.badge)+ notices.push({+ key: 'release',+ tone: release.badge.tone,+ title: `Controller: ${release.badge.label.toLowerCase()}`,+ body: release.title,+ });+ const stuck = machine.providers.filter((p) => !p.ready && p.problem !== 'not installed');+ if (stuck.length > 0)+ notices.push({+ key: 'providers',+ tone: 'warning',+ title:+ stuck.length === 1 ? 'A provider cannot run agents' : 'Some providers cannot run agents',+ body: stuck+ .map((p) => `${providerDisplayName(p.provider) ?? p.provider}: ${p.problem ?? 'not ready'}`)+ .join(' · '),+ });+ return notices;+}++/** How many sessions it runs, against its limit when it enforces one (a limit of 0 means none). */+export function sessionsLabel(resources: NonNullable<MachineDetail['resources']>): string {+ return resources.sessionsMax > 0+ ? `${resources.sessionsRunning} of ${resources.sessionsMax}`+ : `${resources.sessionsRunning}`;+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/machines/machine-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/machines/machine-view.tsxnew file mode 100644index 000000000..b6653b945--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/machines/machine-view.tsx@@ -0,0 +1,87 @@+import { Server } from 'lucide-react';+import { observer } from 'mobx-react-lite';+import type { GuardResult, ViewDefinition } from '@renderer/app/view-registry';+import { useManagedAgents } from '@renderer/features/managed-agents/use-managed-agents';+import { isFrozenServer } from '@renderer/features/switch-servers/managed-server-state';+import { ServerTableEmpty } from '@renderer/features/switch-servers/server-page';+import { ServerSectionTitlebar } from '@renderer/features/switch-servers/server-section-titlebar';+import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';+import { failureText } from '@renderer/lib/errors/describe-failure';+import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';+import { Spinner } from '@renderer/lib/ui/spinner';+import { MachineDetails } from './machine-details';+import { useMachineDetails } from './use-machines';++type MachineParams = { serverId: string; machineId: string; name: string };++const MachineTitlebar = observer(function MachineTitlebar() {+ const { params } = useParams('machine');+ const { navigate } = useNavigate();+ return (+ <ServerSectionTitlebar+ serverId={params.serverId}+ icon={Server}+ label="Your Machines"+ onSectionClick={() => navigate('machines', { serverId: params.serverId })}+ item={{ label: params.name }}+ />+ );+});++/**+ * One of the person's machines, with everything it last reported. Read from+ * the same list as the machines page: the server has no call for one machine.+ */+const MachinePanel = observer(function MachinePanel() {+ const { params } = useParams('machine');+ const server = switchServersStore.servers.find((s) => s.id === params.serverId);+ const machines = useMachineDetails(params.serverId);+ const managed = useManagedAgents(params.serverId);+ const machine = machines.data?.find((m) => m.id === params.machineId);++ return (+ <div className="relative z-10 flex min-h-0 flex-1 flex-col bg-background">+ <div className="flex min-h-0 flex-1 flex-col overflow-auto">+ <div className="mx-auto w-full max-w-[720px] px-6 pt-10 pb-10">+ {machines.error && !(server && isFrozenServer(server)) ? (+ <p role="alert" className="text-sm text-destructive">+ {failureText(machines.error, 'Could not load this machine.')}+ </p>+ ) : machines.data === undefined ? (+ <Spinner />+ ) : machines.data === null ? (+ <ServerTableEmpty>+ {server?.name ?? 'This server'} does not have agent management turned on.+ </ServerTableEmpty>+ ) : !machine ? (+ <ServerTableEmpty>+ {params.name} is no longer one of your machines on {server?.name ?? 'this server'}.+ </ServerTableEmpty>+ ) : (+ <MachineDetails+ serverId={params.serverId}+ machine={machine}+ placed={(managed.data ?? []).filter((agent) => agent.machine?.id === machine.id)}+ />+ )}+ </div>+ </div>+ </div>+ );+});++export const machineView = {+ WrapView: ({ children }: MachineParams & { children: React.ReactNode }) => <>{children}</>,+ TitlebarSlot: MachineTitlebar,+ MainPanel: MachinePanel,+ canActivate: (params: unknown): GuardResult => {+ const value = (params ?? {}) as Partial<Record<keyof MachineParams, unknown>>;+ if (+ typeof value.serverId !== 'string' ||+ typeof value.machineId !== 'string' ||+ typeof value.name !== 'string'+ )+ return { ok: false, redirect: 'home', discardParams: true };+ return { ok: true };+ },+} satisfies ViewDefinition<MachineParams>;diff --git a/console/apps/switch-console-desktop/src/renderer/features/machines/machines-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/machines/machines-view.tsxnew file mode 100644index 000000000..7ac3706ce--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/machines/machines-view.tsx@@ -0,0 +1,215 @@+import { Plus, Server } from 'lucide-react';+import { observer } from 'mobx-react-lite';+import { useState } from 'react';+import type { GuardResult, ViewDefinition } from '@renderer/app/view-registry';+import { useManagedAgents } from '@renderer/features/managed-agents/use-managed-agents';+import { isFrozenServer } from '@renderer/features/switch-servers/managed-server-state';+import { ServerPage, ServerTableEmpty } from '@renderer/features/switch-servers/server-page';+import { ServerSectionTitlebar } from '@renderer/features/switch-servers/server-section-titlebar';+import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';+import { failureText } from '@renderer/lib/errors/describe-failure';+import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';+import { useShowModal } from '@renderer/lib/modal/modal-provider';+import { Button } from '@renderer/lib/ui/button';+import { DisclosureRow } from '@renderer/lib/ui/disclosure-row';+import { SearchInput } from '@renderer/lib/ui/search-input';+import { Spinner } from '@renderer/lib/ui/spinner';+import type { MachineDetail, ManagedAgentView } from '@shared/core/managed-agents/managed-agents';+import { MachineIcon, TonePill } from './machine-marks';+import {+ arrangeMachines,+ controllerRelease,+ filterMachines,+ machineConnection,+ machineSummary,+} from './machine-state';+import { useMachineDetails } from './use-machines';++function useServerId(): string {+ return useParams('machines').params.serverId;+}++const MachinesTitlebar = observer(function MachinesTitlebar() {+ return <ServerSectionTitlebar serverId={useServerId()} icon={Server} label="Your Machines" />;+});++/**+ * The computers that run the signed-in person's managed agents on this+ * server: this computer, their SSH hosts, headless controllers and a Switch+ * cloud machine. One row each, opening the machine's own page; removed+ * machines are folded away at the end. Read-only for now.+ *+ * The server returns the whole list in one response, unpaged, and it holds+ * only this person's own machines, so the filter runs over all of them here.+ */+const MachinesPanel = observer(function MachinesPanel() {+ const serverId = useServerId();+ const server = switchServersStore.servers.find((s) => s.id === serverId);+ const machines = useMachineDetails(serverId);+ const managed = useManagedAgents(serverId);+ const showAddMachineModal = useShowModal('addMachineModal');++ return (+ <ServerPage+ width={880}+ title="Your Machines"+ description={`Computers running an agents controller for you on ${server?.name ?? 'this server'}. Each runs the agents you place on it and reports what it sees.`}+ action={+ machines.data ? (+ <Button size="sm" onClick={() => showAddMachineModal({ serverId })}>+ <Plus className="size-4" />+ Add machine+ </Button>+ ) : undefined+ }+ >+ {machines.error && !(server && isFrozenServer(server)) ? (+ <p role="alert" className="text-sm text-destructive">+ {failureText(machines.error, 'Could not load your machines.')}+ </p>+ ) : machines.data === undefined ? (+ <Spinner />+ ) : machines.data === null ? (+ <ServerTableEmpty>+ {server?.name ?? 'This server'} does not have agent management turned on.+ </ServerTableEmpty>+ ) : (+ <MachineList serverId={serverId} machines={machines.data} agents={managed.data ?? []} />+ )}+ </ServerPage>+ );+});++function MachineList({+ serverId,+ machines,+ agents,+}: {+ serverId: string;+ machines: MachineDetail[];+ /** The person's managed agents, wherever each is placed. */+ agents: ManagedAgentView[];+}) {+ const [filter, setFilter] = useState('');+ const [showRemoved, setShowRemoved] = useState(false);+ const arranged = arrangeMachines(machines);+ const live = filterMachines(arranged.live, filter);+ const removed = filterMachines(arranged.removed, filter);+ const filtering = filter.trim() !== '';+ const placedOn = (machine: MachineDetail) =>+ agents.filter((agent) => agent.machine?.id === machine.id).length;++ if (machines.length === 0)+ return (+ <ServerTableEmpty>+ No machines yet. This computer joins when you run a managed agent on it, and so does an SSH+ host; a headless agents controller joins once it is enrolled.+ </ServerTableEmpty>+ );++ return (+ <div className="flex flex-col gap-6">+ <SearchInput+ value={filter}+ onChange={(e) => setFilter(e.target.value)}+ placeholder="Filter machines…"+ aria-label="Filter machines by name, description or kind"+ />+ {live.length === 0 && removed.length === 0 ? (+ <p className="py-2 text-sm text-foreground-muted">+ No machine here matches “{filter.trim()}”.+ </p>+ ) : (+ <>+ {live.length > 0 && (+ <div className="divide-y divide-border overflow-hidden rounded-[10px] border border-border">+ {live.map((machine) => (+ <MachineRow+ key={machine.id}+ serverId={serverId}+ machine={machine}+ agentCount={placedOn(machine)}+ />+ ))}+ </div>+ )}+ {removed.length > 0 && (+ <div>+ <DisclosureRow+ // A filter that only matches removed machines would otherwise+ // show nothing but a closed fold.+ open={showRemoved || (filtering && live.length === 0)}+ title="Removed"+ summary="Machines revoked from Switch"+ meta={removed.length}+ onToggle={() => setShowRemoved((open) => !open)}+ />+ {(showRemoved || (filtering && live.length === 0)) && (+ <div className="mt-2 divide-y divide-border overflow-hidden rounded-[10px] border border-border">+ {removed.map((machine) => (+ <MachineRow+ key={machine.id}+ serverId={serverId}+ machine={machine}+ agentCount={placedOn(machine)}+ />+ ))}+ </div>+ )}+ </div>+ )}+ </>+ )}+ </div>+ );+}++/** One machine: what it is and what runs on it, whether it is connected, and a way into its page. */+function MachineRow({+ serverId,+ machine,+ agentCount,+}: {+ serverId: string;+ machine: MachineDetail;+ agentCount: number;+}) {+ const { navigate } = useNavigate();+ const connection = machineConnection(machine);+ const badge = controllerRelease(machine).badge;+ return (+ <button+ type="button"+ onClick={() => navigate('machine', { serverId, machineId: machine.id, name: machine.name })}+ className="flex w-full cursor-pointer items-center gap-3 bg-background px-4 py-3 text-left transition-colors hover:bg-[var(--fill)]"+ >+ <MachineIcon machine={machine} />+ <div className="flex min-w-0 flex-1 flex-col">+ <span className="truncate font-mono text-sm font-medium text-foreground">+ {machine.name}+ </span>+ <span className="truncate text-xs text-foreground-muted">+ {machineSummary(machine, agentCount)}+ </span>+ </div>+ {badge && machine.state !== 'revoked' && (+ <TonePill tone={badge.tone} label={badge.label} dot={false} />+ )}+ <TonePill tone={connection.tone} label={connection.label} title={connection.title} />+ </button>+ );+}++export const machinesView = {+ WrapView: ({ children }: { children: React.ReactNode; serverId: string }) => <>{children}</>,+ TitlebarSlot: MachinesTitlebar,+ MainPanel: MachinesPanel,+ canActivate: (params: unknown): GuardResult => {+ const serverId =+ typeof params === 'object' && params !== null+ ? (params as { serverId?: unknown }).serverId+ : undefined;+ if (typeof serverId !== 'string') return { ok: false, redirect: 'home' };+ return { ok: true };+ },+} satisfies ViewDefinition<{ serverId: string }>;diff --git a/console/apps/switch-console-desktop/src/renderer/features/machines/use-machines.ts b/console/apps/switch-console-desktop/src/renderer/features/machines/use-machines.tsnew file mode 100644index 000000000..52d8ff218--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/machines/use-machines.ts@@ -0,0 +1,36 @@+import { useQuery } from '@tanstack/react-query';+import { MANAGED_AGENTS_KEY } from '@renderer/features/managed-agents/use-managed-agents';+import { serverAvailability } from '@renderer/features/switch-servers/server-availability';+import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';+import { rpc } from '@renderer/lib/ipc';++/**+ * How often the page reads the machines again: often enough that a machine+ * going on- or offline shows while the page is looked at. react-query pauses+ * while the window is hidden.+ */+const MACHINES_REFRESH_MS = 5_000;++/**+ * Every one of the signed-in user's machines on the server, revoked ones+ * included, with all each last reported. `null` means the server runs no+ * agent management. Under the managed agents' key, so whatever refreshes+ * those refreshes this too.+ */+export function useMachineDetails(serverId: string) {+ const signedIn =+ switchServersStore.isConnected(serverId) && serverAvailability(serverId) !== 'dormant';+ return useQuery({+ queryKey: [+ MANAGED_AGENTS_KEY,+ serverId,+ 'machine-details',+ workspacesStore.idOnServerInScope(serverId),+ ],+ queryFn: () => rpc.managedAgents.machineDetails(serverId),+ enabled: signedIn,+ refetchInterval: MACHINES_REFRESH_MS,+ retry: false,+ });+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-chats.tsx b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-chats.tsxindex b0961d020..b2bcdf99b 100644--- a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-chats.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-chats.tsx@@ -17,7 +17,7 @@ import { EmbeddedRoom } from '@renderer/features/switch-rooms/view';import { isConsoleDirectChatSummary } from '@renderer/features/switch-servers/room-filters';import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';import { useFeatureFlags } from '@renderer/lib/hooks/useFeatureFlags';-import { useParams } from '@renderer/lib/layout/navigation-provider';+import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';import { showModal } from '@renderer/lib/modal/modal-provider';import { Button } from '@renderer/lib/ui/button';import {@@ -176,6 +176,7 @@ export function openAgentRoom(*/export const AgentChats = observer(function AgentChats({ agent }: { agent: ManagedAgentView }) {const { params, setParams } = useParams('managedAgent');+ const { navigate } = useNavigate();const { serverId, workspaceId, agentId } = agent;useEffect(() => {return switchRoomsStore.watchMembership(workspaceId, agentId);@@ -224,6 +225,8 @@ export const AgentChats = observer(function AgentChats({ agent }: { agent: Manag// oxlint-disable-next-line react-hooks/exhaustive-deps -- runs when the decision turns true, not when newChat is redefined}, [autoStart]);+ const machine = agent.machine;+return (<div className="flex h-full min-h-0"><div className="flex w-[300px] shrink-0 flex-col overflow-y-auto border-r border-border p-2">@@ -235,6 +238,11 @@ export const AgentChats = observer(function AgentChats({ agent }: { agent: Managsections={sections}selected={section}onSelect={(chosen) => setParams({ section: chosen })}+ onOpenMachine={+ machine+ ? () => navigate('machine', { serverId, machineId: machine.id, name: machine.name })+ : null+ }/><Section title="Direct chats" addLabel="New chat" onAdd={newChat} addChoices={null}>{ownServer && chatsStore.listError && (diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-profile.tsx b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-profile.tsxindex 1c4f088ed..ea653fa28 100644--- a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-profile.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-profile.tsx@@ -17,7 +17,10 @@ export const agentSectionLabel = (section: AgentSection): string =>/** Where an agent runs, as the one line under its name says it. */export type AgentMachineLine = {icon: LucideIcon;+ /** The machine, as the line names it. */text: string;+ /** How the agent is doing there when that needs saying; null when it runs fine. */+ status: string | null;/** Hover text, saying more than fits on the line. */title: string;};@@ -32,7 +35,12 @@ export function managedAgentMachineLine(): AgentMachineLine {const machine = agent.machine;if (!machine)- return { icon: ServerOff, text: 'No machine', title: 'It has no machine to run on.' };+ return {+ icon: ServerOff,+ text: 'No machine',+ status: null,+ title: 'It has no machine to run on.',+ };const cloud = isCloudMachine(machine);const name = machine.name;const shown = thisComputer && !cloud ? 'This computer' : name;@@ -40,7 +48,8 @@ export function managedAgentMachineLine(const directory = agent.definition.directory;return {icon: cloud ? Cloud : Laptop,- text: state.tone === 'ok' ? shown : `${shown} · ${state.label}`,+ text: shown,+ status: state.tone === 'ok' ? null : state.label,title: `Runs on ${shown === name ? name : `this computer (${name})`}${directory ? ` · ${directory}` : ''}${state.detail ? `\n${state.label}: ${state.detail}` : ''}`,};}@@ -48,7 +57,8 @@ export function managedAgentMachineLine(/*** The top of an agent's page: its picture, its name and where it runs, and a* button for each of the agent's own sections. `onSelect` is null while the- * agent does not exist yet, so the buttons show but do nothing.+ * agent does not exist yet, so the buttons show but do nothing. With+ * `onOpenMachine` the line saying where it runs opens that machine's page.*/export function AgentProfile({name,@@ -58,6 +68,7 @@ export function AgentProfile({sections,selected,onSelect,+ onOpenMachine,}: {name: string;iconUrl: string | null;@@ -66,6 +77,7 @@ export function AgentProfile({sections: readonly AgentSection[];selected: AgentSection | null;onSelect: ((section: AgentSection) => void) | null;+ onOpenMachine: (() => void) | null;}) {const MachineIcon = machine.icon;return (@@ -78,8 +90,25 @@ export function AgentProfile({className="mt-0.5 flex max-w-full items-center gap-1.5 text-sm text-foreground-muted"title={machine.title}>- <MachineIcon className="size-3.5 shrink-0" aria-hidden />- <span className="truncate">{machine.text}</span>+ {onOpenMachine ? (+ // A quiet link, as the app's others are: muted until hovered, so the+ // line reads as a fact first and a way to the machine second. Only+ // the machine is the link, not how the agent is doing on it.+ <button+ type="button"+ onClick={onOpenMachine}+ className="flex min-w-0 cursor-pointer items-center gap-1.5 underline-offset-2 transition-colors hover:text-foreground hover:underline focus-visible:underline focus-visible:outline-none"+ >+ <MachineIcon className="size-3.5 shrink-0" aria-hidden />+ <span className="truncate">{machine.text}</span>+ </button>+ ) : (+ <>+ <MachineIcon className="size-3.5 shrink-0" aria-hidden />+ <span className="truncate">{machine.text}</span>+ </>+ )}+ {machine.status && <span className="shrink-0">· {machine.status}</span>}</p><div role="toolbar" aria-label="Agent" className="mt-5 flex items-center gap-2">{SECTION_BUTTONS.filter((item) => sections.includes(item.section)).map((item) => {diff --git a/console/apps/switch-console-desktop/src/renderer/features/onboarding/use-onboarding-checklist.ts b/console/apps/switch-console-desktop/src/renderer/features/onboarding/use-onboarding-checklist.tsindex b808d4669..9eec99dc9 100644--- a/console/apps/switch-console-desktop/src/renderer/features/onboarding/use-onboarding-checklist.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/onboarding/use-onboarding-checklist.ts@@ -70,7 +70,7 @@ export function useOnboardingChecklist(): OnboardingChecklist {navigate('settings', { tab: 'clis-models' });return;case 'onboardAgents':- showAddAgentModal({ entryPoint: 'onboarding' });+ showAddAgentModal({ entryPoint: 'onboarding', machineId: null });return;case 'createRoom':showCreateRoomModal({});diff --git a/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/AgentRow.tsx b/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/AgentRow.tsxindex 989877b05..2b0f01d00 100644--- a/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/AgentRow.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/AgentRow.tsx@@ -1,34 +1,19 @@-import { AgentIcon } from '@renderer/lib/components/agent-icon';+import { ProviderStatusRow } from '@renderer/lib/components/provider-status-row';import { useThisComputerReport } from '@renderer/lib/stores/use-this-computer-report';import type { AgentPayload } from '@shared/core/providers/agent-payload';import { asAgentProviderId } from '@shared/core/providers/agent-provider-registry';-import { InstalledBadge, UninstalledBadge } from './agent-status-badge';import { ThisComputerProviderStatus } from './this-computer-provider-status';import { installedHere, reportedProvider } from './this-computer-status';export const AgentRow = ({ agent, onClick }: { agent: AgentPayload; onClick?: () => void }) => {const { data: report } = useThisComputerReport();- const isInstalled = installedHere(reportedProvider(report, agent.id), agent.status);- const isClickable = !!onClick;- const Tag = isClickable ? 'button' : 'div';-return (- <Tag- className={`group flex w-full items-center gap-3 rounded-lg p-3 hover:bg-background-1${isClickable ? ' cursor-pointer text-left' : ''}`}- onClick={isClickable ? onClick : undefined}- >- <div className="flex size-6 items-center justify-center rounded-lg bg-background-1 p-1.5 group-hover:bg-background-2">- <AgentIcon id={agent.id} size={16} />- </div>- <div className="flex w-full flex-col gap-0.5">- <div className="flex w-full items-center justify-between">- <span className="text-sm text-foreground">{agent.name}</span>- <div className="flex items-center gap-1.5">- {isInstalled ? <InstalledBadge /> : <UninstalledBadge />}- </div>- </div>- <ThisComputerProviderStatus providerId={asAgentProviderId(agent.id)} compact />- </div>- </Tag>+ <ProviderStatusRow+ providerId={agent.id}+ name={agent.name}+ installed={installedHere(reportedProvider(report, agent.id), agent.status)}+ status={<ThisComputerProviderStatus providerId={asAgentProviderId(agent.id)} compact />}+ onClick={onClick}+ />);};diff --git a/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/DependencyInstallationStatusCard.tsx b/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/DependencyInstallationStatusCard.tsxindex 576eb935b..1b7bce8d1 100644--- a/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/DependencyInstallationStatusCard.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/DependencyInstallationStatusCard.tsx@@ -1,6 +1,11 @@import { Check, Loader2, MoreHorizontal, X } from 'lucide-react';import { observer } from 'mobx-react-lite';import { toast } from 'sonner';+import {+ InstalledBadge,+ RecommendedBadge,+ UsedBadge,+} from '@renderer/lib/components/provider-status-badges';import type { HostDependencyInstallation } from '@renderer/lib/stores/use-agent-installation-statuses';import {DropdownMenu,@@ -20,7 +25,6 @@ import type {SelectedSource,} from '@shared/core/providers/agent-payload';import { resolveActiveInstallation, sourceKey } from '@shared/core/providers/agent-payload';-import { InstalledBadge, RecommendedBadge, UsedBadge } from './agent-status-badge';import { buildSourceRows, provenanceLabel } from './installation-sources';export type InstallationState = 'found' | 'not-found' | 'uninstalled' | 'checking';diff --git a/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/this-computer-provider-status.tsx b/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/this-computer-provider-status.tsxindex c5c678370..060098236 100644--- a/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/this-computer-provider-status.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/this-computer-provider-status.tsx@@ -1,13 +1,15 @@import { useMutation, useQueryClient } from '@tanstack/react-query';import { CheckCircle2, CircleAlert, Loader2, RefreshCw } from 'lucide-react';import { ProviderConnectionStatus } from '@renderer/lib/components/provider-connection-status';+import { ReportedProviderLine } from '@renderer/lib/components/provider-status-row';+import { reportedHeadline } from '@renderer/lib/components/reported-provider';import {recheckThisComputer,useThisComputerReport,} from '@renderer/lib/stores/use-this-computer-report';import { Button } from '@renderer/lib/ui/button';import { getProvider, type AgentProviderId } from '@shared/core/providers/agent-provider-registry';-import { reportedHeadline, reportedProvider } from './this-computer-status';+import { reportedProvider } from './this-computer-status';/*** A provider's install and sign-in state on this computer, for Settings →@@ -41,13 +43,7 @@ export function ThisComputerProviderStatus({: reportedHeadline(reported);const Icon = checking ? Loader2 : reported.ready ? CheckCircle2 : CircleAlert;const tone = checking || reported.ready ? 'text-foreground-muted' : 'text-foreground-warning';- if (compact)- return (- <span className={`inline-flex items-center gap-1.5 text-xs ${tone}`}>- <Icon className={`size-3.5 ${checking ? 'animate-spin' : ''}`} />- {headline}- </span>- );+ if (compact) return <ReportedProviderLine reported={reported} checking={recheck.isPending} />;const provider = getProvider(providerId);return (<div className="rounded-lg border border-border bg-background-1 p-3 text-sm" role="status">diff --git a/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/this-computer-status.test.ts b/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/this-computer-status.test.tsindex ef28fa038..7d17fa108 100644--- a/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/this-computer-status.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/this-computer-status.test.ts@@ -1,11 +1,7 @@import { describe, expect, it } from 'vitest';+import { reportedHeadline } from '@renderer/lib/components/reported-provider';import type { MachineProvider } from '@shared/core/managed-agents/managed-agents';-import {- installedHere,- installSourcesDiffer,- reportedHeadline,- reportedProvider,-} from './this-computer-status';+import { installedHere, installSourcesDiffer, reportedProvider } from './this-computer-status';function reported(patch: Partial<MachineProvider>): MachineProvider {return {diff --git a/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/this-computer-status.ts b/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/this-computer-status.tsindex 8438a1f1c..5a67bfb07 100644--- a/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/this-computer-status.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/this-computer-status.ts@@ -40,19 +40,3 @@ export function installSourcesDiffer();}-/** The line Settings shows for a provider the controller reported on, worded as Console's own check words it. */-export function reportedHeadline(reported: MachineProvider): string {- if (reported.ready) return 'Signed in';- switch (reported.problem) {- case 'not installed':- return 'CLI not installed';- case 'not logged in':- return reported.loginHelps ? 'Not signed in' : 'Can’t be used yet';- case 'login expired':- return 'Sign-in expired';- case 'login not checked yet':- return 'Checking sign-in…';- default:- return 'Sign-in could not be checked';- }-}diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sessions-section-header.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sessions-section-header.tsxindex 098383370..c43f7c334 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sessions-section-header.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sessions-section-header.tsx@@ -343,7 +343,9 @@ export const SessionsSectionHeader = observer(function SessionsSectionHeader({Collapse all</DropdownMenuItem><DropdownMenuSeparator />- <DropdownMenuItem onClick={() => showAddLocationModal({ entryPoint: 'sidebar' })}>+ <DropdownMenuItem+ onClick={() => showAddLocationModal({ entryPoint: 'sidebar', machineId: null })}+ ><UserPlus className="mr-1.5 h-4 w-4" />Add an agent</DropdownMenuItem>diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav-views.ts b/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav-views.tsindex e84eb4338..0f3beb939 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav-views.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav-views.ts@@ -1,6 +1,7 @@export type WorkspaceNavView =| 'server'| 'serverAgents'+ | 'machines'| 'serverRooms'| 'connectors'| 'templates'@@ -14,17 +15,20 @@ export type WorkspaceNavView =* connections are on, its connector settings needing them, and for whoever* runs the server from this Console, whose status is under Admin's Server* heading: the others are run by someone else, and there is nothing here to- * start, stop or update.+ * start, stop or update. Your Machines follows Your Agents where the server+ * runs agent management: with it off there are no machines to list.*/export function workspaceNavViews(server: {managed: boolean;serviceConnections: boolean;administers: boolean;+ agentManagement: boolean;}): WorkspaceNavView[] {const admin = (server.serviceConnections && server.administers) || server.managed;return ['server','serverAgents',+ ...(server.agentManagement ? (['machines'] as const) : []),'serverRooms',...(server.serviceConnections ? (['connectors'] as const) : []),'templates',diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav.tsxindex 92c2447e8..7eb5845b1 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav.tsx@@ -1,4 +1,13 @@-import { Bot, DoorOpen, FileText, House, type LucideIcon, Plug, ShieldCheck } from 'lucide-react';+import {+ Bot,+ DoorOpen,+ FileText,+ House,+ type LucideIcon,+ Plug,+ Server,+ ShieldCheck,+} from 'lucide-react';import { observer } from 'mobx-react-lite';import { useRoomHealth } from '@renderer/features/switch-rooms/connection-health';import { ManagedServerDot } from '@renderer/features/switch-servers/managed-server-dot';@@ -25,6 +34,8 @@ export const WorkspaceNav = observer(function WorkspaceNav() {const { currentView } = useWorkspaceSlots();const { params: homeParams } = useParams('server');const { params: agentsParams } = useParams('serverAgents');+ const { params: machinesParams } = useParams('machines');+ const { params: machineParams } = useParams('machine');const { params: roomsParams } = useParams('serverRooms');const { params: connectorsParams } = useParams('connectors');const { params: templatesParams } = useParams('templates');@@ -32,7 +43,8 @@ export const WorkspaceNav = observer(function WorkspaceNav() {const { params: managedServerParams } = useParams('managedServer');const active = switchServersStore.activeServer;const health = useRoomHealth(active?.id ?? null);- const serviceConnections = useFeatureFlags(active?.id ?? null).service_connections;+ const flags = useFeatureFlags(active?.id ?? null);+ const serviceConnections = flags.service_connections;const warningCount =health.data?.agents.filter((agent) => connectionNeedsAttention(agent.state)).length ?? 0;if (!active) return null;@@ -52,12 +64,18 @@ export const WorkspaceNav = observer(function WorkspaceNav() {> = {server: { icon: House, label: 'Home', params: homeParams },serverAgents: { icon: Bot, label: 'Your Agents', params: agentsParams },+ machines: { icon: Server, label: 'Your Machines', params: machinesParams },serverRooms: { icon: DoorOpen, label: 'Your Rooms', params: roomsParams },connectors: { icon: Plug, label: 'Connectors', params: connectorsParams },templates: { icon: FileText, label: 'Templates', params: templatesParams },admin: { icon: ShieldCheck, label: 'Admin', params: adminParams },};- const shown = workspaceNavViews({ managed: active.managed, serviceConnections, administers });+ const shown = workspaceNavViews({+ managed: active.managed,+ serviceConnections,+ administers,+ agentManagement: flags.agent_management,+ });return (<SidebarMenu className="flex flex-col gap-[2px] px-2 pt-2">@@ -69,7 +87,9 @@ export const WorkspaceNav = observer(function WorkspaceNav() {isActive={view === 'admin'? onAdmin || onStatus- : isCurrentView(currentView, view) && params?.serverId === active.id+ : view === 'machines' && isCurrentView(currentView, 'machine')+ ? machineParams?.serverId === active.id+ : isCurrentView(currentView, view) && params?.serverId === active.id}onClick={() => navigate(view === 'admin' ? adminTarget : view, { serverId: active.id })}className={cn(frozen && view !== 'admin' && FROZEN)}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/switch-buddy-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/switch-buddy-view.tsxindex 33a0662b8..3e1ff7461 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/switch-buddy-view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/switch-buddy-view.tsx@@ -84,11 +84,13 @@ const SwitchBuddyPanel = observer(function SwitchBuddyPanel() {machine={{icon: Laptop,text: 'This computer',+ status: null,title: 'switch-buddy runs on this computer.',}}sections={agentSections(serviceConnections, undefined)}selected={null}onSelect={null}+ onOpenMachine={null}/><Section title="Direct chats"><SidebarMenuRow isActive onClick={() => {}}>diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-agents-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-agents-view.tsxindex 0b292094e..51e80dab2 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-agents-view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-agents-view.tsx@@ -116,7 +116,7 @@ const ServerAgentsPanel = observer(function ServerAgentsPanel() {<div className="grid grid-cols-[repeat(auto-fill,minmax(180px,1fr))] gap-[14px]"><buttontype="button"- onClick={() => showAddAgentModal({ entryPoint: 'server_page' })}+ onClick={() => showAddAgentModal({ entryPoint: 'server_page', machineId: null })}className="flex min-h-[184px] cursor-pointer items-center justify-center rounded-[11px] border border-dashed border-border text-foreground-muted transition-colors hover:border-border-1 hover:bg-[var(--sel-soft)] hover:text-foreground"aria-label="Add agent">diff --git a/console/apps/switch-console-desktop/src/renderer/lib/commands/app-commands.ts b/console/apps/switch-console-desktop/src/renderer/lib/commands/app-commands.tsindex ae6b92790..bff4747ea 100644--- a/console/apps/switch-console-desktop/src/renderer/lib/commands/app-commands.ts+++ b/console/apps/switch-console-desktop/src/renderer/lib/commands/app-commands.ts@@ -48,7 +48,7 @@ function createAppCommandProvider(): CommandProvider {shortcutKey: newLocationDef.shortcutKey,group: newLocationDef.group,execute() {- showModal('addAgentModal', { entryPoint: 'command_palette' });+ showModal('addAgentModal', { entryPoint: 'command_palette', machineId: null });},},{diff --git a/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/agent-status-badge.tsx b/console/apps/switch-console-desktop/src/renderer/lib/components/provider-status-badges.tsxsimilarity index 100%rename from console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/agent-status-badge.tsxrename to console/apps/switch-console-desktop/src/renderer/lib/components/provider-status-badges.tsxdiff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/provider-status-row.tsx b/console/apps/switch-console-desktop/src/renderer/lib/components/provider-status-row.tsxnew file mode 100644index 000000000..efb9c6448--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/provider-status-row.tsx@@ -0,0 +1,88 @@+import { CheckCircle2, CircleAlert, Loader2 } from 'lucide-react';+import type { ReactNode } from 'react';+import { AgentIcon } from '@renderer/lib/components/agent-icon';+import { InstalledBadge, UninstalledBadge } from '@renderer/lib/components/provider-status-badges';+import { cn } from '@renderer/utils/utils';+import type { MachineProvider } from '@shared/core/managed-agents/managed-agents';+import { reportedHeadline } from './reported-provider';++/**+ * One agent provider on one machine: its icon and name, whether it is+ * installed, and a status line under them. Settings → Agent providers lists+ * this computer's providers with it and a machine's page lists that+ * machine's, so the two read alike.+ */+export function ProviderStatusRow({+ providerId,+ name,+ installed,+ status,+ meta,+ actions,+ onClick,+}: {+ providerId: string;+ name: string;+ installed: boolean;+ /** The line under the name: sign-in state, or a check in progress. */+ status: ReactNode;+ /** A short note after the name, such as the version. */+ meta?: string;+ /** Buttons beside the badge. Not with `onClick`: a button cannot hold buttons. */+ actions?: ReactNode;+ /** Makes the whole row a button. */+ onClick?: () => void;+}) {+ const Tag = onClick ? 'button' : 'div';+ return (+ <Tag+ className={cn(+ 'group flex w-full items-center gap-3 rounded-lg p-3 hover:bg-background-1',+ onClick && 'cursor-pointer text-left'+ )}+ onClick={onClick}+ >+ <div className="flex size-6 items-center justify-center rounded-lg bg-background-1 p-1.5 group-hover:bg-background-2">+ <AgentIcon id={providerId} size={16} />+ </div>+ <div className="flex w-full min-w-0 flex-col gap-0.5">+ <div className="flex w-full items-center justify-between gap-2">+ <span className="min-w-0 truncate text-sm text-foreground">+ {name}+ {meta && <span className="text-foreground-muted"> · {meta}</span>}+ </span>+ <div className="flex shrink-0 items-center gap-1.5">+ {actions}+ {installed ? <InstalledBadge /> : <UninstalledBadge />}+ </div>+ </div>+ {status}+ </div>+ </Tag>+ );+}++/** The status line for a provider as a machine's controller reported it. */+export function ReportedProviderLine({+ reported,+ checking,+}: {+ reported: MachineProvider;+ /** A recheck is under way: says so rather than repeating the last answer. */+ checking: boolean;+}) {+ const busy = checking || reported.problem === 'login not checked yet';+ const headline = checking ? 'Checking installation and sign-in…' : reportedHeadline(reported);+ const Icon = busy ? Loader2 : reported.ready ? CheckCircle2 : CircleAlert;+ return (+ <span+ className={cn(+ 'inline-flex items-center gap-1.5 text-xs',+ busy || reported.ready ? 'text-foreground-muted' : 'text-foreground-warning'+ )}+ >+ <Icon className={cn('size-3.5 shrink-0', busy && 'animate-spin')} />+ {headline}+ </span>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/reported-provider.ts b/console/apps/switch-console-desktop/src/renderer/lib/components/reported-provider.tsnew file mode 100644index 000000000..3716d0475--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/reported-provider.ts@@ -0,0 +1,22 @@+import type { MachineProvider } from '@shared/core/managed-agents/managed-agents';++/**+ * A provider's state as a machine's controller reported it, worded as+ * Console's own check words it on this computer, so Settings and a machine's+ * page say the same thing about the same state.+ */+export function reportedHeadline(reported: MachineProvider): string {+ if (reported.ready) return 'Signed in';+ switch (reported.problem) {+ case 'not installed':+ return 'CLI not installed';+ case 'not logged in':+ return reported.loginHelps ? 'Not signed in' : 'Can’t be used yet';+ case 'login expired':+ return 'Sign-in expired';+ case 'login not checked yet':+ return 'Checking sign-in…';+ default:+ return 'Sign-in could not be checked';+ }+}diff --git a/console/apps/switch-console-desktop/src/renderer/tests/connectors.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/connectors.test.tsindex e3c619a9c..3dbaf2ec6 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/connectors.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/tests/connectors.test.ts@@ -776,24 +776,51 @@ describe('with the service_connections flag off', () => {managed: false,serviceConnections: false,administers: true,+ agentManagement: false,});expect(shown).not.toContain('connectors');expect(shown).not.toContain('admin');expect(- workspaceNavViews({ managed: true, serviceConnections: true, administers: true })+ workspaceNavViews({+ managed: true,+ serviceConnections: true,+ administers: true,+ agentManagement: false,+ })).toEqual(['server', 'serverAgents', 'serverRooms', 'connectors', 'templates', 'admin']);});it('shows Admin only to whoever administers the workspace or runs its server', () => {expect(- workspaceNavViews({ managed: false, serviceConnections: true, administers: false })+ workspaceNavViews({+ managed: false,+ serviceConnections: true,+ administers: false,+ agentManagement: false,+ })).toEqual(['server', 'serverAgents', 'serverRooms', 'connectors', 'templates']);// The server's status lives under Admin, for whoever runs it, flag or role aside.expect(- workspaceNavViews({ managed: true, serviceConnections: false, administers: false })+ workspaceNavViews({+ managed: true,+ serviceConnections: false,+ administers: false,+ agentManagement: false,+ })).toEqual(['server', 'serverAgents', 'serverRooms', 'templates', 'admin']);});+ it('shows Your Machines after Your Agents only where the server runs agent management', () => {+ expect(+ workspaceNavViews({+ managed: false,+ serviceConnections: false,+ administers: false,+ agentManagement: true,+ })+ ).toEqual(['server', 'serverAgents', 'machines', 'serverRooms', 'templates']);+ });+it('opens Admin on its sections, or on the server’s status where there are none to use', () => {expect(adminNavTarget({ serviceConnections: true, administers: true, frozen: false })).toBe('admin'diff --git a/console/apps/switch-console-desktop/src/shared/core/managed-agents/machine-enrollment.test.ts b/console/apps/switch-console-desktop/src/shared/core/managed-agents/machine-enrollment.test.tsnew file mode 100644index 000000000..886489f0e--- /dev/null+++ b/console/apps/switch-console-desktop/src/shared/core/managed-agents/machine-enrollment.test.ts@@ -0,0 +1,28 @@+import { describe, expect, it } from 'vitest';+import { enrollCommand, installCommand, shellQuote } from './machine-enrollment';++describe('machine enrollment commands', () => {+ it('quotes only what the shell would misread', () => {+ expect(shellQuote('https://switch.example.com')).toBe('https://switch.example.com');+ expect(shellQuote("the box's GPU")).toBe(`'the box'\\''s GPU'`);+ });++ it('installs and enrolls with the code, leaving a blank name and description out', () => {+ expect(+ installCommand('https://switch.example.com', 'abc', { name: ' ', description: '' })+ ).toBe(+ 'curl -fsSL https://raw.githubusercontent.com/sandbox-quantum/switch/main/console/packages/agent-controller/install.sh | sh -s -- --server https://switch.example.com --code abc'+ );+ });++ it('enrolls an installed controller with the name and description given', () => {+ expect(+ enrollCommand('https://switch.example.com', 'abc', {+ name: 'build-box',+ description: 'In the office',+ })+ ).toBe(+ "switch-agent-controller enroll --server https://switch.example.com --code abc --name build-box --description 'In the office'"+ );+ });+});diff --git a/console/apps/switch-console-desktop/src/shared/core/managed-agents/machine-enrollment.ts b/console/apps/switch-console-desktop/src/shared/core/managed-agents/machine-enrollment.tsnew file mode 100644index 000000000..654b573ac--- /dev/null+++ b/console/apps/switch-console-desktop/src/shared/core/managed-agents/machine-enrollment.ts@@ -0,0 +1,71 @@+/**+ * Enrolling a new machine: what the server issues, and the commands a person+ * runs on the machine with it. The commands match the gateway's Add machine+ * dialog, so both say the same thing.+ */++/** A one-time enrollment code and where the machine enrolls with it. */+export type MachineEnrollment = {+ code: string;+ expiresAt: string;+ /** The Switch API address the machine enrolls against. */+ serverUrl: string;+ /** `serverUrl` names this computer, so no other machine can reach it there. */+ loopback: boolean;+};++/** The longest name and description a machine can enroll with. */+export const MAX_MACHINE_NAME = 200;+export const MAX_MACHINE_DESCRIPTION = 500;++/**+ * The controller's installer, as published on the default branch: it finds the+ * newest `switch-agent-controller` release and installs it with npm.+ */+export const CONTROLLER_INSTALL_SCRIPT_URL =+ 'https://raw.githubusercontent.com/sandbox-quantum/switch/main/console/packages/agent-controller/install.sh';++/** One word for a POSIX shell: as it is when nothing in it is special, else single-quoted. */+export function shellQuote(value: string): string {+ if (/^[A-Za-z0-9_@%+=:,./-]+$/.test(value)) return value;+ return `'${value.replace(/'/g, `'\\''`)}'`;+}++/** The enroll options for a name and description, when given: blank is left out, so the name defaults to the host name. */+function machineWords(machine: { name: string; description: string }): string[] {+ const words: string[] = [];+ const name = machine.name.trim();+ const description = machine.description.trim();+ if (name) words.push('--name', name);+ if (description) words.push('--description', description);+ return words;+}++/** The one command that installs the controller, enrolls the machine and starts it as a service. */+export function installCommand(+ server: string,+ code: string,+ machine: { name: string; description: string }+): string {+ const options = ['--server', server, '--code', code, ...machineWords(machine)];+ return `curl -fsSL ${CONTROLLER_INSTALL_SCRIPT_URL} | sh -s -- ${options.map(shellQuote).join(' ')}`;+}++/** The command for a machine where the controller is installed already. */+export function enrollCommand(+ server: string,+ code: string,+ machine: { name: string; description: string }+): string {+ return [+ 'switch-agent-controller',+ 'enroll',+ '--server',+ server,+ '--code',+ code,+ ...machineWords(machine),+ ]+ .map(shellQuote)+ .join(' ');+}diff --git a/console/apps/switch-console-desktop/src/shared/core/managed-agents/managed-agents.ts b/console/apps/switch-console-desktop/src/shared/core/managed-agents/managed-agents.tsindex 241aafc71..b42cd4dc4 100644--- a/console/apps/switch-console-desktop/src/shared/core/managed-agents/managed-agents.ts+++ b/console/apps/switch-console-desktop/src/shared/core/managed-agents/managed-agents.ts@@ -134,6 +134,65 @@ export type OwnedMachine = ManagedMachine & {local: MachineLocal;};+/** A provider on a machine with its version and when the machine last checked it. */+export type MachineProviderDetail = MachineProvider & {+ version: string | null;+ checkedAt: string | null;+};++/** An agent a machine runs, as the machine last saw it. */+export type MachineAgentReport = {+ agentId: string;+ process: string;+ attached: boolean;+ activeSessions: number;+ restarts10m: number;+ since: string | null;+ reason: string | null;+ detail: string | null;+};++/**+ * One of the owner's machines as the Machines page shows it: everything Switch+ * holds about it and its last status report, revoked machines included.+ */+export type MachineDetail = Omit<OwnedMachine, 'providers'> & {+ description: string | null;+ providers: MachineProviderDetail[];+ platform: { os: string; arch: string; osVersion: string } | null;+ /** The controller version it last reported. */+ version: string | null;+ /** Its connection as Switch last recorded it: the current one, or the last; null when it never connected. */+ connection: {+ connectedAt: string;+ disconnectedAt: string | null;+ disconnectReason: string | null;+ } | null;+ /** The controller release Switch names for it; null when it names none, as for one Console updates. */+ release: { wanted: string; running: string | null; current: boolean } | null;+ /** Who moves its controller onto another release; null when it has not said. */+ updatedBy: 'self' | 'console' | null;+ /** Why it does not run the release Switch names yet; null when it does or has not said. */+ update: { target: string; state: string; problem: string | null } | null;+ /** The machine's resources as last reported; null before it has. */+ resources: {+ diskFreeBytes: number;+ diskTotalBytes: number;+ memFreeBytes: number;+ memTotalBytes: number;+ sessionsRunning: number;+ sessionsMax: number;+ } | null;+ /** Each agent it runs, as it last reported; empty before it has. */+ agents: MachineAgentReport[];+ /** When it last reported its status. */+ lastSeenAt: string | null;+ /** When its last status report was observed on the machine. */+ observedAt: string | null;+ createdAt: string | null;+ revokedAt: string | null;+};+/** The settings a managed agent's page changes; a field left out stays as the server holds it. */export type ManagedAgentChanges = {definition: Partial<ManagedAgentView['definition']>;diff --git a/console/apps/switch-console-desktop/src/shared/core/switch-servers/loopback.ts b/console/apps/switch-console-desktop/src/shared/core/switch-servers/loopback.tsindex 855da260c..34335fb1a 100644--- a/console/apps/switch-console-desktop/src/shared/core/switch-servers/loopback.ts+++ b/console/apps/switch-console-desktop/src/shared/core/switch-servers/loopback.ts@@ -11,3 +11,12 @@ export function isHttpsOrLoopback(url: URL): boolean {url.protocol === 'https:' || (url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname)));}++/** Whether `url` names this computer itself, so only programs on it can reach it there. */+export function isLoopbackUrl(url: string): boolean {+ try {+ return LOOPBACK_HOSTS.has(new URL(url).hostname);+ } catch {+ return false;+ }+}diff --git a/console/apps/switch-console-desktop/src/shared/core/telemetry/reporting.ts b/console/apps/switch-console-desktop/src/shared/core/telemetry/reporting.tsindex f3d7e2c43..1c8229c8d 100644--- a/console/apps/switch-console-desktop/src/shared/core/telemetry/reporting.ts+++ b/console/apps/switch-console-desktop/src/shared/core/telemetry/reporting.ts@@ -25,6 +25,8 @@ export const UI_ENTRY_POINTS = ['server_page','onboarding','agent_page',+ /** A machine's page, which creates an agent on that machine. */+ 'machine_page','session_list','room_row','link',diff --git a/console/apps/switch-console-desktop/src/shared/core/views/view-ids.ts b/console/apps/switch-console-desktop/src/shared/core/views/view-ids.tsindex ae32a39b4..f2226cead 100644--- a/console/apps/switch-console-desktop/src/shared/core/views/view-ids.ts+++ b/console/apps/switch-console-desktop/src/shared/core/views/view-ids.ts@@ -18,6 +18,8 @@ export const VIEW_IDS = ['server','managedServer','serverAgents',+ 'machines',+ 'machine','connectors','serverRooms','remoteHosts',diff --git a/console/packages/agent-controller/scripts/dev-machines.mjs b/console/packages/agent-controller/scripts/dev-machines.mjsnew file mode 100644index 000000000..bf815fb35--- /dev/null+++ b/console/packages/agent-controller/scripts/dev-machines.mjs@@ -0,0 +1,234 @@+#!/usr/bin/env node+// Dev only: enrolls and runs a crowd of headless agents controllers on this+// computer against the local Switch server a dev Console runs, so pages that+// list machines can be tried with many real ones.+//+// node scripts/dev-machines.mjs [--count 20] [--offline 3]+// [--user-data-dir switchdash-dev-machines] [--prefix test-machine]+//+// Each controller keeps its own data directory under+// ~/.switch/dev-machines/<user-data-dir>/<name>, with its credential in a file+// there, so they share nothing with each other or with this computer's own+// controller. A machine is enrolled once and reused on the next run; delete its+// directory (and remove it in Switch) to start it over. `--offline N` stops the+// last N a few seconds after they connect, so they show as offline. Ctrl-C+// stops them all.+//+// Only a native local server (no Docker) is supported: its admin sign-in is+// read from the environment file Console starts it with.++import { spawn } from 'node:child_process';+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { homedir } from 'node:os';+import { join } from 'node:path';+import { createInterface } from 'node:readline';+import { fileURLToPath } from 'node:url';+import { parseArgs } from 'node:util';++const { values: args } = parseArgs({+ options: {+ count: { type: 'string', default: '20' },+ offline: { type: 'string', default: '0' },+ 'user-data-dir': { type: 'string', default: 'switchdash-dev-machines' },+ prefix: { type: 'string', default: 'test-machine' },+ },+});++const count = wholeNumber('--count', args.count);+const offline = wholeNumber('--offline', args.offline);+if (offline > count) fail('--offline cannot be more than --count.');++const DESCRIPTIONS = [+ 'Build box in the office',+ null,+ 'GPU workstation for the model experiments',+ 'Shared CI runner',+ null,+ 'Spare laptop under the desk',+];+/**+ * Lines each controller prints that say nothing here: Node's notice about+ * SQLite, and the warning that the credential is in a file, which this+ * script asks for.+ */+const EXPECTED_NOISE = [+ 'ExperimentalWarning',+ 'node --trace-warnings',+ 'No OS keychain backend is in use',+];+/** The controllers' environment: quiet unless something goes wrong. */+const CHILD_ENV = {+ ...process.env,+ SWITCH_CONTROLLER_LOG_LEVEL: process.env.SWITCH_CONTROLLER_LOG_LEVEL ?? 'warn',+};+/** How long a machine meant to show as offline runs first, so it has connected once. */+const OFFLINE_AFTER_MS = 20_000;++const cli = fileURLToPath(new URL('../dist/cli.mjs', import.meta.url));+if (!existsSync(cli))+ fail(`${cli} is missing: build the workspace packages first (pnpm -r --filter './packages/**' run build).`);++const server = localServer(args['user-data-dir']);+const root = join(homedir(), '.switch', 'dev-machines', args['user-data-dir']);+const machines = Array.from({ length: count }, (_, i) => {+ const name = `${args.prefix}-${String(i + 1).padStart(2, '0')}`;+ return { name, dir: join(root, name), description: DESCRIPTIONS[i % DESCRIPTIONS.length] };+});++const children = new Set();+let stopping = false;+process.on('SIGINT', stopAll);+process.on('SIGTERM', stopAll);++let cookie = null;+for (const machine of machines) {+ if (existsSync(join(machine.dir, '.dev-machine'))) continue;+ cookie ??= await signIn();+ await enroll(machine, await enrollmentCode());+}++console.log(`Running ${count} controllers against ${server.url}. Ctrl-C stops them all.`);+machines.forEach((machine, i) => {+ const child = run(machine);+ if (i >= count - offline)+ setTimeout(() => {+ if (stopping || child.exitCode !== null) return;+ console.log(`[${machine.name}] stopping it so it shows as offline`);+ child.kill('SIGTERM');+ }, OFFLINE_AFTER_MS);+});++function wholeNumber(flag, value) {+ const number = Number(value);+ if (!Number.isInteger(number) || number < 0) fail(`${flag} takes a whole number, not ${value}.`);+ return number;+}++function fail(message) {+ console.error(`dev-machines: ${message}`);+ process.exit(1);+}++/** The local server's address and admin sign-in, from the files Console keeps for it. */+function localServer(userDataDir) {+ const appData =+ process.platform === 'darwin'+ ? join(homedir(), 'Library', 'Application Support')+ : (process.env.XDG_CONFIG_HOME ?? join(homedir(), '.config'));+ const base = join(appData, userDataDir, 'local-switch-server');+ const portsFile = join(base, 'ports.json');+ const envFile = join(base, 'native', 'run', 'switch-core.env');+ if (!existsSync(portsFile))+ fail(`No local server in ${base}. Start one from the Console run with SWITCH_CONSOLE_USER_DATA_DIR=${userDataDir}.`);+ if (!existsSync(envFile))+ fail(`${envFile} is missing: only a local server that runs without Docker is supported.`);+ const env = Object.fromEntries(+ readFileSync(envFile, 'utf8')+ .split('\n')+ .filter((line) => line && !line.startsWith('#') && line.includes('='))+ .map((line) => [line.slice(0, line.indexOf('=')), line.slice(line.indexOf('=') + 1)])+ );+ const { api } = JSON.parse(readFileSync(portsFile, 'utf8'));+ if (!env.GATEWAY_ADMIN_EMAIL || !env.GATEWAY_ADMIN_PASSWORD)+ fail(`${envFile} names no admin sign-in.`);+ return {+ url: `http://127.0.0.1:${api}`,+ email: env.GATEWAY_ADMIN_EMAIL,+ password: env.GATEWAY_ADMIN_PASSWORD,+ };+}++async function signIn() {+ const res = await fetch(`${server.url}/gateway/auth/login`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ email: server.email, password: server.password }),+ });+ if (!res.ok) fail(`Signing in to ${server.url} failed with HTTP ${res.status}. Is the local server running?`);+ const session = res.headers+ .getSetCookie()+ .map((header) => header.split(';')[0])+ .join('; ');+ if (!session) fail('The server signed in but set no session cookie.');+ return session;+}++async function enrollmentCode() {+ const res = await fetch(`${server.url}/gateway/management/enrollment-codes`, {+ method: 'POST',+ headers: { cookie },+ });+ if (!res.ok)+ fail(`The server gave no enrollment code (HTTP ${res.status}): ${await res.text()}`);+ return (await res.json()).code;+}++async function enroll(machine, code) {+ mkdirSync(machine.dir, { recursive: true });+ const enrollArgs = [+ cli,+ 'enroll',+ '--server',+ server.url,+ '--code',+ code,+ '--name',+ machine.name,+ '--data-dir',+ machine.dir,+ '--secret-store',+ 'file',+ ];+ if (machine.description) enrollArgs.push('--description', machine.description);+ const exitCode = await new Promise((resolve) => {+ const child = spawn(process.execPath, enrollArgs, {+ stdio: ['ignore', 'ignore', 'pipe'],+ env: CHILD_ENV,+ });+ relay(machine, child.stderr);+ child.on('exit', resolve);+ });+ if (exitCode !== 0) fail(`Enrolling ${machine.name} failed (exit ${exitCode}).`);+ writeFileSync(join(machine.dir, '.dev-machine'), `${machine.name}\n`);+ console.log(`[${machine.name}] enrolled`);+}++function run(machine) {+ const child = spawn(process.execPath, [cli, 'run', '--data-dir', machine.dir], {+ stdio: ['ignore', 'pipe', 'pipe'],+ env: CHILD_ENV,+ });+ children.add(child);+ relay(machine, child.stdout);+ relay(machine, child.stderr);+ child.on('exit', (code, signal) => {+ children.delete(child);+ if (stopping) return;+ const why =+ code === 3 || code === 6+ ? `: Switch no longer knows it. Delete ${machine.dir} to enroll it again.`+ : '';+ console.log(`[${machine.name}] exited (${signal ?? `code ${code}`})${why}`);+ });+ return child;+}++/** A controller's output, each line under its name, without the lines expected here. */+function relay(machine, stream) {+ createInterface({ input: stream }).on('line', (line) => {+ if (EXPECTED_NOISE.some((noise) => line.includes(noise))) return;+ console.log(`[${machine.name}] ${line}`);+ });+}++function stopAll() {+ if (stopping) return;+ stopping = true;+ console.log(`Stopping ${children.size} controllers…`);+ for (const child of children) child.kill('SIGTERM');+ const wait = setInterval(() => {+ if (children.size > 0) return;+ clearInterval(wait);+ process.exit(0);+ }, 200);+}