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: follow the workspace, set machines up, drop deleted agents, retry avatars (#761)
Louis Amaudruz83d34cd7652b
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration-service.test.ts b/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration-service.test.tsindex d61f2504a..49c5a4dad 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration-service.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration-service.test.ts@@ -61,7 +61,7 @@ type World = {/** What the machine looks like once `enable` has turned it on; null leaves it as it was. */lookupAfterEnable: TargetLookup | null;enableFails: boolean;- eligibility: { management: boolean; owner: string | null; ownedByMe: boolean };+ eligibility: { management: boolean; owner: string | null; ownedByMe: boolean; gone?: true };stoppedByHand: boolean;controllerRunning: boolean[];failAdoptOn: string | null;@@ -87,6 +87,9 @@ function deps(): AgentMigrationDeps {get: async (agentId) => (agentId === PARENT.id ? PARENT : null),list: async () => [PARENT],stoppedByHand: async () => world.stoppedByHand,+ forget: async (agentId) => {+ world.calls.push(`forget ${agentId}`);+ },},definitions: {build: async () => BUILT,@@ -915,6 +918,18 @@ describe('moving every agent automatically', () => {expect(adopted()).toHaveLength(1);});+ it('removes an agent its server has deleted, and moves nothing for it', async () => {+ all = [PARENT];+ world.eligibility = { management: true, owner: null, ownedByMe: false, gone: true };+ const migration = service();+ await migration.migrateEverything();+ expect(world.calls).toContain(`forget ${PARENT.id}`);+ expect(adopted()).toHaveLength(0);+ const overview = await migration.overview();+ expect(overview.leftAlone).toBe(0);+ expect(overview.unasked).toBe(0);+ });+it('counts what it left alone and what it could not ask about', async () => {const base = deps().management;const migration = service({diff --git a/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration-service.ts b/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration-service.tsindex 4fa331495..18327d5be 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration-service.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration-service.ts@@ -70,11 +70,15 @@ export type MachineHealth =/** Switch's agent management, through the signed-in session of the agent's workspace. */export interface MigrationManagementPort {- /** Whether the server runs agent management, and whether the signed-in user owns the agent. */+ /**+ * Whether the server runs agent management, and whether the signed-in user+ * owns the agent. `gone` when the server says it has no such agent: it was+ * deleted there.+ */eligibility(workspaceId: string,switchAgentId: string- ): Promise<{ management: boolean; owner: string | null; ownedByMe: boolean }>;+ ): Promise<{ management: boolean; owner: string | null; ownedByMe: boolean; gone?: true }>;/** `PUT /gateway/management/agents/{id}`: places the agent on the controller. */adopt(workspaceId: string,@@ -155,6 +159,11 @@ export type AgentMigrationDeps = {list(): Promise<MigrationAgent[]>;/** Somebody stopped this agent's watcher by hand. */stoppedByHand(agentId: string): Promise<boolean>;+ /**+ * Removes an agent its server has deleted from this Console. Only the+ * Console's row: files on its machine are left where they are.+ */+ forget(agentId: string): Promise<void>;};definitions: {build(agent: MigrationAgent): Promise<BuiltDefinition>;@@ -454,6 +463,26 @@ export class AgentMigrationService {}this.unasked.delete(agent.id);this.retryAt.delete(`ask:${agent.id}`);+ if (eligibility.gone) {+ // Deleted on its server: there is nothing to move it to and no way back,+ // and listing it here (and under Legacy) only keeps asking about it.+ this.deps.log.warn('Removing an agent its server no longer has', {+ agentId: agent.id,+ switchAgentId: agent.switchAgentId,+ });+ try {+ await this.deps.agents.forget(agent.id);+ } catch (error) {+ this.deps.log.error('Could not remove an agent its server no longer has', {+ agentId: agent.id,+ error: message(error),+ });+ this.backOff(`ask:${agent.id}`, now);+ }+ this.leftAlone.delete(agent.id);+ this.problems.delete(agent.id);+ continue;+ }if (!eligibility.management || !eligibility.ownedByMe) {this.unmanageableUntil.set(agent.id, now + this.deps.unmanageableRecheckMs);this.problems.delete(agent.id);@@ -1001,6 +1030,8 @@ export class AgentMigrationService {agent.workspaceId!,agent.switchAgentId!);+ if (eligibility.gone)+ return 'Its server no longer has this agent, so Console removes it on its next check.';if (!eligibility.management)return 'This server does not have agent management turned on, so it cannot run agents on machines.';if (!eligibility.ownedByMe)diff --git a/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration.ts b/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration.tsindex dcad2327a..716eb898a 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration.ts@@ -7,6 +7,7 @@ import { agentLaunchConfig } from '@main/core/agents/agent-launch-config';import { getAgentLocation } from '@main/core/agents/agent-location';import { resolveWorkdirFsFor } from '@main/core/agents/agent-workdir-fs';import { connectRemoteAgent } from '@main/core/agents/connect-remote-agent';+import { deleteAgent } from '@main/core/agents/deleteAgent';import { getAgentById } from '@main/core/agents/getAgentById';import { getAgents } from '@main/core/agents/getAgents';import { agentSettingsRelativePath } from '@main/core/agents/switch-settings-paths';@@ -37,6 +38,7 @@ import {fetchManagedAgent,fetchManagementControllers,fetchMe,+ GatewayError,managementErrorMessage,putManagedAgent,revealAgentApiKey,@@ -290,10 +292,15 @@ const management: MigrationManagementPort = {return { management: false, owner: null, ownedByMe: false };throw error;}- const [me, detail] = await Promise.all([- fetchMe(server),- fetchAgentDetail(server, switchAgentId),- ]);+ let detail;+ try {+ detail = await fetchAgentDetail(server, switchAgentId);+ } catch (error) {+ if (error instanceof GatewayError && error.kind === 'http' && error.status === 404)+ return { management: true, owner: null, ownedByMe: false, gone: true };+ throw error;+ }+ const me = await fetchMe(server);return {management: true,owner: detail.ownerName,@@ -724,6 +731,12 @@ export const agentMigrationService = new AgentMigrationService({return agents;},stoppedByHand: async (agentId) => (await listStoppedControllerAgentIds()).includes(agentId),+ forget: (agentId) =>+ deleteAgent(agentId, {+ deleteInSwitch: false,+ removeProvisionedFiles: false,+ trigger: 'server_teardown',+ }),},definitions: { build: buildDefinition },targets: {diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/managed-run-location-notice.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/managed-run-location-notice.tsxindex 188ad682c..1879b2fd6 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/managed-run-location-notice.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/managed-run-location-notice.tsx@@ -1,7 +1,7 @@import type { AdvancedConfigValue } from '@switch-console/plugins/agents';import { useQuery } from '@tanstack/react-query';import { CircleAlert, Server } from 'lucide-react';-import { useEffect, useMemo, useState } from 'react';+import { useEffect, useMemo, useRef, useState } from 'react';import {advancedConfigFromForm,MODEL_FIELD,@@ -41,7 +41,34 @@ export function ManagedRunLocationNotice({onEnabled: () => void;}) {const [enabling, setEnabling] = useState(false);+ const [autoTried, setAutoTried] = useState<string | null>(null);const notice = newAgentMachineNotice(machine, { label, sshHost });+ const canEnable = notice.kind === 'blocked' && notice.enable !== null;+ const where = `${serverId}:${workspaceId}:${sshHost ?? 'this-computer'}`;+ const enableRef = useRef(enable);+ enableRef.current = enable;++ // A machine that can be set up for managed agents is set up as soon as it is+ // chosen, as the automatic move to managed would: on a server with agent+ // management that is how agents run, so asking first only stands in the way.+ // Tried once per machine; if it fails, the button below is the way to retry.+ useEffect(() => {+ if (!canEnable || autoTried === where) return;+ setAutoTried(where);+ void enableRef.current();+ }, [canEnable, where, autoTried]);++ if (enabling)+ return (+ <p className="flex items-start gap-1.5 text-xs text-foreground-muted">+ <Server className="mt-0.5 size-3.5 shrink-0" />+ <span>+ {sshHost+ ? `Setting ${label} up to run managed agents…`+ : 'Setting this computer up to run managed agents…'}+ </span>+ </p>+ );if (notice.kind !== 'blocked')return (@@ -51,7 +78,7 @@ export function ManagedRunLocationNotice({</p>);- const enable = async () => {+ async function enable() {setEnabling(true);try {if (sshHost) await rpc.hostControllers.enable({ sshHost, serverId, workspaceId });@@ -66,7 +93,7 @@ export function ManagedRunLocationNotice({} finally {setEnabling(false);}- };+ }return (<div className="flex items-start gap-2 rounded-md border border-border bg-background-1 px-2 py-1.5 text-xs text-foreground-muted">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 ce57ff1d2..9fb8f58ce 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@@ -151,7 +151,12 @@ export const NewAgentForm = observer(function NewAgentForm({const askForMachines =!!selectedServerId && !!workspacesStore.idOnServerInScope(selectedServerId);const machinesQuery = useQuery({- queryKey: [MANAGED_AGENTS_KEY, selectedServerId, 'machines'],+ queryKey: [+ MANAGED_AGENTS_KEY,+ selectedServerId,+ 'machines',+ workspacesStore.idOnServerInScope(selectedServerId),+ ],queryFn: () => rpc.managedAgents.machines(selectedServerId!),enabled: askForMachines,refetchInterval: (query) => (query.state.data ? 5000 : false),diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-list.tsx b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-list.tsxindex 013cc94dd..44b43b41f 100644--- a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-list.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-list.tsx@@ -33,7 +33,7 @@ export const ManagedAgentList = observer(function ManagedAgentList() {if (!agents.data?.length) return null;return (<div className="flex flex-col gap-[2px]" aria-label="Managed agents">- {attentionFirst(agents.data).map((agent) => (+ {disconnectedLast(agents.data).map((agent) => (<ManagedAgentRow key={agent.agentId} agent={agent} />))}</div>@@ -41,12 +41,14 @@ export const ManagedAgentList = observer(function ManagedAgentList() {});/**- * The agents that need looking at first — a failed agent, or one whose machine- * is gone — and the rest in the order the server listed them.+ * The agents in the order the server listed them, with the ones that cannot+ * run right now — no machine, or a machine that is offline or removed — at the+ * bottom, where they stay out of the way of the agents that can.*/-export function attentionFirst(agents: ManagedAgentView[]): ManagedAgentView[] {- const needsAttention = (agent: ManagedAgentView) => managedAgentState(agent).tone === 'problem';- return [...agents.filter(needsAttention), ...agents.filter((agent) => !needsAttention(agent))];+export function disconnectedLast(agents: ManagedAgentView[]): ManagedAgentView[] {+ const disconnected = (agent: ManagedAgentView) =>+ agent.machine === null || agent.machine.state !== 'online';+ return [...agents.filter((agent) => !disconnected(agent)), ...agents.filter(disconnected)];}const ManagedAgentRow = observer(function ManagedAgentRow({ agent }: { agent: ManagedAgentView }) {diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/use-managed-agents.test.ts b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/use-managed-agents.test.tsindex 2e023bfc4..6aa188940 100644--- a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/use-managed-agents.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/use-managed-agents.test.ts@@ -5,6 +5,9 @@ vi.mock('@renderer/lib/ipc', () => ({ rpc: {} }));vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({switchServersStore: {},}));+vi.mock('@renderer/features/workspaces/workspaces-store', () => ({+ workspacesStore: {},+}));const { withoutManaged } = await import('./use-managed-agents');diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/use-managed-agents.ts b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/use-managed-agents.tsindex d7ab5a650..a007d9f2e 100644--- a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/use-managed-agents.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/use-managed-agents.ts@@ -1,6 +1,7 @@import { useQuery, useQueryClient } from '@tanstack/react-query';import { useEffect } from 'react';import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { events, rpc } from '@renderer/lib/ipc';import type { ManagedAgentView } from '@shared/core/managed-agents/managed-agents';import { agentMigrationChannel } from '@shared/events/agentMigrationEvents';@@ -24,6 +25,9 @@ export function useManagedAgents(serverId: string | null) {const queryClient = useQueryClient();const signedIn = serverId !== null && switchServersStore.isConnected(serverId);const user = serverId === null ? null : (switchServersStore.statusFor(serverId)?.user ?? null);+ // The list is the workspace's, not the server's: switching workspace on the+ // same server has to read it again rather than show the last one.+ const workspaceId = workspacesStore.idOnServerInScope(serverId);useEffect(() =>events.on(agentMigrationChannel, (event) => {@@ -33,7 +37,7 @@ export function useManagedAgents(serverId: string | null) {[queryClient, serverId]);return useQuery({- queryKey: [MANAGED_AGENTS_KEY, serverId, user?.id ?? null],+ queryKey: [MANAGED_AGENTS_KEY, serverId, workspaceId, user?.id ?? null],queryFn: () => rpc.managedAgents.list(serverId!),enabled: signedIn,refetchInterval: (query) => (query.state.data === null ? false : MANAGED_AGENTS_REFRESH_MS),@@ -44,7 +48,12 @@ export function useManagedAgents(serverId: string | null) {/** The signed-in user's machines on the server, with what each reported; null without agent management. */export function useOwnedMachines(serverId: string) {return useQuery({- queryKey: [MANAGED_AGENTS_KEY, serverId, 'machines'],+ queryKey: [+ MANAGED_AGENTS_KEY,+ serverId,+ 'machines',+ workspacesStore.idOnServerInScope(serverId),+ ],queryFn: () => rpc.managedAgents.machines(serverId),refetchInterval: 15000,});@@ -53,7 +62,12 @@ export function useOwnedMachines(serverId: string) {/** The owner's machines on the server, with what each last reported. Null without agent management. */export function useManagedMachines(serverId: string) {return useQuery({- queryKey: [MANAGED_AGENTS_KEY, serverId, 'machines'],+ queryKey: [+ MANAGED_AGENTS_KEY,+ serverId,+ 'machines',+ workspacesStore.idOnServerInScope(serverId),+ ],queryFn: () => rpc.managedAgents.machines(serverId),refetchInterval: (query) => (query.state.data ? 5000 : false),retry: false,diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/agent-avatar.tsx b/console/apps/switch-console-desktop/src/renderer/lib/components/agent-avatar.tsxindex 125652118..7e88438a5 100644--- a/console/apps/switch-console-desktop/src/renderer/lib/components/agent-avatar.tsx+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/agent-avatar.tsx@@ -1,4 +1,4 @@-import { useState } from 'react';+import { useEffect, useState } from 'react';import { cn } from '@renderer/utils/utils';import { agentAvatarUrlForName, agentInitials } from '@shared/core/agents/agent-avatar';@@ -17,6 +17,10 @@ import { agentAvatarUrlForName, agentInitials } from '@shared/core/agents/agent-* machine is offline — its initials. Deliberately visible rather than a* blank square or a broken-image glyph: a missing avatar should read as a* missing avatar.+ *+ * A failed load is tried again a few times, further apart each time, before+ * the initials stay: the avatar service refuses a burst of requests (a sidebar+ * of twenty agents asks for twenty at once), and those refusals pass.*/export function AgentAvatar({name,@@ -33,6 +37,19 @@ export function AgentAvatar({}) {const src = iconUrl ?? agentAvatarUrlForName(name);const [failedSrc, setFailedSrc] = useState<string | null>(null);+ const [attempt, setAttempt] = useState({ src, count: 0 });+ const tries = attempt.src === src ? attempt.count : 0;++ // After a failed load, try again later; the initials show in the meantime.+ useEffect(() => {+ if (failedSrc !== src || tries >= RETRY_DELAYS_MS.length) return;+ const delay = RETRY_DELAYS_MS[tries] * (0.75 + Math.random() * 0.5);+ const timer = setTimeout(() => {+ setAttempt({ src, count: tries + 1 });+ setFailedSrc(null);+ }, delay);+ return () => clearTimeout(timer);+ }, [failedSrc, src, tries]);const shape = cn('inline-flex shrink-0 items-center justify-center rounded-full', className);@@ -51,6 +68,7 @@ export function AgentAvatar({return (<span className={shape} style={{ width: size, height: size }}><img+ key={tries}src={src}alt=""width={size}@@ -61,3 +79,6 @@ export function AgentAvatar({</span>);}++/** How long to wait before each new try of an avatar that did not load. */+const RETRY_DELAYS_MS = [1_500, 5_000, 15_000];diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/agent-avatar-retry.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/agent-avatar-retry.test.tsxnew file mode 100644index 000000000..5d5218b8a--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/agent-avatar-retry.test.tsx@@ -0,0 +1,46 @@+/**+ * An agent's avatar that fails to load is tried again before the initials+ * stay: the avatar service refuses bursts, and those refusals pass.+ */+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, expect, it, vi } from 'vitest';+import { AgentAvatar } from '@renderer/lib/components/agent-avatar';++let container: HTMLDivElement | null = null;+let root: Root | null = null;++afterEach(async () => {+ vi.useRealTimers();+ if (root) await act(async () => root!.unmount());+ container?.remove();+ container = null;+ root = null;+});++async function fail(img: HTMLImageElement) {+ await act(async () => img.dispatchEvent(new Event('error')));+}++it('tries a failed avatar again, then keeps the initials after the last try', async () => {+ vi.useFakeTimers();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ await act(async () =>+ root!.render(<AgentAvatar name="Ada Lovelace" iconUrl="https://avatars.invalid/ada.svg" />)+ );++ for (let tryNumber = 0; tryNumber < 3; tryNumber++) {+ const img = container.querySelector('img');+ expect(img, `try ${tryNumber + 1} draws the image`).not.toBeNull();+ await fail(img!);+ expect(container.textContent).toBe('AL');+ await act(async () => vi.advanceTimersByTime(20_000));+ }++ await fail(container.querySelector('img')!);+ await act(async () => vi.advanceTimersByTime(60_000));+ expect(container.querySelector('img')).toBeNull();+ expect(container.textContent).toBe('AL');+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-managed-machine.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-managed-machine.test.tsxindex add0e43cb..d2125fd73 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-managed-machine.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-managed-machine.test.tsx@@ -123,18 +123,16 @@ describe('where a new agent runs', () => {expect(el.querySelector('button')).toBeNull();});- it('turns this computer on from the form, then looks again', async () => {+ it('sets this computer up for managed agents as soon as it is chosen, without asking', async () => {const onEnabled = vi.fn();- const el = await render(+ await render(notice({ management: true, target: null, blocker: 'Turn it on first.', canEnable: true },null,onEnabled));- const button = el.querySelector('button')!;- expect(button.textContent).toBe('Run managed agents on this computer');- await act(async () => button.click());+ expect(embeddedEnable).toHaveBeenCalledTimes(1);expect(embeddedEnable).toHaveBeenCalledWith({serverId: 'server-1',workspaceId: 'workspace-1',@@ -143,14 +141,13 @@ describe('where a new agent runs', () => {expect(onEnabled).toHaveBeenCalled();});- it('makes an SSH host a machine from the form', async () => {- const el = await render(+ it('sets an SSH host up as a machine as soon as it is chosen', async () => {+ await render(notice({ management: true, target: null, blocker: 'Make it a machine.', canEnable: true },'box'));- await act(async () => el.querySelector('button')!.click());expect(hostEnable).toHaveBeenCalledWith({sshHost: 'box',serverId: 'server-1',@@ -158,6 +155,21 @@ describe('where a new agent runs', () => {});});+ it('offers the button to try again when setting it up failed, and does not retry by itself', async () => {+ embeddedEnable.mockRejectedValueOnce(new Error('no controller'));+ const el = await render(+ notice(+ { management: true, target: null, blocker: 'Turn it on first.', canEnable: true },+ null+ )+ );+ expect(embeddedEnable).toHaveBeenCalledTimes(1);+ const button = el.querySelector('button')!;+ expect(button.textContent).toBe('Run managed agents on this computer');+ await act(async () => button.click());+ expect(embeddedEnable).toHaveBeenCalledTimes(2);+ });+it('says Console runs the agent on a server without agent management', async () => {const el = await render(notice({ management: false }, null));expect(el.textContent).toMatch(/so this Console runs the agent/);