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
fix(console): hide moved agents instead of deleting them; scope room membership to tracked identities
raullopez-sandbox4de435bd88c1
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/controller.ts b/console/apps/switch-console-desktop/src/main/core/agents/controller.tsindex b59a2ce75..3e5f1a163 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/controller.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/controller.ts@@ -1,4 +1,5 @@import type { RepoAgentAttributes } from '@switch-console/core/agents/plugins';+import { listManagedAgentRecords } from '@main/core/agent-migration/managed-agents-store';import type { OnboardAgentParams } from '@shared/core/agents/onboarding';import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';import type { AgentVerifyResult } from '@shared/core/switch-servers/switch-servers';@@ -79,6 +80,9 @@ export const agentsController = createRPCController({removeLoadableAgentConfig: (params: RemoveLoadableAgentConfigParams) =>removeLoadableAgentConfig(params),getAgents: (locationId?: string) => getAgents(locationId),+ /** The Console agents moved to agent management: shown through the managed list only, never as Console agents. */+ movedAgentIds: async (): Promise<string[]> =>+ (await listManagedAgentRecords()).map((record) => record.agentId),/*** Give a Console agent its new name locally, after its Switch server has* renamed it (`workspaces.renameAgent`): the row and the files keyed by thediff --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 e982a62ff..e9bff4e4e 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@@ -6,8 +6,6 @@ import {vertexLoginCredential,} from '@switch-console/agent-providers';import { agentMigrationService } from '@main/core/agent-migration/agent-migration';-import { listManagedAgentRecords } from '@main/core/agent-migration/managed-agents-store';-import { deleteAgent as deleteConsoleAgent } from '@main/core/agents/deleteAgent';import { embeddedControllerService } from '@main/core/embedded-controller/embedded-controllers';import { hostControllerService } from '@main/core/host-controllers/host-controllers';import {@@ -46,7 +44,6 @@ import type {} from '@shared/core/managed-agents/managed-agents';import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';import { createRPCController } from '@shared/lib/ipc/rpc';-import { forgetDeletedManagedAgents } from './forget-deleted';import { ownedMachines, preferredFirst, thisComputerReport } from './owned-machines';async function machinesOn(serverId: string): Promise<OwnedMachine[] | null> {@@ -94,22 +91,6 @@ export const managedAgentsController = createRPCController({if (error instanceof AgentManagementUnavailableError) return null;throw error;}- // The list came back: a moved agent missing from it was deleted on the server.- await forgetDeletedManagedAgents(- workspace.id,- new Set(agents.map((agent) => agent.agentId)),- {- records: listManagedAgentRecords,- forget: (consoleAgentId) =>- deleteConsoleAgent(consoleAgentId, {- deleteInSwitch: false,- removeProvisionedFiles: false,- trigger: 'server_teardown',- }),- warn: (message, context) => log.warn(message, context),- now: Date.now,- }- );return agents.map((agent): ManagedAgentView => {const machine =agent.machine !== undefineddiff --git a/console/apps/switch-console-desktop/src/main/core/managed-agents/forget-deleted.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-agents/forget-deleted.test.tsdeleted file mode 100644index 301f4f403..000000000--- a/console/apps/switch-console-desktop/src/main/core/managed-agents/forget-deleted.test.ts+++ /dev/null@@ -1,68 +0,0 @@-import { describe, expect, it, vi } from 'vitest';-import type { ManagedAgentRecord } from '@main/core/agent-migration/managed-agents-store';-import { forgetDeletedManagedAgents, RECENT_MOVE_GRACE_MS } from './forget-deleted';--const NOW = Date.parse('2026-10-27T12:00:00Z');--const record = (- agentId: string,- switchAgentId: string,- movedAgoMs: number,- workspaceId = 'ws'-): ManagedAgentRecord => ({- agentId,- workspaceId,- controllerId: 'controller',- placement: { kind: 'this-computer', serverId: 'srv' },- identities: [- {- switchAgentId,- slug: agentId,- subagent: null,- credentialsStashed: false,- controllerRoot: '~/agents',- },- ],- movedAt: new Date(NOW - movedAgoMs).toISOString(),-});--function deps(records: ManagedAgentRecord[]) {- return {- records: async () => records,- forget: vi.fn(async () => {}),- warn: vi.fn(),- now: () => NOW,- };-}--describe('forgetDeletedManagedAgents', () => {- it('forgets a moved agent the server no longer lists, and keeps the listed ones', async () => {- const calls = deps([- record('console-gone', 'switch-gone', 60 * 60_000),- record('console-kept', 'switch-kept', 60 * 60_000),- ]);- await forgetDeletedManagedAgents('ws', new Set(['switch-kept']), calls);- expect(calls.forget).toHaveBeenCalledTimes(1);- expect(calls.forget).toHaveBeenCalledWith('console-gone');- });-- it('leaves another workspace’s agents and one moved moments ago', async () => {- const calls = deps([- record('other-ws', 'switch-a', 60 * 60_000, 'ws-2'),- record('just-moved', 'switch-b', RECENT_MOVE_GRACE_MS / 2),- ]);- await forgetDeletedManagedAgents('ws', new Set(), calls);- expect(calls.forget).not.toHaveBeenCalled();- });-- it('logs one that cannot be forgotten and goes on with the rest', async () => {- const calls = deps([- record('a', 'switch-a', 60 * 60_000),- record('b', 'switch-b', 60 * 60_000),- ]);- calls.forget.mockRejectedValueOnce(new Error('locked'));- await forgetDeletedManagedAgents('ws', new Set(), calls);- expect(calls.forget).toHaveBeenCalledTimes(2);- expect(calls.warn).toHaveBeenCalledOnce();- });-});diff --git a/console/apps/switch-console-desktop/src/main/core/managed-agents/forget-deleted.ts b/console/apps/switch-console-desktop/src/main/core/managed-agents/forget-deleted.tsdeleted file mode 100644index f91ffab26..000000000--- a/console/apps/switch-console-desktop/src/main/core/managed-agents/forget-deleted.ts+++ /dev/null@@ -1,53 +0,0 @@-import type { ManagedAgentRecord } from '@main/core/agent-migration/managed-agents-store';--/** How long after a move an agent may be missing from the list without being forgotten. */-export const RECENT_MOVE_GRACE_MS = 2 * 60_000;--/**- * The Console agents moved to management in a workspace that its server no- * longer lists: deleted there, from another device or while this Console was- * closed. Only a list the server actually returned counts as proof; an agent- * moved moments ago may not be listed yet and is left alone.- */-export function goneManagedRecords(- records: readonly ManagedAgentRecord[],- workspaceId: string,- listedAgentIds: ReadonlySet<string>,- now: number-): ManagedAgentRecord[] {- return records.filter(- (record) =>- record.workspaceId === workspaceId &&- !listedAgentIds.has(record.identities[0].switchAgentId) &&- now - Date.parse(record.movedAt) > RECENT_MOVE_GRACE_MS- );-}--/**- * Forgets the moved agents the server no longer lists, so their old Console- * rows stop showing as agents. A failure to forget one is logged by the caller- * and leaves the rest to be tried.- */-export async function forgetDeletedManagedAgents(- workspaceId: string,- listedAgentIds: ReadonlySet<string>,- deps: {- records: () => Promise<ManagedAgentRecord[]>;- forget: (consoleAgentId: string) => Promise<void>;- warn: (message: string, context: Record<string, unknown>) => void;- now: () => number;- }-): Promise<void> {- const gone = goneManagedRecords(await deps.records(), workspaceId, listedAgentIds, deps.now());- for (const record of gone) {- try {- await deps.forget(record.agentId);- } catch (error) {- deps.warn('Could not forget an agent its server no longer lists', {- event: 'managed_agent_forget_failed',- agentId: record.agentId,- error: String(error),- });- }- }-}diff --git a/console/apps/switch-console-desktop/src/main/core/managed-agents/give-machine-login.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-agents/give-machine-login.test.tsindex 8ec053fad..ff5853a5f 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-agents/give-machine-login.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-agents/give-machine-login.test.ts@@ -21,10 +21,6 @@ const mocks = vi.hoisted(() => ({}));vi.mock('@main/core/agent-migration/agent-migration', () => ({ agentMigrationService: {} }));-vi.mock('@main/core/agent-migration/managed-agents-store', () => ({- listManagedAgentRecords: async () => [],-}));-vi.mock('@main/core/agents/deleteAgent', () => ({ deleteAgent: vi.fn() }));vi.mock('@main/lib/logger', () => ({ log: { warn: vi.fn(), error: vi.fn(), info: vi.fn() } }));vi.mock('@main/core/embedded-controller/embedded-controllers', () => ({embeddedControllerService: {},diff --git a/console/apps/switch-console-desktop/src/main/core/managed-agents/list-reconcile.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-agents/list-reconcile.test.tsdeleted file mode 100644index ba324ae61..000000000--- a/console/apps/switch-console-desktop/src/main/core/managed-agents/list-reconcile.test.ts+++ /dev/null@@ -1,108 +0,0 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';--const mocks = vi.hoisted(() => ({- fetchManagedAgents: vi.fn(),- deleteConsoleAgent: vi.fn(async () => {}),- records: vi.fn(),-}));--vi.mock('@main/core/agent-migration/agent-migration', () => ({ agentMigrationService: {} }));-vi.mock('@main/core/agent-migration/managed-agents-store', () => ({- listManagedAgentRecords: mocks.records,-}));-vi.mock('@main/core/agents/deleteAgent', () => ({ deleteAgent: mocks.deleteConsoleAgent }));-vi.mock('@main/lib/logger', () => ({ log: { warn: vi.fn(), error: vi.fn(), info: vi.fn() } }));-vi.mock('@main/core/embedded-controller/embedded-controllers', () => ({- embeddedControllerService: {},-}));-vi.mock('@main/core/host-controllers/host-controllers', () => ({ hostControllerService: {} }));-vi.mock('@main/core/workspaces/workspaces-store', () => ({- requireWorkspaceForServer: async () => ({ id: 'ws' }),-}));-vi.mock('@main/core/workspaces/workspace-session', () => ({- withReachableServerWorkspaceSession: (_serverId: string, run: (server: unknown) => unknown) =>- run({ id: 'server-1', url: 'https://switch.example.com' }),-}));-vi.mock('@main/core/switch-servers/local-provider-sign-in', () => ({- localProviderAuthPath: () => '',- readLocalProviderSignIn: vi.fn(),-}));-vi.mock('@main/core/switch-servers/gateway-client', () => ({- AgentManagementUnavailableError: class extends Error {},- GatewayError: class extends Error {},- deleteAgent: vi.fn(),- deleteManagedAgent: vi.fn(),- fetchAdvancedConfigSchema: vi.fn(),- fetchManagedAgents: mocks.fetchManagedAgents,- managementErrorMessage: vi.fn(),- setManagedAgentDesiredState: vi.fn(),- updateManagedAgent: vi.fn(),- fetchManagementControllers: vi.fn(async () => []),- giveMachineLogin: vi.fn(),- fetchMachineOperation: vi.fn(),-}));--const { managedAgentsController } = await import('./controller');--const moved = (agentId: string, switchAgentId: string) => ({- agentId,- workspaceId: 'ws',- controllerId: 'controller',- placement: { kind: 'this-computer', serverId: 'server-1' },- identities: [- {- switchAgentId,- slug: agentId,- subagent: null,- credentialsStashed: false,- controllerRoot: '~',- },- ],- movedAt: '2026-01-01T00:00:00Z',-});--const listed = (agentId: string) => ({- agentId,- name: agentId,- displayName: null,- iconUrl: null,- description: '',- machine: null,- controllerId: null,- desiredState: 'running',- revision: 1,- provider: 'claude',- model: null,- advancedConfig: {},- instructions: '',- autoMode: false,- autoApprove: false,- directory: null,- isolation: 'shared',- status: null,-});--beforeEach(() => {- vi.clearAllMocks();- mocks.records.mockResolvedValue([moved('console-gone', 'gone'), moved('console-kept', 'kept')]);-});--describe('listing managed agents', () => {- it('forgets on load a moved agent deleted on the server, and only that one', async () => {- mocks.fetchManagedAgents.mockResolvedValue([listed('kept')]);- const agents = await managedAgentsController.list('server-1');- expect(agents?.map((agent) => agent.agentId)).toEqual(['kept']);- expect(mocks.deleteConsoleAgent).toHaveBeenCalledTimes(1);- expect(mocks.deleteConsoleAgent).toHaveBeenCalledWith('console-gone', {- deleteInSwitch: false,- removeProvisionedFiles: false,- trigger: 'server_teardown',- });- });-- it('forgets nothing when the list could not be read', async () => {- mocks.fetchManagedAgents.mockRejectedValue(new Error('unreachable'));- await expect(managedAgentsController.list('server-1')).rejects.toThrow('unreachable');- expect(mocks.deleteConsoleAgent).not.toHaveBeenCalled();- });-});diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/stores/agents-store.ts b/console/apps/switch-console-desktop/src/renderer/features/locations/stores/agents-store.tsindex 3d446c8f7..e6afd6609 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/stores/agents-store.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/stores/agents-store.ts@@ -27,13 +27,26 @@ export class AgentsStore {readonly optimisticWorkspaceByLocation = new Map<string, string>();loaded = false;+ /**+ * Console agents moved to agent management. Their rows stay (Console can+ * bring one back), but they are never listed as Console agents: whether or+ * not the server still lists the managed agent, it shows only through the+ * managed list.+ */+ moved: ReadonlySet<string> = new Set();+constructor() {makeAutoObservable(this);}+ isMoved(agentId: string): boolean {+ return this.moved.has(agentId);+ }+async load(): Promise<void> {- const agents = await rpc.agents.getAgents();+ const [agents, moved] = await Promise.all([rpc.agents.getAgents(), rpc.agents.movedAgentIds()]);runInAction(() => {+ this.moved = new Set(moved);this.byLocation.clear();for (const agent of agents) {const list = this.byLocation.get(agent.locationId);diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/stores/location-manager.test.ts b/console/apps/switch-console-desktop/src/renderer/features/locations/stores/location-manager.test.tsindex 3cbbb0e79..5c37985c0 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/stores/location-manager.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/stores/location-manager.test.ts@@ -28,6 +28,7 @@ vi.mock('@renderer/lib/ipc', () => ({agents: {onboardAgent: mocks.onboardAgent,getAgents: mocks.getAgents,+ movedAgentIds: async () => [],deleteAgent: mocks.deleteAgent,},locations: {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 bf8146e6b..acdb3d12e 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@@ -11,6 +11,10 @@ vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({vi.mock('@renderer/features/workspaces/workspaces-store', () => ({workspacesStore: {},}));+const moved = vi.hoisted(() => new Set<string>());+vi.mock('@renderer/features/locations/stores/agents-store', () => ({+ agentsStore: { isMoved: (agentId: string) => moved.has(agentId) },+}));const { withoutManaged } = await import('./use-managed-agents');@@ -33,4 +37,20 @@ describe('withoutManaged', () => {const rows = [{ id: 'moved', switchAgentId: 'sw-moved' }];expect(withoutManaged(rows, undefined)).toEqual(rows);});++ it('never shows a moved agent’s old row, whatever the server lists', () => {+ moved.add('moved');+ try {+ const rows = [+ { id: 'moved', switchAgentId: 'sw-moved' },+ { id: 'local', switchAgentId: 'sw-local' },+ ];+ // Deleted on the server, another account, or no access: the list lacks it.+ expect(withoutManaged(rows, []).map((row) => row.id)).toEqual(['local']);+ expect(withoutManaged(rows, null).map((row) => row.id)).toEqual(['local']);+ expect(withoutManaged(rows, undefined).map((row) => row.id)).toEqual(['local']);+ } finally {+ moved.clear();+ }+ });});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 51978d045..7a52e45e8 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,5 +1,6 @@import { useQuery, useQueryClient } from '@tanstack/react-query';import { useEffect } from 'react';+import { agentsStore } from '@renderer/features/locations/stores/agents-store';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';@@ -204,11 +205,13 @@ export function useAdvancedConfigSchema(serverId: string | null) {* the way every managed agent is, from the server, rather than twice or as a* Console agent with a room watcher that no longer runs here.*/-export function withoutManaged<T extends { switchAgentId: string | null }>(+export function withoutManaged<T extends { id: string; switchAgentId: string | null }>(agents: T[],managed: ManagedAgentView[] | null | undefined): T[] {- if (!managed) return agents;+ // A moved agent's old row never shows as a Console agent, listed by the server or not.+ const own = agents.filter((agent) => !agentsStore.isMoved(agent.id));+ if (!managed) return own;const ids = new Set(managed.map((agent) => agent.agentId));- return agents.filter((agent) => agent.switchAgentId === null || !ids.has(agent.switchAgentId));+ return own.filter((agent) => agent.switchAgentId === null || !ids.has(agent.switchAgentId));}diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-tree.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-tree.tsxindex c6baef0fb..9feb41a54 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-tree.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-tree.tsx@@ -1,4 +1,5 @@import { observer } from 'mobx-react-lite';+import { agentsStore } from '@renderer/features/locations/stores/agents-store';import { useManagedAgents } from '@renderer/features/managed-agents/use-managed-agents';import type { SessionStore } from '@renderer/features/sessions/stores/session-store';import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';@@ -100,7 +101,9 @@ export const AgentTree = observer(function AgentTree() {const managed = useManagedAgents(switchServersStore.activeServerId);const managedIds = new Set((managed.data ?? []).map((agent) => agent.agentId));const entries = scopedAgents().filter(- (entry) => entry.agent.switchAgentId === null || !managedIds.has(entry.agent.switchAgentId)+ (entry) =>+ !agentsStore.isMoved(entry.agent.id) &&+ (entry.agent.switchAgentId === null || !managedIds.has(entry.agent.switchAgentId)));return (<SortableListdiff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/managed-identities.test.ts b/console/apps/switch-console-desktop/src/renderer/features/sidebar/managed-identities.test.tsindex e749b679c..a707db14a 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/managed-identities.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/managed-identities.test.ts@@ -1,17 +1,52 @@-import { describe, expect, it, vi } from 'vitest';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const servers = vi.hoisted(() => ({+ servers: [{ id: 'srv' }],+ user: 'user-1' as string | null,+}));vi.mock('@renderer/lib/ipc', () => ({ events: { on: vi.fn() }, rpc: {} }));+vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({+ switchServersStore: {+ get servers() {+ return servers.servers;+ },+ statusFor: () => (servers.user ? { user: { id: servers.user } } : null),+ },+}));+vi.mock('@renderer/features/workspaces/workspaces-store', () => ({+ workspacesStore: { idOnServerInScope: () => 'ws-a' },+}));const { managedIdentities } = await import('./sidebar-tree-data');const { queryClient } = await import('@renderer/lib/query-client');describe('managedIdentities', () => {- it('names the managed agents the list last read, so their rooms are reconciled too', () => {+ beforeEach(() => {+ queryClient.clear();+ servers.user = 'user-1';+ });++ it('reads the current user’s agent list only, not machines kept under the same prefix', () => {queryClient.setQueryData(- ['managed-agents', 'srv', 'ws-a', 'user'],- [{ agentId: 'buddy', workspaceId: 'ws-a' }]+ ['managed-agents', 'srv', 'ws-a', 'user-1'],+ [{ agentId: 'buddy', workspaceId: 'ws-a' }, { agentId: 'buddy', workspaceId: 'ws-a' }, {}]);- queryClient.setQueryData(['managed-agents', 'srv-2', 'ws-b', 'user'], null);+ queryClient.setQueryData(['managed-agents', 'srv', 'machines', 'ws-a'], [{ machine_id: 'm1' }]);expect(managedIdentities()).toEqual([{ workspaceId: 'ws-a', switchAgentId: 'buddy' }]);});++ it('leaves another account’s list alone after switching accounts', () => {+ queryClient.setQueryData(+ ['managed-agents', 'srv', 'ws-a', 'user-1'],+ [{ agentId: 'old-users-agent', workspaceId: 'ws-a' }]+ );+ servers.user = 'user-2';+ expect(managedIdentities()).toEqual([]);+ queryClient.setQueryData(+ ['managed-agents', 'srv', 'ws-a', 'user-2'],+ [{ agentId: 'mine', workspaceId: 'ws-a' }]+ );+ expect(managedIdentities()).toEqual([{ workspaceId: 'ws-a', switchAgentId: 'mine' }]);+ });});diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsxindex 5ceab9c44..5841efcc1 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx@@ -2,6 +2,7 @@ import { AlertTriangle } from 'lucide-react';import { reaction } from 'mobx';import { observer } from 'mobx-react-lite';import { useEffect, useRef } from 'react';+import { agentsStore } from '@renderer/features/locations/stores/agents-store';import { ManagedAgentList } from '@renderer/features/managed-agents/managed-agent-list';import { useManagedAgents } from '@renderer/features/managed-agents/use-managed-agents';import { hostReachabilityStore } from '@renderer/features/remote-hosts/host-reachability-store';@@ -115,7 +116,9 @@ export const SidebarGroupedList = observer(function SidebarGroupedList() {if (managementMode) {const managedIds = new Set((managedAgents.data ?? []).map((agent) => agent.agentId));const legacyCount = agentsInActiveScope().filter(- (entry) => entry.agent.switchAgentId === null || !managedIds.has(entry.agent.switchAgentId)+ (entry) =>+ !agentsStore.isMoved(entry.agent.id) &&+ (entry.agent.switchAgentId === null || !managedIds.has(entry.agent.switchAgentId))).length;return (<divdiff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-icon-backfill-toast.test.ts b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-icon-backfill-toast.test.tsindex e645a15c5..56c19dd1b 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-icon-backfill-toast.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-icon-backfill-toast.test.ts@@ -43,6 +43,9 @@ vi.mock('@renderer/features/switch-servers/switch-rooms-store', () => ({},}));const availability = vi.hoisted(() => ({ value: 'available' }));+vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({+ switchServersStore: { servers: [], statusFor: () => null },+}));vi.mock('@renderer/features/switch-servers/server-availability', () => ({serverAvailability: () => availability.value,}));diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-tree-data.ts b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-tree-data.tsindex 8ef5d4c71..a7af70acd 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-tree-data.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-tree-data.ts@@ -4,6 +4,7 @@ import { MANAGED_AGENTS_KEY } from '@renderer/features/managed-agents/use-manageimport type { SessionStore } from '@renderer/features/sessions/stores/session-store';import { serverAvailability } from '@renderer/features/switch-servers/server-availability';import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';+import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { toast } from '@renderer/lib/hooks/use-toast';import { rpc } from '@renderer/lib/ipc';@@ -111,13 +112,33 @@ export function switchIdentities(): { workspaceId: string; switchAgentId: string/*** The user's managed agents, as the shared list last read them: their rooms- * belong in the sidebar too, wherever the agents run.+ * belong in the sidebar too, wherever the agents run. Read from each server's+ * current list only (the key `useManagedAgents` reads: server, the workspace+ * in scope there, the signed-in user), so another account's or workspace's+ * list left in the cache, or the machines kept under the same prefix, is not.*/export function managedIdentities(): { workspaceId: string; switchAgentId: string }[] {- return queryClient- .getQueriesData<ManagedAgentView[] | null>({ queryKey: [MANAGED_AGENTS_KEY] })- .flatMap(([, agents]) => (Array.isArray(agents) ? agents : []))- .map((agent) => ({ workspaceId: agent.workspaceId, switchAgentId: agent.agentId }));+ const identities = new Map<string, { workspaceId: string; switchAgentId: string }>();+ for (const server of switchServersStore.servers) {+ const userId = switchServersStore.statusFor(server.id)?.user?.id ?? null;+ if (userId === null) continue;+ const workspaceId = workspacesStore.idOnServerInScope(server.id);+ const agents = queryClient.getQueryData<unknown>([+ MANAGED_AGENTS_KEY,+ server.id,+ workspaceId,+ userId,+ ]);+ if (!Array.isArray(agents)) continue;+ for (const agent of agents as Partial<ManagedAgentView>[]) {+ if (typeof agent?.agentId !== 'string' || typeof agent.workspaceId !== 'string') continue;+ identities.set(`${agent.workspaceId}:${agent.agentId}`, {+ workspaceId: agent.workspaceId,+ switchAgentId: agent.agentId,+ });+ }+ }+ return [...identities.values()];}/**diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsxindex ad5788ff9..b852f2ef0 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx@@ -35,7 +35,12 @@ import { Input } from '@renderer/lib/ui/input';import { Textarea } from '@renderer/lib/ui/textarea';import { knownAgentTypeDisplayName } from '@shared/core/providers/agent-provider-registry';import { MessagingAppSelector, SWITCH_CONSOLE } from './messaging-app-selector';-import { CreateRequestIds, canCreate, roomCreateRequest } from './room-create-request';+import {+ CreateRequestIds,+ canCreate,+ roomCreateRequest,+ startingAgentResolution,+} from './room-create-request';import { RoomNameInput } from './room-name-input';import { switchServersStore } from './switch-servers-store';@@ -142,21 +147,40 @@ export const CreateRoomModal = observer(function CreateRoomModal({personParticipant),];- // The agent the room is made from starts picked, once the agents are read.- const [seeded, setSeeded] = useState(startingAgentId === undefined);- if (!seeded) {- const start = candidates.find((each) => each.kind === 'agent' && each.id === startingAgentId);- if (start) {- setSeeded(true);- setPicked((current) => [start, ...current.filter((each) => each.id !== start.id)]);- }- }- const agentIds = picked.filter((each) => each.kind === 'agent').map((each) => each.id);- const memberUserIds = picked.filter((each) => each.kind === 'person').map((each) => each.id);+ // The agent the room is made from shows picked once the agents are read, until the+ // picks are changed by hand (removing it then leaves it out).+ const [touched, setTouched] = useState(false);+ const startChip =+ startingAgentId === undefined || touched+ ? null+ : (candidates.find((each) => each.kind === 'agent' && each.id === startingAgentId) ?? null);+ const shownPicked = startChip+ ? [startChip, ...picked.filter((each) => each.id !== startChip.id)]+ : picked;+ const changePicks = (next: Participant[]) => {+ setTouched(true);+ setPicked(next);+ };+ const agentIds = shownPicked.filter((each) => each.kind === 'agent').map((each) => each.id);+ const memberUserIds = shownPicked.filter((each) => each.kind === 'person').map((each) => each.id);const trimmedName = name.trim();+ // The agent the room is made from must be applied, or known not to be, before creating:+ // a quick Create would otherwise make the room without it.+ const startingAgentState = startingAgentResolution({+ startingAgentId,+ applied: touched || startChip !== null,+ failed: agentsQuery.isError || (!selectedBridge && allowedQuery.isError),+ loaded:+ agentsQuery.isSuccess &&+ !agentsQuery.isFetching &&+ (selectedBridge !== null || (allowedQuery.isSuccess && !allowedQuery.isFetching)),+ });+ const startingAgentName =+ (agentsQuery.data ?? []).find((agent) => agent.id === startingAgentId)?.name ?? 'This agent';const canSubmit =workspaceId !== null &&+ startingAgentState !== 'pending' &&!nowhere &&canCreate({ bridgeId: selectedBridge?.id ?? null, name, description }) &&!isSubmitting;@@ -269,8 +293,8 @@ export const CreateRoomModal = observer(function CreateRoomModal({busy={isSubmitting}overlay={false}candidates={candidates}- picked={picked}- onChange={setPicked}+ picked={shownPicked}+ onChange={changePicks}serverId={serverId || null}loading={agentsQuery.isLoading ||@@ -321,6 +345,20 @@ export const CreateRoomModal = observer(function CreateRoomModal({can create a channel, so there is nowhere to create a room.</p>)}+ {startingAgentState === 'failed' && (+ <p className="text-xs text-destructive">+ {startingAgentName} can't be added to the new room:{' '}+ {failureText(+ agentsQuery.error ?? allowedQuery.error,+ 'the agents could not be loaded.'+ )}+ </p>+ )}+ {startingAgentState === 'unavailable' && (+ <p className="text-xs text-destructive">+ {startingAgentName} can't be added to this room: it is not one you can add here.+ </p>+ )}{bridgesQuery.isError && (<p className="text-xs text-destructive">{failureText(bridgesQuery.error, 'Could not load messaging apps.')}@@ -339,7 +377,7 @@ export const CreateRoomModal = observer(function CreateRoomModal({setError(null);// A bridged room starts with agents only.if (next !== SWITCH_CONSOLE)- setPicked((current) => current.filter((each) => each.kind === 'agent'));+ changePicks(shownPicked.filter((each) => each.kind === 'agent'));}}/><div className="ml-auto flex items-center gap-2">diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/create-room-modal.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/create-room-modal.test.tsindex e8bcd3976..49e1cbaf1 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/create-room-modal.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/create-room-modal.test.ts@@ -8,6 +8,12 @@ const flags = vi.hoisted(() => ({ group_chats: true }));vi.mock('@renderer/lib/hooks/useFeatureFlags', () => ({ useFeatureFlags: () => flags }));vi.mock('@renderer/lib/ipc', () => ({ events: { on: vi.fn() }, rpc: {} }));vi.mock('@renderer/features/chats/stores/chats', () => ({ chatsStore: {} }));+vi.mock('@renderer/features/workspaces/workspaces-store', () => ({+ workspacesStore: {+ workspaces: [{ id: 'ws', tenantId: null }],+ idOnServerInScope: (serverId: string | null) => (serverId ? 'ws' : null),+ },+}));vi.mock('@renderer/lib/modal/modal-provider', () => ({useModalContext: () => ({ setCloseGuard: () => {} }),}));@@ -54,4 +60,28 @@ describe('CreateRoomModal', () => {flags.group_chats = true;}});++ const render = (client: QueryClient) =>+ renderToStaticMarkup(+ createElement(+ QueryClientProvider,+ { client },+ createElement(CreateRoomModal, {+ serverId: 'srv',+ agentId: 'a1',+ onSuccess: () => {},+ onClose: () => {},+ })+ )+ );++ it('starts with the agent it is made from picked, once the agents are read', () => {+ const client = new QueryClient();+ client.setQueryData(+ ['remote-agents', 'ws'],+ [{ id: 'a1', name: 'agent-one', displayName: null, iconUrl: null, knownAgentType: null }]+ );+ client.setQueryData(['chat-agent-candidates', 'srv', 'ws', null], ['a1']);+ expect(render(client)).toContain('aria-label="Remove agent-one"');+ });});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-create-request.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-create-request.test.tsindex 19af0525e..28fddb66f 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-create-request.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-create-request.test.ts@@ -1,5 +1,10 @@import { describe, expect, it } from 'vitest';-import { CreateRequestIds, canCreate, roomCreateRequest } from './room-create-request';+import {+ CreateRequestIds,+ canCreate,+ roomCreateRequest,+ startingAgentResolution,+} from './room-create-request';const form = {serverId: 's',@@ -77,3 +82,18 @@ describe('CreateRequestIds', () => {expect(ids.for({ ...chatForm, name: 'Ship reviews', memberUserIds: ['u2'] })).toBe('id-4');});});++describe('startingAgentResolution', () => {+ const base = { startingAgentId: 'a1', applied: false, failed: false, loaded: false };++ it('keeps Create waiting while the agents load, then is resolved once the agent is picked', () => {+ expect(startingAgentResolution(base)).toBe('pending');+ expect(startingAgentResolution({ ...base, loaded: true, applied: true })).toBe('resolved');+ expect(startingAgentResolution({ ...base, startingAgentId: undefined })).toBe('resolved');+ });++ it('says why the agent is left out when the agents fail to load or it is not among them', () => {+ expect(startingAgentResolution({ ...base, failed: true })).toBe('failed');+ expect(startingAgentResolution({ ...base, loaded: true })).toBe('unavailable');+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-create-request.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-create-request.tsindex c9709f08b..ed4fe7485 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-create-request.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-create-request.ts@@ -106,3 +106,19 @@ export class CreateRequestIds {this.key = null;}}++/**+ * Where the agent a room is made from stands: no such agent or already picked+ * (`resolved`), the agents still loading (`pending`, when Create waits), or it+ * cannot be picked because the agents failed to load or it is not among them.+ */+export function startingAgentResolution(state: {+ startingAgentId: string | undefined;+ applied: boolean;+ failed: boolean;+ loaded: boolean;+}): 'resolved' | 'pending' | 'failed' | 'unavailable' {+ if (state.startingAgentId === undefined || state.applied) return 'resolved';+ if (state.failed) return 'failed';+ return state.loaded ? 'unavailable' : 'pending';+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.test.tsindex e9ff2994b..3ee1fe633 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.test.ts@@ -159,6 +159,29 @@ describe('listed rooms', () => {expect(store.listedRoomsInActiveScope.map((r: { id: string }) => r.id)).toEqual([]);});+ it('drops an agent’s rooms once it is no longer tracked, as after a delete or account switch', async () => {+ listRooms.mockImplementation(async (workspaceId: string) =>+ workspaceId === 'ws-a' ? [room('agents-room', 'user-of-someone-else')] : []+ );+ listAgentRooms.mockResolvedValue([+ {+ roomId: 'agents-room',+ roomName: 'agents-room',+ archived: false,+ status: 'active',+ roomRole: null,+ },+ ]);+ const store = new SwitchRoomsStore();+ await store.loadRoomNames();+ await store.ensureMembershipsFor([{ workspaceId: 'ws-a', switchAgentId: 'gone' }]);+ expect(store.listedRoomsInActiveScope.map((r: { id: string }) => r.id)).toEqual([+ 'agents-room',+ ]);+ await store.ensureMembershipsFor([]);+ expect(store.listedRoomsInActiveScope.map((r: { id: string }) => r.id)).toEqual([]);+ });+it('shows only the active workspace’s rooms, not every connected one’s', async () => {listRooms.mockImplementation(async (workspaceId: string) => [room(`${workspaceId}-room`, `user-of-${workspaces.serverIdFor(workspaceId)}`),diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.tsindex 7cc6f08e3..78c69d2d8 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts@@ -445,7 +445,14 @@ export class SwitchRoomsStore {*/get localMemberIdsByRoom(): Map<string, string[]> {const byRoom = new Map<string, string[]>();+ // Only agents tracked or on screen now: a deleted agent's, or another+ // account's, memberships stay in the cache but claim no room.+ const current = new Set([+ ...this.trackedIdentities.map((a) => key(a.workspaceId, a.switchAgentId)),+ ...this.watchedIdentities.keys(),+ ]);for (const [cacheKey, memberships] of this.roomsByAgent) {+ if (!current.has(cacheKey)) continue;const switchAgentId = cacheKey.slice(cacheKey.indexOf(':') + 1);for (const membership of memberships) {if (membership.archived) continue;