Skip to content

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

refactor(console): address tenant-owned data by workspace, not by server

Petr Bauch8dffa475ebad
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.ts
index 952451f5c..7da7b134a 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
@@ -82,7 +82,7 @@ export const agentsController = createRPCController({
onboardAgent: (params: OnboardAgentParams) => onboardAgent(params),
discoverLoadableAgentsOnHost: (params: DiscoverLoadableAgentsParams) =>
discoverLoadableAgentsOnHost(params),
- discoverLoadableAgentsInDir: (params: { sshHost: string; dir: string; serverId: string }) =>
+ discoverLoadableAgentsInDir: (params: { sshHost: string; dir: string; workspaceId: string }) =>
discoverLoadableAgentsInDir(params),
attachConfiguredAgents: (params: AttachConfiguredAgentsParams) => attachConfiguredAgents(params),
removeLoadableAgentConfig: (params: RemoveLoadableAgentConfigParams) =>
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.test.ts
index a4b58f4ee..78d8ef6cc 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.test.ts
@@ -85,7 +85,10 @@ vi.mock('@main/core/switch-servers/gateway-client', () => ({
}
},
}));
-vi.mock('@main/core/switch-servers/servers-store', () => ({ getServer: vi.fn() }));
+vi.mock('@main/core/workspaces/workspace-session', () => ({
+ withWorkspaceSession: (_workspaceId: string, fn: (server: { id: string }) => unknown) =>
+ fn({ id: 'srv-1' }),
+}));
vi.mock('@main/core/view-state/view-state-service', () => ({
viewStateService: { del: vi.fn(async () => {}) },
}));
@@ -333,10 +336,9 @@ describe('deleteAgent', () => {
providerId: 'claude',
locationId: 'loc',
serverId: 'srv-1',
+ workspaceId: 'ws-1',
switchAgentId: 'sw-1',
};
- const { getServer } = await import('@main/core/switch-servers/servers-store');
- vi.mocked(getServer).mockResolvedValue({ id: 'srv-1' } as never);
await expect(
deleteAgent('agent-1', {
@@ -359,6 +361,7 @@ describe('deleteAgent', () => {
providerId: 'claude',
locationId: 'loc',
serverId: null,
+ workspaceId: null,
switchAgentId: null,
};
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.ts b/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.ts
index 9fca99885..c0dc01e0f 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.ts
@@ -11,7 +11,6 @@ import {
deleteAgent as gatewayDeleteAgent,
GatewayError,
} from '@main/core/switch-servers/gateway-client';
-import { getServer } from '@main/core/switch-servers/servers-store';
import { agentTypeOf } from '@main/core/telemetry/agent-type';
import type {
TelemetryAgentRemoveFailure,
@@ -21,6 +20,7 @@ import type {
import { agentRemoveTriggerOf } from '@main/core/telemetry/narrow';
import { trackEvent } from '@main/core/telemetry/telemetry-service';
import { viewStateService } from '@main/core/view-state/view-state-service';
+import { withWorkspaceSession } from '@main/core/workspaces/workspace-session';
import { db } from '@main/db/client';
import { agents, sessions } from '@main/db/schema';
import { log } from '@main/lib/logger';
@@ -101,17 +101,14 @@ function locationKindOfRow(location: Location | null): TelemetryLocationKind {
* rather than leaving the row gone but the Switch identity orphaned.
*/
async function deleteAgentInSwitch(agent: Agent): Promise<void> {
- if (!agent.serverId || !agent.switchAgentId) {
+ const { workspaceId, switchAgentId } = agent;
+ if (!workspaceId || !switchAgentId) {
throw new AgentNotLinkedToSwitchError(
- `Agent ${agent.id} is not linked to a Switch server, so it cannot be deleted in Switch.`
+ `Agent ${agent.id} is not linked to a Switch workspace, so it cannot be deleted in Switch.`
);
}
- const server = await getServer(agent.serverId);
- if (!server) {
- throw new AgentNotLinkedToSwitchError(`No Switch server with id ${agent.serverId}`);
- }
- await gatewayDeleteAgent(server, agent.switchAgentId);
+ await withWorkspaceSession(workspaceId, (server) => gatewayDeleteAgent(server, switchAgentId));
}
/**
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/discover-loadable-agents.ts b/console/apps/switch-console-desktop/src/main/core/agents/discover-loadable-agents.ts
index b43e7a13b..c622c1803 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/discover-loadable-agents.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/discover-loadable-agents.ts
@@ -2,7 +2,7 @@ import { SshExecutionContext } from '@main/core/execution-context/ssh-execution-
import { sshConnectionIdForHost } from '@main/core/locations/location-transport';
import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';
import { fetchAgents, fetchMe } from '@main/core/switch-servers/gateway-client';
-import { getServer } from '@main/core/switch-servers/servers-store';
+import { withWorkspaceSession, workspaceServer } from '@main/core/workspaces/workspace-session';
import { log } from '@main/lib/logger';
import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';
import { sameApiEndpoint } from '@shared/core/switch-servers/switch-servers';
@@ -41,7 +41,7 @@ export type LoadableAgent = {
export type DiscoverLoadableAgentsParams = {
sshHost: string;
- serverId: string;
+ workspaceId: string;
/** When true, run a depth-limited `find` over `$HOME` in addition to the
* cheap server-assisted discovery. Off by default — the walk can be slow
* on large VMs. */
@@ -68,17 +68,22 @@ export type DiscoverLoadableAgentsResult = {
export async function discoverLoadableAgentsOnHost(
params: DiscoverLoadableAgentsParams
): Promise<DiscoverLoadableAgentsResult> {
- const server = await getServer(params.serverId);
- if (!server) throw new Error(`No Switch server with id ${params.serverId}`);
+ const server = await workspaceServer(params.workspaceId);
// Key: "dir\0name" → LoadableAgent. Server entries inserted first win.
const seen = new Map<string, LoadableAgent>();
// --- Source 1: Server-assisted discovery ---
try {
- const remoteAgents = await fetchAgents(server);
- // Marks rows the signed-in user owns; an auth failure degrades to not-owner.
- const me = await fetchMe(server).catch(() => null);
+ // Leased together: `GET /agents` answers for the selected tenant, and the
+ // owner marks below are only meaningful against the same one. The on-host
+ // scans that follow are SSH and need no session, so the lease ends here
+ // rather than being held across them.
+ const { remoteAgents, me } = await withWorkspaceSession(params.workspaceId, async () => ({
+ remoteAgents: await fetchAgents(server),
+ // Marks rows the signed-in user owns; an auth failure degrades to not-owner.
+ me: await fetchMe(server).catch(() => null),
+ }));
// Collect distinct repo_dirs from agents whose known_agent_options carry one.
type ServerAgentInfo = {
@@ -109,7 +114,7 @@ export async function discoverLoadableAgentsOnHost(
const discovered = await discoverConfiguredAgents({
sshHost: params.sshHost,
dir,
- serverId: params.serverId,
+ serverId: server.id,
});
for (const agent of discovered) {
const key = `${dir}\0${agent.name}`;
@@ -140,7 +145,7 @@ export async function discoverLoadableAgentsOnHost(
}
} catch (error) {
log.warn('discoverLoadableAgentsOnHost: server-assisted discovery failed', {
- serverId: params.serverId,
+ workspaceId: params.workspaceId,
error: error instanceof Error ? error.message : String(error),
});
}
@@ -154,7 +159,7 @@ export async function discoverLoadableAgentsOnHost(
const discovered = await discoverConfiguredAgents({
sshHost: params.sshHost,
dir,
- serverId: params.serverId,
+ serverId: server.id,
});
for (const agent of discovered) {
const key = `${dir}\0${agent.name}`;
@@ -250,15 +255,16 @@ async function findSwitchAgentDirsOnHost(sshHost: string): Promise<string[]> {
export async function discoverLoadableAgentsInDir(params: {
sshHost: string;
dir: string;
- serverId: string;
+ workspaceId: string;
}): Promise<{ agents: LoadableAgent[]; serverApiUrl: string }> {
- const server = await getServer(params.serverId);
- if (!server) throw new Error(`No Switch server with id ${params.serverId}`);
+ // The server only, with no lease: this path makes no gateway call — the scan
+ // is on-host and the server is here for its API URL.
+ const server = await workspaceServer(params.workspaceId);
const discovered = await discoverConfiguredAgents({
sshHost: params.sshHost,
dir: params.dir,
- serverId: params.serverId,
+ serverId: server.id,
});
const agents = discovered.map((agent) => ({
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/remote-session-reconciler.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/remote-session-reconciler.test.ts
index 3e0492a85..931a07e23 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/remote-session-reconciler.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/remote-session-reconciler.test.ts
@@ -7,7 +7,6 @@ import {
const mocks = vi.hoisted(() => ({
list: vi.fn(),
- server: vi.fn(async () => ({ id: 'server', gatewayUrl: 'https://example.test' })),
snapshot: vi.fn(),
room: vi.fn(),
create: vi.fn(async () => ({ success: true })),
@@ -25,12 +24,14 @@ vi.mock('./getAgentById', () => ({
id: 'local',
switchAgentId: 'agent',
serverId: 'server',
+ workspaceId: 'workspace',
providerId: 'codex',
autoApprove: false,
}),
}));
-vi.mock('@main/core/switch-servers/servers-store', () => ({
- getServer: mocks.server,
+vi.mock('@main/core/workspaces/workspace-session', () => ({
+ withWorkspaceSession: (_workspaceId: string, fn: (server: { id: string }) => Promise<unknown>) =>
+ fn({ id: 'server' }),
}));
vi.mock('@main/core/switch-servers/gateway-client', () => ({
fetchRoomDetail: mocks.room,
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/remote-session-reconciler.ts b/console/apps/switch-console-desktop/src/main/core/agents/remote-session-reconciler.ts
index cc84c333a..1a9d85b32 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/remote-session-reconciler.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/remote-session-reconciler.ts
@@ -6,7 +6,7 @@ import { sessionWasDeleted } from '@main/core/sessions/deleted-sessions';
import { sessionService } from '@main/core/sessions/session-service';
import { switchRoomService } from '@main/core/switch-rooms/switch-room-service';
import { fetchRoomDetail } from '@main/core/switch-servers/gateway-client';
-import { getServer } from '@main/core/switch-servers/servers-store';
+import { withWorkspaceSession } from '@main/core/workspaces/workspace-session';
import { db } from '@main/db/client';
import { sessions } from '@main/db/schema';
import { events } from '@main/lib/events';
@@ -73,9 +73,8 @@ class RemoteSessionReconciler {
this.stop(agentId);
return;
}
- if (!agent.serverId) throw new Error('This linked agent has no Switch server configured.');
- const server = await getServer(agent.serverId);
- if (!server) throw new Error('The session discovery server is missing.');
+ if (!agent.workspaceId) throw new Error('This linked agent has no workspace configured.');
+ const workspaceId = agent.workspaceId;
const remote: unknown[] = await listHostSessions(agentId);
const failures: string[] = [];
const local = new Map(
@@ -145,7 +144,7 @@ class RemoteSessionReconciler {
id: session.sessionId,
agentId,
title: roomId
- ? `Session for ${(await fetchRoomDetail(server, roomId)).name}`
+ ? `Session for ${(await withWorkspaceSession(workspaceId, (server) => fetchRoomDetail(server, roomId))).name}`
: 'Shared session',
attach: false,
startSource: 'adopted',
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/reset-remote-agent.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/reset-remote-agent.test.ts
index 88f646e30..5b2ac49ac 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/reset-remote-agent.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/reset-remote-agent.test.ts
@@ -10,10 +10,11 @@ const mocks = vi.hoisted(() => ({
teardown: vi.fn(async () => ({ success: true })),
}));
vi.mock('./getAgentById', () => ({
- getAgentById: async () => ({ id: 'local', serverId: 'server', switchAgentId: 'agent' }),
+ getAgentById: async () => ({ id: 'local', workspaceId: 'workspace', switchAgentId: 'agent' }),
}));
-vi.mock('@main/core/switch-servers/servers-store', () => ({
- getServer: async () => ({ id: 'server' }),
+vi.mock('@main/core/workspaces/workspace-session', () => ({
+ withWorkspaceSession: (_workspaceId: string, fn: (server: { id: string }) => Promise<unknown>) =>
+ fn({ id: 'server' }),
}));
vi.mock('@main/core/sdk-host/host-sessions', () => ({ listHostSessions: mocks.list }));
vi.mock('@main/core/sdk-host/shared-agent-runtime', () => ({ stopSharedSession: mocks.stop }));
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/reset-remote-agent.ts b/console/apps/switch-console-desktop/src/main/core/agents/reset-remote-agent.ts
index 199b2d4de..aeebeb943 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/reset-remote-agent.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/reset-remote-agent.ts
@@ -6,7 +6,6 @@ import { manageAgentSidecar } from '@main/core/sdk-host/sidecar-management';
import { sessionHooks } from '@main/core/sessions/session-hooks';
import { sessionRuntimeManager } from '@main/core/sessions/session-runtime-manager';
import { switchRoomService } from '@main/core/switch-rooms/switch-room-service';
-import { getServer } from '@main/core/switch-servers/servers-store';
import { viewStateService } from '@main/core/view-state/view-state-service';
import { db } from '@main/db/client';
import { sessions } from '@main/db/schema';
@@ -19,10 +18,8 @@ import { startRemoteDiscovery } from './remote-watcher';
export async function resetRemoteAgent(agentId: string): Promise<void> {
const agent = await getAgentById(agentId);
- if (!agent?.serverId || !agent.switchAgentId)
+ if (!agent?.workspaceId || !agent.switchAgentId)
throw new Error('The agent is not linked to Switch.');
- const server = await getServer(agent.serverId);
- if (!server) throw new Error('The agent’s Switch server is missing.');
await configureSharedWatcher(agentId, { connected: false, spawning: false }, 'explicit');
remoteSessionReconciler.stop(agentId);
const remote = await listHostSessions(agentId);
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/setAgentAutoSession.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/setAgentAutoSession.test.ts
index 9d06c2d91..adffb0acd 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/setAgentAutoSession.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/setAgentAutoSession.test.ts
@@ -28,8 +28,9 @@ vi.mock('@main/core/switch-servers/gateway-client', () => ({
setAutoSession: h.setAutoSession,
GatewayError: class GatewayError extends Error {},
}));
-vi.mock('@main/core/switch-servers/servers-store', () => ({
- getServer: vi.fn(async () => ({ id: 'server-1' })),
+vi.mock('@main/core/workspaces/workspace-session', () => ({
+ withWorkspaceSession: (_id: string, fn: (server: { id: string }) => unknown) =>
+ fn({ id: 'server-1' }),
}));
vi.mock('@main/lib/logger', () => ({ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));
vi.mock('./agent-location', () => ({ getRemoteAgentLocation: async () => h.state.sshHost }));
@@ -42,7 +43,7 @@ beforeEach(() => {
vi.clearAllMocks();
h.calls.length = 0;
h.state.sshHost = null;
- h.state.agent = { id: 'agent-1', serverId: 'server-1', switchAgentId: 'switch-1' };
+ h.state.agent = { id: 'agent-1', workspaceId: 'workspace-1', switchAgentId: 'switch-1' };
});
it('makes the controller spawn-capable before claiming the profile that promises a session', async () => {
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/setAgentAutoSession.ts b/console/apps/switch-console-desktop/src/main/core/agents/setAgentAutoSession.ts
index fc61c494d..1d0f9dece 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/setAgentAutoSession.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/setAgentAutoSession.ts
@@ -8,7 +8,7 @@ import {
GatewayError,
setAutoSession,
} from '@main/core/switch-servers/gateway-client';
-import { getServer } from '@main/core/switch-servers/servers-store';
+import { withWorkspaceSession } from '@main/core/workspaces/workspace-session';
import { log } from '@main/lib/logger';
import type { Agent } from '@shared/core/agents/agents';
import { getRemoteAgentLocation } from './agent-location';
@@ -54,18 +54,19 @@ async function applyLocalAutoSessionState(agent: Agent, enabled: boolean): Promi
export async function setAgentAutoSession(params: AgentAutoSessionParams): Promise<void> {
const agent = await getAgentById(params.agentId);
if (!agent) throw new Error(`No agent with id ${params.agentId}`);
- if (!agent.serverId || !agent.switchAgentId) {
- throw new Error('Agent is not linked to a Switch server; cannot set auto_session.');
+ const { workspaceId, switchAgentId } = agent;
+ if (!workspaceId || !switchAgentId) {
+ throw new Error('Agent is not linked to a Switch workspace; cannot set auto_session.');
}
- const server = await getServer(agent.serverId);
- if (!server) throw new Error(`No Switch server with id ${agent.serverId}`);
if (params.enabled) {
await applyLocalAutoSessionState(agent, true);
- await setAutoSession(server, agent.switchAgentId, true);
+ await withWorkspaceSession(workspaceId, (server) =>
+ setAutoSession(server, switchAgentId, true)
+ );
return;
}
- await setAutoSession(server, agent.switchAgentId, false);
+ await withWorkspaceSession(workspaceId, (server) => setAutoSession(server, switchAgentId, false));
await applyLocalAutoSessionState(agent, false);
}
@@ -75,15 +76,17 @@ export async function setAgentAutoSession(params: AgentAutoSessionParams): Promi
* after an agent is created so a fresh agent registered with `auto_session: true`
* starts watching immediately, without the operator having to toggle it off→on.
* Returns whether auto_session is enabled. No-ops for agents not linked to a
- * Switch server.
+ * Switch workspace.
*/
export async function reconcileAgentAutoSessionFromGateway(agentId: string): Promise<boolean> {
const agent = await getAgentById(agentId);
- if (!agent?.serverId || !agent.switchAgentId) return false;
- const server = await getServer(agent.serverId);
- if (!server) return false;
+ if (!agent) return false;
+ const { workspaceId, switchAgentId } = agent;
+ if (!workspaceId || !switchAgentId) return false;
- const { connectionModel } = await fetchAgentOptions(server, agent.switchAgentId);
+ const { connectionModel } = await withWorkspaceSession(workspaceId, (server) =>
+ fetchAgentOptions(server, switchAgentId)
+ );
const enabled = connectionModel === 'auto_session';
await applyLocalAutoSessionState(agent, enabled);
return enabled;
@@ -97,7 +100,7 @@ export async function reconcileAgentAutoSessionFromGateway(agentId: string): Pro
*/
export async function getAgentAutoSession(params: { agentId: string }): Promise<boolean> {
const agent = await getAgentById(params.agentId);
- if (!agent?.serverId || !agent.switchAgentId) return false;
+ if (!agent?.workspaceId || !agent.switchAgentId) return false;
try {
return await reconcileAgentAutoSessionFromGateway(params.agentId);
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/stop-shared-agent-sessions.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/stop-shared-agent-sessions.test.ts
index 782f44938..0cf2792ba 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/stop-shared-agent-sessions.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/stop-shared-agent-sessions.test.ts
@@ -16,8 +16,9 @@ vi.mock('@main/core/sdk-host/session-commands', () => ({
submitSessionCommand: mocks.submit,
sessionCommandStatus: mocks.status,
}));
-vi.mock('@main/core/switch-servers/servers-store', () => ({
- getServer: async () => ({ id: 'server' }),
+vi.mock('@main/core/workspaces/workspace-session', () => ({
+ withWorkspaceSession: (_workspaceId: string, fn: (server: { id: string }) => Promise<unknown>) =>
+ fn({ id: 'server' }),
}));
const { stopSharedAgentSessions } = await import('./stop-shared-agent-sessions');
const session = {
@@ -40,7 +41,7 @@ const session = {
attachmentMimeTypes: [],
},
};
-const agent = { id: 'local-agent', serverId: 'server', switchAgentId: 'agent' } as Agent;
+const agent = { id: 'local-agent', workspaceId: 'workspace', switchAgentId: 'agent' } as Agent;
const receipt = {
type: 'command.status',
commandId: 'stop-epoch',
@@ -90,3 +91,8 @@ it('does not stop other agents or retired sessions', async () => {
await stopSharedAgentSessions(agent);
expect(mocks.submit).not.toHaveBeenCalled();
});
+
+it('does nothing for an agent with no workspace to address', async () => {
+ await stopSharedAgentSessions({ ...agent, workspaceId: null } as Agent);
+ expect(mocks.list).not.toHaveBeenCalled();
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/stop-shared-agent-sessions.ts b/console/apps/switch-console-desktop/src/main/core/agents/stop-shared-agent-sessions.ts
index b308523cb..d6743f137 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/stop-shared-agent-sessions.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/stop-shared-agent-sessions.ts
@@ -1,12 +1,9 @@
import { listHostSessions } from '@main/core/sdk-host/host-sessions';
import { stopSharedSession } from '@main/core/sdk-host/stop-shared-session';
-import { getServer } from '@main/core/switch-servers/servers-store';
import type { Agent } from '@shared/core/agents/agents';
export async function stopSharedAgentSessions(agent: Agent): Promise<void> {
- if (!agent.serverId || !agent.switchAgentId) return;
- const server = await getServer(agent.serverId);
- if (!server) throw new Error('Cannot stop SDK sessions: the Switch server is missing.');
+ if (!agent.workspaceId || !agent.switchAgentId) return;
const sessions = await listHostSessions(agent.id);
for (const session of sessions.filter(
(session) =>
diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.test.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.test.ts
index c762cc7cb..ec7f2f1bf 100644
--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.test.ts
@@ -4,8 +4,7 @@ import { adoptSubagent } from './adopt-subagent';
const mocks = vi.hoisted(() => ({
local: vi.fn(),
- workspace: vi.fn(),
- server: vi.fn(),
+ session: vi.fn(),
remote: vi.fn(),
create: vi.fn(),
emit: vi.fn(),
@@ -18,8 +17,9 @@ vi.mock('@main/core/agents/remote-session-reconciler', () => ({
remoteSessionReconciler: { start: mocks.start },
}));
vi.mock('@main/core/switch-servers/gateway-client', () => ({ fetchAgentDetail: mocks.remote }));
-vi.mock('@main/core/switch-servers/servers-store', () => ({ getServer: mocks.server }));
-vi.mock('@main/core/workspaces/workspaces-store', () => ({ requireWorkspace: mocks.workspace }));
+vi.mock('@main/core/workspaces/workspace-session', () => ({
+ withWorkspaceSession: mocks.session,
+}));
const parent = {
id: 'parent',
locationId: 'location',
@@ -33,8 +33,9 @@ const parent = {
beforeEach(() => {
vi.resetAllMocks();
mocks.local.mockResolvedValue([]);
- mocks.workspace.mockResolvedValue({ id: 'workspace', serverId: 'server' });
- mocks.server.mockResolvedValue({ id: 'server' });
+ mocks.session.mockImplementation(
+ (_workspaceId: string, fn: (server: { id: string }) => Promise<unknown>) => fn({ id: 'server' })
+ );
mocks.remote.mockResolvedValue({ id: 'child', ownerName: 'Owner' });
mocks.create.mockImplementation(async (value) => ({ ...value, id: 'local-child' }));
});
diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.ts
index d69d0f911..de40a0d41 100644
--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.ts
+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.ts
@@ -4,8 +4,7 @@ import { createAgent } from '@main/core/agents/createAgent';
import { getLocationAgentsInWorkspace } from '@main/core/agents/getAgents';
import { remoteSessionReconciler } from '@main/core/agents/remote-session-reconciler';
import { fetchAgentDetail } from '@main/core/switch-servers/gateway-client';
-import { getServer } from '@main/core/switch-servers/servers-store';
-import { requireWorkspace } from '@main/core/workspaces/workspaces-store';
+import { withWorkspaceSession } from '@main/core/workspaces/workspace-session';
import type { Agent } from '@shared/core/agents/agents';
export async function adoptSubagent(
@@ -24,10 +23,9 @@ export async function adoptSubagent(
}
if (local.some((agent) => agent.name === name))
throw new Error('This subagent name is already linked to a different Switch identity.');
- const workspace = await requireWorkspace(parent.workspaceId);
- const server = await getServer(workspace.serverId);
- if (!server) throw new Error('The subagent’s Switch server is missing.');
- const remote = await fetchAgentDetail(server, switchAgentId);
+ const remote = await withWorkspaceSession(parent.workspaceId, (server) =>
+ fetchAgentDetail(server, switchAgentId)
+ );
if (remote.id !== switchAgentId)
throw new Error('Switch returned a different subagent identity.');
const agent = await createAgent({
diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/controller.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/controller.ts
index a53f811db..c325420c4 100644
--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/controller.ts
+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/controller.ts
@@ -29,10 +29,10 @@ export const sdkHostController = createRPCController({
agentLogs: sharedAgentLogs,
manageSidecar: async (agentId: string, action: 'update' | 'restart' | 'stop' | 'start') =>
manageAgentSidecar(agentId, z.enum(['update', 'restart', 'stop', 'start']).parse(action)),
- serverForAgent: async (agentId: string) => {
+ workspaceForAgent: async (agentId: string) => {
const agent = await getAgentById(agentId);
- if (!agent?.serverId) throw new Error('This agent has no Switch server.');
- return agent.serverId;
+ if (!agent?.workspaceId) throw new Error('This agent has no Switch workspace.');
+ return agent.workspaceId;
},
transcriptSource,
transcriptOpen: (agentId: string, sessionId: string) => openTranscript(agentId, sessionId),
diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/diagnostics.test.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/diagnostics.test.ts
index 8965944a7..151570f0b 100644
--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/diagnostics.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/diagnostics.test.ts
@@ -5,7 +5,11 @@ vi.mock('@main/core/agent-runtime/impl/resolve-sidecar-bundle', () => ({
resolveSharedHostBundlePath: () => import.meta.filename,
}));
vi.mock('@main/core/agents/getAgentById', () => ({
- getAgentById: async () => ({ id: 'agent', switchAgentId: 'remote-agent', serverId: 'server' }),
+ getAgentById: async () => ({
+ id: 'agent',
+ switchAgentId: 'remote-agent',
+ workspaceId: 'workspace',
+ }),
}));
vi.mock('@main/core/agents/agent-location', () => ({
getAgentLocation: async () => ({ sshHost: 'host', dir: '/work' }),
@@ -16,8 +20,9 @@ vi.mock('@main/core/agents/connect-remote-agent', () => ({
vi.mock('@main/core/execution-context/local-execution-context', () => ({
LocalExecutionContext: class {},
}));
-vi.mock('@main/core/switch-servers/servers-store', () => ({
- getServer: async () => ({ id: 'server' }),
+vi.mock('@main/core/workspaces/workspace-session', () => ({
+ withWorkspaceSession: (_workspaceId: string, fn: (server: { id: string }) => Promise<unknown>) =>
+ fn({ id: 'server' }),
}));
vi.mock('./host-sessions', () => ({ listHostSessions: mocks.sessions }));
const { sharedAgentDiagnostics, sharedAgentLogs } = await import('./diagnostics');
diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/diagnostics.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/diagnostics.ts
index fec2b7801..e0c0c1c0c 100644
--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/diagnostics.ts
+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/diagnostics.ts
@@ -6,7 +6,6 @@ import { getAgentLocation } from '@main/core/agents/agent-location';
import { connectRemoteAgent } from '@main/core/agents/connect-remote-agent';
import { getAgentById } from '@main/core/agents/getAgentById';
import { LocalExecutionContext } from '@main/core/execution-context/local-execution-context';
-import { getServer } from '@main/core/switch-servers/servers-store';
import { redactSecrets } from '@main/lib/file-logger';
import { listHostSessions } from './host-sessions';
import { inspectWatchers } from './watcher-inspection';
@@ -28,7 +27,7 @@ const watcherSchema = z.object({
async function agentHost(agentId: string) {
const agent = await getAgentById(agentId);
- if (!agent?.serverId || !agent.switchAgentId)
+ if (!agent?.workspaceId || !agent.switchAgentId)
throw new Error('The agent is not linked to Switch.');
const location = await getAgentLocation(agent);
const ctx = location.sshHost
@@ -39,8 +38,6 @@ async function agentHost(agentId: string) {
export async function sharedAgentDiagnostics(agentId: string) {
const { agent, location, ctx } = await agentHost(agentId);
- const server = await getServer(agent.serverId!);
- if (!server) throw new Error('The agent’s Switch server is missing.');
const [host, bundle, remote] = await Promise.all([
ctx.exec('node', ['-e', inspectWatchers, agent.switchAgentId!, 'status']),
readFile(resolveSharedHostBundlePath()),
diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.initial-prompt.test.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.initial-prompt.test.ts
index 6f59eaaa9..8a8a27d73 100644
--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.initial-prompt.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.initial-prompt.test.ts
@@ -34,7 +34,7 @@ vi.mock('@main/core/switch-rooms/session-room-store', () => ({
getPersistedRoomConnection: mocks.persistedRoom,
}));
vi.mock('@main/core/agents/getAgentById', () => ({ getAgentById: mocks.agent }));
-vi.mock('@main/core/switch-servers/servers-store', () => ({ getServer: mocks.server }));
+vi.mock('@main/core/workspaces/workspace-session', () => ({ workspaceServer: mocks.server }));
class FakeNotRecorded extends Error {}
vi.mock('./session-commands', () => ({
CommandNotRecordedError: FakeNotRecorded,
@@ -107,7 +107,7 @@ beforeEach(() => {
id: 'agent-1',
name: 'scout',
switchAgentId: 'remote-agent',
- serverId: 'server-1',
+ workspaceId: 'workspace-1',
});
mocks.server.mockResolvedValue({ id: 'server-1' });
mocks.ready.mockResolvedValue(undefined);
@@ -308,7 +308,7 @@ it('reports restart progress through host replacement and authentication until r
release = resolve;
})
);
- mocks.loadSession.mockResolvedValue({ serverId: 'server-1', row: { config: {} } });
+ mocks.loadSession.mockResolvedValue({ workspaceId: 'workspace-1', row: { config: {} } });
mocks.snapshot
.mockResolvedValueOnce({
session: { epoch: 'old', connectivity: 'online', status: 'ready' },
diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.ts
index 14f2949a5..3ecb01950 100644
--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.ts
+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.ts
@@ -37,11 +37,10 @@ import { controllerConnectionId } from '@main/core/switch-rooms/session-connecti
import { getPersistedRoomConnection } from '@main/core/switch-rooms/session-room-store';
import { switchNotificationPoller } from '@main/core/switch-rooms/switch-notification-poller';
import { switchRoomService } from '@main/core/switch-rooms/switch-room-service';
-import { getServer } from '@main/core/switch-servers/servers-store';
+import { workspaceServer } from '@main/core/workspaces/workspace-session';
import { log } from '@main/lib/logger';
import { makeHookSessionId } from '@shared/core/providers/hook-session-id';
import type { Session } from '@shared/core/sessions/sessions';
-import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';
import { JournalUnavailableError } from './host-journal';
import { currentSnapshot } from './transcripts';
@@ -63,7 +62,7 @@ function launchSettled(snapshot: Snapshot): boolean {
}
export class SharedAgentRuntime implements AgentRuntimeProvider {
- private server: SwitchServer | null = null;
+ private workspaceId: string | null = null;
private starting: Promise<void> | null = null;
private opened: Promise<void> | null = null;
private startupError: string | null = null;
@@ -123,12 +122,11 @@ export class SharedAgentRuntime implements AgentRuntimeProvider {
): Promise<void> {
this.startupStage = 'Preparing the session on its host…';
const agent = await getAgentById(session.agentId);
- if (!agent?.switchAgentId || !agent.serverId)
- throw new Error('Link this agent to a Switch server before starting a session.');
- this.server = await getServer(agent.serverId);
- if (!this.server) throw new Error('The agent’s Switch server is missing.');
+ if (!agent?.switchAgentId || !agent.workspaceId)
+ throw new Error('Link this agent to a Switch workspace before starting a session.');
+ this.workspaceId = agent.workspaceId;
this.startupStage = 'Waiting for the Switch server to be ready…';
- await ensureServerSessionReady(this.server);
+ await ensureServerSessionReady(await workspaceServer(agent.workspaceId));
this.startupStage = 'Preparing the session on its host…';
const intended = switchNotificationPoller.getSharedIntent(session.id, agent.switchAgentId);
const config = await buildSharedHostConfig(session, this.params, this.transport);
@@ -323,7 +321,7 @@ export class SharedAgentRuntime implements AgentRuntimeProvider {
}
async restart(session: Session): Promise<void> {
- await this.resolveServer();
+ await this.resolveWorkspace();
if (this.starting) await this.starting;
this.startupError = null;
this.starting = this.open(session, undefined, true, true, () => {});
@@ -348,11 +346,12 @@ export class SharedAgentRuntime implements AgentRuntimeProvider {
if (!joined) throw new Error('The session is no longer recorded in Console.');
await stopSharedSession(joined.row.agentId, this.params.sessionId);
}
- private async resolveServer(): Promise<void> {
- if (this.server) return;
+ private async resolveWorkspace(): Promise<string> {
+ if (this.workspaceId) return this.workspaceId;
const session = await loadSessionWithAgent(this.params.sessionId);
- this.server = session?.serverId ? await getServer(session.serverId) : null;
- if (!this.server) throw new Error('The session’s Switch server is missing.');
+ if (!session?.workspaceId) throw new Error('The session’s Switch workspace is missing.');
+ this.workspaceId = session.workspaceId;
+ return this.workspaceId;
}
}
diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/stop-saved-session.test.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/stop-saved-session.test.ts
index 9c881fff1..b6a6b18de 100644
--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/stop-saved-session.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/stop-saved-session.test.ts
@@ -12,7 +12,7 @@ vi.mock('./local-host', () => ({ stopLocalSession: mocks.stopLocal }));
beforeEach(() => {
vi.resetAllMocks();
- mocks.agent.mockResolvedValue({ switchAgentId: 'remote-agent', serverId: 'server' });
+ mocks.agent.mockResolvedValue({ switchAgentId: 'remote-agent', workspaceId: 'workspace' });
mocks.stop.mockResolvedValue(undefined);
mocks.stopLocal.mockResolvedValue(undefined);
});
diff --git a/console/apps/switch-console-desktop/src/main/core/sessions/session-join.ts b/console/apps/switch-console-desktop/src/main/core/sessions/session-join.ts
index bba4c1bde..716c94524 100644
--- a/console/apps/switch-console-desktop/src/main/core/sessions/session-join.ts
+++ b/console/apps/switch-console-desktop/src/main/core/sessions/session-join.ts
@@ -10,6 +10,10 @@ export type SessionWithAgent = {
/** The owning agent's `name` — the session's identity source. The creds slug
* and `--agent` launch name derive from it, read live, not from a frozen tag. */
name: string;
+ /** The workspace the owning agent belongs to; null for an agent not linked to
+ * Switch. This is what a call about the session is addressed with — a server
+ * can host several workspaces and answers for only the selected one. */
+ workspaceId: string | null;
/** The server hosting the agent's workspace; null once that server has been
* removed, which leaves the agent's endpoint and token pointing at something
* that no longer exists. */
@@ -29,6 +33,7 @@ export async function loadSessionWithAgent(
locationId: agents.locationId,
providerId: agents.providerId,
name: agents.name,
+ workspaceId: agents.workspaceId,
serverId: workspaces.serverId,
})
.from(sessions)
@@ -43,6 +48,7 @@ export async function loadSessionWithAgent(
locationId: joined.locationId,
providerId: joined.providerId,
name: joined.name,
+ workspaceId: joined.workspaceId,
serverId: joined.serverId,
};
}
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/auth.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/auth.ts
index 3db499561..0acdb6ec3 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/auth.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/auth.ts
@@ -21,7 +21,7 @@ function gatewayUrl(server: SwitchServer, path: string): string {
}
/** Pull the `switch_auth` value out of the response's Set-Cookie headers. */
-function extractAuthCookie(setCookies: string[]): string | null {
+export function extractAuthCookie(setCookies: string[]): string | null {
for (const raw of setCookies) {
const [pair] = raw.split(';');
const eq = pair.indexOf('=');
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.test.ts
index 90aee30fa..f285bbe7b 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.test.ts
@@ -55,20 +55,25 @@ function server(id: string): SwitchServer {
}
/**
- * Set up a server's agent list and which of them this install manages locally.
- * `managed` defaults to all of them — the ordinary case of a machine looking at
- * its own agents.
+ * Set up a workspace's agent list and which of them this install manages
+ * locally. `managed` defaults to all of them — the ordinary case of a machine
+ * looking at its own agents.
*/
function given(remote: RemoteAgentSummary[], managed?: string[]) {
const ids = managed ?? remote.map((a) => a.id);
fetchAgents.mockResolvedValue(remote);
getAgents.mockResolvedValue(
- ids.map((switchAgentId) => ({ id: `local-${switchAgentId}`, switchAgentId, serverId: 's-1' }))
+ ids.map((switchAgentId) => ({
+ id: `local-${switchAgentId}`,
+ switchAgentId,
+ workspaceId: 'ws-1',
+ }))
);
}
-/** Re-imported per test: the module remembers which servers it has done, which
- * is the behaviour under test in one case and interference in every other. */
+/** Re-imported per test: the module remembers which workspaces it has done,
+ * which is the behaviour under test in one case and interference in every
+ * other. */
async function loadFresh() {
vi.resetModules();
return (await import('./backfill-agent-icons')).backfillAgentIcons;
@@ -85,7 +90,7 @@ describe('backfillAgentIcons', () => {
given([agent({ id: 'a-1', name: 'switch_worker' })]);
const backfill = await loadFresh();
- expect(await backfill(server('s-1'))).toEqual({ kind: 'written', written: 1 });
+ expect(await backfill('ws-1', server('s-1'))).toEqual({ kind: 'written', written: 1 });
expect(updateAgentIcon).toHaveBeenCalledWith(
expect.anything(),
'a-1',
@@ -101,7 +106,7 @@ describe('backfillAgentIcons', () => {
given([agent({ id: 'a-1', name: 'ancient', ownerId: null })]);
const backfill = await loadFresh();
- expect(await backfill(server('s-1'))).toEqual({ kind: 'written', written: 1 });
+ expect(await backfill('ws-1', server('s-1'))).toEqual({ kind: 'written', written: 1 });
expect(updateAgentIcon).toHaveBeenCalledOnce();
});
@@ -111,7 +116,7 @@ describe('backfillAgentIcons', () => {
given([agent({ iconUrl: 'https://example.com/mine.png' })]);
const backfill = await loadFresh();
- expect(await backfill(server('s-1'))).toEqual({ kind: 'written', written: 0 });
+ expect(await backfill('ws-1', server('s-1'))).toEqual({ kind: 'written', written: 0 });
expect(updateAgentIcon).not.toHaveBeenCalled();
});
@@ -121,18 +126,18 @@ describe('backfillAgentIcons', () => {
given([agent({ id: 'a-1' }), agent({ id: 'someone-elses' })], ['a-1']);
const backfill = await loadFresh();
- expect(await backfill(server('s-1'))).toEqual({ kind: 'written', written: 1 });
+ expect(await backfill('ws-1', server('s-1'))).toEqual({ kind: 'written', written: 1 });
expect(updateAgentIcon).toHaveBeenCalledWith(expect.anything(), 'a-1', expect.any(String));
});
- it('ignores a local agent belonging to a different server', async () => {
+ it('ignores a local agent belonging to a different workspace', async () => {
fetchAgents.mockResolvedValue([agent({ id: 'a-1' })]);
getAgents.mockResolvedValue([
- { id: 'local-1', switchAgentId: 'a-1', serverId: 'another-server' },
+ { id: 'local-1', switchAgentId: 'a-1', workspaceId: 'another-workspace' },
]);
const backfill = await loadFresh();
- expect(await backfill(server('s-1'))).toEqual({ kind: 'written', written: 0 });
+ expect(await backfill('ws-1', server('s-1'))).toEqual({ kind: 'written', written: 0 });
expect(updateAgentIcon).not.toHaveBeenCalled();
});
@@ -141,7 +146,7 @@ describe('backfillAgentIcons', () => {
updateAgentIcon.mockRejectedValueOnce(new FakeGatewayError('http', 'forbidden', 403));
const backfill = await loadFresh();
- expect(await backfill(server('s-1'))).toEqual({ kind: 'written', written: 0 });
+ expect(await backfill('ws-1', server('s-1'))).toEqual({ kind: 'written', written: 0 });
});
it('reports a server with no icon endpoint', async () => {
@@ -152,7 +157,7 @@ describe('backfillAgentIcons', () => {
updateAgentIcon.mockRejectedValue(new FakeGatewayError('http', 'not found', 404));
const backfill = await loadFresh();
- expect(await backfill(server('s-1'))).toEqual({ kind: 'unsupported' });
+ expect(await backfill('ws-1', server('s-1'))).toEqual({ kind: 'unsupported' });
});
it('reports the agents that kept the old icon', async () => {
@@ -160,17 +165,21 @@ describe('backfillAgentIcons', () => {
updateAgentIcon.mockRejectedValueOnce(new Error('boom'));
const backfill = await loadFresh();
- expect(await backfill(server('s-1'))).toEqual({ kind: 'partial', written: 2, failed: 1 });
+ expect(await backfill('ws-1', server('s-1'))).toEqual({
+ kind: 'partial',
+ written: 2,
+ failed: 1,
+ });
expect(updateAgentIcon).toHaveBeenCalledTimes(3);
});
- it('asks the gateway once per server however often it is called', async () => {
+ it('asks the gateway once per workspace however often it is called', async () => {
given([agent({})]);
const backfill = await loadFresh();
- await backfill(server('s-1'));
- await backfill(server('s-1'));
- await backfill(server('s-1'));
+ await backfill('ws-1', server('s-1'));
+ await backfill('ws-1', server('s-1'));
+ await backfill('ws-1', server('s-1'));
expect(updateAgentIcon).toHaveBeenCalledTimes(1);
expect(fetchAgents).toHaveBeenCalledTimes(1);
@@ -180,7 +189,7 @@ describe('backfillAgentIcons', () => {
// Two sidebar refreshes can land together on startup; without this each
// would see no icons yet and write every agent twice.
let release = (_: RemoteAgentSummary[]) => {};
- getAgents.mockResolvedValue([{ id: 'local-1', switchAgentId: 'a-1', serverId: 's-1' }]);
+ getAgents.mockResolvedValue([{ id: 'local-1', switchAgentId: 'a-1', workspaceId: 'ws-1' }]);
fetchAgents.mockReturnValue(
new Promise<RemoteAgentSummary[]>((resolve) => {
release = resolve;
@@ -188,8 +197,8 @@ describe('backfillAgentIcons', () => {
);
const backfill = await loadFresh();
- const first = backfill(server('s-1'));
- const second = backfill(server('s-1'));
+ const first = backfill('ws-1', server('s-1'));
+ const second = backfill('ws-1', server('s-1'));
release([agent({ id: 'a-1' })]);
await Promise.all([first, second]);
@@ -203,23 +212,45 @@ describe('backfillAgentIcons', () => {
fetchAgents.mockRejectedValueOnce(new Error('offline'));
const backfill = await loadFresh();
- await expect(backfill(server('s-1'))).rejects.toThrow('offline');
+ await expect(backfill('ws-1', server('s-1'))).rejects.toThrow('offline');
given([agent({})]);
- expect(await backfill(server('s-1'))).toEqual({ kind: 'written', written: 1 });
+ expect(await backfill('ws-1', server('s-1'))).toEqual({ kind: 'written', written: 1 });
});
- it('handles each server separately', async () => {
+ it('handles each workspace separately', async () => {
fetchAgents.mockResolvedValue([agent({ id: 'a-1' })]);
getAgents.mockResolvedValue([
- { id: 'local-1', switchAgentId: 'a-1', serverId: 's-1' },
- { id: 'local-2', switchAgentId: 'a-1', serverId: 's-2' },
+ { id: 'local-1', switchAgentId: 'a-1', workspaceId: 'ws-1' },
+ { id: 'local-2', switchAgentId: 'a-1', workspaceId: 'ws-2' },
]);
const backfill = await loadFresh();
- await backfill(server('s-1'));
- await backfill(server('s-2'));
+ await backfill('ws-1', server('s-1'));
+ await backfill('ws-2', server('s-2'));
expect(updateAgentIcon).toHaveBeenCalledTimes(2);
});
+
+ /**
+ * Two workspaces on one server are two different agent lists: `GET /agents`
+ * answers for whichever tenant the session has selected. Remembering the pass
+ * against the server would have the first workspace's result stand in for the
+ * second's — its agents never written, and its report describing a pass that
+ * never looked at them.
+ */
+ it('does a second workspace on the same server rather than reusing the first', async () => {
+ fetchAgents.mockResolvedValue([agent({ id: 'a-1' })]);
+ getAgents.mockResolvedValue([
+ { id: 'local-1', switchAgentId: 'a-1', workspaceId: 'ws-1' },
+ { id: 'local-2', switchAgentId: 'a-1', workspaceId: 'ws-2' },
+ ]);
+ const backfill = await loadFresh();
+
+ await backfill('ws-1', server('s-1'));
+ await backfill('ws-2', server('s-1'));
+
+ expect(fetchAgents).toHaveBeenCalledTimes(2);
+ expect(updateAgentIcon).toHaveBeenCalledTimes(2);
+ });
});
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.ts
index 3f6427268..fa6d64e26 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.ts
@@ -29,37 +29,51 @@ import { fetchAgents, GatewayError, updateAgentIcon } from './gateway-client';
* server — still show the lettered avatar. Nothing on screen would say why, so
* the caller is handed what happened and tells the user.
*/
-export function backfillAgentIcons(server: SwitchServer): Promise<AgentIconBackfill> {
- const settled = completed.get(server.id);
+export function backfillAgentIcons(
+ workspaceId: string,
+ server: SwitchServer
+): Promise<AgentIconBackfill> {
+ const settled = completed.get(workspaceId);
if (settled !== undefined) return Promise.resolve(settled);
- const running = inFlight.get(server.id);
+ const running = inFlight.get(workspaceId);
if (running) return running;
- const run = writeMissingIcons(server)
+ const run = writeMissingIcons(workspaceId, server)
.then((outcome) => {
- completed.set(server.id, outcome);
+ completed.set(workspaceId, outcome);
return outcome;
})
- .finally(() => inFlight.delete(server.id));
+ .finally(() => inFlight.delete(workspaceId));
- inFlight.set(server.id, run);
+ inFlight.set(workspaceId, run);
return run;
}
-/** Servers already done this run, and what happened to each. Kept so opening
- * the agents page repeatedly does not re-ask the gateway; a server that threw
- * is deliberately absent, so the next refresh tries again. */
+/**
+ * Workspaces already done this run, and what happened to each. Kept so opening
+ * the agents page repeatedly does not re-ask the gateway; a workspace whose
+ * pass threw is deliberately absent, so the next refresh tries again.
+ *
+ * Per workspace and not per server: `GET /agents` answers for the tenant the
+ * session has selected, so one server's two workspaces are two different lists.
+ * Keying on the server would let the first workspace's pass stand in for the
+ * second's — the second's agents never written, and the first's outcome
+ * reported under the second's name.
+ */
const completed = new Map<string, AgentIconBackfill>();
const inFlight = new Map<string, Promise<AgentIconBackfill>>();
-async function writeMissingIcons(server: SwitchServer): Promise<AgentIconBackfill> {
+async function writeMissingIcons(
+ workspaceId: string,
+ server: SwitchServer
+): Promise<AgentIconBackfill> {
const [agents, local] = await Promise.all([fetchAgents(server), getAgents()]);
- // `GET /agents` lists the whole server, most of which is nothing to do with
- // this computer.
+ // `GET /agents` lists the whole workspace, most of which is nothing to do
+ // with this computer.
const managed = new Set(
local
- .filter((agent) => agent.serverId === server.id && agent.switchAgentId !== null)
+ .filter((agent) => agent.workspaceId === workspaceId && agent.switchAgentId !== null)
.map((agent) => agent.switchAgentId as string)
);
const missing = agents.filter((agent) => agent.iconUrl === null && managed.has(agent.id));
@@ -94,6 +108,7 @@ async function writeMissingIcons(server: SwitchServer): Promise<AgentIconBackfil
if (written === 0 && notFound > 0 && notFound === missing.length) {
log.warn('agent icon backfill: this server has no agent-icon endpoint', {
event: 'agent_icon_backfill',
+ workspaceId,
serverId: server.id,
agents: missing.length,
});
@@ -103,6 +118,7 @@ async function writeMissingIcons(server: SwitchServer): Promise<AgentIconBackfil
if (failures.length > 0) {
log.warn('agent icon backfill: some agents kept the lettered avatar', {
event: 'agent_icon_backfill',
+ workspaceId,
serverId: server.id,
written,
failed: failures.length,
@@ -113,6 +129,7 @@ async function writeMissingIcons(server: SwitchServer): Promise<AgentIconBackfil
log.info('agent icon backfill: done', {
event: 'agent_icon_backfill',
+ workspaceId,
serverId: server.id,
written,
});
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.test.ts
index 8412beec6..c92c0f62f 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.test.ts
@@ -9,10 +9,6 @@ const fetchAuthConfig = vi.hoisted(() => vi.fn());
const trackEvent = vi.hoisted(() => vi.fn());
const addServer = vi.hoisted(() => vi.fn());
const passwordLogin = vi.hoisted(() => vi.fn());
-const createRoomOnServer = vi.hoisted(() => vi.fn());
-const deleteBridge = vi.hoisted(() => vi.fn());
-const deleteRoom = vi.hoisted(() => vi.fn());
-const fetchBridges = vi.hoisted(() => vi.fn());
// Stubbed rather than reimplemented: what the tests below assert is that the
// kind reaches the event, not how a row is read as one.
const serverKindOf = vi.hoisted(() => vi.fn(() => 'remote_managed'));
@@ -43,18 +39,14 @@ vi.mock('./auth', () => ({ oidcLogin: vi.fn(), passwordLogin }));
vi.mock('./backfill-agent-icons', () => ({ backfillAgentIcons: vi.fn() }));
// Reaches the encrypted secrets store, and through it the database client.
vi.mock('./bundled-chat-sign-in', () => ({ bundledChatSignInFor: vi.fn() }));
-vi.mock('./create-room', () => ({ createRoomOnServer }));
vi.mock('./gateway-web', () => ({ openAuthenticatedGatewayPage: vi.fn() }));
vi.mock('./gateway-client', () => ({
fetchMe,
agentExistsOnServer: vi.fn(),
- deleteBridge,
- deleteRoom,
fetchAgentDetail: vi.fn(),
fetchAgentRooms: vi.fn(),
fetchAgents: vi.fn(),
fetchAuthConfig,
- fetchBridges,
fetchRoomRoles: vi.fn(),
fetchRooms: vi.fn(),
registerKnownAgent: vi.fn(),
@@ -153,43 +145,6 @@ describe('gateway calls on an unreachable host', () => {
});
});
-describe('disconnecting a bridge', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- managedServerHostBlocked.mockReturnValue(null);
- getServer.mockResolvedValue(server({}));
- fetchBridges.mockResolvedValue([{ id: 'b1', type: 'slack' }]);
- });
-
- it('reports a disconnection the gateway carried out', async () => {
- deleteBridge.mockResolvedValue({ kind: 'deleted' });
-
- await switchServersController.deleteBridge({ serverId: 'srv', bridgeId: 'b1' });
-
- await vi.waitFor(() =>
- expect(trackEvent).toHaveBeenCalledWith('bridge_disconnected', {
- bridge_platform: 'slack',
- outcome: 'success',
- })
- );
- });
-
- it('reports a refusal as a failure rather than as a disconnection', async () => {
- // Admin-only, and the gateway hands back the refusal instead of throwing
- // it — so the await returns exactly as it does for a bridge that went.
- deleteBridge.mockResolvedValue({ kind: 'forbidden' });
-
- await switchServersController.deleteBridge({ serverId: 'srv', bridgeId: 'b1' });
-
- await vi.waitFor(() =>
- expect(trackEvent).toHaveBeenCalledWith('bridge_disconnected', {
- bridge_platform: 'slack',
- outcome: 'failure',
- })
- );
- });
-});
-
describe('an action a server whose host has gone down cannot take', () => {
const blocked = {
sshHost: 'h',
@@ -202,45 +157,6 @@ describe('an action a server whose host has gone down cannot take', () => {
vi.clearAllMocks();
getServer.mockResolvedValue(server({ managed: true, managementKind: 'remote', sshHost: 'h' }));
managedServerHostBlocked.mockReturnValue(blocked);
- // What the gateway does on a host that cannot be reached: the platform is
- // then unknowable rather than absent.
- fetchBridges.mockRejectedValue(new Error('no route to host'));
- });
-
- it('reports the room it refused to create', async () => {
- await expect(
- switchServersController.createRoom({
- serverId: 'srv',
- name: 'Room',
- description: '',
- bridgeId: 'b1',
- agentIds: ['a1'],
- })
- ).rejects.toBeInstanceOf(HostUnreachableError);
-
- expect(createRoomOnServer).not.toHaveBeenCalled();
- await vi.waitFor(() =>
- expect(trackEvent).toHaveBeenCalledWith('room_created', {
- server_kind: 'remote_managed',
- bridge_platform: 'unknown',
- agent_count: 1,
- has_instructions: false,
- outcome: 'failure',
- failure_reason: 'unreachable',
- })
- );
- });
-
- it('reports the room it refused to delete', async () => {
- await expect(
- switchServersController.deleteRoom({ serverId: 'srv', roomId: 'r1' })
- ).rejects.toBeInstanceOf(HostUnreachableError);
-
- expect(deleteRoom).not.toHaveBeenCalled();
- expect(trackEvent).toHaveBeenCalledWith('room_deleted', {
- server_kind: 'remote_managed',
- outcome: 'failure',
- });
});
it('reports the sign-in that never left this machine', async () => {
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts
index b4db6d50f..3752d42e6 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts
@@ -1,108 +1,26 @@
import type { Result } from '@switch-console/shared';
import { propagateServerApiUrl } from '@main/core/agents/propagate-server-api-url';
import { appService } from '@main/core/app/service';
-import {
- isManagedServerRunning,
- managedServerHostBlocked,
-} from '@main/core/managed-switch-server/managed-server-status';
-import { bridgePlatformOfType } from '@main/core/telemetry/bridge-platform';
-import type {
- TelemetryAuthMethod,
- TelemetryBridgeFailure,
- TelemetryBridgePlatform,
- TelemetryOutcome,
- TelemetryRoomAgentsDirection,
- TelemetryRoomCreateFailure,
- TelemetryServerKind,
- TelemetrySignInFailure,
-} from '@main/core/telemetry/events';
-import { roomAgentsDirectionOf } from '@main/core/telemetry/narrow';
+import { isManagedServerRunning } from '@main/core/managed-switch-server/managed-server-status';
+import type { TelemetryAuthMethod, TelemetrySignInFailure } from '@main/core/telemetry/events';
import { trackEvent } from '@main/core/telemetry/telemetry-service';
-import { HostUnreachableError } from '@shared/core/remote-hosts/reachability';
import type {
- AddressingPolicy,
AddServerParams,
- AgentVerifyResult,
- BridgeDirectorySearchResult,
- AgentIconBackfill,
BundledChatSignIn,
- ClaimIdentityParams,
- ClaimIdentityResult,
- CreateBridgeParams,
- CreateBridgeResult,
- CreateRoomParams,
- CreateRoomResult,
- DeleteBridgeParams,
- DeleteBridgeResult,
- LinkedIdentity,
PasswordLoginParams,
- RemoteAgentRoom,
- RemoteAgentSummary,
- RemoteBridge,
- RemoteBridgeType,
- RemoteExternalUser,
- RemoteRoomDetail,
- RemoteRoomGroup,
- RemoteRoomRole,
- RemoteRoomSummary,
RenameServerParams,
ServerConnectionStatus,
SwitchAuthConfig,
SwitchServer,
- UpdateBridgeParams,
- UpdateBridgeResult,
- UpdateRoomParams,
UpdateServerParams,
UpdateServerResult,
} from '@shared/core/switch-servers/switch-servers';
import { createRPCController } from '@shared/lib/ipc/rpc';
import { type LoginError, oidcLogin, passwordLogin } from './auth';
-import { backfillAgentIcons } from './backfill-agent-icons';
-import { withResolvedHomeUrls } from './bridge-home-url';
import { bundledChatSignInFor } from './bundled-chat-sign-in';
-import { createBridgeOnServer } from './create-bridge';
-import { createRoomOnServer } from './create-room';
-import {
- addRoomAgents,
- agentExistsOnServer,
- deleteBridge,
- deleteRoom,
- fetchAddressingPolicy,
- fetchAgentRooms,
- fetchAgents,
- fetchAllExternalUsers,
- fetchAuthConfig,
- fetchBridges,
- fetchBridgeTypes,
- fetchMe,
- fetchMyIdentities,
- fetchRoomAgentIds,
- fetchRoomDetail,
- fetchRoomGroups,
- fetchRoomRoles,
- fetchRooms,
- createTemplate,
- deleteTemplate,
- updateTemplate,
- fetchTemplateDetail,
- fetchTemplates,
- GatewayError,
- ownsOwnerAddressedAgent,
- releaseBridgeIdentity,
- createRoomFromTemplate,
- exportRoomYaml,
- fetchTemplateSchema,
- removeRoomAgent,
- type StoredTemplateDetail,
- type StoredTemplateSummary,
- type TemplateVisibility,
- type ProvisionFromTemplateResult,
- updateAddressingPolicy,
- updateAgentIcon,
- updateRoom,
-} from './gateway-client';
+import { fetchAuthConfig, fetchMe, GatewayError } from './gateway-client';
import { openAuthenticatedGatewayPage } from './gateway-web';
-import { claimIdentityOnServer, searchDirectoryOnServer } from './identities';
+import { hostUnreachable, requireReachableServer, requireServer } from './require-server';
import {
addServer,
deleteSessionCookie,
@@ -111,62 +29,10 @@ import {
listServers,
removeServer,
renameServer,
+ serverKindOf,
setActiveServerId,
updateServer,
- serverKindOf,
} from './servers-store';
-import { updateBridgeOnServer } from './update-bridge';
-
-async function requireServer(serverId: string): Promise<SwitchServer> {
- const server = await getServer(serverId);
- if (!server) {
- throw new Error(`No Switch server with id ${serverId}`);
- }
- return server;
-}
-
-/**
- * The refusal a managed server's host being down produces, or null while it is
- * up.
- *
- * Returned rather than thrown so a path that reports its own outcome can count
- * the refusal before it propagates: the server is what an event describes
- * itself with, and a helper that throws leaves the caller holding nothing.
- */
-function hostUnreachable(server: SwitchServer): HostUnreachableError | null {
- const blocked = managedServerHostBlocked(server);
- return blocked ? new HostUnreachableError(blocked) : null;
-}
-
-/**
- * Resolve a server and refuse to touch its gateway while the host it is managed
- * on is unreachable (CHOO-1780). `gatewayFetch` enforces the same rule at the
- * transport, so this is for the paths that reach the gateway some other way —
- * sign-in and the dashboard window — and for failing before the side effects a
- * write would otherwise start.
- */
-async function requireReachableServer(serverId: string): Promise<SwitchServer> {
- const server = await requireServer(serverId);
- const unreachable = hostUnreachable(server);
- if (unreachable) throw unreachable;
- return server;
-}
-
-/** A bridge result's discriminant as a code. Never the message beside it. */
-function bridgeFailureReason(kind: string): TelemetryBridgeFailure {
- switch (kind) {
- case 'created':
- return 'none';
- case 'unauthenticated':
- return 'unauthenticated';
- case 'forbidden':
- return 'forbidden';
- case 'invalid':
- return 'invalid';
- default:
- return 'error';
- }
-}
/** A sign-in's own error union, as a reportable code. Never its message. */
const SIGN_IN_FAILURE: Record<LoginError['kind'], TelemetrySignInFailure> = {
@@ -197,78 +63,6 @@ function reportSignIn(
});
}
-/** A room-create result's discriminant as a code. */
-function roomCreateFailureReason(result: CreateRoomResult): TelemetryRoomCreateFailure {
- switch (result.kind) {
- case 'created':
- return 'none';
- case 'unauthenticated':
- return 'unauthenticated';
- case 'bridge-unavailable':
- return 'bridge_unavailable';
- case 'invalid':
- return 'invalid';
- default:
- return 'error';
- }
-}
-
-/**
- * Which platform a bridge id is on.
- *
- * A lookup rather than a field: these operations take a bridge id, and the type
- * either never appears (a delete) or appears only on success (a room). Best
- * effort — an unreachable server yields `unknown` rather than failing the
- * operation it is only describing.
- *
- * **Never awaited by a caller doing real work.** It asks the gateway, and making
- * someone wait on a network round trip so we can describe what they did would
- * put reporting in the path of the thing being reported. `reportWithBridge` is
- * how the answer is used once it arrives.
- */
-function bridgePlatformOf(
- server: SwitchServer,
- bridgeId: string | null | undefined
-): Promise<TelemetryBridgePlatform> {
- if (!bridgeId) return Promise.resolve('unknown');
- return fetchBridges(server)
- .then((bridges) => bridgePlatformOfType(bridges.find((b) => b.id === bridgeId)?.type))
- .catch((): TelemetryBridgePlatform => 'unknown');
-}
-
-/**
- * Report once the platform is known, without anyone waiting for it.
- *
- * The event arrives a moment after the action rather than with it, which costs
- * nothing: it carries its own timestamp, taken when the work happened.
- */
-function reportWithBridge(
- platform: Promise<TelemetryBridgePlatform>,
- emit: (platform: TelemetryBridgePlatform) => void
-): void {
- void platform.then(emit).catch(() => {});
-}
-
-/** The same, for a room create whose other properties are already known. */
-function reportRoomCreated(
- server: SwitchServer,
- bridgeId: string | null | undefined,
- rest: {
- server_kind: TelemetryServerKind;
- agent_count: number;
- has_instructions: boolean;
- failure_reason: TelemetryRoomCreateFailure;
- }
-): void {
- reportWithBridge(bridgePlatformOf(server, bridgeId), (bridge_platform) =>
- trackEvent('room_created', {
- ...rest,
- bridge_platform,
- outcome: rest.failure_reason === 'none' ? 'success' : 'failure',
- })
- );
-}
-
export const switchServersController = createRPCController({
listServers: (): Promise<SwitchServer[]> => listServers(),
@@ -388,20 +182,6 @@ export const switchServersController = createRPCController({
}
},
- listRemoteAgents: async (serverId: string): Promise<RemoteAgentSummary[]> =>
- fetchAgents(await requireServer(serverId)),
-
- listRemoteRooms: async (serverId: string): Promise<RemoteRoomSummary[]> =>
- fetchRooms(await requireServer(serverId)),
-
- listRemoteBridges: async (serverId: string): Promise<RemoteBridge[]> => {
- const server = await requireReachableServer(serverId);
- return withResolvedHomeUrls(server, await fetchBridges(server));
- },
-
- listRemoteBridgeTypes: async (serverId: string): Promise<RemoteBridgeType[]> =>
- fetchBridgeTypes(await requireReachableServer(serverId)),
-
/**
* The bundled chat's address and sign-in for a managed server (CHOO-1787).
*
@@ -411,367 +191,4 @@ export const switchServersController = createRPCController({
*/
getBundledChatSignIn: async (serverId: string): Promise<BundledChatSignIn> =>
bundledChatSignInFor(await getServer(serverId)),
-
- /**
- * Attach a collaboration bridge to the chosen server (CHOO-1784).
- *
- * `params.connectionConfig` carries platform credentials. They cross the IPC
- * boundary once, on the way out, and are never written to Switch Console's disk
- * or returned to the renderer — the server stores them. Keep it that way: do
- * not log `params` here.
- */
- createBridge: async (params: CreateBridgeParams): Promise<CreateBridgeResult> => {
- const server = await requireReachableServer(params.serverId);
- const platform = bridgePlatformOfType(params.bridgeType);
- let result: CreateBridgeResult;
- try {
- result = await createBridgeOnServer(server, {
- bridgeType: params.bridgeType,
- displayName: params.displayName,
- connectionConfig: params.connectionConfig,
- setAsDefault: params.setAsDefault,
- channelCreationEnabled: params.channelCreationEnabled,
- });
- } catch (error) {
- trackEvent('bridge_connected', {
- bridge_platform: platform,
- outcome: 'failure',
- failure_reason: 'error',
- });
- throw error;
- }
- trackEvent('bridge_connected', {
- bridge_platform: platform,
- outcome: result.kind === 'created' ? 'success' : 'failure',
- failure_reason: bridgeFailureReason(result.kind),
- });
- return result;
- },
-
- /**
- * Edit a bridge's operator-controlled switches — today, only whether the
- * connection may create channels. Admin-only, like registering one; see
- * `updateBridgeOnServer` for the recoverable-failure mapping.
- */
- updateBridge: async (params: UpdateBridgeParams): Promise<UpdateBridgeResult> => {
- const server = await requireReachableServer(params.serverId);
- return updateBridgeOnServer(server, {
- bridgeId: params.bridgeId,
- channelCreationEnabled: params.channelCreationEnabled,
- });
- },
-
- /**
- * Disconnect a messaging app from the chosen server. Admin-only, and the
- * gateway deletes every Switch room on the bridge on the way — see
- * `deleteBridge`. The renderer owns the confirmation; by the time this runs
- * the rooms are being given up deliberately.
- */
- deleteBridge: async (params: DeleteBridgeParams): Promise<DeleteBridgeResult> => {
- const server = await requireReachableServer(params.serverId);
- // Started before the delete, because afterwards there is no bridge left to
- // read a platform from — but never waited on: see `reportWithBridge`.
- const platform = bridgePlatformOf(server, params.bridgeId);
- const result = await deleteBridge(server, params.bridgeId);
- reportWithBridge(platform, (bridge_platform) =>
- trackEvent('bridge_disconnected', {
- bridge_platform,
- outcome: result.kind === 'deleted' ? 'success' : 'failure',
- })
- );
- return result;
- },
-
- /**
- * Create a room on the chosen server, owned by the signed-in user. Room
- * provisioning stays server-side (`POST /gateway/rooms`); this only maps
- * recoverable failures onto a typed result the modal can act on.
- */
- createRoom: async (params: CreateRoomParams): Promise<CreateRoomResult> => {
- const server = await requireServer(params.serverId);
- const report = (failure_reason: TelemetryRoomCreateFailure) =>
- reportRoomCreated(server, params.bridgeId, {
- server_kind: serverKindOf(server),
- agent_count: params.agentIds.length,
- has_instructions: (params.instructions?.trim().length ?? 0) > 0,
- failure_reason,
- });
-
- const unreachable = hostUnreachable(server);
- if (unreachable) {
- report('unreachable');
- throw unreachable;
- }
-
- let result: CreateRoomResult;
- try {
- result = await createRoomOnServer(server, {
- name: params.name,
- description: params.description,
- instructions: params.instructions,
- bridgeId: params.bridgeId,
- agentIds: params.agentIds,
- });
- } catch (error) {
- report('error');
- throw error;
- }
-
- report(roomCreateFailureReason(result));
- return result;
- },
-
- createRoomFromTemplate: async (
- serverId: string,
- yamlText: string,
- inputs: Record<string, string | number | boolean>
- ): Promise<ProvisionFromTemplateResult> =>
- createRoomFromTemplate(await requireServer(serverId), yamlText, inputs),
-
- listTemplates: async (params: {
- serverId: string;
- kind?: string;
- /** Narrows to templates whose name or description contains it. */
- q?: string;
- }): Promise<StoredTemplateSummary[]> =>
- fetchTemplates(await requireServer(params.serverId), { kind: params.kind, q: params.q }),
-
- getTemplateDetail: async (params: {
- serverId: string;
- templateId: string;
- }): Promise<StoredTemplateDetail> =>
- fetchTemplateDetail(await requireServer(params.serverId), params.templateId),
-
- deleteTemplate: async (params: { serverId: string; templateId: string }): Promise<void> =>
- deleteTemplate(await requireServer(params.serverId), params.templateId),
-
- updateTemplate: async (params: {
- serverId: string;
- templateId: string;
- name?: string;
- description?: string;
- kind?: string;
- content?: string;
- readVisibility?: TemplateVisibility;
- writeVisibility?: TemplateVisibility;
- }): Promise<StoredTemplateDetail> => {
- const { serverId, templateId, ...changes } = params;
- return updateTemplate(await requireServer(serverId), templateId, changes);
- },
-
- saveTemplate: async (params: {
- serverId: string;
- name: string;
- description: string;
- kind: string;
- content: string;
- readVisibility?: TemplateVisibility;
- writeVisibility?: TemplateVisibility;
- }): Promise<StoredTemplateDetail> => {
- const { serverId, ...template } = params;
- return createTemplate(await requireServer(serverId), template);
- },
-
- fetchTemplateSchema: async (serverId: string): Promise<Record<string, unknown> | null> =>
- fetchTemplateSchema(await requireServer(serverId)),
-
- exportRoomYaml: async (params: { serverId: string; roomId: string }): Promise<string> =>
- exportRoomYaml(await requireServer(params.serverId), params.roomId),
-
- listAgentRooms: async (params: {
- serverId: string;
- agentId: string;
- }): Promise<RemoteAgentRoom[]> =>
- fetchAgentRooms(await requireServer(params.serverId), params.agentId),
-
- listRoomRoles: async (params: { serverId: string; roomId: string }): Promise<RemoteRoomRole[]> =>
- fetchRoomRoles(await requireServer(params.serverId), params.roomId),
-
- listRoomAgentIds: async (params: { serverId: string; roomId: string }): Promise<string[]> =>
- fetchRoomAgentIds(await requireServer(params.serverId), params.roomId),
-
- /** One room in full, for its configuration page. */
- getRoomDetail: async (params: { serverId: string; roomId: string }): Promise<RemoteRoomDetail> =>
- fetchRoomDetail(await requireServer(params.serverId), params.roomId),
-
- /**
- * Change a room's own settings. Failures propagate as-is — a user without
- * write access to the room needs the gateway's refusal, not a saved-looking
- * field holding a value the server never took.
- */
- updateRoom: async (params: UpdateRoomParams): Promise<RemoteRoomDetail> =>
- updateRoom(await requireReachableServer(params.serverId), params.roomId, {
- description: params.description,
- instructions: params.instructions,
- }),
-
- /**
- * Add agents to a room. Failures propagate as-is: the caller shows the
- * gateway's own words (e.g. an agent whose server-side client is not running,
- * which the gateway rejects) rather than a generic message.
- */
- addRoomAgents: async (params: {
- serverId: string;
- roomId: string;
- agentIds: string[];
- /**
- * Which screen this came from. The same call serves both, and the
- * one-agent-to-many-rooms screen loops it once per room — so without this,
- * adding an agent to five rooms is indistinguishable from five people each
- * adding one agent.
- */
- direction: TelemetryRoomAgentsDirection;
- }): Promise<void> => {
- await addRoomAgents(
- await requireReachableServer(params.serverId),
- params.roomId,
- params.agentIds
- );
- trackEvent('room_agents_added', {
- agent_count: params.agentIds.length,
- direction: roomAgentsDirectionOf(params.direction),
- });
- },
-
- /** Remove one agent from a room. Membership only — the agent is not deleted. */
- removeRoomAgent: async (params: {
- serverId: string;
- roomId: string;
- agentId: string;
- }): Promise<void> =>
- removeRoomAgent(await requireReachableServer(params.serverId), params.roomId, params.agentId),
-
- /** Delete a room and everything in it. The gateway enforces who may. */
- deleteRoom: async (params: { serverId: string; roomId: string }): Promise<void> => {
- const server = await requireServer(params.serverId);
- const report = (outcome: TelemetryOutcome) =>
- trackEvent('room_deleted', { server_kind: serverKindOf(server), outcome });
-
- // A host that has gone down refuses the deletion as surely as the gateway
- // can, and the event has an outcome precisely so a refusal is counted.
- const unreachable = hostUnreachable(server);
- if (unreachable) {
- report('failure');
- throw unreachable;
- }
-
- try {
- await deleteRoom(server, params.roomId);
- } catch (error) {
- report('failure');
- throw error;
- }
- report('success');
- },
-
- listRemoteRoomGroups: async (serverId: string): Promise<RemoteRoomGroup[]> =>
- fetchRoomGroups(await requireServer(serverId)),
-
- listRemoteExternalUsers: async (serverId: string): Promise<RemoteExternalUser[]> =>
- fetchAllExternalUsers(await requireServer(serverId)),
-
- /**
- * Search a bridge's own user directory so the signed-in user can find
- * themselves before they have ever posted in the chat workspace (CHOO-2137).
- */
- searchBridgeDirectory: async (params: {
- serverId: string;
- bridgeId: string;
- query: string;
- }): Promise<BridgeDirectorySearchResult> =>
- searchDirectoryOnServer(
- await requireReachableServer(params.serverId),
- params.bridgeId,
- params.query
- ),
-
- /** Claim a messaging-app account as the signed-in Switch user's own. */
- claimBridgeIdentity: async (params: ClaimIdentityParams): Promise<ClaimIdentityResult> => {
- const server = await requireReachableServer(params.serverId);
- const result = await claimIdentityOnServer(server, {
- bridgeId: params.bridgeId,
- externalUserId: params.externalUserId,
- username: params.username,
- });
- reportWithBridge(bridgePlatformOf(server, params.bridgeId), (bridge_platform) =>
- trackEvent('bridge_identity_claimed', {
- bridge_platform,
- outcome: result.kind === 'claimed' ? 'success' : 'failure',
- })
- );
- return result;
- },
-
- /** Give up a claim on a messaging-app account, leaving any other user's claim
- * on it in place. `userId` is whose claim to drop — null for the signed-in
- * user, which is the only one this app offers. Failures propagate: unclaiming
- * is a deliberate act, and reporting success for one that did not happen
- * would leave the user thinking an agent is no longer reachable by them when
- * it still is. */
- releaseBridgeIdentity: async (params: {
- serverId: string;
- bridgeId: string;
- identityId: string;
- userId: string | null;
- }): Promise<void> =>
- releaseBridgeIdentity(
- await requireReachableServer(params.serverId),
- params.bridgeId,
- params.identityId,
- params.userId
- ),
-
- /** The messaging accounts the signed-in user has claimed on this server. */
- listMyIdentities: async (serverId: string): Promise<LinkedIdentity[]> =>
- fetchMyIdentities(await requireServer(serverId)),
-
- /** Whether the signed-in user owns an agent here that is set to answer its
- * owner, which is what makes an unlinked messaging account worth warning
- * about. One agent-list read, so callers need not ration it. */
- ownsOwnerAddressedAgent: async (serverId: string): Promise<boolean> =>
- ownsOwnerAddressedAgent(await requireServer(serverId)),
-
- getAddressingPolicy: async (params: {
- serverId: string;
- agentId: string;
- }): Promise<AddressingPolicy | null> =>
- fetchAddressingPolicy(await requireServer(params.serverId), params.agentId),
-
- updateAddressingPolicy: async (params: {
- serverId: string;
- agentId: string;
- policy: AddressingPolicy | null;
- }): Promise<void> =>
- updateAddressingPolicy(await requireServer(params.serverId), params.agentId, params.policy),
-
- /** Give this user's icon-less agents the avatar their name generates. Runs
- * once per server per app run; reports what happened so the caller can say
- * when the icons did not reach the server. */
- backfillAgentIcons: async (serverId: string): Promise<AgentIconBackfill> =>
- backfillAgentIcons(await requireServer(serverId)),
-
- /** Set or clear an agent's icon. Returns the agent as the server now holds
- * it, so the caller refreshes from the stored value rather than the one it
- * hoped for. */
- updateAgentIcon: async (params: {
- serverId: string;
- agentId: string;
- iconUrl: string | null;
- }): Promise<RemoteAgentSummary> =>
- updateAgentIcon(await requireServer(params.serverId), params.agentId, params.iconUrl),
-
- verifyAgent: async (params: {
- serverId: string;
- agentId: string;
- }): Promise<AgentVerifyResult> => {
- const server = await requireServer(params.serverId);
- try {
- return (await agentExistsOnServer(server, params.agentId)) ? 'found' : 'not-found';
- } catch (cause) {
- if (cause instanceof GatewayError && cause.kind === 'unauthorized') {
- return 'unauthenticated';
- }
- throw cause;
- }
- },
});
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.ts
index 8b34fab8f..4226079fd 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.ts
@@ -18,7 +18,7 @@ import type {
*/
export async function createBridgeOnServer(
server: SwitchServer,
- params: Omit<CreateBridgeParams, 'serverId'>
+ params: Omit<CreateBridgeParams, 'workspaceId'>
): Promise<CreateBridgeResult> {
try {
const bridge = await createBridge(server, {
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/create-room.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/create-room.ts
index c1bc0b288..276f7c679 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/create-room.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/create-room.ts
@@ -33,7 +33,7 @@ function isBridgeFailure(detail: string): boolean {
*/
export async function createRoomOnServer(
server: SwitchServer,
- params: Omit<CreateRoomParams, 'serverId'>
+ params: Omit<CreateRoomParams, 'workspaceId'>
): Promise<CreateRoomResult> {
try {
const room = await createRoom(server, {
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.ts
index e12000267..4ffb91dbb 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
@@ -3,6 +3,7 @@ import {
managedServerHostBlocked,
managedServerStoppedPhase,
} from '@main/core/managed-switch-server/managed-server-status';
+import { assertedTenant } from '@main/core/workspaces/asserted-tenant';
import { ManagedServerStoppedError } from '@shared/core/managed-switch-server/managed-switch-server';
import { HostUnreachableError } from '@shared/core/remote-hosts/reachability';
import { policyNamesOwner } from '@shared/core/switch-servers/owner-policy';
@@ -26,8 +27,9 @@ import type {
SwitchServerDeclaration,
SwitchUser,
} from '@shared/core/switch-servers/switch-servers';
-import { reauthenticateManagedServer, refreshSession } from './auth';
-import { getSessionCookie } from './servers-store';
+import type { WorkspaceRole } from '@shared/core/workspaces/workspaces';
+import { extractAuthCookie, reauthenticateManagedServer, refreshSession } from './auth';
+import { getSessionCookie, setSessionCookie } from './servers-store';
/** The gateway management API is mounted under `/gateway` on the server. */
function gatewayUrl(server: SwitchServer, path: string): string {
@@ -58,6 +60,30 @@ function decodeJwtExpMs(jwt: string): number | null {
}
}
+/**
+ * Read the `tenant_id` claim out of a JWT without verifying it. Returns null
+ * for a malformed token, and for a session that has selected no tenant — the
+ * gateway mints the claim as null until `/tenants/{id}/switch` is called.
+ *
+ * Unverified is the right level here: the claim only ever *selects* which
+ * workspace a call is scoped to, and the gateway re-checks membership against
+ * a live row on every request, so nothing this reads can grant access. It is
+ * read to know whether the selection already matches the workspace being
+ * addressed, or whether a switch has to happen first.
+ */
+export function decodeJwtTenantId(jwt: string): string | null {
+ const parts = jwt.split('.');
+ if (parts.length !== 3) return null;
+ try {
+ const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8')) as {
+ tenant_id?: unknown;
+ };
+ return typeof payload.tenant_id === 'string' ? payload.tenant_id : null;
+ } catch {
+ return null;
+ }
+}
+
/** Dedupe concurrent renewals per server so a burst of authenticated calls
* triggers at most one refresh round-trip (and one cookie write). */
const inflightRefresh = new Map<string, Promise<string | null>>();
@@ -139,12 +165,42 @@ async function resolveAuthCookie(server: SwitchServer): Promise<string> {
return renewIfExpiring(server, stored);
}
if (server.managed) {
- const minted = await reauthenticateManagedServer(server);
+ const minted = await silentLogin(server);
if (minted) return minted;
}
throw new GatewayError('unauthorized', 'Not signed in to this Switch server.');
}
+/**
+ * Servers whose silent re-login is putting a tenant back, so the switch it makes
+ * does not try to re-login its way out of its own 401.
+ */
+const restoringTenant = new Set<string>();
+
+/**
+ * Log a managed server back in silently, and re-select the workspace the calls
+ * in flight on it were addressing.
+ *
+ * A login cookie names no tenant. Handed back on its own it would answer the
+ * rest of a workspace-scoped call with the account's default workspace —
+ * succeeding, and looking exactly like the answer that was asked for.
+ */
+async function silentLogin(server: SwitchServer): Promise<string | null> {
+ const minted = await reauthenticateManagedServer(server);
+ if (!minted) return null;
+ const tenantId = assertedTenant(server.id);
+ if (tenantId === null || restoringTenant.has(server.id)) return minted;
+ restoringTenant.add(server.id);
+ try {
+ await switchTenant(server, tenantId);
+ } finally {
+ restoringTenant.delete(server.id);
+ }
+ // `switchTenant` stores the scoped cookie; the minted one it replaced would
+ // send this very call to the wrong workspace.
+ return (await getSessionCookie(server.id)) ?? minted;
+}
+
async function gatewayFetch(
server: SwitchServer,
path: string,
@@ -199,7 +255,7 @@ async function gatewayFetch(
// We hold its admin creds, so re-login and retry the call once rather than
// bouncing the user to a sign-in screen for a password they never saw.
if (response.status === 401 && options.authenticated && server.managed) {
- const renewed = await reauthenticateManagedServer(server);
+ const renewed = await silentLogin(server);
if (renewed) {
response = await sendOnce(renewed);
}
@@ -277,6 +333,59 @@ export async function fetchMe(server: SwitchServer): Promise<SwitchUser> {
return mapUser((await res.json()) as UserResponseJson);
}
+/** A tenant the signed-in user belongs to, as `GET /tenants` reports it. */
+export type RemoteTenant = {
+ id: string;
+ slug: string;
+ name: string;
+ role: WorkspaceRole;
+};
+
+function mapRole(raw: unknown): WorkspaceRole {
+ if (raw === 'owner' || raw === 'admin' || raw === 'member') return raw;
+ throw new GatewayError('http', `Switch server reported an unknown workspace role: ${raw}`);
+}
+
+/**
+ * The tenants the signed-in user belongs to. Answered without a tenant being
+ * selected on the session, which is what makes it the entry point: a user with
+ * several memberships has none selected until they pick one.
+ */
+export async function fetchTenants(server: SwitchServer): Promise<RemoteTenant[]> {
+ const res = await gatewayFetch(server, '/tenants', { authenticated: true });
+ const json = (await res.json()) as Array<{
+ id: string;
+ slug: string;
+ name: string;
+ role: string;
+ }>;
+ return json.map((t) => ({ id: t.id, slug: t.slug, name: t.name, role: mapRole(t.role) }));
+}
+
+/**
+ * Select a tenant for this server's session, persisting the re-minted cookie.
+ *
+ * One session holds one selected tenant, so this is what makes a call scoped to
+ * a particular workspace rather than to whichever one was picked last. The
+ * gateway verifies membership before it mints, so a refusal here is a real
+ * answer — it is raised rather than swallowed, because the alternative is
+ * issuing the caller's next request against somebody else's workspace.
+ */
+export async function switchTenant(server: SwitchServer, tenantId: string): Promise<void> {
+ const res = await gatewayFetch(server, `/tenants/${encodeURIComponent(tenantId)}/switch`, {
+ authenticated: true,
+ method: 'POST',
+ });
+ const cookie = extractAuthCookie(res.headers.getSetCookie());
+ if (!cookie) {
+ throw new GatewayError(
+ 'http',
+ `${server.name} accepted the workspace selection but returned no session cookie.`
+ );
+ }
+ await setSessionCookie(server.id, cookie);
+}
+
/** Options for `registerKnownAgent`, matching the gateway's
* `RegisterKnownAgentRequest.options`. The gateway validates these against the
* options schema of the `agent_type` being registered and ignores keys that type
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/identities.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/identities.ts
index 920157230..dd231daeb 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/identities.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/identities.ts
@@ -68,7 +68,7 @@ export async function searchDirectoryOnServer(
*/
export async function claimIdentityOnServer(
server: SwitchServer,
- params: Omit<ClaimIdentityParams, 'serverId'>
+ params: Omit<ClaimIdentityParams, 'workspaceId'>
): Promise<ClaimIdentityResult> {
try {
const claimed = await claimBridgeIdentity(server, params.bridgeId, {
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/require-server.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/require-server.ts
new file mode 100644
index 000000000..ed42d6b84
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/require-server.ts
@@ -0,0 +1,39 @@
+import { managedServerHostBlocked } from '@main/core/managed-switch-server/managed-server-status';
+import { HostUnreachableError } from '@shared/core/remote-hosts/reachability';
+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';
+import { getServer } from './servers-store';
+
+export async function requireServer(serverId: string): Promise<SwitchServer> {
+ const server = await getServer(serverId);
+ if (!server) {
+ throw new Error(`No Switch server with id ${serverId}`);
+ }
+ return server;
+}
+
+/**
+ * The refusal a managed server's host being down produces, or null while it is
+ * up.
+ *
+ * Returned rather than thrown so a path that reports its own outcome can count
+ * the refusal before it propagates: the server is what an event describes
+ * itself with, and a helper that throws leaves the caller holding nothing.
+ */
+export function hostUnreachable(server: SwitchServer): HostUnreachableError | null {
+ const blocked = managedServerHostBlocked(server);
+ return blocked ? new HostUnreachableError(blocked) : null;
+}
+
+/**
+ * Resolve a server and refuse to touch its gateway while the host it is managed
+ * on is unreachable (CHOO-1780). `gatewayFetch` enforces the same rule at the
+ * transport, so this is for the paths that reach the gateway some other way —
+ * sign-in and the dashboard window — and for failing before the side effects a
+ * write would otherwise start.
+ */
+export async function requireReachableServer(serverId: string): Promise<SwitchServer> {
+ const server = await requireServer(serverId);
+ const unreachable = hostUnreachable(server);
+ if (unreachable) throw unreachable;
+ return server;
+}
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/servers-store.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/servers-store.ts
index 69d3852aa..e94b945c5 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/servers-store.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/servers-store.ts
@@ -3,6 +3,7 @@ import { and, desc, eq, isNull, ne, or, sql } from 'drizzle-orm';
import { encryptedAppSecretsStore } from '@main/core/secrets/encrypted-app-secrets-store';
import type { TelemetryEventMap } from '@main/core/telemetry/events';
import { trackEvent } from '@main/core/telemetry/telemetry-service';
+import { forgetServerSession } from '@main/core/workspaces/workspace-session';
import {
clearActiveWorkspaceOnServer,
ensureServerWorkspace,
@@ -256,6 +257,7 @@ export async function removeServer(id: string): Promise<void> {
// Deleting the server takes its workspaces with it and unlinks their agents,
// both by foreign key: workspaces cascade, agents are set null.
await db.delete(switchServers).where(eq(switchServers.id, id));
+ forgetServerSession(id);
// Removing an already-absent server is not a server being removed.
if (server) trackEvent('server_removed', { server_kind: serverKindOf(server) });
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/update-bridge.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/update-bridge.ts
index 9b3e03d35..d1e3fa08a 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/update-bridge.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/update-bridge.ts
@@ -15,7 +15,7 @@ import type {
*/
export async function updateBridgeOnServer(
server: SwitchServer,
- params: Omit<UpdateBridgeParams, 'serverId'>
+ params: Omit<UpdateBridgeParams, 'workspaceId'>
): Promise<UpdateBridgeResult> {
try {
const bridge = await updateBridge(server, params.bridgeId, {
diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/asserted-tenant.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/asserted-tenant.ts
new file mode 100644
index 000000000..5843c48bd
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/asserted-tenant.ts
@@ -0,0 +1,36 @@
+/**
+ * Which tenant a server's session is currently selecting on behalf of the calls
+ * holding a lease on it.
+ *
+ * The session seam owns this; it lives in a module of its own so the gateway
+ * client can read it without importing the seam that switches tenants through
+ * the gateway client.
+ *
+ * Every lease outstanding on a server at one moment names the same tenant — a
+ * switch waits for every lease to be given up first — so there is one answer per
+ * server rather than one per call.
+ */
+const asserted = new Map<string, string>();
+
+/** Record the tenant `serverId`'s first outstanding lease was taken against. */
+export function setAssertedTenant(serverId: string, tenantId: string): void {
+ asserted.set(serverId, tenantId);
+}
+
+/** Forget it once nothing is leasing the server. */
+export function clearAssertedTenant(serverId: string): void {
+ asserted.delete(serverId);
+}
+
+/**
+ * The tenant that has to hold for the calls in flight on `serverId`, or null
+ * when nothing is leasing it or the lease named no tenant.
+ *
+ * Read by anything that replaces the session cookie underneath those calls: a
+ * cookie minted by a fresh login selects no tenant, and handing it back
+ * unchanged would answer the rest of the lease with the account's default
+ * workspace while the caller still believes it is addressing the one it named.
+ */
+export function assertedTenant(serverId: string): string | null {
+ return asserted.get(serverId) ?? null;
+}
diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.test.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.test.ts
new file mode 100644
index 000000000..8f2fc597f
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.test.ts
@@ -0,0 +1,251 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { HostUnreachableError } from '@shared/core/remote-hosts/reachability';
+
+const managedServerHostBlocked = vi.hoisted(() => vi.fn((): unknown => null));
+const trackEvent = vi.hoisted(() => vi.fn());
+const createRoomOnServer = vi.hoisted(() => vi.fn());
+const deleteBridge = vi.hoisted(() => vi.fn());
+const deleteRoom = vi.hoisted(() => vi.fn());
+const fetchBridges = vi.hoisted(() => vi.fn());
+const getServer = vi.hoisted(() => vi.fn());
+const getSessionCookie = vi.hoisted(() => vi.fn());
+const requireWorkspace = vi.hoisted(() => vi.fn());
+const switchTenant = vi.hoisted(() => vi.fn());
+// Stubbed rather than reimplemented: what the tests below assert is that the
+// kind reaches the event, not how a row is read as one.
+const serverKindOf = vi.hoisted(() => vi.fn(() => 'remote_managed'));
+
+// Stub the modules the controller imports that would otherwise pull electron /
+// ssh / agent side effects at load.
+vi.mock('@main/core/agents/agent-credentials-slot', () => ({ foreignCredentialsOwner: vi.fn() }));
+vi.mock('@main/core/agents/agent-workdir-fs', () => ({ resolveWorkdirFsFor: vi.fn() }));
+vi.mock('@main/core/agents/known-agent-type', () => ({ knownAgentTypeForProvider: vi.fn() }));
+vi.mock('@main/core/agents/register-agent-identity', () => ({ registerAgentIdentity: vi.fn() }));
+vi.mock('@main/core/agents/write-remote-switch-settings', () => ({
+ writeRemoteSwitchSettings: vi.fn(),
+}));
+vi.mock('@main/core/agents/write-switch-settings', () => ({
+ writeNeutralAgentSettingsFs: vi.fn(),
+ writeSwitchSettings: vi.fn(),
+}));
+vi.mock('@main/core/fs/impl/ssh-fs', () => ({ SshFileSystem: vi.fn() }));
+vi.mock('@main/core/locations/location-transport', () => ({ sshConnectionIdForHost: vi.fn() }));
+vi.mock('@main/core/ssh/connect/connect-agent-ssh', () => ({ ensureSshConnected: vi.fn() }));
+vi.mock('@main/core/telemetry/telemetry-service', () => ({ trackEvent }));
+vi.mock('@main/core/managed-switch-server/managed-server-status', () => ({
+ isManagedServerRunning: vi.fn(() => true),
+ managedServerHostBlocked,
+}));
+// Writes to the app's log file, which a test has no business creating.
+vi.mock('@main/lib/logger', () => ({
+ log: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() },
+}));
+// Reads this install's own agent rows, and through them the database client.
+vi.mock('@main/core/switch-servers/backfill-agent-icons', () => ({ backfillAgentIcons: vi.fn() }));
+vi.mock('@main/core/switch-servers/bridge-home-url', () => ({ withResolvedHomeUrls: vi.fn() }));
+vi.mock('@main/core/switch-servers/create-bridge', () => ({ createBridgeOnServer: vi.fn() }));
+vi.mock('@main/core/switch-servers/create-room', () => ({ createRoomOnServer }));
+vi.mock('@main/core/switch-servers/identities', () => ({
+ claimIdentityOnServer: vi.fn(),
+ searchDirectoryOnServer: vi.fn(),
+}));
+vi.mock('@main/core/switch-servers/update-bridge', () => ({ updateBridgeOnServer: vi.fn() }));
+vi.mock('@main/core/switch-servers/gateway-client', () => ({
+ addRoomAgents: vi.fn(),
+ agentExistsOnServer: vi.fn(),
+ createRoomFromTemplate: vi.fn(),
+ decodeJwtTenantId: vi.fn(() => null),
+ deleteBridge,
+ deleteRoom,
+ fetchAddressingPolicy: vi.fn(),
+ fetchAgentDetail: vi.fn(),
+ fetchAgentRooms: vi.fn(),
+ fetchAgents: vi.fn(),
+ fetchAllExternalUsers: vi.fn(),
+ fetchBridges,
+ fetchBridgeTypes: vi.fn(),
+ fetchMyIdentities: vi.fn(),
+ fetchRoomAgentIds: vi.fn(),
+ fetchRoomDetail: vi.fn(),
+ fetchRoomGroups: vi.fn(),
+ fetchRoomRoles: vi.fn(),
+ fetchRooms: vi.fn(),
+ fetchTemplateSchema: vi.fn(),
+ GatewayError: class GatewayError extends Error {},
+ ownsOwnerAddressedAgent: vi.fn(),
+ releaseBridgeIdentity: vi.fn(),
+ removeRoomAgent: vi.fn(),
+ switchTenant,
+ updateAddressingPolicy: vi.fn(),
+ updateAgentIcon: vi.fn(),
+ updateRoom: vi.fn(),
+}));
+vi.mock('@main/core/switch-servers/servers-store', () => ({
+ getServer,
+ getSessionCookie,
+ serverKindOf,
+}));
+vi.mock('./workspaces-store', () => ({
+ getActiveWorkspaceId: vi.fn(),
+ listWorkspaces: vi.fn(),
+ requireWorkspace,
+ setActiveWorkspaceId: vi.fn(),
+}));
+
+const { workspacesController } = await import('./controller');
+
+function server(overrides: Record<string, unknown>) {
+ return {
+ id: 'srv',
+ name: 'S',
+ gatewayUrl: 'http://localhost:3300',
+ apiUrl: 'http://localhost:8000',
+ managed: false,
+ managementKind: null,
+ sshHost: null,
+ createdAt: '',
+ updatedAt: '',
+ ...overrides,
+ };
+}
+
+/** The workspace every call below names, on the server the test set up. */
+function workspace(tenantId: string | null = null) {
+ return { id: 'ws', serverId: 'srv', name: 'S', tenantId, createdAt: '', updatedAt: '' };
+}
+
+describe('disconnecting a bridge', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ managedServerHostBlocked.mockReturnValue(null);
+ getServer.mockResolvedValue(server({}));
+ requireWorkspace.mockResolvedValue(workspace());
+ fetchBridges.mockResolvedValue([{ id: 'b1', type: 'slack' }]);
+ });
+
+ it('reports a disconnection the gateway carried out', async () => {
+ deleteBridge.mockResolvedValue({ kind: 'deleted' });
+
+ await workspacesController.deleteBridge({ workspaceId: 'ws', bridgeId: 'b1' });
+
+ await vi.waitFor(() =>
+ expect(trackEvent).toHaveBeenCalledWith('bridge_disconnected', {
+ bridge_platform: 'slack',
+ outcome: 'success',
+ })
+ );
+ });
+
+ it('reports a refusal as a failure rather than as a disconnection', async () => {
+ // Admin-only, and the gateway hands back the refusal instead of throwing
+ // it — so the await returns exactly as it does for a bridge that went.
+ deleteBridge.mockResolvedValue({ kind: 'forbidden' });
+
+ await workspacesController.deleteBridge({ workspaceId: 'ws', bridgeId: 'b1' });
+
+ await vi.waitFor(() =>
+ expect(trackEvent).toHaveBeenCalledWith('bridge_disconnected', {
+ bridge_platform: 'slack',
+ outcome: 'failure',
+ })
+ );
+ });
+});
+
+describe('an action a workspace whose host has gone down cannot take', () => {
+ const blocked = {
+ sshHost: 'h',
+ status: 'unreachable',
+ lastError: 'no route to host',
+ lastCheckedAt: null,
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getServer.mockResolvedValue(server({ managed: true, managementKind: 'remote', sshHost: 'h' }));
+ requireWorkspace.mockResolvedValue(workspace());
+ managedServerHostBlocked.mockReturnValue(blocked);
+ // What the gateway does on a host that cannot be reached: the platform is
+ // then unknowable rather than absent.
+ fetchBridges.mockRejectedValue(new Error('no route to host'));
+ });
+
+ it('reports the room it refused to create', async () => {
+ await expect(
+ workspacesController.createRoom({
+ workspaceId: 'ws',
+ name: 'Room',
+ description: '',
+ bridgeId: 'b1',
+ agentIds: ['a1'],
+ })
+ ).rejects.toBeInstanceOf(HostUnreachableError);
+
+ expect(createRoomOnServer).not.toHaveBeenCalled();
+ await vi.waitFor(() =>
+ expect(trackEvent).toHaveBeenCalledWith('room_created', {
+ server_kind: 'remote_managed',
+ bridge_platform: 'unknown',
+ agent_count: 1,
+ has_instructions: false,
+ outcome: 'failure',
+ failure_reason: 'unreachable',
+ })
+ );
+ });
+
+ it('reports the room it refused to delete', async () => {
+ await expect(
+ workspacesController.deleteRoom({ workspaceId: 'ws', roomId: 'r1' })
+ ).rejects.toBeInstanceOf(HostUnreachableError);
+
+ expect(deleteRoom).not.toHaveBeenCalled();
+ expect(trackEvent).toHaveBeenCalledWith('room_deleted', {
+ server_kind: 'remote_managed',
+ outcome: 'failure',
+ });
+ });
+});
+
+/**
+ * The seam's whole point: a call names a workspace, and the session it goes out
+ * on must be selecting that workspace's tenant. A read that answered from the
+ * previously selected tenant would succeed and look right.
+ */
+describe('selecting the workspace’s tenant before the call', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ managedServerHostBlocked.mockReturnValue(null);
+ getServer.mockResolvedValue(server({}));
+ fetchBridges.mockResolvedValue([]);
+ });
+
+ it('switches when the session is selecting another tenant', async () => {
+ requireWorkspace.mockResolvedValue(workspace('tenant-b'));
+ getSessionCookie.mockResolvedValue('cookie-for-tenant-a');
+
+ await workspacesController.listBridges('ws');
+
+ expect(switchTenant).toHaveBeenCalledWith(expect.objectContaining({ id: 'srv' }), 'tenant-b');
+ });
+
+ it('does not switch when the session already selects it', async () => {
+ const { decodeJwtTenantId } = await import('@main/core/switch-servers/gateway-client');
+ vi.mocked(decodeJwtTenantId).mockReturnValue('tenant-b');
+ requireWorkspace.mockResolvedValue(workspace('tenant-b'));
+ getSessionCookie.mockResolvedValue('cookie-for-tenant-b');
+
+ await workspacesController.listBridges('ws');
+
+ expect(switchTenant).not.toHaveBeenCalled();
+ });
+
+ it('asserts nothing for a workspace with no tenant of its own', async () => {
+ requireWorkspace.mockResolvedValue(workspace(null));
+
+ await workspacesController.listBridges('ws');
+
+ expect(switchTenant).not.toHaveBeenCalled();
+ expect(getSessionCookie).not.toHaveBeenCalled();
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts
new file mode 100644
index 000000000..12a137eaf
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts
@@ -0,0 +1,615 @@
+import { backfillAgentIcons } from '@main/core/switch-servers/backfill-agent-icons';
+import { withResolvedHomeUrls } from '@main/core/switch-servers/bridge-home-url';
+import { createBridgeOnServer } from '@main/core/switch-servers/create-bridge';
+import { createRoomOnServer } from '@main/core/switch-servers/create-room';
+import {
+ addRoomAgents,
+ agentExistsOnServer,
+ createRoomFromTemplate,
+ createTemplate,
+ deleteBridge,
+ deleteRoom,
+ deleteTemplate,
+ exportRoomYaml,
+ fetchAddressingPolicy,
+ fetchAgentRooms,
+ fetchAgents,
+ fetchAllExternalUsers,
+ fetchBridges,
+ fetchBridgeTypes,
+ fetchMyIdentities,
+ fetchRoomAgentIds,
+ fetchRoomDetail,
+ fetchRoomGroups,
+ fetchRoomRoles,
+ fetchRooms,
+ fetchTemplateDetail,
+ fetchTemplates,
+ fetchTemplateSchema,
+ GatewayError,
+ ownsOwnerAddressedAgent,
+ releaseBridgeIdentity,
+ removeRoomAgent,
+ type StoredTemplateDetail,
+ type StoredTemplateSummary,
+ type ProvisionFromTemplateResult,
+ type TemplateVisibility,
+ updateAddressingPolicy,
+ updateAgentIcon,
+ updateRoom,
+ updateTemplate,
+} from '@main/core/switch-servers/gateway-client';
+import {
+ claimIdentityOnServer,
+ searchDirectoryOnServer,
+} from '@main/core/switch-servers/identities';
+import { hostUnreachable } from '@main/core/switch-servers/require-server';
+import { serverKindOf } from '@main/core/switch-servers/servers-store';
+import { updateBridgeOnServer } from '@main/core/switch-servers/update-bridge';
+import { bridgePlatformOfType } from '@main/core/telemetry/bridge-platform';
+import type {
+ TelemetryBridgeFailure,
+ TelemetryBridgePlatform,
+ TelemetryOutcome,
+ TelemetryRoomAgentsDirection,
+ TelemetryRoomCreateFailure,
+ TelemetryServerKind,
+} from '@main/core/telemetry/events';
+import { roomAgentsDirectionOf } from '@main/core/telemetry/narrow';
+import { trackEvent } from '@main/core/telemetry/telemetry-service';
+import type {
+ AddressingPolicy,
+ AgentIconBackfill,
+ AgentVerifyResult,
+ BridgeDirectorySearchResult,
+ ClaimIdentityParams,
+ ClaimIdentityResult,
+ CreateBridgeParams,
+ CreateBridgeResult,
+ CreateRoomParams,
+ CreateRoomResult,
+ DeleteBridgeParams,
+ DeleteBridgeResult,
+ LinkedIdentity,
+ RemoteAgentRoom,
+ RemoteAgentSummary,
+ RemoteBridge,
+ RemoteBridgeType,
+ RemoteExternalUser,
+ RemoteRoomDetail,
+ RemoteRoomGroup,
+ RemoteRoomRole,
+ RemoteRoomSummary,
+ SwitchServer,
+ UpdateBridgeParams,
+ UpdateBridgeResult,
+ UpdateRoomParams,
+} from '@shared/core/switch-servers/switch-servers';
+import type { Workspace } from '@shared/core/workspaces/workspaces';
+import { createRPCController } from '@shared/lib/ipc/rpc';
+import {
+ withReachableWorkspaceSession,
+ withWorkspaceSession,
+ workspaceServer,
+} from './workspace-session';
+import { getActiveWorkspaceId, listWorkspaces, setActiveWorkspaceId } from './workspaces-store';
+
+/** A bridge result's discriminant as a code. Never the message beside it. */
+function bridgeFailureReason(kind: string): TelemetryBridgeFailure {
+ switch (kind) {
+ case 'created':
+ return 'none';
+ case 'unauthenticated':
+ return 'unauthenticated';
+ case 'forbidden':
+ return 'forbidden';
+ case 'invalid':
+ return 'invalid';
+ default:
+ return 'error';
+ }
+}
+
+/** A room-create result's discriminant as a code. */
+function roomCreateFailureReason(result: CreateRoomResult): TelemetryRoomCreateFailure {
+ switch (result.kind) {
+ case 'created':
+ return 'none';
+ case 'unauthenticated':
+ return 'unauthenticated';
+ case 'bridge-unavailable':
+ return 'bridge_unavailable';
+ case 'invalid':
+ return 'invalid';
+ default:
+ return 'error';
+ }
+}
+
+/**
+ * Which platform a bridge id is on.
+ *
+ * A lookup rather than a field: these operations take a bridge id, and the type
+ * either never appears (a delete) or appears only on success (a room). Best
+ * effort — an unreachable server yields `unknown` rather than failing the
+ * operation it is only describing.
+ *
+ * **Never awaited by a caller doing real work.** It asks the gateway, and making
+ * someone wait on a network round trip so we can describe what they did would
+ * put reporting in the path of the thing being reported. `reportWithBridge` is
+ * how the answer is used once it arrives.
+ *
+ * It takes its own lease, so it must be started outside one: unawaited inside
+ * another call's lease it would be left addressing whatever workspace the
+ * session had moved on to. Where the answer is only readable before the work —
+ * a delete — read it in that call's lease with
+ * {@link bridgePlatformOnServer} instead.
+ */
+function bridgePlatformOf(
+ workspaceId: string,
+ bridgeId: string | null | undefined
+): Promise<TelemetryBridgePlatform> {
+ if (!bridgeId) return Promise.resolve('unknown');
+ return withWorkspaceSession(workspaceId, fetchBridges)
+ .then((bridges) => bridgePlatformOfType(bridges.find((b) => b.id === bridgeId)?.type))
+ .catch((): TelemetryBridgePlatform => 'unknown');
+}
+
+/** {@link bridgePlatformOf} against a server already leased by the caller. */
+function bridgePlatformOnServer(
+ server: SwitchServer,
+ bridgeId: string | null | undefined
+): Promise<TelemetryBridgePlatform> {
+ if (!bridgeId) return Promise.resolve('unknown');
+ return fetchBridges(server)
+ .then((bridges) => bridgePlatformOfType(bridges.find((b) => b.id === bridgeId)?.type))
+ .catch((): TelemetryBridgePlatform => 'unknown');
+}
+
+/**
+ * Report once the platform is known, without anyone waiting for it.
+ *
+ * The event arrives a moment after the action rather than with it, which costs
+ * nothing: it carries its own timestamp, taken when the work happened.
+ */
+function reportWithBridge(
+ platform: Promise<TelemetryBridgePlatform>,
+ emit: (platform: TelemetryBridgePlatform) => void
+): void {
+ void platform.then(emit).catch(() => {});
+}
+
+/** The same, for a room create whose other properties are already known. */
+function reportRoomCreated(
+ workspaceId: string,
+ bridgeId: string | null | undefined,
+ rest: {
+ server_kind: TelemetryServerKind;
+ agent_count: number;
+ has_instructions: boolean;
+ failure_reason: TelemetryRoomCreateFailure;
+ }
+): void {
+ reportWithBridge(bridgePlatformOf(workspaceId, bridgeId), (bridge_platform) =>
+ trackEvent('room_created', {
+ ...rest,
+ bridge_platform,
+ outcome: rest.failure_reason === 'none' ? 'success' : 'failure',
+ })
+ );
+}
+
+/**
+ * Everything that reads or writes what a workspace owns — its rooms, agents,
+ * bridges and identities.
+ *
+ * Every one of these is addressed by workspace rather than by server, because
+ * that is what the data belongs to: a server can host several workspaces, and
+ * the same call against the same server means a different thing in each. The
+ * server is resolved from the workspace, and the session's selected tenant is
+ * made to match it, inside `withWorkspaceSession` — see there for why that is
+ * the seam and not a courtesy at each call site.
+ *
+ * Registering a server, signing in to one and asking whether it can be reached
+ * are not workspace-scoped and stay in `switch-servers/controller.ts`.
+ */
+export const workspacesController = createRPCController({
+ list: (): Promise<Workspace[]> => listWorkspaces(),
+
+ getActiveId: (): Promise<string | null> => getActiveWorkspaceId(),
+
+ setActive: (workspaceId: string): Promise<void> => setActiveWorkspaceId(workspaceId),
+
+ listAgents: (workspaceId: string): Promise<RemoteAgentSummary[]> =>
+ withWorkspaceSession(workspaceId, fetchAgents),
+
+ listRooms: (workspaceId: string): Promise<RemoteRoomSummary[]> =>
+ withWorkspaceSession(workspaceId, fetchRooms),
+
+ listBridges: (workspaceId: string): Promise<RemoteBridge[]> =>
+ withReachableWorkspaceSession(workspaceId, async (server) =>
+ withResolvedHomeUrls(server, await fetchBridges(server))
+ ),
+
+ listBridgeTypes: (workspaceId: string): Promise<RemoteBridgeType[]> =>
+ withReachableWorkspaceSession(workspaceId, fetchBridgeTypes),
+
+ /**
+ * Attach a collaboration bridge to the chosen workspace (CHOO-1784).
+ *
+ * `params.connectionConfig` carries platform credentials. They cross the IPC
+ * boundary once, on the way out, and are never written to Switch Console's disk
+ * or returned to the renderer — the server stores them. Keep it that way: do
+ * not log `params` here.
+ */
+ createBridge: (params: CreateBridgeParams): Promise<CreateBridgeResult> =>
+ withReachableWorkspaceSession(params.workspaceId, async (server) => {
+ const platform = bridgePlatformOfType(params.bridgeType);
+ let result: CreateBridgeResult;
+ try {
+ result = await createBridgeOnServer(server, {
+ bridgeType: params.bridgeType,
+ displayName: params.displayName,
+ connectionConfig: params.connectionConfig,
+ setAsDefault: params.setAsDefault,
+ channelCreationEnabled: params.channelCreationEnabled,
+ });
+ } catch (error) {
+ trackEvent('bridge_connected', {
+ bridge_platform: platform,
+ outcome: 'failure',
+ failure_reason: 'error',
+ });
+ throw error;
+ }
+ trackEvent('bridge_connected', {
+ bridge_platform: platform,
+ outcome: result.kind === 'created' ? 'success' : 'failure',
+ failure_reason: bridgeFailureReason(result.kind),
+ });
+ return result;
+ }),
+
+ /**
+ * Edit a bridge's operator-controlled switches — today, only whether the
+ * connection may create channels. Admin-only, like registering one; see
+ * `updateBridgeOnServer` for the recoverable-failure mapping.
+ */
+ updateBridge: (params: UpdateBridgeParams): Promise<UpdateBridgeResult> =>
+ withReachableWorkspaceSession(params.workspaceId, (server) =>
+ updateBridgeOnServer(server, {
+ bridgeId: params.bridgeId,
+ channelCreationEnabled: params.channelCreationEnabled,
+ })
+ ),
+
+ /**
+ * Disconnect a messaging app from the chosen workspace. Admin-only, and the
+ * gateway deletes every Switch room on the bridge on the way — see
+ * `deleteBridge`. The renderer owns the confirmation; by the time this runs
+ * the rooms are being given up deliberately.
+ */
+ deleteBridge: (params: DeleteBridgeParams): Promise<DeleteBridgeResult> =>
+ withReachableWorkspaceSession(params.workspaceId, async (server) => {
+ // Read before the delete, because afterwards there is no bridge left to
+ // read a platform from — and awaited, unlike every other report: left to
+ // resolve on its own it would outlive the lease that scopes it to this
+ // workspace. A disconnect is a confirmed, destructive action, not a hot
+ // path, so it can afford the round trip.
+ const platform = await bridgePlatformOnServer(server, params.bridgeId);
+ const result = await deleteBridge(server, params.bridgeId);
+ trackEvent('bridge_disconnected', {
+ bridge_platform: platform,
+ outcome: result.kind === 'deleted' ? 'success' : 'failure',
+ });
+ return result;
+ }),
+
+ /**
+ * Create a room in the chosen workspace, owned by the signed-in user. Room
+ * provisioning stays server-side (`POST /gateway/rooms`); this only maps
+ * recoverable failures onto a typed result the modal can act on.
+ */
+ createRoom: async (params: CreateRoomParams): Promise<CreateRoomResult> => {
+ // A host that has gone down is counted before it is raised, which is why
+ // this is here rather than left to the session seam.
+ const known = await workspaceServer(params.workspaceId);
+
+ // Every report is made out here, after the lease rather than inside it: the
+ // platform lookup behind it takes a lease of its own, and one started from
+ // within this call's would be left addressing whichever workspace the
+ // session had moved on to by the time it ran.
+ const report = (failure_reason: TelemetryRoomCreateFailure) =>
+ reportRoomCreated(params.workspaceId, params.bridgeId, {
+ server_kind: serverKindOf(known),
+ agent_count: params.agentIds.length,
+ has_instructions: (params.instructions?.trim().length ?? 0) > 0,
+ failure_reason,
+ });
+
+ const unreachable = hostUnreachable(known);
+ if (unreachable) {
+ report('unreachable');
+ throw unreachable;
+ }
+
+ let result: CreateRoomResult;
+ try {
+ result = await withWorkspaceSession(params.workspaceId, (server) =>
+ createRoomOnServer(server, {
+ name: params.name,
+ description: params.description,
+ instructions: params.instructions,
+ bridgeId: params.bridgeId,
+ agentIds: params.agentIds,
+ })
+ );
+ } catch (error) {
+ report('error');
+ throw error;
+ }
+
+ report(roomCreateFailureReason(result));
+ return result;
+ },
+
+ createRoomFromTemplate: (
+ workspaceId: string,
+ yamlText: string,
+ inputs: Record<string, string | number | boolean>
+ ): Promise<ProvisionFromTemplateResult> =>
+ withWorkspaceSession(workspaceId, (server) => createRoomFromTemplate(server, yamlText, inputs)),
+
+ fetchTemplateSchema: (workspaceId: string): Promise<Record<string, unknown> | null> =>
+ withWorkspaceSession(workspaceId, fetchTemplateSchema),
+
+ listTemplates: (params: {
+ workspaceId: string;
+ kind?: string;
+ q?: string;
+ }): Promise<StoredTemplateSummary[]> =>
+ withWorkspaceSession(params.workspaceId, (server) =>
+ fetchTemplates(server, { kind: params.kind, q: params.q })
+ ),
+
+ getTemplateDetail: (params: {
+ workspaceId: string;
+ templateId: string;
+ }): Promise<StoredTemplateDetail> =>
+ withWorkspaceSession(params.workspaceId, (server) =>
+ fetchTemplateDetail(server, params.templateId)
+ ),
+
+ deleteTemplate: (params: { workspaceId: string; templateId: string }): Promise<void> =>
+ withWorkspaceSession(params.workspaceId, (server) => deleteTemplate(server, params.templateId)),
+
+ saveTemplate: (params: {
+ workspaceId: string;
+ name: string;
+ description: string;
+ kind: string;
+ content: string;
+ readVisibility?: TemplateVisibility;
+ writeVisibility?: TemplateVisibility;
+ }): Promise<StoredTemplateDetail> => {
+ const { workspaceId, ...template } = params;
+ return withWorkspaceSession(workspaceId, (server) => createTemplate(server, template));
+ },
+
+ updateTemplate: (params: {
+ workspaceId: string;
+ templateId: string;
+ name?: string;
+ description?: string;
+ kind?: string;
+ content?: string;
+ readVisibility?: TemplateVisibility;
+ writeVisibility?: TemplateVisibility;
+ }): Promise<StoredTemplateDetail> => {
+ const { workspaceId, templateId, ...changes } = params;
+ return withWorkspaceSession(workspaceId, (server) =>
+ updateTemplate(server, templateId, changes)
+ );
+ },
+
+ exportRoomYaml: (params: { workspaceId: string; roomId: string }): Promise<string> =>
+ withWorkspaceSession(params.workspaceId, (server) => exportRoomYaml(server, params.roomId)),
+
+ listAgentRooms: (params: { workspaceId: string; agentId: string }): Promise<RemoteAgentRoom[]> =>
+ withWorkspaceSession(params.workspaceId, (server) => fetchAgentRooms(server, params.agentId)),
+
+ listRoomRoles: (params: { workspaceId: string; roomId: string }): Promise<RemoteRoomRole[]> =>
+ withWorkspaceSession(params.workspaceId, (server) => fetchRoomRoles(server, params.roomId)),
+
+ listRoomAgentIds: (params: { workspaceId: string; roomId: string }): Promise<string[]> =>
+ withWorkspaceSession(params.workspaceId, (server) => fetchRoomAgentIds(server, params.roomId)),
+
+ /** One room in full, for its configuration page. */
+ getRoomDetail: (params: { workspaceId: string; roomId: string }): Promise<RemoteRoomDetail> =>
+ withWorkspaceSession(params.workspaceId, (server) => fetchRoomDetail(server, params.roomId)),
+
+ /**
+ * Change a room's own settings. Failures propagate as-is — a user without
+ * write access to the room needs the gateway's refusal, not a saved-looking
+ * field holding a value the server never took.
+ */
+ updateRoom: (params: UpdateRoomParams): Promise<RemoteRoomDetail> =>
+ withReachableWorkspaceSession(params.workspaceId, (server) =>
+ updateRoom(server, params.roomId, {
+ description: params.description,
+ instructions: params.instructions,
+ })
+ ),
+
+ /**
+ * Add agents to a room. Failures propagate as-is: the caller shows the
+ * gateway's own words (e.g. an agent whose server-side client is not running,
+ * which the gateway rejects) rather than a generic message.
+ */
+ addRoomAgents: (params: {
+ workspaceId: string;
+ roomId: string;
+ agentIds: string[];
+ /**
+ * Which screen this came from. The same call serves both, and the
+ * one-agent-to-many-rooms screen loops it once per room — so without this,
+ * adding an agent to five rooms is indistinguishable from five people each
+ * adding one agent.
+ */
+ direction: TelemetryRoomAgentsDirection;
+ }): Promise<void> =>
+ withReachableWorkspaceSession(params.workspaceId, async (server) => {
+ await addRoomAgents(server, params.roomId, params.agentIds);
+ trackEvent('room_agents_added', {
+ agent_count: params.agentIds.length,
+ direction: roomAgentsDirectionOf(params.direction),
+ });
+ }),
+
+ /** Remove one agent from a room. Membership only — the agent is not deleted. */
+ removeRoomAgent: (params: {
+ workspaceId: string;
+ roomId: string;
+ agentId: string;
+ }): Promise<void> =>
+ withReachableWorkspaceSession(params.workspaceId, (server) =>
+ removeRoomAgent(server, params.roomId, params.agentId)
+ ),
+
+ /** Delete a room and everything in it. The gateway enforces who may. */
+ deleteRoom: async (params: { workspaceId: string; roomId: string }): Promise<void> => {
+ const known = await workspaceServer(params.workspaceId);
+ const report = (outcome: TelemetryOutcome) =>
+ trackEvent('room_deleted', { server_kind: serverKindOf(known), outcome });
+
+ // A host that has gone down refuses the deletion as surely as the gateway
+ // can, and the event has an outcome precisely so a refusal is counted.
+ const unreachable = hostUnreachable(known);
+ if (unreachable) {
+ report('failure');
+ throw unreachable;
+ }
+
+ await withWorkspaceSession(params.workspaceId, async (server) => {
+ try {
+ await deleteRoom(server, params.roomId);
+ } catch (error) {
+ report('failure');
+ throw error;
+ }
+ report('success');
+ });
+ },
+
+ listRoomGroups: (workspaceId: string): Promise<RemoteRoomGroup[]> =>
+ withWorkspaceSession(workspaceId, fetchRoomGroups),
+
+ listExternalUsers: (workspaceId: string): Promise<RemoteExternalUser[]> =>
+ withWorkspaceSession(workspaceId, fetchAllExternalUsers),
+
+ /**
+ * Search a bridge's own user directory so the signed-in user can find
+ * themselves before they have ever posted in the chat workspace (CHOO-2137).
+ */
+ searchBridgeDirectory: (params: {
+ workspaceId: string;
+ bridgeId: string;
+ query: string;
+ }): Promise<BridgeDirectorySearchResult> =>
+ withReachableWorkspaceSession(params.workspaceId, (server) =>
+ searchDirectoryOnServer(server, params.bridgeId, params.query)
+ ),
+
+ /** Claim a messaging-app account as the signed-in Switch user's own. */
+ claimBridgeIdentity: async (params: ClaimIdentityParams): Promise<ClaimIdentityResult> => {
+ const result = await withReachableWorkspaceSession(params.workspaceId, (server) =>
+ claimIdentityOnServer(server, {
+ bridgeId: params.bridgeId,
+ externalUserId: params.externalUserId,
+ username: params.username,
+ })
+ );
+ // Reported after the lease, not inside it: the platform lookup takes a lease
+ // of its own, and the bridge is still there to read afterwards.
+ reportWithBridge(bridgePlatformOf(params.workspaceId, params.bridgeId), (bridge_platform) =>
+ trackEvent('bridge_identity_claimed', {
+ bridge_platform,
+ outcome: result.kind === 'claimed' ? 'success' : 'failure',
+ })
+ );
+ return result;
+ },
+
+ /** Give up a claim on a messaging-app account, leaving any other user's claim
+ * on it in place. `userId` is whose claim to drop — null for the signed-in
+ * user, which is the only one this app offers. Failures propagate: unclaiming
+ * is a deliberate act, and reporting success for one that did not happen
+ * would leave the user thinking an agent is no longer reachable by them when
+ * it still is. */
+ releaseBridgeIdentity: (params: {
+ workspaceId: string;
+ bridgeId: string;
+ identityId: string;
+ userId: string | null;
+ }): Promise<void> =>
+ withReachableWorkspaceSession(params.workspaceId, (server) =>
+ releaseBridgeIdentity(server, params.bridgeId, params.identityId, params.userId)
+ ),
+
+ /** The messaging accounts the signed-in user has claimed in this workspace. */
+ listMyIdentities: (workspaceId: string): Promise<LinkedIdentity[]> =>
+ withWorkspaceSession(workspaceId, fetchMyIdentities),
+
+ /** Whether the signed-in user owns an agent here that is set to answer its
+ * owner, which is what makes an unlinked messaging account worth warning
+ * about. One agent-list read, so callers need not ration it. */
+ ownsOwnerAddressedAgent: (workspaceId: string): Promise<boolean> =>
+ withWorkspaceSession(workspaceId, ownsOwnerAddressedAgent),
+
+ getAddressingPolicy: (params: {
+ workspaceId: string;
+ agentId: string;
+ }): Promise<AddressingPolicy | null> =>
+ withWorkspaceSession(params.workspaceId, (server) =>
+ fetchAddressingPolicy(server, params.agentId)
+ ),
+
+ updateAddressingPolicy: (params: {
+ workspaceId: string;
+ agentId: string;
+ policy: AddressingPolicy | null;
+ }): Promise<void> =>
+ withWorkspaceSession(params.workspaceId, (server) =>
+ updateAddressingPolicy(server, params.agentId, params.policy)
+ ),
+
+ /** Give this user's icon-less agents the avatar their name generates. Runs
+ * once per workspace per app run; reports what happened so the caller can say
+ * when the icons did not reach the server. */
+ backfillAgentIcons: (workspaceId: string): Promise<AgentIconBackfill> =>
+ withWorkspaceSession(workspaceId, (server) => backfillAgentIcons(workspaceId, server)),
+
+ /** Set or clear an agent's icon. Returns the agent as the server now holds
+ * it, so the caller refreshes from the stored value rather than the one it
+ * hoped for. */
+ updateAgentIcon: (params: {
+ workspaceId: string;
+ agentId: string;
+ iconUrl: string | null;
+ }): Promise<RemoteAgentSummary> =>
+ withWorkspaceSession(params.workspaceId, (server) =>
+ updateAgentIcon(server, params.agentId, params.iconUrl)
+ ),
+
+ verifyAgent: (params: { workspaceId: string; agentId: string }): Promise<AgentVerifyResult> =>
+ withWorkspaceSession(params.workspaceId, async (server) => {
+ try {
+ return (await agentExistsOnServer(server, params.agentId)) ? 'found' : 'not-found';
+ } catch (cause) {
+ if (cause instanceof GatewayError && cause.kind === 'unauthorized') {
+ return 'unauthenticated';
+ }
+ throw cause;
+ }
+ }),
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/workspace-session.test.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/workspace-session.test.ts
new file mode 100644
index 000000000..716f64940
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/workspace-session.test.ts
@@ -0,0 +1,270 @@
+/**
+ * The seam every tenant-owned gateway call goes through.
+ *
+ * What it has to get right is not visible in any one call: a Switch session
+ * selects one tenant at a time, so the guarantee is about what happens when
+ * calls for two workspaces on the same server overlap. If a switch can land
+ * between another call reading the cookie and sending it, that call quietly
+ * answers with the wrong workspace's data and nothing anywhere reports an
+ * error. These tests drive that overlap deliberately, since it is not a state
+ * the app reaches on demand.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const decodeJwtTenantId = vi.hoisted(() => vi.fn<(jwt: string) => string | null>());
+const switchTenant = vi.hoisted(() =>
+ vi.fn<(server: unknown, tenantId: string) => Promise<void>>()
+);
+const getSessionCookie = vi.hoisted(() => vi.fn<(serverId: string) => Promise<string | null>>());
+const requireWorkspace = vi.hoisted(() => vi.fn());
+const listWorkspacesForServer = vi.hoisted(() => vi.fn());
+const hostUnreachable = vi.hoisted(() => vi.fn((): unknown => null));
+
+vi.mock('@main/core/switch-servers/gateway-client', () => ({ decodeJwtTenantId, switchTenant }));
+vi.mock('@main/core/switch-servers/servers-store', () => ({ getSessionCookie }));
+vi.mock('@main/core/switch-servers/require-server', () => ({
+ hostUnreachable,
+ requireServer: async (serverId: string) => ({ id: serverId, name: serverId }),
+}));
+vi.mock('./workspaces-store', () => ({ requireWorkspace, listWorkspacesForServer }));
+
+import { assertedTenant } from './asserted-tenant';
+import {
+ forgetServerSession,
+ withReachableWorkspaceSession,
+ withWorkspaceSession,
+} from './workspace-session';
+
+const SERVER = 'srv-1';
+
+/**
+ * The tenant the server's session currently selects, as the cookie would carry
+ * it.
+ *
+ * Modelled rather than stubbed away: the seam decides whether to switch by
+ * reading the cookie back, so a `switchTenant` that left it unchanged would
+ * make every call look like a switch and hide the very interleaving these tests
+ * are about.
+ */
+let selected: string | null = null;
+
+/** The rows the seam resolves, keyed by workspace id. */
+const rows = new Map<string, { id: string; serverId: string; tenantId: string | null }>();
+
+function workspace(id: string, tenantId: string | null) {
+ const row = { id, serverId: SERVER, tenantId };
+ rows.set(id, row);
+ return row;
+}
+
+/** A promise plus the handles to settle it, so a call can be held mid-flight. */
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ let reject!: (cause: unknown) => void;
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, resolve, reject };
+}
+
+/**
+ * Let everything that can proceed proceed, so "still pending" means blocked
+ * rather than merely not got to yet. A macrotask boundary, since the admission
+ * queue is several promise hops deep.
+ */
+async function settle(): Promise<void> {
+ for (let i = 0; i < 4; i++) await new Promise((resolve) => setTimeout(resolve, 0));
+}
+
+beforeEach(() => {
+ rows.clear();
+ forgetServerSession(SERVER);
+ // A session that has selected nothing, as it is straight after signing in.
+ selected = null;
+ switchTenant.mockReset().mockImplementation(async (_server: unknown, tenantId: string) => {
+ selected = tenantId;
+ });
+ hostUnreachable.mockReset().mockReturnValue(null);
+ getSessionCookie.mockReset().mockImplementation(async () => `cookie:${selected ?? 'none'}`);
+ decodeJwtTenantId.mockReset().mockImplementation((jwt: string) => {
+ const tenant = jwt.slice('cookie:'.length);
+ return tenant === 'none' ? null : tenant;
+ });
+ requireWorkspace.mockReset().mockImplementation(async (id: string) => {
+ const row = rows.get(id);
+ if (!row) throw new Error(`no workspace ${id}`);
+ return row;
+ });
+ listWorkspacesForServer.mockReset().mockImplementation(async () => [...rows.values()]);
+});
+
+describe('withWorkspaceSession', () => {
+ it('selects the workspace’s tenant before the call goes out', async () => {
+ workspace('ws-a', 'tenant-a');
+ const order: string[] = [];
+ switchTenant.mockImplementation(async () => void order.push('switch'));
+
+ await withWorkspaceSession('ws-a', async (server) => {
+ order.push(`call:${server.id}`);
+ });
+
+ expect(order).toEqual(['switch', `call:${SERVER}`]);
+ expect(switchTenant).toHaveBeenCalledWith(expect.objectContaining({ id: SERVER }), 'tenant-a');
+ });
+
+ it('does not switch when the session already selects that tenant', async () => {
+ workspace('ws-a', 'tenant-a');
+ selected = 'tenant-a';
+
+ await withWorkspaceSession('ws-a', async () => {});
+
+ expect(switchTenant).not.toHaveBeenCalled();
+ });
+
+ /**
+ * The row a server is registered with, before any gateway has been asked.
+ * There is no id to select and nothing to confuse it with, so the call goes
+ * out as it did before workspaces existed.
+ */
+ it('asks a tenant-less workspace’s server without selecting anything', async () => {
+ workspace('ws-only', null);
+
+ await withWorkspaceSession('ws-only', async () => {});
+
+ expect(switchTenant).not.toHaveBeenCalled();
+ });
+
+ it('runs calls on the same tenant at the same time', async () => {
+ workspace('ws-a', 'tenant-a');
+ const first = deferred<void>();
+ const inFlight: string[] = [];
+
+ const a = withWorkspaceSession('ws-a', async () => {
+ inFlight.push('a');
+ await first.promise;
+ });
+ const b = withWorkspaceSession('ws-a', async () => void inFlight.push('b'));
+ await settle();
+
+ // Serialising here would be a correctness-free cost: they name one tenant,
+ // so there is no switch between them to be straddled.
+ expect(inFlight).toEqual(['a', 'b']);
+ expect(switchTenant).toHaveBeenCalledTimes(1);
+
+ first.resolve();
+ await Promise.all([a, b]);
+ });
+
+ /**
+ * The whole point of the lease. `switchTenant` replaces the selection for
+ * every call on that server at once, so letting it run while another
+ * workspace's call is outstanding would answer that call from the new tenant
+ * — the exact silent wrong answer the seam exists to make impossible.
+ */
+ it('holds a switch back until the calls it would disturb are done', async () => {
+ workspace('ws-a', 'tenant-a');
+ workspace('ws-b', 'tenant-b');
+ const holding = deferred<void>();
+ const ranB = vi.fn();
+
+ const a = withWorkspaceSession('ws-a', async () => {
+ await holding.promise;
+ });
+ await settle();
+ const b = withWorkspaceSession('ws-b', ranB);
+ await settle();
+
+ expect(switchTenant).toHaveBeenCalledTimes(1);
+ expect(ranB).not.toHaveBeenCalled();
+
+ holding.resolve();
+ await a;
+ await b;
+
+ expect(switchTenant).toHaveBeenNthCalledWith(2, expect.anything(), 'tenant-b');
+ expect(ranB).toHaveBeenCalled();
+ });
+
+ it('gives the lease up when the call throws, so the next switch is not stuck', async () => {
+ workspace('ws-a', 'tenant-a');
+ workspace('ws-b', 'tenant-b');
+
+ await expect(
+ withWorkspaceSession('ws-a', async () => {
+ throw new Error('the gateway said no');
+ })
+ ).rejects.toThrow('the gateway said no');
+
+ await withWorkspaceSession('ws-b', async () => {});
+
+ expect(switchTenant).toHaveBeenNthCalledWith(2, expect.anything(), 'tenant-b');
+ });
+
+ /**
+ * Read by anything that replaces the cookie underneath a call in flight: a
+ * cookie minted by a fresh login selects no tenant, and handing it back
+ * unchanged would finish the lease against the account's default workspace.
+ */
+ it('publishes the tenant the calls in flight are relying on, and forgets it after', async () => {
+ workspace('ws-a', 'tenant-a');
+ const holding = deferred<void>();
+
+ const call = withWorkspaceSession('ws-a', async () => {
+ await holding.promise;
+ });
+ await settle();
+
+ expect(assertedTenant(SERVER)).toBe('tenant-a');
+
+ holding.resolve();
+ await call;
+
+ expect(assertedTenant(SERVER)).toBeNull();
+ });
+
+ it('wakes a switch queued behind a server that has been removed', async () => {
+ workspace('ws-a', 'tenant-a');
+ workspace('ws-b', 'tenant-b');
+ const holding = deferred<void>();
+
+ const a = withWorkspaceSession('ws-a', async () => {
+ await holding.promise;
+ });
+ await settle();
+ const b = withWorkspaceSession('ws-b', async () => {});
+ await settle();
+
+ // The lease is never given up: the call belongs to a server that is gone.
+ forgetServerSession(SERVER);
+ await expect(b).resolves.toBeUndefined();
+
+ holding.resolve();
+ await a;
+ });
+});
+
+describe('withReachableWorkspaceSession', () => {
+ it('refuses before touching the session when the managed host is down', async () => {
+ workspace('ws-a', 'tenant-a');
+ hostUnreachable.mockReturnValue(new Error('build-box is not reachable'));
+ const ran = vi.fn();
+
+ await expect(withReachableWorkspaceSession('ws-a', ran)).rejects.toThrow('not reachable');
+
+ // No switch means no side effect to undo, and the next call to a reachable
+ // server does not find the session selecting a tenant nobody asked for.
+ expect(switchTenant).not.toHaveBeenCalled();
+ expect(ran).not.toHaveBeenCalled();
+ expect(assertedTenant(SERVER)).toBeNull();
+ });
+
+ it('selects the tenant and runs while the host is up', async () => {
+ workspace('ws-a', 'tenant-a');
+
+ await expect(withReachableWorkspaceSession('ws-a', async () => 'answered')).resolves.toBe(
+ 'answered'
+ );
+ expect(switchTenant).toHaveBeenCalledWith(expect.anything(), 'tenant-a');
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/workspace-session.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/workspace-session.ts
new file mode 100644
index 000000000..c4334a21d
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/workspace-session.ts
@@ -0,0 +1,167 @@
+import { decodeJwtTenantId, switchTenant } from '@main/core/switch-servers/gateway-client';
+import { hostUnreachable, requireServer } from '@main/core/switch-servers/require-server';
+import { getSessionCookie } from '@main/core/switch-servers/servers-store';
+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';
+import { clearAssertedTenant, setAssertedTenant } from './asserted-tenant';
+import { requireWorkspace } from './workspaces-store';
+
+/**
+ * Calls in flight on a server's current tenant selection, and the queue that
+ * changes it.
+ *
+ * A server session selects one tenant at a time, so a workspace-scoped call is
+ * only addressing the workspace it names while that selection matches. Calls
+ * that share the selection run in parallel and hold a lease; changing the
+ * selection waits for every lease to be given up, so a switch can never land
+ * between another call reading the cookie and sending it.
+ */
+type ServerSession = {
+ leases: number;
+ /** Resolvers waiting for `leases` to reach zero. */
+ idle: Array<() => void>;
+};
+
+const sessions = new Map<string, ServerSession>();
+
+/** Serialises the decision to switch, per server — never the calls themselves. */
+const admissions = new Map<string, Promise<unknown>>();
+
+function sessionFor(serverId: string): ServerSession {
+ let session = sessions.get(serverId);
+ if (!session) {
+ session = { leases: 0, idle: [] };
+ sessions.set(serverId, session);
+ }
+ return session;
+}
+
+function release(serverId: string, session: ServerSession): void {
+ session.leases -= 1;
+ if (session.leases > 0) return;
+ for (const resolve of session.idle.splice(0)) resolve();
+ clearAssertedTenant(serverId);
+}
+
+/**
+ * Drop everything held for a server that no longer exists.
+ *
+ * Nothing prunes these as calls finish — an entry is the server's, not a call's
+ * — so a removal is the one moment they can go. Left behind, a lease that leaked
+ * would be inherited by whatever next holds the id, and a switch waiting for it
+ * to be given up would wait for a call that ended with the server.
+ */
+export function forgetServerSession(serverId: string): void {
+ const session = sessions.get(serverId);
+ // Waiters first: a switch queued behind a server that has just gone would
+ // otherwise never be woken at all.
+ if (session) for (const resolve of session.idle.splice(0)) resolve();
+ sessions.delete(serverId);
+ admissions.delete(serverId);
+ clearAssertedTenant(serverId);
+}
+
+function whenIdle(session: ServerSession): Promise<void> {
+ if (session.leases === 0) return Promise.resolve();
+ return new Promise<void>((resolve) => session.idle.push(resolve));
+}
+
+function admit<T>(serverId: string, task: () => Promise<T>): Promise<T> {
+ const queued = (admissions.get(serverId) ?? Promise.resolve()).then(task, task);
+ admissions.set(
+ serverId,
+ queued.then(
+ () => {},
+ () => {}
+ )
+ );
+ return queued;
+}
+
+/**
+ * Take a lease on `server`'s session with `tenantId` selected, switching the
+ * selection first if it is something else.
+ *
+ * The caller must release the lease. Never call this from inside a leased call
+ * on the same server: a switch waits for outstanding leases, and a call waiting
+ * on its own would wait forever.
+ */
+async function acquire(server: SwitchServer, tenantId: string | null): Promise<ServerSession> {
+ const session = sessionFor(server.id);
+ await admit(server.id, async () => {
+ if (tenantId !== null) {
+ const cookie = await getSessionCookie(server.id);
+ if (!cookie || decodeJwtTenantId(cookie) !== tenantId) {
+ await whenIdle(session);
+ await switchTenant(server, tenantId);
+ }
+ setAssertedTenant(server.id, tenantId);
+ }
+ session.leases += 1;
+ });
+ return session;
+}
+
+/**
+ * The server hosting a workspace, with no session work done.
+ *
+ * For the callers that have to know which server they are about to address
+ * before they address it — the ones that report their own outcome, and so must
+ * be able to count a refusal the session seam would otherwise raise past them.
+ */
+export async function workspaceServer(workspaceId: string): Promise<SwitchServer> {
+ const workspace = await requireWorkspace(workspaceId);
+ return requireServer(workspace.serverId);
+}
+
+/**
+ * Run `fn` against the server hosting `workspaceId`, with that workspace's
+ * tenant selected on the session.
+ *
+ * This is the seam every call that reads or writes tenant-owned data goes
+ * through — rooms, agents, bridges, identities. Without it the renderer showing
+ * one workspace while the session still selects another is invisible: every
+ * call succeeds and answers with the other workspace's data. Making the
+ * selection part of resolving the workspace makes that impossible rather than
+ * something a bug report eventually surfaces.
+ *
+ * A workspace that has not been matched to a tenant yet asserts nothing — there
+ * is no id to select, and the call goes out against whatever the session
+ * resolves, which is the single membership that produced the row. It still
+ * takes a lease, so it cannot straddle another workspace's switch.
+ */
+export async function withWorkspaceSession<T>(
+ workspaceId: string,
+ fn: (server: SwitchServer) => Promise<T>
+): Promise<T> {
+ const workspace = await requireWorkspace(workspaceId);
+ const server = await requireServer(workspace.serverId);
+ const session = await acquire(server, workspace.tenantId);
+ try {
+ return await fn(server);
+ } finally {
+ release(server.id, session);
+ }
+}
+
+/**
+ * {@link withWorkspaceSession}, refusing to touch the gateway while the host
+ * the server is managed on is unreachable (CHOO-1780).
+ *
+ * Checked before the session is acquired, so an unreachable host costs no
+ * switch and starts no side effect it cannot finish.
+ */
+export async function withReachableWorkspaceSession<T>(
+ workspaceId: string,
+ fn: (server: SwitchServer) => Promise<T>
+): Promise<T> {
+ const workspace = await requireWorkspace(workspaceId);
+ const server = await requireServer(workspace.serverId);
+ const unreachable = hostUnreachable(server);
+ if (unreachable) throw unreachable;
+ const session = await acquire(server, workspace.tenantId);
+ try {
+ return await fn(server);
+ } finally {
+ release(server.id, session);
+ }
+}
diff --git a/console/apps/switch-console-desktop/src/main/rpc.ts b/console/apps/switch-console-desktop/src/main/rpc.ts
index 4893c74dd..404a6e31e 100644
--- a/console/apps/switch-console-desktop/src/main/rpc.ts
+++ b/console/apps/switch-console-desktop/src/main/rpc.ts
@@ -20,6 +20,7 @@ import { switchServersController } from './core/switch-servers/controller';
import { telemetryController } from './core/telemetry/controller';
import { updateController } from './core/updates/controller';
import { viewStateController } from './core/view-state/controller';
+import { workspacesController } from './core/workspaces/controller';
export const rpcRouter = createRPCRouter({
sdkHost: sdkHostController,
@@ -37,6 +38,7 @@ export const rpcRouter = createRPCRouter({
switchRooms: switchRoomsController,
switchServers: switchServersController,
agentTypes: agentTypesController,
+ workspaces: workspacesController,
localSwitchServer: localSwitchServerController,
remoteSwitchServer: remoteSwitchServerController,
remoteHosts: remoteHostsController,
diff --git a/console/apps/switch-console-desktop/src/renderer/features/command-palette/command-palette-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/command-palette/command-palette-modal.tsx
index 42ee93357..f64a11142 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/command-palette/command-palette-modal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/command-palette/command-palette-modal.tsx
@@ -194,7 +194,7 @@ export function CommandPaletteModal({
// Search spans every server, but the sidebar only loads the one it is showing
// — so the others' rooms are pulled here, by the feature that needs them.
useEffect(() => {
- void switchRoomsStore.loadRoomsOnAllServers();
+ void switchRoomsStore.loadRoomsInAllWorkspaces();
}, []);
// Prefetch recents immediately on mount so the empty-query view is instant.
@@ -272,7 +272,7 @@ export function CommandPaletteModal({
// span every server, not the active one: you search precisely because you do
// not know where a thing is.
const roomResults = useObserver(() =>
- matchRooms(switchRoomsStore.listedRoomsOnAllServers, debouncedQuery)
+ matchRooms(switchRoomsStore.listedRoomsInAllWorkspaces, debouncedQuery)
);
const serverResults = useObserver(() => matchServers(switchServersStore.servers, debouncedQuery));
diff --git a/console/apps/switch-console-desktop/src/renderer/features/command-palette/palette-agent-item.tsx b/console/apps/switch-console-desktop/src/renderer/features/command-palette/palette-agent-item.tsx
index a8e7ab034..c2ba81298 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/command-palette/palette-agent-item.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/command-palette/palette-agent-item.tsx
@@ -5,7 +5,7 @@ import { agentsStore } from '@renderer/features/locations/stores/agents-store';
import { AgentAvatar } from '@renderer/lib/components/agent-avatar';
import { AgentIcon } from '@renderer/lib/components/agent-icon';
import { sidebarStore } from '@renderer/lib/stores/app-state';
-import { useAgentIconUrl } from '@renderer/lib/stores/use-remote-agents';
+import { useAgentIconUrl } from '@renderer/lib/stores/use-workspace-agents';
import type { SearchItem } from '@shared/core/search';
import { PALETTE_ITEM_CLASS } from './palette-item-styles';
@@ -14,7 +14,7 @@ import { PALETTE_ITEM_CLASS } from './palette-item-styles';
* agent's own face leads, and what it runs on follows its name as a small mark.
*
* A row of its own rather than a branch of `PaletteKindIcon`, because the
- * chosen icon comes from a query keyed by server and a hook cannot be called
+ * chosen icon comes from a query keyed by workspace and a hook cannot be called
* from inside a switch. An agent this app does not hold — a hit whose local row
* has gone — still gets the bot drawn from its name, which is the same face the
* Switch bridges show.
@@ -29,7 +29,7 @@ export const PaletteAgentItem = observer(function PaletteAgentItem({
onSelect: () => void;
}) {
const agent = agentsStore.agentById(item.id);
- const iconUrl = useAgentIconUrl(agent?.serverId ?? null, agent?.switchAgentId ?? null);
+ const iconUrl = useAgentIconUrl(agent?.workspaceId ?? null, agent?.switchAgentId ?? null);
return (
<Command.Item value={value} onSelect={onSelect} className={PALETTE_ITEM_CLASS}>
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.tsx
index b206cd4bb..87d968d42 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
@@ -13,6 +13,7 @@ import {
} from '@renderer/features/remote-hosts/host-readiness-notice';
import { policyHasDeadRule } from '@renderer/features/switch-servers/addressing-policy-editor';
import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { ProviderConnectionStatus } from '@renderer/lib/components/provider-connection-status';
import { describeFailure } from '@renderer/lib/errors/describe-failure';
import { toast } from '@renderer/lib/hooks/use-toast';
@@ -23,7 +24,7 @@ import {
useShowModal,
type BaseModalProps,
} from '@renderer/lib/modal/modal-provider';
-import { useRemoteAgents } from '@renderer/lib/stores/use-remote-agents';
+import { useWorkspaceAgents } from '@renderer/lib/stores/use-workspace-agents';
import { Button } from '@renderer/lib/ui/button';
import { ConfirmButton } from '@renderer/lib/ui/confirm-button';
import {
@@ -137,7 +138,7 @@ export const AddAgentModal = observer(function AddAgentModal({
// Names already taken on the server, so a clash is refused before anything
// is created rather than reported by the server afterwards.
- const remoteAgents = useRemoteAgents(pickState.serverId);
+ const remoteAgents = useWorkspaceAgents(workspacesStore.soleIdOnServer(pickState.serverId));
const takenNames = useMemo(
() => new Set((remoteAgents.data ?? []).map((a) => a.name)),
[remoteAgents.data]
@@ -386,9 +387,13 @@ export const AddAgentModal = observer(function AddAgentModal({
setSubmitState('idle');
return;
}
- if (form.addressingPolicy !== null && result.agent.switchAgentId) {
- await rpc.switchServers.updateAddressingPolicy({
- serverId: pickState.serverId,
+ if (
+ form.addressingPolicy !== null &&
+ result.agent.switchAgentId &&
+ result.agent.workspaceId
+ ) {
+ await rpc.workspaces.updateAddressingPolicy({
+ workspaceId: result.agent.workspaceId,
agentId: result.agent.switchAgentId,
policy: form.addressingPolicy,
});
@@ -599,7 +604,7 @@ export const AddAgentModal = observer(function AddAgentModal({
{canConfigureAgent && (
<AgentSettingsSection
form={form}
- serverId={pickState.serverId}
+ workspaceId={workspacesStore.soleIdOnServer(pickState.serverId)}
onAddServer={() => showAddServerModal({})}
onOpenMessagingApps={() => {
onClose();
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsx
index 428feb0e5..7a7c13c41 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsx
@@ -9,6 +9,7 @@ import { switchServersStore } from '@renderer/features/switch-servers/switch-ser
import { useMyIdentities } from '@renderer/features/switch-servers/use-my-identities';
import { AgentIconPicker } from '@renderer/lib/components/agent-icon-picker';
import { rpc } from '@renderer/lib/ipc';
+import { useWorkspaceAgents } from '@renderer/lib/stores/use-workspace-agents';
import { Alert, AlertAction, AlertDescription } from '@renderer/lib/ui/alert';
import { Button } from '@renderer/lib/ui/button';
import { DisclosureRow } from '@renderer/lib/ui/disclosure-row';
@@ -29,12 +30,12 @@ import type { ConfigureAgentFormState } from './modes';
*/
export const AgentSettingsSection = observer(function AgentSettingsSection({
form,
- serverId,
+ workspaceId,
onAddServer,
onOpenMessagingApps,
}: {
form: ConfigureAgentFormState;
- serverId: string | null;
+ workspaceId: string | null;
onAddServer: () => void;
onOpenMessagingApps: () => void;
}) {
@@ -48,27 +49,24 @@ export const AgentSettingsSection = observer(function AgentSettingsSection({
const servers = switchServersStore.servers;
- // Selector data for the addressing-policy editor, scoped to the chosen server.
+ // Selector data for the addressing-policy editor, scoped to the workspace the
+ // chosen server is in scope for.
const roomsQuery = useQuery({
- queryKey: ['remote-rooms', serverId],
- queryFn: () => rpc.switchServers.listRemoteRooms(serverId as string),
- enabled: serverId !== null,
+ queryKey: ['remote-rooms', workspaceId],
+ queryFn: () => rpc.workspaces.listRooms(workspaceId as string),
+ enabled: workspaceId !== null,
});
const groupsQuery = useQuery({
- queryKey: ['remote-room-groups', serverId],
- queryFn: () => rpc.switchServers.listRemoteRoomGroups(serverId as string),
- enabled: serverId !== null,
+ queryKey: ['remote-room-groups', workspaceId],
+ queryFn: () => rpc.workspaces.listRoomGroups(workspaceId as string),
+ enabled: workspaceId !== null,
});
const usersQuery = useQuery({
- queryKey: ['remote-external-users', serverId],
- queryFn: () => rpc.switchServers.listRemoteExternalUsers(serverId as string),
- enabled: serverId !== null,
- });
- const agentsQuery = useQuery({
- queryKey: ['remote-agents', serverId],
- queryFn: () => rpc.switchServers.listRemoteAgents(serverId as string),
- enabled: serverId !== null,
+ queryKey: ['remote-external-users', workspaceId],
+ queryFn: () => rpc.workspaces.listExternalUsers(workspaceId as string),
+ enabled: workspaceId !== null,
});
+ const agentsQuery = useWorkspaceAgents(workspaceId);
const roomOptions: OptionItem[] = (roomsQuery.data ?? []).map((r) => ({
id: r.id,
label: r.name,
@@ -88,11 +86,11 @@ export const AgentSettingsSection = observer(function AgentSettingsSection({
// Read here rather than inside the editor so the owner-only default can be
// questioned before the agent exists, not after it has gone quiet.
- const { identities } = useMyIdentities(serverId);
+ const { identities } = useMyIdentities(workspaceId);
const bridgesQuery = useQuery({
- queryKey: ['remote-bridges', serverId],
- queryFn: () => rpc.switchServers.listRemoteBridges(serverId as string),
- enabled: serverId !== null,
+ queryKey: ['remote-bridges', workspaceId],
+ queryFn: () => rpc.workspaces.listBridges(workspaceId as string),
+ enabled: workspaceId !== null,
});
const unlinkedApps =
identities === null || bridgesQuery.data === undefined
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/location-titlebar.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/location-titlebar.tsx
index 4dc8dfbfe..1745fd09f 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/location-titlebar.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/location-titlebar.tsx
@@ -19,7 +19,7 @@ import { useToast } from '@renderer/lib/hooks/use-toast';
import { rpc } from '@renderer/lib/ipc';
import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';
import { useShowModal } from '@renderer/lib/modal/modal-provider';
-import { useAgentIconUrl } from '@renderer/lib/stores/use-remote-agents';
+import { useAgentIconUrl } from '@renderer/lib/stores/use-workspace-agents';
import { Button } from '@renderer/lib/ui/button';
import {
DropdownMenu,
@@ -38,7 +38,7 @@ import type { Agent } from '@shared/core/agents/agents';
*/
const AgentCrumb = observer(function AgentCrumb({ agent }: { agent: Agent | null }) {
const label = agent?.name ?? 'Agent';
- const iconUrl = useAgentIconUrl(agent?.serverId ?? null, agent?.switchAgentId ?? null);
+ const iconUrl = useAgentIconUrl(agent?.workspaceId ?? null, agent?.switchAgentId ?? null);
return (
<TitlebarBreadcrumb
crumbs={[
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-page-header.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-page-header.tsx
index ee7380ce1..896aff096 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-page-header.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-page-header.tsx
@@ -8,7 +8,10 @@ import { useToast } from '@renderer/lib/hooks/use-toast';
import { rpc } from '@renderer/lib/ipc';
import { useParams } from '@renderer/lib/layout/navigation-provider';
import { useShowModal } from '@renderer/lib/modal/modal-provider';
-import { remoteAgentsQueryKey, useRemoteAgents } from '@renderer/lib/stores/use-remote-agents';
+import {
+ workspaceAgentsQueryKey,
+ useWorkspaceAgents,
+} from '@renderer/lib/stores/use-workspace-agents';
import { Badge } from '@renderer/lib/ui/badge';
import { Button } from '@renderer/lib/ui/button';
import { providerDisplayName } from '@shared/core/providers/agent-provider-registry';
@@ -35,8 +38,8 @@ export const AgentPageHeader = observer(function AgentPageHeader() {
const agentMachineName = agent?.name ?? agentName ?? 'Agent';
const provider = agent?.providerId ? providerDisplayName(agent.providerId) : null;
- const serverId = agent?.serverId ?? null;
- const { data: remoteAgents } = useRemoteAgents(serverId);
+ const workspaceId = agent?.workspaceId ?? null;
+ const { data: remoteAgents } = useWorkspaceAgents(workspaceId);
const remote = (remoteAgents ?? []).find((a) => a.id === agent?.switchAgentId) ?? null;
const description = remote?.description ?? null;
@@ -45,7 +48,7 @@ export const AgentPageHeader = observer(function AgentPageHeader() {
// Show machine name as subtitle only if displayName exists and differs from name
const showMachineName = remote?.displayName != null && remote.displayName !== agentMachineName;
- const roomable = serverId !== null && agent?.switchAgentId != null;
+ const roomable = workspaceId !== null && agent?.switchAgentId != null;
const queryClient = useQueryClient();
const { toast } = useToast();
@@ -55,10 +58,10 @@ export const AgentPageHeader = observer(function AgentPageHeader() {
* request that can fail. It is reported rather than swallowed: a picture
* that silently reverts on the next refresh is worse than an error. */
const changeIcon = async (iconUrl: string | null) => {
- if (serverId === null || switchAgentId === null) return;
+ if (workspaceId === null || switchAgentId === null) return;
try {
- await rpc.switchServers.updateAgentIcon({ serverId, agentId: switchAgentId, iconUrl });
- await queryClient.invalidateQueries({ queryKey: remoteAgentsQueryKey(serverId) });
+ await rpc.workspaces.updateAgentIcon({ workspaceId, agentId: switchAgentId, iconUrl });
+ await queryClient.invalidateQueries({ queryKey: workspaceAgentsQueryKey(workspaceId) });
} catch (cause) {
const { headline, detail } = describeFailure(cause, "Could not change the agent's icon.");
toast({
@@ -69,7 +72,7 @@ export const AgentPageHeader = observer(function AgentPageHeader() {
}
};
- const editableIcon = serverId !== null && switchAgentId !== null;
+ const editableIcon = workspaceId !== null && switchAgentId !== null;
return (
<header className="flex shrink-0 items-start gap-5 pt-10">
@@ -117,7 +120,7 @@ export const AgentPageHeader = observer(function AgentPageHeader() {
variant="outline"
onClick={() =>
showAddToRoom({
- serverId: serverId as string,
+ workspaceId: workspaceId as string,
switchAgentId: agent.switchAgentId as string,
agentName: title,
})
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section.tsx
index fc9f8de75..fb9c4a4c2 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section.tsx
@@ -32,7 +32,7 @@ export function AddressingPolicySettingsSection({
});
const switchAgents = (agents ?? []).filter(
- (a) => a.serverId && a.switchAgentId && (!agentId || a.id === agentId)
+ (a) => a.workspaceId && a.switchAgentId && (!agentId || a.id === agentId)
);
if (switchAgents.length === 0) return null;
@@ -41,6 +41,7 @@ export function AddressingPolicySettingsSection({
{switchAgents.map((agent) => (
<AddressingPolicyRow
key={agent.id}
+ workspaceId={agent.workspaceId as string}
serverId={agent.serverId as string}
agentId={agent.switchAgentId as string}
agentName={agent.name}
@@ -52,11 +53,15 @@ export function AddressingPolicySettingsSection({
}
function AddressingPolicyRow({
+ workspaceId,
serverId,
agentId,
agentName,
showName,
}: {
+ workspaceId: string;
+ /** Only for the link out to the server's messaging apps, which is a page
+ * about the gateway rather than about this workspace's data. */
serverId: string;
agentId: string;
agentName: string;
@@ -64,37 +69,37 @@ function AddressingPolicyRow({
}) {
const queryClient = useQueryClient();
const { navigate } = useNavigate();
- const { identities } = useMyIdentities(serverId);
+ const { identities } = useMyIdentities(workspaceId);
const [draft, setDraft] = useState<AddressingPolicy | null>(null);
const [dirty, setDirty] = useState(false);
const [error, setError] = useState<string | null>(null);
- const policyKey = ['agent-addressing-policy', serverId, agentId];
+ const policyKey = ['agent-addressing-policy', workspaceId, agentId];
const { data: saved } = useQuery({
queryKey: policyKey,
- queryFn: () => rpc.switchServers.getAddressingPolicy({ serverId, agentId }),
+ queryFn: () => rpc.workspaces.getAddressingPolicy({ workspaceId, agentId }),
});
const rooms = useQuery({
- queryKey: ['remote-rooms', serverId],
- queryFn: () => rpc.switchServers.listRemoteRooms(serverId),
+ queryKey: ['remote-rooms', workspaceId],
+ queryFn: () => rpc.workspaces.listRooms(workspaceId),
});
const groups = useQuery({
- queryKey: ['remote-room-groups', serverId],
- queryFn: () => rpc.switchServers.listRemoteRoomGroups(serverId),
+ queryKey: ['remote-room-groups', workspaceId],
+ queryFn: () => rpc.workspaces.listRoomGroups(workspaceId),
});
const users = useQuery({
- queryKey: ['remote-external-users', serverId],
- queryFn: () => rpc.switchServers.listRemoteExternalUsers(serverId),
+ queryKey: ['remote-external-users', workspaceId],
+ queryFn: () => rpc.workspaces.listExternalUsers(workspaceId),
});
const remoteAgents = useQuery({
- queryKey: ['remote-agents', serverId],
- queryFn: () => rpc.switchServers.listRemoteAgents(serverId),
+ queryKey: ['remote-agents', workspaceId],
+ queryFn: () => rpc.workspaces.listAgents(workspaceId),
});
const bridges = useQuery({
- queryKey: ['remote-bridges', serverId],
- queryFn: () => rpc.switchServers.listRemoteBridges(serverId),
+ queryKey: ['remote-bridges', workspaceId],
+ queryFn: () => rpc.workspaces.listBridges(workspaceId),
});
- // The apps on this server the user has claimed no account on. Null until both
+ // The apps in this workspace the user has claimed no account on. Null until both
// halves have arrived: a bridge list without the identities would read as
// every app unlinked.
const unlinkedApps =
@@ -109,7 +114,7 @@ function AddressingPolicyRow({
const mutation = useMutation({
mutationFn: (policy: AddressingPolicy | null) =>
- rpc.switchServers.updateAddressingPolicy({ serverId, agentId, policy }),
+ rpc.workspaces.updateAddressingPolicy({ workspaceId, agentId, policy }),
onSuccess: (_result, policy) => {
queryClient.setQueryData(policyKey, policy);
setDirty(false);
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.ts
index 42a27c5bd..8771222b6 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
@@ -97,6 +97,25 @@ export class AgentsStore {
return matching.sort((a, b) => a.name.localeCompare(b.name));
}
+ /**
+ * This install's agents in a given workspace — the ones the room views may
+ * list and offer.
+ *
+ * The workspace-addressed counterpart of {@link agentsOnServer}, and what a
+ * view scoped to a workspace asks for: its rooms and their members are that
+ * workspace's, and a server hosting several would otherwise offer agents from
+ * all of them.
+ */
+ agentsInWorkspace(workspaceId: string): Agent[] {
+ const matching: Agent[] = [];
+ for (const agents of this.byLocation.values()) {
+ for (const agent of agents) {
+ if (agent.workspaceId === workspaceId && agent.switchAgentId) matching.push(agent);
+ }
+ }
+ return matching.sort((a, b) => a.name.localeCompare(b.name));
+ }
+
/** A location's agents that belong to one server — what the sidebar renders
* under that server. Agents in the same directory registered elsewhere are not
* this server's to show. */
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.ts
index 1b79489ee..b808d4669 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
@@ -33,7 +33,7 @@ export function useOnboardingProgress(): OnboardingProgress {
addServer: switchServersStore.servers.length > 0,
agentProviders: (agentTypes ?? []).some((type) => type.available),
onboardAgents: appState.locations.locations.size > 0,
- createRoom: switchRoomsStore.listedRoomsOnAllServers.length > 0,
+ createRoom: switchRoomsStore.listedRoomsInAllWorkspaces.length > 0,
};
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/load-existing-agents-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/load-existing-agents-section.tsx
index 5b2890e03..b947f3e3e 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/load-existing-agents-section.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/load-existing-agents-section.tsx
@@ -64,10 +64,14 @@ export const LOAD_AGENTS_QUERY_KEY = 'load-existing-agents';
export function LoadExistingAgentsSection({
sshHost,
serverId,
+ workspaceId,
initiallyOpen = false,
}: {
sshHost: string;
serverId: string;
+ /** The workspace whose agents are discovered. One server can host several,
+ * and each answers `GET /agents` with its own list. */
+ workspaceId: string;
initiallyOpen?: boolean;
}) {
const [isOpen, setIsOpen] = useState(initiallyOpen);
@@ -76,8 +80,8 @@ export function LoadExistingAgentsSection({
const showRemoveConfig = useShowModal('removeAgentConfigModal');
const discovery = useQuery({
- queryKey: [LOAD_AGENTS_QUERY_KEY, sshHost, serverId],
- queryFn: () => rpc.agents.discoverLoadableAgentsOnHost({ sshHost, serverId }),
+ queryKey: [LOAD_AGENTS_QUERY_KEY, sshHost, workspaceId],
+ queryFn: () => rpc.agents.discoverLoadableAgentsOnHost({ sshHost, workspaceId }),
enabled: isOpen && scanRequested,
});
@@ -194,7 +198,7 @@ export function LoadExistingAgentsSection({
// waiting for the SSH round trip that a full refetch requires.
const loaded = new Set(names);
queryClient.setQueryData(
- [LOAD_AGENTS_QUERY_KEY, sshHost, serverId],
+ [LOAD_AGENTS_QUERY_KEY, sshHost, workspaceId],
(prev: { agents: LoadableAgentRow[]; serverApiUrl: string } | undefined) => {
if (!prev) return prev;
return {
@@ -216,7 +220,9 @@ export function LoadExistingAgentsSection({
)
);
- void queryClient.invalidateQueries({ queryKey: [LOAD_AGENTS_QUERY_KEY, sshHost, serverId] });
+ void queryClient.invalidateQueries({
+ queryKey: [LOAD_AGENTS_QUERY_KEY, sshHost, workspaceId],
+ });
},
onError: (error) => {
toast({
@@ -246,7 +252,9 @@ export function LoadExistingAgentsSection({
next.delete(key);
return next;
});
- void queryClient.invalidateQueries({ queryKey: [LOAD_AGENTS_QUERY_KEY, sshHost, serverId] });
+ void queryClient.invalidateQueries({
+ queryKey: [LOAD_AGENTS_QUERY_KEY, sshHost, workspaceId],
+ });
},
onError: (error) => {
toast({
@@ -271,7 +279,8 @@ export function LoadExistingAgentsSection({
const [manualDir, setManualDir] = useState('');
const manualScan = useMutation({
- mutationFn: (dir: string) => rpc.agents.discoverLoadableAgentsInDir({ sshHost, dir, serverId }),
+ mutationFn: (dir: string) =>
+ rpc.agents.discoverLoadableAgentsInDir({ sshHost, dir, workspaceId }),
onSuccess: (found) => {
setManualServerApiUrl(found.serverApiUrl);
setManualAgents((prev) => {
@@ -287,9 +296,9 @@ export function LoadExistingAgentsSection({
const deepScan = useMutation({
mutationFn: () =>
- rpc.agents.discoverLoadableAgentsOnHost({ sshHost, serverId, includeHomeScan: true }),
+ rpc.agents.discoverLoadableAgentsOnHost({ sshHost, workspaceId, includeHomeScan: true }),
onSuccess: (result) => {
- queryClient.setQueryData([LOAD_AGENTS_QUERY_KEY, sshHost, serverId], result);
+ queryClient.setQueryData([LOAD_AGENTS_QUERY_KEY, sshHost, workspaceId], result);
},
});
@@ -404,7 +413,7 @@ export function LoadExistingAgentsSection({
disabled={discovery.isFetching}
onClick={() =>
void queryClient.invalidateQueries({
- queryKey: [LOAD_AGENTS_QUERY_KEY, sshHost, serverId],
+ queryKey: [LOAD_AGENTS_QUERY_KEY, sshHost, workspaceId],
})
}
>
diff --git a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-host-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-host-view.tsx
index b8b34f509..627fed353 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-host-view.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-host-view.tsx
@@ -32,6 +32,7 @@ import { StatusBadge } from '@renderer/lib/ui/status-badge';
import { deriveHostStatus } from '@shared/core/remote-hosts/host-status';
import { isHostBlocked } from '@shared/core/remote-hosts/reachability';
import { switchServersStore } from '../../switch-servers/switch-servers-store';
+import { workspacesStore } from '../../workspaces/workspaces-store';
import { hostReachabilityStore } from '../host-reachability-store';
import { hostSetupStore } from '../host-setup-store';
import { HostUnreachablePanel } from '../host-unreachable-panel';
@@ -113,6 +114,10 @@ export const RemoteHostMainPanel = observer(function RemoteHostMainPanel() {
if (managed) return managed.id;
return activeServer?.id ?? servers[0]?.id ?? null;
}, [sshHost, servers, activeServer]);
+ // Which of that server's workspaces the discovery below asks. `GET /agents`
+ // answers for one tenant, so without it the list would be whichever workspace
+ // the session last selected.
+ const workspaceId = workspacesStore.soleIdOnServer(serverId);
const status = deriveHostStatus(reachability, plan.data ?? null);
const { prerequisites, agentTypes } = useMemo(
@@ -280,10 +285,11 @@ export const RemoteHostMainPanel = observer(function RemoteHostMainPanel() {
</section>
)}
- {serverId && (
+ {serverId && workspaceId && (
<LoadExistingAgentsSection
sshHost={sshHost}
serverId={serverId}
+ workspaceId={workspaceId}
initiallyOpen={justAdded}
/>
)}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/room-templates/entity-fields.tsx b/console/apps/switch-console-desktop/src/renderer/features/room-templates/entity-fields.tsx
index 88b0d245d..05d7ed228 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/room-templates/entity-fields.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/room-templates/entity-fields.tsx
@@ -20,11 +20,11 @@ import type {
} from '@shared/core/switch-servers/switch-servers';
/**
- * Everything the server has that a template can point at, read once by the
+ * Everything the workspace has that a template can point at, read once by the
* wizard and handed to every field that offers a choice from it.
*/
export type EntityLists = {
- serverId: string;
+ workspaceId: string | null;
agents: AgentPick[];
agentsLoading: boolean;
rooms: RoomPick[];
@@ -32,10 +32,10 @@ export type EntityLists = {
bridges: RemoteBridge[];
/** Null while the signed-in user's linked accounts are unknown. */
identities: LinkedIdentity[] | null;
- /** Platform users Switch has already seen on this server. */
+ /** Platform users Switch has already seen in this workspace. */
knownUsers: RemoteExternalUser[];
/** The bridge the room will land on, for directory lookups. Null when the
- * template leaves it open and the server has no default. */
+ * template leaves it open and the workspace has no default. */
bridgeId: string | null;
};
@@ -54,7 +54,7 @@ function agentTileFor(name: string, lists: EntityLists, onRemove: () => void) {
<ChosenAgentTile
key={name}
agent={found}
- subtitle={agentProviderLabelFor(found.id, lists.serverId)}
+ subtitle={agentProviderLabelFor(found.id, lists.workspaceId)}
onRemove={onRemove}
/>
) : (
@@ -84,7 +84,10 @@ function AgentCombobox({
onPick={(agent) => onPick(agent.name)}
searchText={(agent) => agent.name}
renderItem={(agent) => (
- <AgentPickerRow agent={agent} subtitle={agentProviderLabelFor(agent.id, lists.serverId)} />
+ <AgentPickerRow
+ agent={agent}
+ subtitle={agentProviderLabelFor(agent.id, lists.workspaceId)}
+ />
)}
disabled={lists.agentsLoading}
placeholder={lists.agentsLoading ? 'Loading agents…' : 'Search agents…'}
@@ -275,12 +278,13 @@ function UserCombobox({
const [query, setQuery] = useState('');
const debounced = useDebounce(query.trim(), SEARCH_DEBOUNCE_MS);
const bridgeId = lists.bridgeId;
- const searchable = bridgeId !== null && debounced.length >= MIN_QUERY_LENGTH;
+ const searchable =
+ bridgeId !== null && lists.workspaceId !== null && debounced.length >= MIN_QUERY_LENGTH;
const directory = useQuery({
- queryKey: ['bridge-directory', lists.serverId, bridgeId, debounced],
+ queryKey: ['bridge-directory', lists.workspaceId, bridgeId, debounced],
queryFn: () =>
- rpc.switchServers.searchBridgeDirectory({
- serverId: lists.serverId,
+ rpc.workspaces.searchBridgeDirectory({
+ workspaceId: lists.workspaceId as string,
bridgeId: bridgeId as string,
query: debounced,
}),
diff --git a/console/apps/switch-console-desktop/src/renderer/features/room-templates/room-template-capture-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/room-templates/room-template-capture-view.tsx
index f6f3bddca..bb60498a3 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/room-templates/room-template-capture-view.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/room-templates/room-template-capture-view.tsx
@@ -8,6 +8,7 @@ import { ServerSectionTitlebar } from '@renderer/features/switch-servers/server-
import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
import { prefillForSave } from '@renderer/features/templates/agent-template-data';
+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { failureText } from '@renderer/lib/errors/describe-failure';
import { rpc } from '@renderer/lib/ipc';
import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';
@@ -238,7 +239,10 @@ const CapturePanel = observer(function CapturePanel() {
let cancelled = false;
void (async () => {
try {
- const yaml = await rpc.switchServers.exportRoomYaml({ serverId, roomId });
+ const yaml = await rpc.workspaces.exportRoomYaml({
+ workspaceId: workspacesStore.requireSoleIdOnServer(serverId),
+ roomId,
+ });
if (cancelled) return;
setOriginalYaml(yaml);
setCandidates(extractCandidates(yaml));
diff --git a/console/apps/switch-console-desktop/src/renderer/features/room-templates/room-template-import-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/room-templates/room-template-import-view.tsx
index ea7f4c836..5a11a022f 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/room-templates/room-template-import-view.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/room-templates/room-template-import-view.tsx
@@ -12,6 +12,7 @@ import {
type TemplateAccess,
visibilityOf,
} from '@renderer/features/templates/template-visibility';
+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { failureText } from '@renderer/lib/errors/describe-failure';
import { toast } from '@renderer/lib/hooks/use-toast';
import { rpc } from '@renderer/lib/ipc';
@@ -288,8 +289,8 @@ const TemplateImportPanel = observer(function TemplateImportPanel() {
const kind = yamlText !== initialYaml ? await rpc.agentTemplates.kind({ yamlText }) : null;
// Each field is sent only when changed, so saving one cannot put back
// another that someone else changed meanwhile.
- const saved = await rpc.switchServers.updateTemplate({
- serverId,
+ const saved = await rpc.workspaces.updateTemplate({
+ workspaceId: workspacesStore.requireSoleIdOnServer(serverId),
templateId: editingTemplate.id,
...(name.trim() !== editingTemplate.name.trim() ? { name: name.trim() } : {}),
...(description.trim() !== editingTemplate.description.trim()
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sessions/create-session-modal/create-session-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/sessions/create-session-modal/create-session-modal.tsx
index 6bd08e04f..161812877 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sessions/create-session-modal/create-session-modal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/sessions/create-session-modal/create-session-modal.tsx
@@ -83,28 +83,27 @@ function useDefaultLocationId(propLocationId?: string): string | undefined {
*/
function useRoomMemberAgents(roomId: string | undefined): {
agents: Agent[];
- serverId: string | null;
+ workspaceId: string | null;
loading: boolean;
} {
- const serverId = roomId ? switchRoomsStore.roomServerId(roomId) : null;
+ const workspaceId = roomId ? switchRoomsStore.roomWorkspaceId(roomId) : null;
useEffect(() => {
if (roomId) void agentsStore.load();
}, [roomId]);
const membersQuery = useQuery({
- queryKey: ['roomAgentIds', serverId, roomId],
- queryFn: () => rpc.switchServers.listRoomAgentIds({ serverId: serverId!, roomId: roomId! }),
- enabled: !!serverId && !!roomId,
+ queryKey: ['roomAgentIds', workspaceId, roomId],
+ queryFn: () => rpc.workspaces.listRoomAgentIds({ workspaceId: workspaceId!, roomId: roomId! }),
+ enabled: !!workspaceId && !!roomId,
});
const memberIds = useMemo(() => new Set(membersQuery.data ?? []), [membersQuery.data]);
- const agents = [...agentsStore.byLocation.values()]
- .flat()
- .filter((a) => a.serverId === serverId && a.switchAgentId && memberIds.has(a.switchAgentId))
- .sort((a, b) => a.name.localeCompare(b.name));
+ const agents = (workspaceId ? agentsStore.agentsInWorkspace(workspaceId) : []).filter(
+ (a) => a.switchAgentId && memberIds.has(a.switchAgentId)
+ );
- return { agents, serverId, loading: membersQuery.isLoading || !agentsStore.loaded };
+ return { agents, workspaceId, loading: membersQuery.isLoading || !agentsStore.loaded };
}
/**
@@ -211,24 +210,30 @@ export const CreateSessionModal = observer(function CreateSessionModal({
? (locationAgents.find((a) => a.name === effectiveAgentName) ?? null)
: null;
- const serverId = effectiveAgentName ? (subagent?.serverId ?? null) : (agent?.serverId ?? null);
+ const agentWorkspaceId = effectiveAgentName
+ ? (subagent?.workspaceId ?? null)
+ : (agent?.workspaceId ?? null);
const switchAgentId = effectiveAgentName
? (subagent?.switchAgentId ?? null)
: (agent?.switchAgentId ?? null);
useEffect(() => {
- if (!roomFirst && serverId && switchAgentId) {
- void switchRoomsStore.fetchAgentRooms(serverId, switchAgentId);
+ if (!roomFirst && agentWorkspaceId && switchAgentId) {
+ void switchRoomsStore.fetchAgentRooms(agentWorkspaceId, switchAgentId);
}
- }, [roomFirst, serverId, switchAgentId]);
+ }, [roomFirst, agentWorkspaceId, switchAgentId]);
const rooms =
- serverId && switchAgentId
- ? (switchRoomsStore.roomsFor(serverId, switchAgentId) ?? []).filter((r) => !r.archived)
+ agentWorkspaceId && switchAgentId
+ ? (switchRoomsStore.roomsFor(agentWorkspaceId, switchAgentId) ?? []).filter(
+ (r) => !r.archived
+ )
: [];
const roomsLoading =
- !!serverId && !!switchAgentId && switchRoomsStore.isLoading(serverId, switchAgentId);
- const canConnectRoom = !roomFirst && !!serverId && !!switchAgentId;
+ !!agentWorkspaceId &&
+ !!switchAgentId &&
+ switchRoomsStore.isLoading(agentWorkspaceId, switchAgentId);
+ const canConnectRoom = !roomFirst && !!agentWorkspaceId && !!switchAgentId;
// In room-first mode the room is given, not chosen; everything downstream
// (roles, the connect prompt) keys off the same value either way.
@@ -243,15 +248,15 @@ export const CreateSessionModal = observer(function CreateSessionModal({
}
: null
: room;
- const roleServerId = roomFirst ? roomMembers.serverId : serverId;
+ const roleWorkspaceId = roomFirst ? roomMembers.workspaceId : agentWorkspaceId;
// Roles are room-scoped, so only fetch once a room is chosen. The set is small
// and changes rarely, so a plain per-room query (no shared cache) is enough.
const rolesQuery = useQuery({
- queryKey: ['roomRoles', roleServerId, activeRoom?.roomId],
+ queryKey: ['roomRoles', roleWorkspaceId, activeRoom?.roomId],
queryFn: () =>
- rpc.switchServers.listRoomRoles({ serverId: roleServerId!, roomId: activeRoom!.roomId }),
- enabled: !!roleServerId && !!activeRoom,
+ rpc.workspaces.listRoomRoles({ workspaceId: roleWorkspaceId!, roomId: activeRoom!.roomId }),
+ enabled: !!roleWorkspaceId && !!activeRoom,
});
const roles = rolesQuery.data ?? [];
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-item.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-item.tsx
index 21f2996a7..d229f9169 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-item.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-item.tsx
@@ -22,7 +22,7 @@ import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider
import { useWorkspaceSlots } from '@renderer/lib/layout/workspace-slots';
import { useShowModal } from '@renderer/lib/modal/modal-provider';
import { sidebarStore } from '@renderer/lib/stores/app-state';
-import { useAgentIconUrl } from '@renderer/lib/stores/use-remote-agents';
+import { useAgentIconUrl } from '@renderer/lib/stores/use-workspace-agents';
import {
ContextMenu,
ContextMenuContent,
@@ -63,7 +63,7 @@ export const SidebarAgentItem = observer(function SidebarAgentItem({
const agentName = agent.name;
const location = getLocationStore(agent.locationId);
- const iconUrl = useAgentIconUrl(agent.serverId, agent.switchAgentId);
+ const iconUrl = useAgentIconUrl(agent.workspaceId, agent.switchAgentId);
// The agent's name IS its Switch identity: Switch Console chose it, registered it
// under that name, and keys its credentials and definition by it. Reading the
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-agent-row.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-agent-row.tsx
index baa528a4d..ec2802abc 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-agent-row.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-agent-row.tsx
@@ -12,7 +12,7 @@ import { rpc } from '@renderer/lib/ipc';
import { useNavigate } from '@renderer/lib/layout/navigation-provider';
import { useShowModal } from '@renderer/lib/modal/modal-provider';
import { appState, sidebarStore } from '@renderer/lib/stores/app-state';
-import { useAgentIconUrl } from '@renderer/lib/stores/use-remote-agents';
+import { useAgentIconUrl } from '@renderer/lib/stores/use-workspace-agents';
import {
ContextMenu,
ContextMenuContent,
@@ -60,7 +60,7 @@ export const RoomAgentRow = observer(function RoomAgentRow({
// This is a Switch room's member list, so the Switch identity is what matters
// — and that is the stored name: it is what was registered on the server.
const label = agent.name || 'Unnamed agent';
- const iconUrl = useAgentIconUrl(agent.serverId, agent.switchAgentId);
+ const iconUrl = useAgentIconUrl(agent.workspaceId, agent.switchAgentId);
const expandKey = roomAgentGroupKey(roomId, agent.id);
const expanded = sidebarStore.isGroupExpanded(expandKey);
@@ -80,12 +80,12 @@ export const RoomAgentRow = observer(function RoomAgentRow({
if (!location) return null;
const removeFromRoom = () => {
- const serverId = switchRoomsStore.roomServerId(roomId);
- if (!serverId || !agent.switchAgentId) return;
+ const workspaceId = switchRoomsStore.roomWorkspaceId(roomId);
+ if (!workspaceId || !agent.switchAgentId) return;
const roomLabel = switchRoomsStore.roomNameById(roomId) ?? 'the room';
void toastPromise(
- rpc.switchServers
- .removeRoomAgent({ serverId, roomId, agentId: agent.switchAgentId })
+ rpc.workspaces
+ .removeRoomAgent({ workspaceId, roomId, agentId: agent.switchAgentId })
.then(() => switchRoomsStore.refreshRoomState()),
{
loading: `Removing ${label} from ${roomLabel}…`,
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.tsx
index 94aac1b64..996bed691 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
@@ -132,8 +132,8 @@ export const SidebarGroupedList = observer(function SidebarGroupedList() {
*/
const RoomStateDisclosure = observer(function RoomStateDisclosure() {
const { navigate } = useNavigate();
- const signedOut = switchRoomsStore.serversNotSignedIn;
- const failed = switchRoomsStore.serversThatFailedToLoad;
+ const signedOut = switchRoomsStore.workspacesNotSignedIn;
+ const failed = switchRoomsStore.workspacesThatFailedToLoad;
// Being signed out is the whole explanation, so it is said on its own: the
// memberships that "didn't load" are the same fact, and offering a retry for
diff --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.ts
index d1076cb30..dbf393f81 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
@@ -1,8 +1,8 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
/**
- * The agent-icon backfill notice must be said once per server per run, however
- * many times the sidebar refreshes (CHOO-2344).
+ * The agent-icon backfill notice must be said once per workspace per run,
+ * however many times the sidebar refreshes (CHOO-2344).
*
* `refreshSidebarRoomState` runs on first paint, window focus, sign-in, the
* background reconcile, the retry button and every membership-changing
@@ -20,13 +20,14 @@ const AGENT = {
id: 'agent-1',
name: 'agent one',
serverId: 'server-1',
+ workspaceId: 'workspace-1',
switchAgentId: 'switch-agent-1',
createdAt: '2026-01-01T00:00:00.000Z',
};
vi.mock('@renderer/lib/hooks/use-toast', () => ({ toast }));
vi.mock('@renderer/lib/ipc', () => ({
- rpc: { switchServers: { backfillAgentIcons } },
+ rpc: { workspaces: { backfillAgentIcons } },
}));
vi.mock('@renderer/features/locations/stores/agents-store', () => ({
agentsStore: {
@@ -68,7 +69,7 @@ describe('agent icon backfill reporting', () => {
backfillAgentIcons.mockReset();
});
- it('reports a server without the icon endpoint once, not on every refresh', async () => {
+ it('reports a workspace without the icon endpoint once, not on every refresh', async () => {
backfillAgentIcons.mockResolvedValue({ kind: 'unsupported' });
const { refreshSidebarRoomState } = await loadSubject();
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsx
index 697081c75..afb66e379 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsx
@@ -54,14 +54,14 @@ export function isRoomNameKnown(roomKey: string): boolean {
*/
export function deleteRoomAction(
roomKey: string,
- showDeleteRoomModal: (args: { serverId: string; roomId: string; roomName: string }) => void
+ showDeleteRoomModal: (args: { workspaceId: string; roomId: string; roomName: string }) => void
): (() => void) | null {
if (roomKey === UNASSIGNED_ROOM_KEY) return null;
- const serverId = switchRoomsStore.roomServerId(roomKey);
+ const workspaceId = switchRoomsStore.roomWorkspaceId(roomKey);
const room = switchRoomsStore.roomSummaryById(roomKey);
- if (!serverId || !room) return null;
- if (!switchRoomsStore.canDeleteRoom(serverId, room)) return null;
- return () => showDeleteRoomModal({ serverId, roomId: roomKey, roomName: room.name });
+ if (!workspaceId || !room) return null;
+ if (!switchRoomsStore.canDeleteRoom(workspaceId, room)) return null;
+ return () => showDeleteRoomModal({ workspaceId, roomId: roomKey, roomName: room.name });
}
/** Show a room's conversation in the main panel (no-op for Unassigned, which
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.ts
index f9e406607..6bf725275 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
@@ -88,14 +88,14 @@ export function agentSessions(entry: AgentEntry): SessionStore[] {
);
}
-/** Every agent on the active server that has a Switch identity, as
+/** Every agent in the active scope that has a Switch identity, as
* membership-lookup keys. Unfiltered on purpose — see
* {@link agentsInActiveScope}. */
-export function switchIdentities(): { serverId: string; switchAgentId: string }[] {
- const identities: { serverId: string; switchAgentId: string }[] = [];
+export function switchIdentities(): { workspaceId: string; switchAgentId: string }[] {
+ const identities: { workspaceId: string; switchAgentId: string }[] = [];
for (const { agent } of agentsInActiveScope()) {
- if (agent.serverId && agent.switchAgentId) {
- identities.push({ serverId: agent.serverId, switchAgentId: agent.switchAgentId });
+ if (agent.workspaceId && agent.switchAgentId) {
+ identities.push({ workspaceId: agent.workspaceId, switchAgentId: agent.switchAgentId });
}
}
return identities;
@@ -164,13 +164,13 @@ export async function refreshSidebarRoomStateAfterOnboarding(): Promise<void> {
* lettered picture with nothing explaining why.
*/
async function giveExistingAgentsAnIcon(): Promise<void> {
- const serverIds = new Set(switchIdentities().map((identity) => identity.serverId));
- for (const serverId of serverIds) {
+ const workspaceIds = new Set(switchIdentities().map((identity) => identity.workspaceId));
+ for (const workspaceId of workspaceIds) {
try {
- reportBackfill(serverId, await rpc.switchServers.backfillAgentIcons(serverId));
+ reportBackfill(workspaceId, await rpc.workspaces.backfillAgentIcons(workspaceId));
} catch (cause) {
- log.warn('could not give existing agents their icons', { serverId, cause });
- reportOnce(serverId, 'failed', {
+ log.warn('could not give existing agents their icons', { workspaceId, cause });
+ reportOnce(workspaceId, 'failed', {
title: 'Agent icons could not be saved',
description:
'Your agents show a generated icon here, but the Switch server has not stored it — so they keep their old picture in Slack and the other chat apps.',
@@ -181,13 +181,14 @@ async function giveExistingAgentsAnIcon(): Promise<void> {
}
/**
- * What each server was last told to the user about, so an unresolved condition
- * is not re-announced on every refresh.
+ * What each workspace was last told to the user about, so an unresolved
+ * condition is not re-announced on every refresh.
*
* The caller runs on first paint, window focus, sign-in, the background
- * reconcile, the retry button and every membership-changing mutation. A server
- * that is signed out or too old to store icons fails all of them, which turned
- * one standing problem into a toast every few seconds (CHOO-2344).
+ * reconcile, the retry button and every membership-changing mutation. A
+ * workspace whose server is signed out or too old to store icons fails all of
+ * them, which turned one standing problem into a toast every few seconds
+ * (CHOO-2344).
*
* Keyed by outcome, not a bare "said something already": if the situation
* changes — a signed-out server starts answering and turns out to be too old —
@@ -196,15 +197,15 @@ async function giveExistingAgentsAnIcon(): Promise<void> {
*/
const reportedBackfill = new Map<string, string>();
-function reportOnce(serverId: string, outcome: string, notice: Parameters<typeof toast>[0]) {
- if (reportedBackfill.get(serverId) === outcome) return;
- reportedBackfill.set(serverId, outcome);
+function reportOnce(workspaceId: string, outcome: string, notice: Parameters<typeof toast>[0]) {
+ if (reportedBackfill.get(workspaceId) === outcome) return;
+ reportedBackfill.set(workspaceId, outcome);
toast(notice);
}
-function reportBackfill(serverId: string, outcome: AgentIconBackfill): void {
+function reportBackfill(workspaceId: string, outcome: AgentIconBackfill): void {
if (outcome.kind === 'unsupported') {
- reportOnce(serverId, 'unsupported', {
+ reportOnce(workspaceId, 'unsupported', {
title: 'This Switch server does not support agent icons yet',
description:
'Your agents show a generated icon here, but it cannot be saved, so they keep their old picture in Slack and the other chat apps. Updating the server fixes it.',
@@ -213,7 +214,7 @@ function reportBackfill(serverId: string, outcome: AgentIconBackfill): void {
return;
}
if (outcome.kind === 'partial') {
- reportOnce(serverId, `partial:${outcome.failed}`, {
+ reportOnce(workspaceId, `partial:${outcome.failed}`, {
title: `${outcome.failed} agent${outcome.failed === 1 ? '' : 's'} kept the old icon`,
description:
'Their icon could not be saved to the Switch server, so it will not show in Slack or the other chat apps.',
@@ -221,5 +222,5 @@ function reportBackfill(serverId: string, outcome: AgentIconBackfill): void {
});
return;
}
- reportedBackfill.delete(serverId);
+ reportedBackfill.delete(workspaceId);
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentToRoomsModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentToRoomsModal.tsx
index e4a435895..e1e09335c 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentToRoomsModal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentToRoomsModal.tsx
@@ -17,12 +17,12 @@ import {
import { Field, FieldLabel } from '@renderer/lib/ui/field';
type Props = BaseModalProps<void> & {
- serverId: string;
+ workspaceId: string;
switchAgentId: string;
agentName: string;
};
-/** A room the agent can be put in: one on its own server it is not already in. */
+/** A room the agent can be put in: one in its own workspace it is not already in. */
type Candidate = { id: string; name: string; bridgeType: string | null };
/**
@@ -31,10 +31,11 @@ type Candidate = { id: string; name: string; bridgeType: string | null };
*
* Both write the same membership through `addRoomAgents`; which one you reach
* for is only a matter of what you were looking at. An agent can only join rooms
- * on the server it is registered with, so the choice is scoped to that server.
+ * in the workspace it is registered in, so the choice is scoped to that
+ * workspace.
*/
export const AddAgentToRoomsModal = observer(function AddAgentToRoomsModal({
- serverId,
+ workspaceId,
switchAgentId,
agentName,
onSuccess,
@@ -50,7 +51,7 @@ export const AddAgentToRoomsModal = observer(function AddAgentToRoomsModal({
// so the rooms offered here and the rooms the agent is shown under cannot
// disagree. Undefined means it was never fetched — offering every room then
// would invite a join that is already in place, so say so instead.
- const memberships = switchRoomsStore.roomsFor(serverId, switchAgentId);
+ const memberships = switchRoomsStore.roomsFor(workspaceId, switchAgentId);
const membershipUnknown = memberships === undefined;
const alreadyIn = new Set((memberships ?? []).map((m) => m.roomId));
@@ -58,7 +59,7 @@ export const AddAgentToRoomsModal = observer(function AddAgentToRoomsModal({
// agent's usefulness is mostly in rooms someone else set up, and a picker that
// omitted them made those rooms unreachable from here entirely.
const candidates: Candidate[] = switchRoomsStore
- .readableRoomsOnServer(serverId)
+ .readableRoomsInWorkspace(workspaceId)
.filter((room) => !alreadyIn.has(room.id) && !selected.some((s) => s.id === room.id))
.map((room) => ({ id: room.id, name: room.name, bridgeType: room.bridgeType }));
const nothingToAdd = candidates.length === 0 && selected.length === 0;
@@ -70,8 +71,8 @@ export const AddAgentToRoomsModal = observer(function AddAgentToRoomsModal({
setError(null);
try {
for (const room of selected) {
- await rpc.switchServers.addRoomAgents({
- serverId,
+ await rpc.workspaces.addRoomAgents({
+ workspaceId,
roomId: room.id,
agentIds: [switchAgentId],
direction: 'room_to_agents',
@@ -85,7 +86,7 @@ export const AddAgentToRoomsModal = observer(function AddAgentToRoomsModal({
setIsSubmitting(false);
setCloseGuard(false);
}
- }, [serverId, switchAgentId, selected, onSuccess, setCloseGuard]);
+ }, [workspaceId, switchAgentId, selected, onSuccess, setCloseGuard]);
return (
<>
@@ -130,13 +131,13 @@ export const AddAgentToRoomsModal = observer(function AddAgentToRoomsModal({
/>
{membershipUnknown && (
<p className="mt-1 text-xs text-foreground-warning">
- Which rooms {agentName} is already in could not be read, so every room on the server
- is listed. Adding it to one it already belongs to changes nothing.
+ Which rooms {agentName} is already in could not be read, so every room in the
+ workspace is listed. Adding it to one it already belongs to changes nothing.
</p>
)}
{nothingToAdd && !membershipUnknown && (
<p className="mt-1 text-xs text-foreground-muted">
- {agentName} is already in every room you can see on this server.
+ {agentName} is already in every room you can see in this workspace.
</p>
)}
</Field>
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentsToRoomModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentsToRoomModal.tsx
index 0398d3a8d..34cc9679f 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentsToRoomModal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentsToRoomModal.tsx
@@ -6,6 +6,7 @@ import { agentsStore } from '@renderer/features/locations/stores/agents-store';
import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
import { bundledTemplates } from '@renderer/features/templates/bundled-templates';
+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { agentProviderLabel } from '@renderer/lib/components/agent-mark';
import { AgentPickerRow, ChosenAgentTile } from '@renderer/lib/components/agent-picker';
import { PickerCombobox } from '@renderer/lib/components/picker-combobox';
@@ -14,7 +15,7 @@ import { toast } from '@renderer/lib/hooks/use-toast';
import { rpc } from '@renderer/lib/ipc';
import { useNavigate } from '@renderer/lib/layout/navigation-provider';
import { type BaseModalProps, useModalContext } from '@renderer/lib/modal/modal-provider';
-import { useRemoteAgents } from '@renderer/lib/stores/use-remote-agents';
+import { useWorkspaceAgents } from '@renderer/lib/stores/use-workspace-agents';
import { Button } from '@renderer/lib/ui/button';
import { ConfirmButton } from '@renderer/lib/ui/confirm-button';
import {
@@ -42,7 +43,10 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({
}: Props) {
const { setCloseGuard } = useModalContext();
const { navigate } = useNavigate();
- const serverId = switchRoomsStore.roomServerId(roomId);
+ const workspaceId = switchRoomsStore.roomWorkspaceId(roomId);
+ // The template pages are still routed by server, so the Use page is reached
+ // through the workspace's host.
+ const serverId = workspaceId === null ? null : workspacesStore.serverIdFor(workspaceId);
const roomName = switchRoomsStore.roomNameById(roomId);
// Templates can create an agent straight into this room. The bundled
@@ -50,10 +54,10 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({
// returns.
const [serverTemplates, setServerTemplates] = useState<StoredTemplateSummary[]>([]);
useEffect(() => {
- if (!serverId) return;
+ if (workspaceId === null) return;
let cancelled = false;
- rpc.switchServers
- .listTemplates({ serverId, kind: 'agent' })
+ rpc.workspaces
+ .listTemplates({ workspaceId, kind: 'agent' })
.then((list) => {
if (!cancelled) setServerTemplates(list);
})
@@ -69,7 +73,7 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({
return () => {
cancelled = true;
};
- }, [serverId]);
+ }, [workspaceId]);
// A built-in template the signed-in user saved to the workspace is listed
// once, as their copy. Names are unique only per owner, so someone else's
// template of the same name is not a copy.
@@ -116,14 +120,14 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({
const members = new Set(switchRoomsStore.localMemberIds(roomId));
// The agents' own icons live on the server, not in the local row, so the
// list is joined against the server's summary to draw them.
- const { data: remoteAgents } = useRemoteAgents(serverId);
+ const { data: remoteAgents } = useWorkspaceAgents(workspaceId);
const remoteById = new Map((remoteAgents ?? []).map((agent) => [agent.id, agent]));
// Only this install's agents are offered. An agent registered on another
// Switch Console could be added server-side but could never be shown or driven
// from here, so it is not ours to offer.
- const candidates: Candidate[] = serverId
+ const candidates: Candidate[] = workspaceId
? agentsStore
- .agentsOnServer(serverId)
+ .agentsInWorkspace(workspaceId)
.map((agent) => ({
id: agent.switchAgentId as string,
name: agent.name,
@@ -135,13 +139,13 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({
const nothingToAdd = candidates.length === 0 && selected.length === 0;
const handleSubmit = useCallback(async () => {
- if (!serverId || selected.length === 0) return;
+ if (!workspaceId || selected.length === 0) return;
setIsSubmitting(true);
setCloseGuard(true);
setError(null);
try {
- await rpc.switchServers.addRoomAgents({
- serverId,
+ await rpc.workspaces.addRoomAgents({
+ workspaceId,
roomId,
agentIds: selected.map((a) => a.id),
direction: 'agents_to_room',
@@ -154,7 +158,7 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({
setIsSubmitting(false);
setCloseGuard(false);
}
- }, [serverId, roomId, selected, onSuccess, setCloseGuard]);
+ }, [workspaceId, roomId, selected, onSuccess, setCloseGuard]);
return (
<>
@@ -163,9 +167,9 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({
</DialogHeader>
<DialogContentArea className="pt-0">
<div className="flex w-full flex-col gap-4">
- {!serverId && (
+ {!workspaceId && (
<p className="text-xs text-destructive">
- This room&apos;s server is not known yet, so its members cannot be changed.
+ This room&apos;s workspace is not known yet, so its members cannot be changed.
</p>
)}
@@ -247,7 +251,7 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({
</Button>
<ConfirmButton
onClick={() => void handleSubmit()}
- disabled={!serverId || selected.length === 0 || isSubmitting}
+ disabled={!workspaceId || selected.length === 0 || isSubmitting}
>
{isSubmitting ? 'Adding…' : 'Add to room'}
</ConfirmButton>
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/DeleteRoomModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/DeleteRoomModal.tsx
index 11a65e610..889d29585 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/DeleteRoomModal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/DeleteRoomModal.tsx
@@ -15,7 +15,7 @@ import {
} from '@renderer/lib/ui/dialog';
type Props = BaseModalProps<void> & {
- serverId: string;
+ workspaceId: string;
roomId: string;
roomName: string;
};
@@ -28,7 +28,7 @@ type Props = BaseModalProps<void> & {
* trying, so they are said before rather than reported after.
*/
export const DeleteRoomModal = observer(function DeleteRoomModal({
- serverId,
+ workspaceId,
roomId,
roomName,
onSuccess,
@@ -47,7 +47,7 @@ export const DeleteRoomModal = observer(function DeleteRoomModal({
setCloseGuard(true);
setError(null);
try {
- await switchRoomsStore.deleteRoom(serverId, roomId);
+ await switchRoomsStore.deleteRoom(workspaceId, roomId);
onSuccess();
} catch (cause) {
setError(failureText(cause, 'Could not delete the room.'));
@@ -55,7 +55,7 @@ export const DeleteRoomModal = observer(function DeleteRoomModal({
} finally {
setCloseGuard(false);
}
- }, [serverId, roomId, onSuccess, setCloseGuard]);
+ }, [workspaceId, roomId, onSuccess, setCloseGuard]);
return (
<>
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx
index 0e827fc81..19d924287 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx
@@ -10,7 +10,7 @@ import { describeFailure, failureText } from '@renderer/lib/errors/describe-fail
import { rpc } from '@renderer/lib/ipc';
import { useNavigate } from '@renderer/lib/layout/navigation-provider';
import { useShowModal } from '@renderer/lib/modal/modal-provider';
-import { useRemoteAgents } from '@renderer/lib/stores/use-remote-agents';
+import { useWorkspaceAgents } from '@renderer/lib/stores/use-workspace-agents';
import { Button } from '@renderer/lib/ui/button';
import { Input } from '@renderer/lib/ui/input';
import {
@@ -31,8 +31,8 @@ import { openRoomChannel } from './room-links';
/** Query key for one room's own settings — shared so a save can write the
* server's answer straight back into what the page is reading. */
-function roomDetailKey(serverId: string, roomId: string) {
- return ['remote-room-detail', serverId, roomId] as const;
+function roomDetailKey(workspaceId: string, roomId: string) {
+ return ['remote-room-detail', workspaceId, roomId] as const;
}
/**
@@ -48,15 +48,15 @@ export const RoomConfigurationPanel = observer(function RoomConfigurationPanel({
}: {
roomId: string;
}) {
- const serverId = switchRoomsStore.roomServerId(roomId);
+ const workspaceId = switchRoomsStore.roomWorkspaceId(roomId);
const query = useQuery({
- queryKey: roomDetailKey(serverId ?? '', roomId),
- queryFn: () => rpc.switchServers.getRoomDetail({ serverId: serverId as string, roomId }),
- enabled: serverId !== null,
+ queryKey: roomDetailKey(workspaceId ?? '', roomId),
+ queryFn: () => rpc.workspaces.getRoomDetail({ workspaceId: workspaceId as string, roomId }),
+ enabled: workspaceId !== null,
});
- if (serverId === null) {
- return <PanelNotice title="This room’s server is still loading." />;
+ if (workspaceId === null) {
+ return <PanelNotice title="This room’s workspace is still loading." />;
}
if (query.isPending) {
@@ -91,13 +91,13 @@ export const RoomConfigurationPanel = observer(function RoomConfigurationPanel({
return (
<div className="h-full overflow-y-auto">
<div className="mx-auto flex w-full max-w-4xl flex-col gap-8 px-10 py-8">
- <RoomHeading serverId={serverId} room={room} />
+ <RoomHeading serverId={switchRoomsStore.roomServerId(roomId)} room={room} />
{/* Keyed on the room so the drafts below belong to the room on screen:
switching rooms starts a fresh form rather than carrying half-typed
text across. */}
- <GeneralSection key={room.id} serverId={serverId} room={room} />
- <ParticipantsSection serverId={serverId} room={room} />
- <DeleteRoomSection serverId={serverId} room={room} />
+ <GeneralSection key={room.id} workspaceId={workspaceId} room={room} />
+ <ParticipantsSection workspaceId={workspaceId} room={room} />
+ <DeleteRoomSection workspaceId={workspaceId} room={room} />
</div>
</div>
);
@@ -111,16 +111,16 @@ export const RoomConfigurationPanel = observer(function RoomConfigurationPanel({
* none to find — the room is someone else's.
*/
const DeleteRoomSection = observer(function DeleteRoomSection({
- serverId,
+ workspaceId,
room,
}: {
- serverId: string;
+ workspaceId: string;
room: RemoteRoomDetail;
}) {
const showDeleteRoomModal = useShowModal('deleteRoomModal');
const { navigate } = useNavigate();
- if (!switchRoomsStore.canDeleteRoom(serverId, room)) return null;
+ if (!switchRoomsStore.canDeleteRoom(workspaceId, room)) return null;
return (
<section className="border-t border-border pt-6">
@@ -138,7 +138,7 @@ const DeleteRoomSection = observer(function DeleteRoomSection({
className="shrink-0 border-red-500/40 text-red-500 hover:bg-red-500/10 hover:text-red-500"
onClick={() =>
showDeleteRoomModal({
- serverId,
+ workspaceId,
roomId: room.id,
roomName: roomTitle(room),
// The page this is on is the deleted room's own, so staying would
@@ -154,7 +154,7 @@ const DeleteRoomSection = observer(function DeleteRoomSection({
);
});
-function RoomHeading({ serverId, room }: { serverId: string; room: RemoteRoomDetail }) {
+function RoomHeading({ serverId, room }: { serverId: string | null; room: RemoteRoomDetail }) {
const platform = bridgePlatformLabel(room.bridgeType);
const { navigate } = useNavigate();
return (
@@ -168,14 +168,16 @@ function RoomHeading({ serverId, room }: { serverId: string; room: RemoteRoomDet
</p>
</div>
<div className="flex shrink-0 items-center gap-2">
- <Button
- variant="outline"
- size="sm"
- onClick={() => navigate('templateCapture', { serverId, roomId: room.id })}
- >
- <FileText className="size-3.5" />
- Capture as template
- </Button>
+ {serverId !== null && (
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => navigate('templateCapture', { serverId, roomId: room.id })}
+ >
+ <FileText className="size-3.5" />
+ Capture as template
+ </Button>
+ )}
{room.externalChannelUrl && (
<>
{room.bridgeDisplayName && (
@@ -208,7 +210,7 @@ type SaveState = { phase: 'idle' | 'saving' | 'saved' } | { phase: 'failed'; mes
*
* One request carries both fields, so the pair is stored together or not at all.
*/
-function GeneralSection({ serverId, room }: { serverId: string; room: RemoteRoomDetail }) {
+function GeneralSection({ workspaceId, room }: { workspaceId: string; room: RemoteRoomDetail }) {
const queryClient = useQueryClient();
const savedDescription = room.description;
const savedInstructions = room.instructions ?? '';
@@ -221,13 +223,13 @@ function GeneralSection({ serverId, room }: { serverId: string; room: RemoteRoom
async function save() {
setState({ phase: 'saving' });
try {
- const updated = await rpc.switchServers.updateRoom({
- serverId,
+ const updated = await rpc.workspaces.updateRoom({
+ workspaceId,
roomId: room.id,
description,
instructions,
});
- queryClient.setQueryData(roomDetailKey(serverId, room.id), updated);
+ queryClient.setQueryData(roomDetailKey(workspaceId, room.id), updated);
setState({ phase: 'saved' });
} catch (cause) {
setState({ phase: 'failed', message: failureText(cause, 'Could not save the change.') });
@@ -322,10 +324,10 @@ function Field({
* hierarchy the room does not have.
*/
const ParticipantsSection = observer(function ParticipantsSection({
- serverId,
+ workspaceId,
room,
}: {
- serverId: string;
+ workspaceId: string;
room: RemoteRoomDetail;
}) {
const queryClient = useQueryClient();
@@ -335,11 +337,11 @@ const ParticipantsSection = observer(function ParticipantsSection({
// Names for agents belonging to other installs, which this computer has no
// local record of. Shares its key with the rest of the app, so it is usually
// already in hand.
- const remoteAgents = useRemoteAgents(serverId);
+ const remoteAgents = useWorkspaceAgents(workspaceId);
const remoteById = new Map((remoteAgents.data ?? []).map((a) => [a.id, a]));
async function refresh() {
- await queryClient.invalidateQueries({ queryKey: roomDetailKey(serverId, room.id) });
+ await queryClient.invalidateQueries({ queryKey: roomDetailKey(workspaceId, room.id) });
await switchRoomsStore.refreshRoomState();
}
@@ -380,9 +382,11 @@ const ParticipantsSection = observer(function ParticipantsSection({
{room.agentIds.map((agentId) => (
<ParticipantCard
key={agentId}
- mark={<AgentMark agentId={agentId} serverId={serverId} remoteById={remoteById} />}
- name={agentNameFor(agentId, serverId, remoteById)}
- detail={agentKindFor(agentId, serverId, remoteById)}
+ mark={
+ <AgentMark agentId={agentId} workspaceId={workspaceId} remoteById={remoteById} />
+ }
+ name={agentNameFor(agentId, workspaceId, remoteById)}
+ detail={agentKindFor(agentId, workspaceId, remoteById)}
/>
))}
{room.connectedUserNames.map((name) => (
@@ -400,7 +404,7 @@ const ParticipantsSection = observer(function ParticipantsSection({
</div>
)}
- {adding && <AddAgentPanel serverId={serverId} room={room} onAdded={refresh} />}
+ {adding && <AddAgentPanel workspaceId={workspaceId} room={room} onAdded={refresh} />}
</section>
);
});
@@ -433,11 +437,11 @@ function ParticipantCard({
* whose owner never agreed to it.
*/
const AddAgentPanel = observer(function AddAgentPanel({
- serverId,
+ workspaceId,
room,
onAdded,
}: {
- serverId: string;
+ workspaceId: string;
room: RemoteRoomDetail;
onAdded: () => Promise<void>;
}) {
@@ -446,11 +450,11 @@ const AddAgentPanel = observer(function AddAgentPanel({
const [error, setError] = useState<string | null>(null);
const members = new Set(room.agentIds);
- const { data: remoteAgents } = useRemoteAgents(serverId);
+ const { data: remoteAgents } = useWorkspaceAgents(workspaceId);
const remoteById = new Map((remoteAgents ?? []).map((agent) => [agent.id, agent]));
const query = filter.trim().toLowerCase();
const candidates = agentsStore
- .agentsOnServer(serverId)
+ .agentsInWorkspace(workspaceId)
.filter((agent) => agent.switchAgentId !== null && !members.has(agent.switchAgentId))
.filter((agent) => query === '' || agent.name.toLowerCase().includes(query));
@@ -458,8 +462,8 @@ const AddAgentPanel = observer(function AddAgentPanel({
setBusyId(switchAgentId);
setError(null);
try {
- await rpc.switchServers.addRoomAgents({
- serverId,
+ await rpc.workspaces.addRoomAgents({
+ workspaceId,
roomId: room.id,
agentIds: [switchAgentId],
direction: 'agents_to_room',
@@ -569,18 +573,18 @@ function PanelNotice({
/** An agent's own picture, beside the human participants' initials discs. */
function AgentMark({
agentId,
- serverId,
+ workspaceId,
remoteById,
}: {
agentId: string;
- serverId: string;
+ workspaceId: string;
remoteById: Map<string, RemoteAgentSummary>;
}) {
const remote = remoteById.get(agentId) ?? null;
return (
<span className="flex size-7 shrink-0 items-center justify-center">
<AgentAvatar
- name={agentNameFor(agentId, serverId, remoteById)}
+ name={agentNameFor(agentId, workspaceId, remoteById)}
iconUrl={remote?.iconUrl ?? null}
size={26}
/>
@@ -590,19 +594,22 @@ function AgentMark({
/** This install's record of a Switch agent, which is where its provider is
* known — the server says what type an agent is, not what runs it here. */
-function localAgentFor(switchAgentId: string, serverId: string) {
+function localAgentFor(switchAgentId: string, workspaceId: string) {
return (
- agentsStore.agentsOnServer(serverId).find((a) => a.switchAgentId === switchAgentId) ?? null
+ agentsStore.agentsInWorkspace(workspaceId).find((a) => a.switchAgentId === switchAgentId) ??
+ null
);
}
function agentNameFor(
switchAgentId: string,
- serverId: string,
+ workspaceId: string,
remoteById: Map<string, RemoteAgentSummary>
): string {
return (
- localAgentFor(switchAgentId, serverId)?.name ?? remoteById.get(switchAgentId)?.name ?? 'Agent'
+ localAgentFor(switchAgentId, workspaceId)?.name ??
+ remoteById.get(switchAgentId)?.name ??
+ 'Agent'
);
}
@@ -610,10 +617,10 @@ function agentNameFor(
* otherwise the type the server knows it by. */
function agentKindFor(
switchAgentId: string,
- serverId: string,
+ workspaceId: string,
remoteById: Map<string, RemoteAgentSummary>
): string {
- const providerId = localAgentFor(switchAgentId, serverId)?.providerId ?? null;
+ const providerId = localAgentFor(switchAgentId, workspaceId)?.providerId ?? null;
const knownType = remoteById.get(switchAgentId)?.knownAgentType ?? null;
return providerDisplayName(providerId) ?? providerDisplayName(knownType) ?? 'agent';
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ClaimIdentityModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ClaimIdentityModal.tsx
index 47be809ce..4d234aea1 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ClaimIdentityModal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ClaimIdentityModal.tsx
@@ -13,15 +13,14 @@ import {
} from '@renderer/lib/ui/dialog';
import type { LinkedIdentity } from '@shared/core/switch-servers/switch-servers';
import { BridgeIdentitySearch } from './bridge-identity-search';
-import { switchServersStore } from './switch-servers-store';
import { useMyIdentities } from './use-my-identities';
type ClaimIdentityModalArgs = {
- /** Claim on this server instead of the active one. */
- serverId?: string;
- /** The messaging app to claim an account in. Required: an account is claimed
- * in one workspace, and every entry point knows which one it opened from —
- * asking again would be a question the caller has already answered. */
+ /** The workspace the account is claimed in. Required rather than defaulted to
+ * the active one: every entry point knows which workspace it opened from, and
+ * falling back would claim the account somewhere the user was not looking. */
+ workspaceId: string;
+ /** The messaging app to claim an account in. */
bridgeId: string;
};
@@ -41,22 +40,20 @@ type Props = BaseModalProps<{ identity: LinkedIdentity }> & ClaimIdentityModalAr
* never posted in.
*/
export const ClaimIdentityModal = observer(function ClaimIdentityModal({
- serverId: overrideServerId,
+ workspaceId,
bridgeId,
onSuccess,
onClose,
}: Props) {
- const serverId = overrideServerId ?? switchServersStore.activeServerId ?? '';
// The search raises the close guard while a claim or unlink is in flight, so
// this is also the signal that leaving now would abandon one.
const { hasActiveCloseGuard } = useModalContext();
- const { identities } = useMyIdentities(serverId || null);
+ const { identities } = useMyIdentities(workspaceId);
const bridgesQuery = useQuery({
- queryKey: ['remote-bridges', serverId],
- queryFn: () => rpc.switchServers.listRemoteBridges(serverId),
- enabled: !!serverId,
+ queryKey: ['remote-bridges', workspaceId],
+ queryFn: () => rpc.workspaces.listBridges(workspaceId),
});
const bridges = bridgesQuery.data ?? [];
@@ -80,15 +77,9 @@ export const ClaimIdentityModal = observer(function ClaimIdentityModal({
Tell Switch which account is you, so your own agents can tell it&apos;s you.
</p>
- {!serverId && (
- <p className="text-xs text-destructive">
- No Switch server is selected. Choose a server in the sidebar first.
- </p>
- )}
-
{bridgeIsGone && (
<p className="text-xs text-destructive">
- That messaging app is no longer connected to this server.
+ That messaging app is no longer connected to this workspace.
</p>
)}
@@ -105,7 +96,7 @@ export const ClaimIdentityModal = observer(function ClaimIdentityModal({
)}
<BridgeIdentitySearch
- serverId={serverId}
+ workspaceId={workspaceId}
bridgeId={bridgeId}
bridgeDisplayName={selectedBridge?.displayName ?? 'the workspace'}
platform={bridgePlatformLabel(selectedBridge?.type ?? '')}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsx
index 28f13a321..0728fdcf3 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsx
@@ -2,6 +2,7 @@ import { useQuery } from '@tanstack/react-query';
import { ExternalLink } from 'lucide-react';
import { observer } from 'mobx-react-lite';
import { useCallback, useMemo, useState } from 'react';
+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';
import { bridgePlatformLabel, bridgeSetupDocsUrl } from '@renderer/lib/components/bridge-platform';
import { failureText } from '@renderer/lib/errors/describe-failure';
@@ -55,6 +56,7 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppMod
const { setCloseGuard } = useModalContext();
const serverId = overrideServerId ?? switchServersStore.activeServerId ?? '';
+ const workspaceId = workspacesStore.soleIdOnServer(serverId || null);
const server = switchServersStore.servers.find((s) => s.id === serverId) ?? null;
const isAdmin = switchServersStore.statusFor(serverId)?.user?.role === 'admin';
@@ -73,9 +75,9 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppMod
const [error, setError] = useState<string | null>(null);
const typesQuery = useQuery({
- queryKey: ['remote-bridge-types', serverId],
- queryFn: () => rpc.switchServers.listRemoteBridgeTypes(serverId),
- enabled: !!serverId,
+ queryKey: ['remote-bridge-types', workspaceId],
+ queryFn: () => rpc.workspaces.listBridgeTypes(workspaceId as string),
+ enabled: workspaceId !== null,
});
const types = useMemo(() => typesQuery.data ?? [], [typesQuery.data]);
@@ -113,7 +115,12 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppMod
return !(value ?? '').trim();
});
const canSubmit =
- !!serverId && isAdmin && !!selectedType && !!trimmedName && !missingRequired && !isSubmitting;
+ workspaceId !== null &&
+ isAdmin &&
+ !!selectedType &&
+ !!trimmedName &&
+ !missingRequired &&
+ !isSubmitting;
const handleSubmit = useCallback(async () => {
if (!canSubmit || !selectedType) return;
@@ -135,8 +142,8 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppMod
if (trimmed) connectionConfig[field.key] = trimmed;
}
- const result = await rpc.switchServers.createBridge({
- serverId,
+ const result = await rpc.workspaces.createBridge({
+ workspaceId: workspaceId as string,
bridgeType: selectedType.key,
displayName: trimmedName,
connectionConfig,
@@ -165,7 +172,7 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppMod
}, [
canSubmit,
selectedType,
- serverId,
+ workspaceId,
trimmedName,
config,
setAsDefault,
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.tsx
index 759887001..cbf5dc9e9 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
@@ -4,6 +4,7 @@ import { useCallback, useState } from 'react';
import { agentsStore } from '@renderer/features/locations/stores/agents-store';
import { openRoomView } from '@renderer/features/sidebar/sidebar-room-grouping';
import { refreshSidebarRoomState } from '@renderer/features/sidebar/sidebar-tree-data';
+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import {
AgentPickerRow,
ChosenAgentTile,
@@ -49,6 +50,7 @@ export const CreateRoomModal = observer(function CreateRoomModal({
// asking again would let the user create a room somewhere they are not
// looking, and then wonder where it went.
const serverId = overrideServerId ?? switchServersStore.activeServerId ?? '';
+ const workspaceId = workspacesStore.soleIdOnServer(serverId || null);
const server = switchServersStore.servers.find((s) => s.id === serverId) ?? null;
const [name, setName] = useState('');
@@ -61,20 +63,20 @@ export const CreateRoomModal = observer(function CreateRoomModal({
const [error, setError] = useState<string | null>(null);
const bridgesQuery = useQuery({
- queryKey: ['remote-bridges', serverId],
- queryFn: () => rpc.switchServers.listRemoteBridges(serverId),
- enabled: !!serverId,
+ queryKey: ['remote-bridges', workspaceId],
+ queryFn: () => rpc.workspaces.listBridges(workspaceId as string),
+ enabled: workspaceId !== null,
});
const agentsQuery = useQuery({
- queryKey: ['remote-agents', serverId],
- queryFn: () => rpc.switchServers.listRemoteAgents(serverId),
- enabled: !!serverId,
+ queryKey: ['remote-agents', workspaceId],
+ queryFn: () => rpc.workspaces.listAgents(workspaceId as string),
+ enabled: workspaceId !== null,
});
// Which account on each app is the person creating the room. A room on an app
// they have not claimed an account on works, but their own messages in it are
// from a stranger as far as the agents are concerned — so it is said here,
// while the app is being chosen, rather than discovered later.
- const { identities } = useMyIdentities(serverId);
+ const { identities } = useMyIdentities(workspaceId);
/**
* Only agents this install registered on the server.
@@ -86,7 +88,11 @@ export const CreateRoomModal = observer(function CreateRoomModal({
* follow.
*/
const invitableAgents = (agentsQuery.data ?? []).filter((remote) =>
- agentsStore.agentsOnServer(serverId).some((local) => local.switchAgentId === remote.id)
+ workspaceId === null
+ ? false
+ : agentsStore
+ .agentsInWorkspace(workspaceId)
+ .some((local) => local.switchAgentId === remote.id)
);
// Only a running bridge can back a new room, and creating a room here means
@@ -111,7 +117,11 @@ export const CreateRoomModal = observer(function CreateRoomModal({
const trimmedName = name.trim();
const trimmedDescription = description.trim();
const canSubmit =
- !!serverId && !!trimmedName && !!trimmedDescription && !!selectedBridge && !isSubmitting;
+ workspaceId !== null &&
+ !!trimmedName &&
+ !!trimmedDescription &&
+ !!selectedBridge &&
+ !isSubmitting;
const handleSubmit = useCallback(async () => {
if (!canSubmit || !selectedBridge) return;
@@ -120,8 +130,8 @@ export const CreateRoomModal = observer(function CreateRoomModal({
setError(null);
try {
- const result = await rpc.switchServers.createRoom({
- serverId,
+ const result = await rpc.workspaces.createRoom({
+ workspaceId: workspaceId as string,
name: trimmedName,
description: trimmedDescription,
instructions: instructions.trim() || undefined,
@@ -160,7 +170,7 @@ export const CreateRoomModal = observer(function CreateRoomModal({
}, [
canSubmit,
selectedBridge,
- serverId,
+ workspaceId,
trimmedName,
trimmedDescription,
instructions,
@@ -286,7 +296,7 @@ export const CreateRoomModal = observer(function CreateRoomModal({
<ChosenAgentTile
key={agent.id}
agent={agent}
- subtitle={agentProviderLabelFor(agent.id, serverId)}
+ subtitle={agentProviderLabelFor(agent.id, workspaceId)}
onRemove={() =>
setAgents((current) => current.filter((a) => a.id !== agent.id))
}
@@ -300,7 +310,10 @@ export const CreateRoomModal = observer(function CreateRoomModal({
onPick={(next) => setAgents((current) => [...current, next])}
searchText={(item) => item.name}
renderItem={(item) => (
- <AgentPickerRow agent={item} subtitle={agentProviderLabelFor(item.id, serverId)} />
+ <AgentPickerRow
+ agent={item}
+ subtitle={agentProviderLabelFor(item.id, workspaceId)}
+ />
)}
disabled={agentsQuery.isLoading}
placeholder={agentsQuery.isLoading ? 'Loading agents…' : 'Search agents to add...'}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/DisconnectMessagingAppModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/DisconnectMessagingAppModal.tsx
index dad51f0b5..47494721b 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/DisconnectMessagingAppModal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/DisconnectMessagingAppModal.tsx
@@ -17,7 +17,7 @@ import { Input } from '@renderer/lib/ui/input';
import type { DeleteBridgeResult } from '@shared/core/switch-servers/switch-servers';
type DisconnectMessagingAppModalArgs = {
- serverId: string;
+ workspaceId: string;
bridgeId: string;
bridgeDisplayName: string;
};
@@ -25,7 +25,7 @@ type DisconnectMessagingAppModalArgs = {
type Props = BaseModalProps<void> & DisconnectMessagingAppModalArgs;
/**
- * Confirm disconnecting a messaging app from a Switch server (CHOO-2137).
+ * Confirm disconnecting a messaging app from a workspace (CHOO-2137).
*
* "Disconnect" undersells it: the server deletes every Switch room on the
* bridge before removing the bridge itself, so this is the most destructive
@@ -40,7 +40,7 @@ type Props = BaseModalProps<void> & DisconnectMessagingAppModalArgs;
export const DisconnectMessagingAppModal = observer(function DisconnectMessagingAppModal({
bridgeDisplayName,
bridgeId,
- serverId,
+ workspaceId,
onSuccess,
onClose,
}: Props) {
@@ -55,7 +55,7 @@ export const DisconnectMessagingAppModal = observer(function DisconnectMessaging
setIsDeleting(true);
setError(null);
try {
- const result = await rpc.switchServers.deleteBridge({ serverId, bridgeId });
+ const result = await rpc.workspaces.deleteBridge({ workspaceId, bridgeId });
if (result.kind !== 'deleted') {
setError(messageFor(result));
setIsDeleting(false);
@@ -66,7 +66,7 @@ export const DisconnectMessagingAppModal = observer(function DisconnectMessaging
setError(failureText(cause, 'Could not disconnect the messaging app.'));
setIsDeleting(false);
}
- }, [typeConfirmed, serverId, bridgeId, onSuccess]);
+ }, [typeConfirmed, workspaceId, bridgeId, onSuccess]);
return (
<>
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx
index eb09a49d1..798eae8aa 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx
@@ -14,6 +14,7 @@ import {
} from 'lucide-react';
import { observer } from 'mobx-react-lite';
import { useEffect, useMemo, useState } from 'react';
+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';
import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';
import { failureText } from '@renderer/lib/errors/describe-failure';
@@ -90,15 +91,16 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({
const showConnectMessagingApp = useShowModal('connectMessagingAppModal');
const showClaimIdentity = useShowModal('claimIdentityModal');
const showDisconnectMessagingApp = useShowModal('disconnectMessagingAppModal');
+ const workspaceId = workspacesStore.soleIdOnServer(serverId);
const isAdmin = switchServersStore.statusFor(serverId)?.user?.role === 'admin';
// Only a stack Switch Console runs has a chat whose credentials it generated and
// can therefore show; anyone else's Mattermost is their own to hand out.
const isManaged = !!switchServersStore.servers.find((s) => s.id === serverId)?.managed;
const bridgesQuery = useQuery({
- queryKey: ['remote-bridges', serverId],
- queryFn: () => rpc.switchServers.listRemoteBridges(serverId),
- enabled: !!serverId,
+ queryKey: ['remote-bridges', workspaceId],
+ queryFn: () => rpc.workspaces.listBridges(workspaceId as string),
+ enabled: workspaceId !== null,
});
const bridges = useMemo(() => orderBridges(bridgesQuery.data ?? []), [bridgesQuery.data]);
@@ -107,7 +109,7 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({
identities,
error: identitiesError,
refresh: refreshIdentities,
- } = useMyIdentities(serverId);
+ } = useMyIdentities(workspaceId);
// Whose claim to drop when unlinking. Every account here is one the signed-in
// user claimed, and other people may hold the same one — so name the user
// rather than let the server infer it. Null until the session is read back,
@@ -122,9 +124,9 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({
// agent's policy should stop the warning on the next look, not a minute later.
const anyUnlinked = hasUnlinkedMessagingApp(bridges, identities);
const ownerAgentsQuery = useQuery({
- queryKey: ['owns-owner-addressed-agent', serverId],
- queryFn: () => rpc.switchServers.ownsOwnerAddressedAgent(serverId),
- enabled: !!serverId && anyUnlinked,
+ queryKey: ['owns-owner-addressed-agent', workspaceId],
+ queryFn: () => rpc.workspaces.ownsOwnerAddressedAgent(workspaceId as string),
+ enabled: workspaceId !== null && anyUnlinked,
});
// The probe failing costs no data on screen, only the warning — so it is
// logged rather than shown, and the card does not warn on a guess.
@@ -132,11 +134,11 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({
useEffect(() => {
if (ownerAgentsError) {
log.warn('Could not check for owner-addressed agents', {
- serverId,
+ workspaceId,
error: ownerAgentsError,
});
}
- }, [ownerAgentsError, serverId]);
+ }, [ownerAgentsError, workspaceId]);
const unrecognisedIn = unrecognisedMessagingApps({
bridges,
@@ -151,11 +153,12 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({
const [toggleError, setToggleError] = useState<string | null>(null);
const handleToggleChannelCreation = async (bridge: RemoteBridge, enabled: boolean) => {
+ if (workspaceId === null) return;
setSavingBridgeId(bridge.id);
setToggleError(null);
try {
- const result = await rpc.switchServers.updateBridge({
- serverId,
+ const result = await rpc.workspaces.updateBridge({
+ workspaceId,
bridgeId: bridge.id,
channelCreationEnabled: enabled,
});
@@ -163,7 +166,7 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({
setToggleError(`Could not update ${bridge.displayName}: ${messageForUpdate(result)}`);
return;
}
- await queryClient.invalidateQueries({ queryKey: ['remote-bridges', serverId] });
+ await queryClient.invalidateQueries({ queryKey: ['remote-bridges', workspaceId] });
} catch (cause) {
setToggleError(failureText(cause, `Could not update ${bridge.displayName}.`));
} finally {
@@ -206,7 +209,7 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({
onSuccess: ({ bridgeId, displayName, directorySearchSupported }) => {
// Refresh the bridge list everywhere it is consumed — this
// card and the room-creation picker share the query key.
- void queryClient.invalidateQueries({ queryKey: ['remote-bridges', serverId] });
+ void queryClient.invalidateQueries({ queryKey: ['remote-bridges', workspaceId] });
void switchRoomsStore.refreshRoomState();
// Step 2 of connecting a workspace: say which account in it
// is yours (CHOO-2137). Offered here because this is the one
@@ -222,8 +225,11 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({
// has messaged the app and there is a name to pick. Say that,
// rather than closing on nothing and leaving the step looking
// forgotten.
- if (shouldOfferIdentityLinkOnConnect({ directorySearchSupported })) {
- showClaimIdentity({ serverId, bridgeId });
+ if (
+ workspaceId !== null &&
+ shouldOfferIdentityLinkOnConnect({ directorySearchSupported })
+ ) {
+ showClaimIdentity({ workspaceId, bridgeId });
return;
}
const note = identityLinkOrderingNote({ displayName, directorySearchSupported });
@@ -280,6 +286,7 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({
{bridges.map((bridge) => (
<MessagingAppRow
key={bridge.id}
+ workspaceId={workspaceId}
serverId={serverId}
bridge={bridge}
/* Nothing is drawn in the identity column until the list
@@ -295,22 +302,23 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({
onToggleChannelCreation={(enabled) =>
void handleToggleChannelCreation(bridge, enabled)
}
- onDisconnect={() =>
+ onDisconnect={() => {
+ if (workspaceId === null) return;
showDisconnectMessagingApp({
- serverId,
+ workspaceId,
bridgeId: bridge.id,
bridgeDisplayName: bridge.displayName,
onSuccess: () => {
void queryClient.invalidateQueries({
- queryKey: ['remote-bridges', serverId],
+ queryKey: ['remote-bridges', workspaceId],
});
// The rooms on that bridge went with it, so the sidebar
// is stale in a way the bridge list alone does not
// repair.
void switchRoomsStore.refreshRoomState();
},
- })
- }
+ });
+ }}
/>
))}
</div>
@@ -331,6 +339,7 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({
* disconnecting it — is in the menu.
*/
export function MessagingAppRow({
+ workspaceId,
serverId,
bridge,
identities,
@@ -342,9 +351,13 @@ export function MessagingAppRow({
onToggleChannelCreation,
onDisconnect,
}: {
+ /** Null while this install has not resolved the server's workspace; the
+ * identity actions are the only thing that needs it, and they wait. */
+ workspaceId: string | null;
+ /** Only for the bundled chat's sign-in, which is about the gateway. */
serverId: string;
bridge: RemoteBridge;
- /** Accounts the user has claimed on this server, or null while unknown. */
+ /** Accounts the user has claimed in this workspace, or null while unknown. */
identities: LinkedIdentity[] | null;
currentUserId: string | null;
onReleased: () => void;
@@ -361,14 +374,18 @@ export function MessagingAppRow({
const identity = identities?.find((i) => i.bridgeId === bridge.id) ?? null;
const platform = bridgePlatformLabel(bridge.type);
- const claim = () => showClaimIdentity({ serverId, bridgeId: bridge.id });
+ const claim = () => {
+ if (workspaceId === null) return;
+ showClaimIdentity({ workspaceId, bridgeId: bridge.id });
+ };
const release = async (identityId: string) => {
+ if (workspaceId === null) return;
setReleasing(true);
setReleaseError(null);
try {
- await rpc.switchServers.releaseBridgeIdentity({
- serverId,
+ await rpc.workspaces.releaseBridgeIdentity({
+ workspaceId,
bridgeId: bridge.id,
identityId,
userId: currentUserId,
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/agent-server-picker.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/agent-server-picker.tsx
index c3437f11c..4405821ce 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/agent-server-picker.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/agent-server-picker.tsx
@@ -2,6 +2,7 @@ import { useQuery } from '@tanstack/react-query';
import { CheckCircle2, CircleAlert, Loader2 } from 'lucide-react';
import { observer } from 'mobx-react-lite';
import { useEffect } from 'react';
+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { rpc } from '@renderer/lib/ipc';
import {
Select,
@@ -15,7 +16,7 @@ import type { AgentVerifyResult } from '@shared/core/switch-servers/switch-serve
import { switchServersStore } from './switch-servers-store';
/** Verification phase the picker reports up so a parent can gate submission. */
-export type ServerVerifyState = 'idle' | 'checking' | AgentVerifyResult;
+export type ServerVerifyState = 'idle' | 'checking' | 'no-workspace' | AgentVerifyResult;
interface AgentServerPickerProps {
/** The Switch agent id to verify against the chosen server. */
@@ -50,17 +51,24 @@ export const AgentServerPicker = observer(function AgentServerPicker({
const servers = switchServersStore.servers;
+ const workspaceId = workspacesStore.soleIdOnServer(serverId);
const verifyQuery = useQuery({
- queryKey: ['verifyAgent', serverId, switchAgentId],
- queryFn: () => rpc.switchServers.verifyAgent({ serverId: serverId!, agentId: switchAgentId }),
- enabled: !!serverId && !!switchAgentId,
+ queryKey: ['verifyAgent', workspaceId, switchAgentId],
+ queryFn: () =>
+ rpc.workspaces.verifyAgent({ workspaceId: workspaceId!, agentId: switchAgentId }),
+ enabled: !!workspaceId && !!switchAgentId,
});
+ // A disabled query reports `isPending` forever, so a server with no workspace
+ // to verify against has to be its own state: read as "checking" it would spin
+ // for as long as the dialog is open and never say why submit stays shut.
const state: ServerVerifyState = !serverId
? 'idle'
- : verifyQuery.isPending
- ? 'checking'
- : (verifyQuery.data ?? 'checking');
+ : workspaceId === null
+ ? 'no-workspace'
+ : verifyQuery.isPending
+ ? 'checking'
+ : (verifyQuery.data ?? 'checking');
useEffect(() => {
onVerifyStateChange(state);
@@ -117,6 +125,13 @@ function VerifyStatus({ state, serverName }: { state: ServerVerifyState; serverN
</Row>
);
}
+ if (state === 'no-workspace') {
+ return (
+ <Row icon={<CircleAlert className="size-3.5 text-amber-500" />}>
+ {serverName} has no workspace to register this agent in yet.
+ </Row>
+ );
+ }
if (state === 'unauthenticated') {
return (
<Row icon={<CircleAlert className="size-3.5 text-amber-500" />}>
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/bridge-identity-search.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/bridge-identity-search.tsx
index 0439ea870..52e8c8a8d 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/bridge-identity-search.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/bridge-identity-search.tsx
@@ -2,6 +2,7 @@ import { useQuery, useQueryClient } from '@tanstack/react-query';
import { CircleAlert } from 'lucide-react';
import { observer } from 'mobx-react-lite';
import { useState } from 'react';
+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { failureText } from '@renderer/lib/errors/describe-failure';
import { useDebounce } from '@renderer/lib/hooks/useDebounce';
import { rpc } from '@renderer/lib/ipc';
@@ -38,7 +39,7 @@ const MIN_QUERY_LENGTH = 2;
* written first.
*/
export const BridgeIdentitySearch = observer(function BridgeIdentitySearch({
- serverId,
+ workspaceId,
bridgeId,
bridgeDisplayName,
platform,
@@ -46,9 +47,9 @@ export const BridgeIdentitySearch = observer(function BridgeIdentitySearch({
autoFocus,
onClaimed,
}: {
- serverId: string;
+ workspaceId: string;
bridgeId: string;
- /** The workspace being searched — two connections on the same platform can
+ /** The bridge being searched — two connections on the same platform can
* exist, and only the name tells them apart. */
bridgeDisplayName: string;
/** The platform as a person names it, for prose about what is searchable. */
@@ -59,21 +60,24 @@ export const BridgeIdentitySearch = observer(function BridgeIdentitySearch({
}) {
const { setCloseGuard } = useModalContext();
const queryClient = useQueryClient();
- const currentUserId = switchServersStore.statusFor(serverId)?.user?.id ?? null;
+ const serverId = workspacesStore.serverIdFor(workspaceId);
+ const currentUserId = serverId
+ ? (switchServersStore.statusFor(serverId)?.user?.id ?? null)
+ : null;
const [search, setSearch] = useState('');
const [claiming, setClaiming] = useState<string | null>(null);
const [releasing, setReleasing] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
- const { refresh: refreshIdentities } = useMyIdentities(serverId || null);
+ const { refresh: refreshIdentities } = useMyIdentities(workspaceId || null);
const debouncedQuery = useDebounce(search.trim(), SEARCH_DEBOUNCE_MS);
- const searchable = !!serverId && debouncedQuery.length >= MIN_QUERY_LENGTH;
+ const searchable = !!workspaceId && debouncedQuery.length >= MIN_QUERY_LENGTH;
const directoryQuery = useQuery({
- queryKey: ['bridge-directory', serverId, bridgeId, debouncedQuery],
+ queryKey: ['bridge-directory', workspaceId, bridgeId, debouncedQuery],
queryFn: () =>
- rpc.switchServers.searchBridgeDirectory({ serverId, bridgeId, query: debouncedQuery }),
+ rpc.workspaces.searchBridgeDirectory({ workspaceId, bridgeId, query: debouncedQuery }),
enabled: searchable,
});
@@ -82,8 +86,8 @@ export const BridgeIdentitySearch = observer(function BridgeIdentitySearch({
setCloseGuard(true);
setError(null);
try {
- const result = await rpc.switchServers.claimBridgeIdentity({
- serverId,
+ const result = await rpc.workspaces.claimBridgeIdentity({
+ workspaceId,
bridgeId,
externalUserId: person.externalUserId,
username: person.username,
@@ -111,14 +115,16 @@ export const BridgeIdentitySearch = observer(function BridgeIdentitySearch({
setCloseGuard(true);
setError(null);
try {
- await rpc.switchServers.releaseBridgeIdentity({
- serverId,
+ await rpc.workspaces.releaseBridgeIdentity({
+ workspaceId,
bridgeId,
identityId: person.knownExternalUserId,
userId: currentUserId,
});
refreshIdentities();
- await queryClient.invalidateQueries({ queryKey: ['bridge-directory', serverId, bridgeId] });
+ await queryClient.invalidateQueries({
+ queryKey: ['bridge-directory', workspaceId, bridgeId],
+ });
} catch (cause) {
setError(failureText(cause, 'Could not unlink this account.'));
} finally {
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-accounts-step.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-accounts-step.tsx
index 05fa1b28b..37cfeff94 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-accounts-step.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-accounts-step.tsx
@@ -2,6 +2,7 @@ import { useQuery } from '@tanstack/react-query';
import { Check, Link2, MessageSquare, TriangleAlert } from 'lucide-react';
import { observer } from 'mobx-react-lite';
import { useState } from 'react';
+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';
import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';
import { failureText } from '@renderer/lib/errors/describe-failure';
@@ -43,13 +44,15 @@ export const LinkAccountsStep = observer(function LinkAccountsStep({
// to and give the user two Backs meaning different things.
const [linking, setLinking] = useState<RemoteBridge | null>(null);
+ const workspaceId = workspacesStore.soleIdOnServer(serverId);
const bridgesQuery = useQuery({
- queryKey: ['remote-bridges', serverId],
- queryFn: () => rpc.switchServers.listRemoteBridges(serverId),
+ queryKey: ['remote-bridges', workspaceId],
+ queryFn: () => rpc.workspaces.listBridges(workspaceId as string),
+ enabled: workspaceId !== null,
});
- const { identities } = useMyIdentities(serverId);
+ const { identities } = useMyIdentities(workspaceId);
- if (linking) {
+ if (linking && workspaceId !== null) {
return (
<>
<WizardStepHeader
@@ -63,7 +66,7 @@ export const LinkAccountsStep = observer(function LinkAccountsStep({
Find yourself in {linking.displayName} and tell Switch that account is you.
</p>
<BridgeIdentitySearch
- serverId={serverId}
+ workspaceId={workspaceId}
bridgeId={linking.id}
bridgeDisplayName={linking.displayName}
platform={bridgePlatformLabel(linking.type)}
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.tsx
index d8f0c0ede..12e97c28c 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
@@ -13,7 +13,7 @@ import { useToast } from '@renderer/lib/hooks/use-toast';
import { rpc } from '@renderer/lib/ipc';
import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';
import { useShowModal } from '@renderer/lib/modal/modal-provider';
-import { useAgentIconUrl } from '@renderer/lib/stores/use-remote-agents';
+import { useAgentIconUrl } from '@renderer/lib/stores/use-workspace-agents';
import { Button } from '@renderer/lib/ui/button';
import {
DropdownMenu,
@@ -96,7 +96,7 @@ const AgentCard = observer(function AgentCard({
const sshHost = location?.data?.sshHost ?? null;
const label = agent.name || 'Unnamed agent';
const provider = providerDisplayName(agent.providerId);
- const iconUrl = useAgentIconUrl(serverId, agent.switchAgentId);
+ const iconUrl = useAgentIconUrl(agent.workspaceId, agent.switchAgentId);
const gatewayUrl =
agent.switchAgentId && switchRoomsStore.gatewayAgentUrl(serverId, agent.switchAgentId);
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-rooms-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-rooms-view.tsx
index 5ca6828d2..4b7676344 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-rooms-view.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-rooms-view.tsx
@@ -6,12 +6,13 @@ import { agentsStore } from '@renderer/features/locations/stores/agents-store';
import { refreshSidebarRoomState } from '@renderer/features/sidebar/sidebar-tree-data';
import { openRoom } from '@renderer/features/switch-rooms/open-room';
import { roomTitle } from '@renderer/features/switch-rooms/room-labels';
+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { AgentAvatar } from '@renderer/lib/components/agent-avatar';
import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';
import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';
import { useParams } from '@renderer/lib/layout/navigation-provider';
import { useShowModal } from '@renderer/lib/modal/modal-provider';
-import { useRemoteAgents } from '@renderer/lib/stores/use-remote-agents';
+import { useWorkspaceAgents } from '@renderer/lib/stores/use-workspace-agents';
import { Button } from '@renderer/lib/ui/button';
import { SearchInput } from '@renderer/lib/ui/search-input';
import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';
@@ -43,9 +44,10 @@ const ServerRoomsPanel = observer(function ServerRoomsPanel() {
void refreshSidebarRoomState(false);
}, [serverId]);
- const rooms = switchRoomsStore.readableRoomsOnServer(serverId);
- const signedOut = switchRoomsStore.serversNotSignedIn.some((s) => s.id === serverId);
- const failed = switchRoomsStore.serversThatFailedToLoad.some((s) => s.id === serverId);
+ const workspaceId = workspacesStore.soleIdOnServer(serverId);
+ const rooms = workspaceId === null ? [] : switchRoomsStore.readableRoomsInWorkspace(workspaceId);
+ const signedOut = switchRoomsStore.workspacesNotSignedIn.some((w) => w.id === workspaceId);
+ const failed = switchRoomsStore.workspacesThatFailedToLoad.some((w) => w.id === workspaceId);
const query = filter.trim().toLowerCase();
const matching = query === '' ? rooms : rooms.filter((r) => r.name.toLowerCase().includes(query));
@@ -56,16 +58,24 @@ const ServerRoomsPanel = observer(function ServerRoomsPanel() {
title="Your Rooms"
description={`Rooms on ${server?.name ?? 'this server'}. Create one, see who is in it, and where it is bridged.`}
action={
- <Button size="sm" disabled={signedOut} onClick={() => showCreateRoomModal({ serverId })}>
+ <Button
+ size="sm"
+ disabled={signedOut || workspaceId === null}
+ onClick={() => showCreateRoomModal({ serverId })}
+ >
<Plus className="size-4" />
Create room
</Button>
}
>
- {/* Three ways to have no rows, and only one of them means "there are no
- rooms". Saying that in the other two would send someone off to create a
+ {/* Four ways to have no rows, and only one of them means "there are no
+ rooms". Saying that in the others would send someone off to create a
room they already have. */}
- {signedOut ? (
+ {workspaceId === null ? (
+ <ServerTableEmpty>
+ This server has no workspace yet, so its rooms cannot be read.
+ </ServerTableEmpty>
+ ) : signedOut ? (
<ServerTableEmpty>
Sign in to {server?.name ?? 'this server'} to see its rooms.
</ServerTableEmpty>
@@ -98,6 +108,7 @@ const ServerRoomsPanel = observer(function ServerRoomsPanel() {
key={group.key}
group={group}
serverId={serverId}
+ workspaceId={workspaceId}
// Nothing folds while a filter is on. Typing a name and being
// shown a "Show 3 more" where the match is hiding is the one
// moment the fold would cost more than it saves.
@@ -171,10 +182,12 @@ const ROOMS_BEFORE_FOLD = 5;
const MessagingAppGroup = observer(function MessagingAppGroup({
group,
serverId,
+ workspaceId,
fold,
}: {
group: RoomGroup;
serverId: string;
+ workspaceId: string;
/** Whether long groups are cut short. False while the list is filtered. */
fold: boolean;
}) {
@@ -217,7 +230,7 @@ const MessagingAppGroup = observer(function MessagingAppGroup({
{open && (
<div className="divide-y divide-border overflow-hidden rounded-[10px] border border-border">
{shown.map((room) => (
- <RoomRow key={room.id} room={room} serverId={serverId} />
+ <RoomRow key={room.id} room={room} serverId={serverId} workspaceId={workspaceId} />
))}
{fold && group.rooms.length > ROOMS_BEFORE_FOLD && (
<button
@@ -240,12 +253,14 @@ const MessagingAppGroup = observer(function MessagingAppGroup({
const RoomRow = observer(function RoomRow({
room,
serverId,
+ workspaceId,
}: {
room: RemoteRoomSummary;
serverId: string;
+ workspaceId: string;
}) {
const members = switchRoomsStore.localMemberIds(room.id);
- const { data: remoteAgents } = useRemoteAgents(serverId);
+ const { data: remoteAgents } = useWorkspaceAgents(workspaceId);
const remoteById = new Map((remoteAgents ?? []).map((agent) => [agent.id, agent]));
const localAgents = agentsStore
.agentsOnServer(serverId)
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-stat-tiles.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-stat-tiles.tsx
index 185fca734..013426d19 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-stat-tiles.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-stat-tiles.tsx
@@ -2,6 +2,7 @@ import { useQuery } from '@tanstack/react-query';
import { observer } from 'mobx-react-lite';
import { useEffect } from 'react';
import { agentsStore } from '@renderer/features/locations/stores/agents-store';
+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { rpc } from '@renderer/lib/ipc';
import { switchRoomsStore } from './switch-rooms-store';
@@ -18,12 +19,14 @@ export const ServerStatTiles = observer(function ServerStatTiles({
}: {
serverId: string;
}) {
+ const workspaceId = workspacesStore.soleIdOnServer(serverId);
+
// Shares the key every other bridge reader uses, so the list is already in
// cache by the time this renders and the tile never fetches on its own.
const bridgesQuery = useQuery({
- queryKey: ['remote-bridges', serverId],
- queryFn: () => rpc.switchServers.listRemoteBridges(serverId),
- enabled: !!serverId,
+ queryKey: ['remote-bridges', workspaceId],
+ queryFn: () => rpc.workspaces.listBridges(workspaceId as string),
+ enabled: workspaceId !== null,
});
// The sidebar loads this too, but the page must not depend on the sidebar
@@ -40,7 +43,11 @@ export const ServerStatTiles = observer(function ServerStatTiles({
/>
<StatTile
label="Your Rooms"
- value={switchRoomsStore.readableRoomsOnServer(serverId).length}
+ value={
+ workspaceId === null
+ ? null
+ : switchRoomsStore.readableRoomsInWorkspace(workspaceId).length
+ }
/>
<StatTile label="Messaging apps" value={bridgesQuery.data?.length ?? null} />
</div>
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.ts
index eb2e1fcbb..e30d987d9 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
@@ -1,20 +1,32 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { RemoteRoomSummary } from '@shared/core/switch-servers/switch-servers';
-const listRemoteRooms = vi.hoisted(() => vi.fn());
+const listRooms = vi.hoisted(() => vi.fn());
const listAgentRooms = vi.hoisted(() => vi.fn());
const serversStore = vi.hoisted(() => ({
servers: [] as { id: string; name?: string; managed?: boolean }[],
- activeServerId: null as string | null,
isConnected: (_serverId: string): boolean => true,
// These servers answer; they are simply not signed in to.
isUnreachable: (_serverId: string): boolean => false,
statusFor: (serverId: string) => ({ user: { id: `user-of-${serverId}` } }),
}));
+const workspaces = vi.hoisted(() => ({
+ workspaces: [] as { id: string; serverId: string; name: string }[],
+ activeId: null as string | null,
+ byId(workspaceId: string) {
+ return this.workspaces.find((w) => w.id === workspaceId) ?? null;
+ },
+ serverIdFor(workspaceId: string) {
+ return this.byId(workspaceId)?.serverId ?? null;
+ },
+}));
vi.mock('@renderer/lib/ipc', () => ({
events: { on: vi.fn() },
- rpc: { switchServers: { listRemoteRooms, listAgentRooms } },
+ rpc: { workspaces: { listRooms, listAgentRooms } },
+}));
+vi.mock('@renderer/features/workspaces/workspaces-store', () => ({
+ workspacesStore: workspaces,
}));
vi.mock('./switch-servers-store', () => ({ switchServersStore: serversStore }));
vi.mock('./local-server-store', () => ({ localServerStore: { isRunning: true } }));
@@ -39,19 +51,28 @@ function room(id: string, ownerId: string | null, overrides: Partial<RemoteRoomS
} satisfies RemoteRoomSummary;
}
+/** Two workspaces, one per server, which is what every install has today. */
+function twoWorkspaces() {
+ workspaces.workspaces = [
+ { id: 'ws-a', serverId: 'srv-a', name: 'Alpha' },
+ { id: 'ws-b', serverId: 'srv-b', name: 'Beta' },
+ ];
+}
+
describe('listed rooms', () => {
beforeEach(() => {
vi.clearAllMocks();
serversStore.servers = [{ id: 'srv-a' }, { id: 'srv-b' }];
- serversStore.activeServerId = null;
+ twoWorkspaces();
+ workspaces.activeId = null;
});
- it('lists every room on a server this install manages', async () => {
+ it('lists every room in a workspace on a server this install manages', async () => {
// You run that deployment. Nothing on it should need a second app to see.
serversStore.servers = [{ id: 'srv-a', managed: true }, { id: 'srv-b' }];
- serversStore.activeServerId = 'srv-a';
- listRemoteRooms.mockImplementation(async (serverId: string) =>
- serverId === 'srv-a'
+ workspaces.activeId = 'ws-a';
+ listRooms.mockImplementation(async (workspaceId: string) =>
+ workspaceId === 'ws-a'
? [
room('mine', 'user-of-srv-a'),
room('someone-elses', 'user-of-someone-else'),
@@ -67,8 +88,8 @@ describe('listed rooms', () => {
});
it('lists only rooms owned by that server’s signed-in user, excluding archived ones', async () => {
- listRemoteRooms.mockImplementation(async (serverId: string) =>
- serverId === 'srv-a'
+ listRooms.mockImplementation(async (workspaceId: string) =>
+ workspaceId === 'ws-a'
? [
room('mine', 'user-of-srv-a'),
room('someone-elses', 'user-of-someone-else'),
@@ -84,138 +105,117 @@ describe('listed rooms', () => {
expect(store.listedRoomsInActiveScope.map((r: { id: string }) => r.id)).toEqual(['mine']);
});
- it('shows only the active server’s rooms, not every connected server’s', async () => {
- listRemoteRooms.mockImplementation(async (serverId: string) => [
- room(`${serverId}-room`, `user-of-${serverId}`),
+ 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)}`),
]);
const store = new SwitchRoomsStore();
await store.loadRoomNames();
- serversStore.activeServerId = 'srv-b';
+ workspaces.activeId = 'ws-b';
- expect(store.listedRoomsInActiveScope.map((r: { id: string }) => r.id)).toEqual(['srv-b-room']);
+ expect(store.listedRoomsInActiveScope.map((r: { id: string }) => r.id)).toEqual(['ws-b-room']);
});
- it('hides nothing when no server is active, matching how locations are scoped', async () => {
- listRemoteRooms.mockImplementation(async (serverId: string) => [
- room(`${serverId}-room`, `user-of-${serverId}`),
+ it('hides nothing when no workspace is active, matching how locations are scoped', async () => {
+ listRooms.mockImplementation(async (workspaceId: string) => [
+ room(`${workspaceId}-room`, `user-of-${workspaces.serverIdFor(workspaceId)}`),
]);
const store = new SwitchRoomsStore();
await store.loadRoomNames();
expect(store.listedRoomsInActiveScope.map((r: { id: string }) => r.id)).toEqual([
- 'srv-a-room',
- 'srv-b-room',
+ 'ws-a-room',
+ 'ws-b-room',
]);
});
- it('keeps a server that failed to respond from dropping the others', async () => {
- listRemoteRooms.mockImplementation(async (serverId: string) => {
- if (serverId === 'srv-a') throw new Error('unreachable');
- return [room('srv-b-room', 'user-of-srv-b')];
+ it('keeps a workspace that failed to respond from dropping the others', async () => {
+ listRooms.mockImplementation(async (workspaceId: string) => {
+ if (workspaceId === 'ws-a') throw new Error('unreachable');
+ return [room('ws-b-room', 'user-of-srv-b')];
});
const store = new SwitchRoomsStore();
await store.loadRoomNames();
- expect(store.listedRoomsInActiveScope.map((r: { id: string }) => r.id)).toEqual(['srv-b-room']);
+ expect(store.listedRoomsInActiveScope.map((r: { id: string }) => r.id)).toEqual(['ws-b-room']);
});
- it('says the room list is incomplete when a server could not be read', async () => {
- serversStore.servers = [
- { id: 'srv-a', name: 'Alpha' },
- { id: 'srv-b', name: 'Beta' },
- ];
- listRemoteRooms.mockImplementation(async (serverId: string) => {
- if (serverId === 'srv-a') throw new Error('unreachable');
- return [room('srv-b-room', 'user-of-srv-b')];
+ it('says the room list is incomplete when a workspace could not be read', async () => {
+ listRooms.mockImplementation(async (workspaceId: string) => {
+ if (workspaceId === 'ws-a') throw new Error('unreachable');
+ return [room('ws-b-room', 'user-of-srv-b')];
});
const store = new SwitchRoomsStore();
await store.loadRoomNames();
- expect(store.serversThatFailedToLoad.map((s) => s.name)).toEqual(['Alpha']);
+ expect(store.workspacesThatFailedToLoad.map((w) => w.name)).toEqual(['Alpha']);
});
- it('asks only the active server for its rooms', async () => {
- serversStore.servers = [
- { id: 'srv-a', name: 'Alpha' },
- { id: 'srv-b', name: 'Beta' },
- ];
- serversStore.activeServerId = 'srv-b';
- listRemoteRooms.mockImplementation(async () => []);
+ it('asks only the active workspace for its rooms', async () => {
+ workspaces.activeId = 'ws-b';
+ listRooms.mockImplementation(async () => []);
const store = new SwitchRoomsStore();
await store.loadRoomNames();
- expect(listRemoteRooms).toHaveBeenCalledExactlyOnceWith('srv-b');
+ expect(listRooms).toHaveBeenCalledExactlyOnceWith('ws-b');
});
- it('does not report another server’s failure against the one you are viewing', async () => {
- // Each server is its own world. A server you are not looking at being down
- // says nothing about the one you are, and warning about it trains you to
- // ignore the warning.
- serversStore.servers = [
- { id: 'srv-a', name: 'Alpha' },
- { id: 'srv-b', name: 'Beta' },
- ];
- listRemoteRooms.mockImplementation(async (serverId: string) => {
- if (serverId === 'srv-a') throw new Error('unreachable');
- return [room('srv-b-room', 'user-of-srv-b')];
+ it('does not report another workspace’s failure against the one you are viewing', async () => {
+ // Each workspace is its own world. One you are not looking at being
+ // unreadable says nothing about the one you are, and warning about it trains
+ // you to ignore the warning.
+ listRooms.mockImplementation(async (workspaceId: string) => {
+ if (workspaceId === 'ws-a') throw new Error('unreachable');
+ return [room('ws-b-room', 'user-of-srv-b')];
});
const store = new SwitchRoomsStore();
- // Search loads every server, so Alpha's failure is on the record...
- await store.loadRoomsOnAllServers();
- expect(store.serversThatFailedToLoad.map((s) => s.name)).toEqual(['Alpha']);
+ // Search loads every workspace, so Alpha's failure is on the record...
+ await store.loadRoomsInAllWorkspaces();
+ expect(store.workspacesThatFailedToLoad.map((w) => w.name)).toEqual(['Alpha']);
- // ...but it must not surface while Beta is the server on screen.
- serversStore.activeServerId = 'srv-b';
- expect(store.serversThatFailedToLoad).toEqual([]);
- expect(store.serversNotSignedIn).toEqual([]);
+ // ...but it must not surface while Beta is the workspace on screen.
+ workspaces.activeId = 'ws-b';
+ expect(store.workspacesThatFailedToLoad).toEqual([]);
+ expect(store.workspacesNotSignedIn).toEqual([]);
});
- it('does not report a disconnected server you are not viewing', async () => {
- serversStore.servers = [
- { id: 'srv-a', name: 'Alpha' },
- { id: 'srv-b', name: 'Beta' },
- ];
- serversStore.activeServerId = 'srv-b';
+ it('does not report a signed-out workspace you are not viewing', async () => {
+ workspaces.activeId = 'ws-b';
serversStore.isConnected = (serverId: string) => serverId !== 'srv-a';
- listRemoteRooms.mockImplementation(async () => []);
+ listRooms.mockImplementation(async () => []);
const store = new SwitchRoomsStore();
- await store.loadRoomsOnAllServers();
+ await store.loadRoomsInAllWorkspaces();
- expect(store.serversNotSignedIn).toEqual([]);
+ expect(store.workspacesNotSignedIn).toEqual([]);
serversStore.isConnected = () => true;
});
- it('reports a server it is not signed in to as needing sign-in, not as failed', async () => {
+ it('reports a workspace it is not signed in to as needing sign-in, not as failed', async () => {
// Signing in is an action the user takes; a retry button cannot fix it, and
// calling it a failure sends them round in a circle.
- serversStore.servers = [
- { id: 'srv-a', name: 'Alpha' },
- { id: 'srv-b', name: 'Beta' },
- ];
- serversStore.activeServerId = 'srv-b';
+ workspaces.activeId = 'ws-b';
serversStore.isConnected = (serverId: string) => serverId !== 'srv-b';
- listRemoteRooms.mockImplementation(async () => []);
+ listRooms.mockImplementation(async () => []);
const store = new SwitchRoomsStore();
await store.loadRoomNames();
- expect(store.serversNotSignedIn.map((s) => s.name)).toEqual(['Beta']);
- expect(store.serversThatFailedToLoad).toEqual([]);
+ expect(store.workspacesNotSignedIn.map((w) => w.name)).toEqual(['Beta']);
+ expect(store.workspacesThatFailedToLoad).toEqual([]);
serversStore.isConnected = () => true;
});
it('marks a room’s name as blocked on sign-in when its server is signed out', async () => {
- serversStore.servers = [{ id: 'srv-a', name: 'Alpha' }];
- serversStore.activeServerId = 'srv-a';
+ workspaces.activeId = 'ws-a';
serversStore.isConnected = () => false;
- listRemoteRooms.mockImplementation(async () => []);
+ listRooms.mockImplementation(async () => []);
const store = new SwitchRoomsStore();
await store.loadRoomNames();
@@ -225,25 +225,26 @@ describe('listed rooms', () => {
expect(store.roomNameBlockedBySignIn('some-room')).toBe(false);
});
- it('clears a server’s failure once it can be read again', async () => {
- serversStore.servers = [{ id: 'srv-a', name: 'Alpha' }];
- listRemoteRooms.mockImplementation(async () => {
+ it('clears a workspace’s failure once it can be read again', async () => {
+ workspaces.activeId = 'ws-a';
+ listRooms.mockImplementation(async () => {
throw new Error('unreachable');
});
const store = new SwitchRoomsStore();
await store.loadRoomNames();
- expect(store.serversThatFailedToLoad.map((s) => s.name)).toEqual(['Alpha']);
+ expect(store.workspacesThatFailedToLoad.map((w) => w.name)).toEqual(['Alpha']);
- listRemoteRooms.mockImplementation(async () => [room('back', 'user-of-srv-a')]);
+ listRooms.mockImplementation(async () => [room('back', 'user-of-srv-a')]);
await store.loadRoomNames();
- expect(store.serversThatFailedToLoad).toEqual([]);
+ expect(store.workspacesThatFailedToLoad).toEqual([]);
});
});
describe('agent memberships', () => {
beforeEach(() => {
vi.clearAllMocks();
+ twoWorkspaces();
listAgentRooms.mockImplementation(async ({ agentId }: { agentId: string }) => [
{
roomId: `room-of-${agentId}`,
@@ -259,17 +260,17 @@ describe('agent memberships', () => {
const store = new SwitchRoomsStore();
await store.ensureMembershipsFor([
- { serverId: 'srv-a', switchAgentId: 'agent-1' },
- { serverId: 'srv-a', switchAgentId: 'agent-2' },
+ { workspaceId: 'ws-a', switchAgentId: 'agent-1' },
+ { workspaceId: 'ws-a', switchAgentId: 'agent-2' },
]);
- expect(store.roomsFor('srv-a', 'agent-1')?.[0].roomId).toBe('room-of-agent-1');
- expect(store.roomsFor('srv-a', 'agent-2')?.[0].roomId).toBe('room-of-agent-2');
+ expect(store.roomsFor('ws-a', 'agent-1')?.[0].roomId).toBe('room-of-agent-1');
+ expect(store.roomsFor('ws-a', 'agent-2')?.[0].roomId).toBe('room-of-agent-2');
});
it('serves cached memberships without refetching, unless forced', async () => {
const store = new SwitchRoomsStore();
- const agents = [{ serverId: 'srv-a', switchAgentId: 'agent-1' }];
+ const agents = [{ workspaceId: 'ws-a', switchAgentId: 'agent-1' }];
await store.ensureMembershipsFor(agents);
await store.ensureMembershipsFor(agents);
@@ -293,8 +294,8 @@ describe('agent memberships', () => {
const store = new SwitchRoomsStore();
await store.ensureMembershipsFor([
- { serverId: 'srv-a', switchAgentId: 'agent-1' },
- { serverId: 'srv-a', switchAgentId: 'agent-2' },
+ { workspaceId: 'ws-a', switchAgentId: 'agent-1' },
+ { workspaceId: 'ws-a', switchAgentId: 'agent-2' },
]);
expect(store.localMemberIds('shared').sort()).toEqual(['agent-1', 'agent-2']);
@@ -307,7 +308,7 @@ describe('agent memberships', () => {
]);
const store = new SwitchRoomsStore();
- await store.ensureMembershipsFor([{ serverId: 'srv-a', switchAgentId: 'agent-1' }]);
+ await store.ensureMembershipsFor([{ workspaceId: 'ws-a', switchAgentId: 'agent-1' }]);
expect(store.localMemberIds('gone')).toEqual([]);
});
@@ -319,20 +320,20 @@ describe('agent memberships', () => {
if (agentId === 'agent-late') throw new Error('not yet');
return [{ roomId: 'room-a', roomName: 'r', archived: false, status: 'live', roomRole: null }];
});
- listRemoteRooms.mockImplementation(async () => []);
+ listRooms.mockImplementation(async () => []);
const store = new SwitchRoomsStore();
await store.ensureMembershipsFor([
- { serverId: 'srv-a', switchAgentId: 'agent-1' },
- { serverId: 'srv-a', switchAgentId: 'agent-late' },
+ { workspaceId: 'ws-a', switchAgentId: 'agent-1' },
+ { workspaceId: 'ws-a', switchAgentId: 'agent-late' },
]);
- expect(store.roomsFor('srv-a', 'agent-late')).toBeUndefined();
+ expect(store.roomsFor('ws-a', 'agent-late')).toBeUndefined();
listAgentRooms.mockImplementation(async () => [
{ roomId: 'room-b', roomName: 'r', archived: false, status: 'live', roomRole: null },
]);
await store.refreshRoomState();
- expect(store.roomsFor('srv-a', 'agent-late')?.[0].roomId).toBe('room-b');
+ expect(store.roomsFor('ws-a', 'agent-late')?.[0].roomId).toBe('room-b');
});
it('reports an agent whose membership failed as unknown, not as in no rooms', async () => {
@@ -343,8 +344,8 @@ describe('agent memberships', () => {
const store = new SwitchRoomsStore();
await store.ensureMembershipsFor([
- { serverId: 'srv-a', switchAgentId: 'agent-1' },
- { serverId: 'srv-a', switchAgentId: 'agent-2' },
+ { workspaceId: 'ws-a', switchAgentId: 'agent-1' },
+ { workspaceId: 'ws-a', switchAgentId: 'agent-2' },
]);
expect(store.agentsWithUnknownMembership).toBe(1);
@@ -354,8 +355,8 @@ describe('agent memberships', () => {
const store = new SwitchRoomsStore();
await store.ensureMembershipsFor([
- { serverId: 'srv-a', switchAgentId: 'agent-1' },
- { serverId: 'srv-a', switchAgentId: 'agent-2' },
+ { workspaceId: 'ws-a', switchAgentId: 'agent-1' },
+ { workspaceId: 'ws-a', switchAgentId: 'agent-2' },
]);
expect(store.agentsWithUnknownMembership).toBe(0);
@@ -369,15 +370,38 @@ describe('agent memberships', () => {
const store = new SwitchRoomsStore();
await store.ensureMembershipsFor([
- { serverId: 'srv-a', switchAgentId: 'agent-1' },
- { serverId: 'srv-a', switchAgentId: 'agent-2' },
+ { workspaceId: 'ws-a', switchAgentId: 'agent-1' },
+ { workspaceId: 'ws-a', switchAgentId: 'agent-2' },
]);
- expect(store.roomsFor('srv-a', 'agent-1')).toBeUndefined();
- expect(store.errorFor('srv-a', 'agent-1')).toBe(
+ expect(store.roomsFor('ws-a', 'agent-1')).toBeUndefined();
+ expect(store.errorFor('ws-a', 'agent-1')).toBe(
'Could not load the rooms this agent belongs to. (nope)'
);
- expect(store.roomsFor('srv-a', 'agent-2')?.[0].roomId).toBe('room-b');
+ expect(store.roomsFor('ws-a', 'agent-2')?.[0].roomId).toBe('room-b');
+ });
+
+ it('keeps the same agent’s membership in two workspaces apart', async () => {
+ // One server can host several, and an agent id is the server's — so a cache
+ // keyed on the agent alone would answer one workspace with the other's rooms.
+ listAgentRooms.mockImplementation(async ({ workspaceId }: { workspaceId: string }) => [
+ {
+ roomId: `room-in-${workspaceId}`,
+ roomName: 'r',
+ archived: false,
+ status: 'live',
+ roomRole: null,
+ },
+ ]);
+ const store = new SwitchRoomsStore();
+
+ await store.ensureMembershipsFor([
+ { workspaceId: 'ws-a', switchAgentId: 'agent-1' },
+ { workspaceId: 'ws-b', switchAgentId: 'agent-1' },
+ ]);
+
+ expect(store.roomsFor('ws-a', 'agent-1')?.[0].roomId).toBe('room-in-ws-a');
+ expect(store.roomsFor('ws-b', 'agent-1')?.[0].roomId).toBe('room-in-ws-b');
});
});
@@ -385,14 +409,15 @@ describe('rooms offered to a picker', () => {
beforeEach(() => {
vi.clearAllMocks();
serversStore.servers = [{ id: 'srv-a' }];
- serversStore.activeServerId = 'srv-a';
+ workspaces.workspaces = [{ id: 'ws-a', serverId: 'srv-a', name: 'Alpha' }];
+ workspaces.activeId = 'ws-a';
});
- it('offers every room the server returned, not only the ones this user made', async () => {
- // The sidebar deliberately lists a narrower set — see `listedRoomsOnServer`.
+ it('offers every room the workspace returned, not only the ones this user made', async () => {
+ // The sidebar deliberately lists a narrower set — see `listedRoomsInWorkspace`.
// A picker is a list you went looking for, so it must not hide a room you
// are entitled to join.
- listRemoteRooms.mockResolvedValue([
+ listRooms.mockResolvedValue([
room('mine', 'user-of-srv-a'),
room('someone-elses', 'user-of-someone-else'),
room('ownerless', null),
@@ -401,16 +426,16 @@ describe('rooms offered to a picker', () => {
const store = new SwitchRoomsStore();
await store.loadRoomNames();
- expect(store.readableRoomsOnServer('srv-a').map((r) => r.id)).toEqual([
+ expect(store.readableRoomsInWorkspace('ws-a').map((r) => r.id)).toEqual([
'mine',
'someone-elses',
'ownerless',
]);
- expect(store.listedRoomsOnServer('srv-a').map((r) => r.id)).toEqual(['mine']);
+ expect(store.listedRoomsInWorkspace('ws-a').map((r) => r.id)).toEqual(['mine']);
});
it('leaves out archived rooms, which are not joinable', async () => {
- listRemoteRooms.mockResolvedValue([
+ listRooms.mockResolvedValue([
room('live', 'user-of-someone-else'),
room('gone', 'user-of-someone-else', { archived: true }),
]);
@@ -418,11 +443,11 @@ describe('rooms offered to a picker', () => {
const store = new SwitchRoomsStore();
await store.loadRoomNames();
- expect(store.readableRoomsOnServer('srv-a').map((r) => r.id)).toEqual(['live']);
+ expect(store.readableRoomsInWorkspace('ws-a').map((r) => r.id)).toEqual(['live']);
});
- it('offers nothing for a server whose rooms were never read', () => {
- expect(new SwitchRoomsStore().readableRoomsOnServer('srv-a')).toEqual([]);
+ it('offers nothing for a workspace whose rooms were never read', () => {
+ expect(new SwitchRoomsStore().readableRoomsInWorkspace('ws-a')).toEqual([]);
});
});
@@ -435,6 +460,7 @@ describe('who may delete a room', () => {
beforeEach(() => {
vi.clearAllMocks();
serversStore.servers = [{ id: 'srv-a' }];
+ workspaces.workspaces = [{ id: 'ws-a', serverId: 'srv-a', name: 'Alpha' }];
serversStore.statusFor = statusWithRole(undefined);
});
@@ -444,28 +470,36 @@ describe('who may delete a room', () => {
it('lets the owner delete their own room', () => {
const store = new SwitchRoomsStore();
- expect(store.canDeleteRoom('srv-a', room('r', 'user-of-srv-a'))).toBe(true);
+ expect(store.canDeleteRoom('ws-a', room('r', 'user-of-srv-a'))).toBe(true);
});
it('refuses someone else’s room', () => {
const store = new SwitchRoomsStore();
- expect(store.canDeleteRoom('srv-a', room('r', 'user-of-someone-else'))).toBe(false);
+ expect(store.canDeleteRoom('ws-a', room('r', 'user-of-someone-else'))).toBe(false);
});
it('lets an admin delete a room they do not own, matching the gateway', () => {
serversStore.statusFor = statusWithRole('admin');
const store = new SwitchRoomsStore();
- expect(store.canDeleteRoom('srv-a', room('r', 'user-of-someone-else'))).toBe(true);
+ expect(store.canDeleteRoom('ws-a', room('r', 'user-of-someone-else'))).toBe(true);
});
it('refuses an ownerless room to a non-admin, rather than treating it as unclaimed', () => {
const store = new SwitchRoomsStore();
- expect(store.canDeleteRoom('srv-a', room('r', null))).toBe(false);
+ expect(store.canDeleteRoom('ws-a', room('r', null))).toBe(false);
});
it('refuses while signed out, when there is no one to compare against', () => {
serversStore.statusFor = () => ({ user: null }) as never;
const store = new SwitchRoomsStore();
- expect(store.canDeleteRoom('srv-a', room('r', 'user-of-srv-a'))).toBe(false);
+ expect(store.canDeleteRoom('ws-a', room('r', 'user-of-srv-a'))).toBe(false);
+ });
+
+ it('refuses a workspace whose server is not known yet', () => {
+ // The permission is the server's to answer, so an unresolved workspace is
+ // not a licence to offer the action.
+ workspaces.workspaces = [];
+ const store = new SwitchRoomsStore();
+ expect(store.canDeleteRoom('ws-a', room('r', 'user-of-srv-a'))).toBe(false);
});
});
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.ts
index 345702c77..a1de9818b 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
@@ -1,4 +1,5 @@
import { makeAutoObservable, runInAction } from 'mobx';
+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { failureText } from '@renderer/lib/errors/describe-failure';
import { rpc } from '@renderer/lib/ipc';
import type {
@@ -9,9 +10,9 @@ import { UNBRIDGED_FILTER_VALUE } from '@shared/view-state';
import { serverAvailability } from './server-availability';
import { switchServersStore } from './switch-servers-store';
-/** Cache key for an agent's room membership: server + Switch agent id. */
-function key(serverId: string, switchAgentId: string): string {
- return `${serverId}:${switchAgentId}`;
+/** Cache key for an agent's room membership: workspace + Switch agent id. */
+function key(workspaceId: string, switchAgentId: string): string {
+ return `${workspaceId}:${switchAgentId}`;
}
/**
@@ -20,43 +21,50 @@ function key(serverId: string, switchAgentId: string): string {
* Entries are cached in memory and re-fetched on demand or on window focus, so
* the "connect to room" picker and the room-focused sidebar grouping render the
* last-known set instantly while a refresh runs.
+ *
+ * Everything here is keyed by workspace, because that is what a room belongs
+ * to: one server can host several, and the same server answers with a different
+ * set of rooms in each. Where a fact is about the gateway rather than about the
+ * rooms — whether it is reachable, who is signed in, what its web app's URL is
+ * — the server is resolved from the workspace and asked for that alone.
*/
export class SwitchRoomsStore {
- /** Membership per `${serverId}:${switchAgentId}`. */
+ /** Membership per `${workspaceId}:${switchAgentId}`. */
private readonly roomsByAgent = new Map<string, RemoteAgentRoom[]>();
- /** Room id → display name, aggregated across connected servers (room ids are
+ /** Room id → display name, aggregated across workspaces (room ids are
* globally unique UUIDs, so a flat map is safe). Drives sidebar room headers. */
private readonly roomNames = new Map<string, string>();
- /** Room id → owning server id, so a room can be linked to its gateway web app. */
- private readonly roomServerById = new Map<string, string>();
+ /** Room id → owning workspace id, so a room can be addressed and linked. */
+ private readonly roomWorkspaceById = new Map<string, string>();
/** Room id → bridge type (`slack`, `mattermost`, …) when the room is bridged
* to an external platform, so the sidebar can show that platform's icon. */
private readonly bridgeTypeByRoom = new Map<string, string>();
/** Room id → native deeplink that opens its channel in the messaging app's
* desktop client, when the room is bridged and the link could be built. */
private readonly channelUrlByRoom = new Map<string, string>();
- /** Server id → the active rooms on that server owned by the signed-in user.
+ /** Workspace id → the active rooms in it owned by the signed-in user.
* The sidebar lists these even when no session is connected to them, so a
* room you create in Switch Console is visible the moment it exists rather than
* only once an agent joins it. */
- private readonly ownedRoomsByServer = new Map<string, RemoteRoomSummary[]>();
- /** Server id → every active room on it. Listed in full for a server this
- * install manages; elsewhere it backs lookups rather than the room list. */
- private readonly allRoomsByServer = new Map<string, RemoteRoomSummary[]>();
+ private readonly ownedRoomsByWorkspace = new Map<string, RemoteRoomSummary[]>();
+ /** Workspace id → every active room in it. Listed in full for a workspace on a
+ * server this install manages; elsewhere it backs lookups rather than the
+ * room list. */
+ private readonly allRoomsByWorkspace = new Map<string, RemoteRoomSummary[]>();
/** Keys with an in-flight fetch. */
readonly loading = new Set<string>();
/** Last error per key, if the most recent fetch failed. */
readonly errors = new Map<string, string>();
- /** Server id → why its room list could not be read, if the last try failed. */
+ /** Workspace id → why its room list could not be read, if the last try failed. */
private readonly roomListErrors = new Map<string, string>();
- /** Servers that were not connected when the room list was last refreshed, so
- * their rooms were never asked for at all. */
- private unreachableServerIds: string[] = [];
+ /** Workspaces whose server was not connected when the room list was last
+ * refreshed, so their rooms were never asked for at all. */
+ private unreachableWorkspaceIds: string[] = [];
/** The agents whose membership this store is responsible for keeping current.
* Recorded on {@link ensureMembershipsFor} so a refresh re-reads the current
* set rather than only the keys that happen to be cached — an agent created
* after the sidebar mounted is otherwise never fetched. */
- private trackedIdentities: { serverId: string; switchAgentId: string }[] = [];
+ private trackedIdentities: { workspaceId: string; switchAgentId: string }[] = [];
constructor() {
makeAutoObservable(this);
@@ -79,18 +87,26 @@ export class SwitchRoomsStore {
return this.channelUrlByRoom.get(roomId) ?? null;
}
- /** Id of the server a room belongs to, or null if not yet loaded. The room
- * view needs it to resolve that server's Mattermost session. */
+ /** Id of the workspace a room belongs to, or null if not yet loaded. This is
+ * what a call about the room is addressed with. */
+ roomWorkspaceId(roomId: string): string | null {
+ return this.roomWorkspaceById.get(roomId) ?? null;
+ }
+
+ /** Id of the server hosting a room's workspace, for the things that are about
+ * the gateway rather than the room — its web app, its Mattermost session. */
roomServerId(roomId: string): string | null {
- return this.roomServerById.get(roomId) ?? null;
+ const workspaceId = this.roomWorkspaceById.get(roomId);
+ if (!workspaceId) return null;
+ return workspacesStore.serverIdFor(workspaceId);
}
/**
* URL of a room's detail page in the gateway web app, or null if the room's
- * owning server isn't known yet (names/servers are loaded by loadRoomNames).
+ * owning server isn't known yet (names/workspaces are loaded by loadRoomNames).
*/
gatewayRoomUrl(roomId: string): string | null {
- const serverId = this.roomServerById.get(roomId);
+ const serverId = this.roomServerId(roomId);
if (!serverId) return null;
const server = switchServersStore.servers.find((s) => s.id === serverId);
if (!server) return null;
@@ -115,71 +131,69 @@ export class SwitchRoomsStore {
* considered — the ones that are there because of what they are, not because
* one of this install's agents is in them.
*
- * On a server this install manages, that is **every** room: you run the
- * deployment, so there is nothing on it you should have to go elsewhere to
- * see. On any other server it is the rooms you created, which would otherwise
- * disappear the moment you made one and put no agent in it.
+ * In a workspace on a server this install manages, that is **every** room: you
+ * run the deployment, so there is nothing on it you should have to go
+ * elsewhere to see. Anywhere else it is the rooms you created, which would
+ * otherwise disappear the moment you made one and put no agent in it.
*
- * The sidebar tree shows one server at a time, so these follow the same scope
- * rule as locations do — including that no active server hides nothing.
+ * The sidebar tree shows one workspace at a time, so these follow the same
+ * scope rule as locations do — including that no active workspace hides
+ * nothing.
*/
get listedRoomsInActiveScope(): RemoteRoomSummary[] {
- const activeServerId = switchServersStore.activeServerId;
- const serverIds = activeServerId
- ? [activeServerId]
- : [...new Set([...this.allRoomsByServer.keys(), ...this.ownedRoomsByServer.keys()])];
- const listed = serverIds.flatMap((serverId) => this.listedRoomsOnServer(serverId));
+ const listed = this.workspaceIdsInScope.flatMap((id) => this.listedRoomsInWorkspace(id));
return listed.sort((a, b) => a.name.localeCompare(b.name));
}
/**
- * The rooms one server contributes to the lists above, under the same scope
- * rule. Named separately so a page about a single server asks for that
- * server rather than for whichever one happens to be active.
+ * The rooms one workspace contributes to the lists above, under the same scope
+ * rule. Named separately so a page about a single workspace asks for that
+ * workspace rather than for whichever one happens to be active.
*/
- listedRoomsOnServer(serverId: string): RemoteRoomSummary[] {
+ listedRoomsInWorkspace(workspaceId: string): RemoteRoomSummary[] {
+ const serverId = workspacesStore.serverIdFor(workspaceId);
const managed = switchServersStore.servers.find((s) => s.id === serverId)?.managed ?? false;
return (
- (managed ? this.allRoomsByServer.get(serverId) : this.ownedRoomsByServer.get(serverId)) ?? []
+ (managed
+ ? this.allRoomsByWorkspace.get(workspaceId)
+ : this.ownedRoomsByWorkspace.get(workspaceId)) ?? []
);
}
/**
- * Every active room the signed-in user can see on a server — what the gateway
- * returned, which is already scoped to rooms they may read.
+ * Every active room the signed-in user can see in a workspace — what the
+ * gateway returned, which is already scoped to rooms they may read.
*
- * Wider than {@link listedRoomsOnServer} on purpose. A standing list has to
+ * Wider than {@link listedRoomsInWorkspace} on purpose. A standing list has to
* earn its place on screen, so the sidebar shows only rooms with a claim on
* you; a picker is a list you went looking for, and one that hides rooms you
* have every right to join cannot be searched into showing them.
*/
- readableRoomsOnServer(serverId: string): RemoteRoomSummary[] {
- return this.allRoomsByServer.get(serverId) ?? [];
+ readableRoomsInWorkspace(workspaceId: string): RemoteRoomSummary[] {
+ return this.allRoomsByWorkspace.get(workspaceId) ?? [];
}
/**
* The same listed rooms as {@link listedRoomsInActiveScope}, but across every
- * server rather than the active one.
+ * workspace rather than the active one.
*
- * Search is deliberately not scoped to the active server: you search precisely
- * because you do not know where a thing is, and a result set silently limited
- * to the server you happen to be looking at cannot answer that. Navigating to
- * one of these switches the active server (see `scopeToRoomServer`), so the
- * sidebar follows you there rather than filtering the room back out.
+ * Search is deliberately not scoped to the active workspace: you search
+ * precisely because you do not know where a thing is, and a result set
+ * silently limited to the one you happen to be looking at cannot answer that.
+ * Navigating to one of these switches the active workspace (see
+ * `scopeToRoomServer`), so the sidebar follows you there rather than
+ * filtering the room back out.
*/
- get listedRoomsOnAllServers(): RemoteRoomSummary[] {
- const serverIds = [
- ...new Set([...this.allRoomsByServer.keys(), ...this.ownedRoomsByServer.keys()]),
- ];
- const listed = serverIds.flatMap((serverId) => this.listedRoomsOnServer(serverId));
+ get listedRoomsInAllWorkspaces(): RemoteRoomSummary[] {
+ const listed = workspacesStore.workspaces.flatMap((w) => this.listedRoomsInWorkspace(w.id));
return listed.sort((a, b) => a.name.localeCompare(b.name));
}
/**
- * The messaging-app values worth offering as a room filter on the active
- * server: the bridge types actually in use, plus the unbridged sentinel when
- * some room has no messaging app. Offering a platform with no rooms behind it
- * would be a filter that can only ever empty the list.
+ * The messaging-app values worth offering as a room filter in the active
+ * workspace: the bridge types actually in use, plus the unbridged sentinel
+ * when some room has no messaging app. Offering a platform with no rooms
+ * behind it would be a filter that can only ever empty the list.
*/
get bridgeFilterValuesInActiveScope(): string[] {
const present = new Set<string>();
@@ -194,102 +208,105 @@ export class SwitchRoomsStore {
});
}
- /** Full detail for a room, when its server's room list has been loaded. */
+ /** Full detail for a room, when its workspace's room list has been loaded. */
roomSummaryById(roomId: string): RemoteRoomSummary | null {
- const serverId = this.roomServerById.get(roomId);
- if (!serverId) return null;
- return this.allRoomsByServer.get(serverId)?.find((room) => room.id === roomId) ?? null;
+ const workspaceId = this.roomWorkspaceById.get(roomId);
+ if (!workspaceId) return null;
+ return this.allRoomsByWorkspace.get(workspaceId)?.find((room) => room.id === roomId) ?? null;
}
/**
* Whether the signed-in user may delete a room: they own it, or they are an
- * admin on its server.
+ * admin on the server hosting its workspace.
*
* This mirrors the gateway's own rule so the action is not offered where it
* would only be refused. It is not the check that protects anything — the
* server's is — and where ownership is unknown the answer is no, since
* showing a delete that fails is worse than not showing one.
*/
- canDeleteRoom(serverId: string, room: RemoteRoomSummary): boolean {
+ canDeleteRoom(workspaceId: string, room: RemoteRoomSummary): boolean {
+ const serverId = workspacesStore.serverIdFor(workspaceId);
+ if (!serverId) return false;
const user = switchServersStore.statusFor(serverId)?.user ?? null;
if (!user) return false;
return room.ownerId === user.id || user.role === 'admin';
}
/**
- * Delete a room on its server, then re-read what is left.
+ * Delete a room in its workspace, then re-read what is left.
*
* Throws on refusal rather than reporting a boolean: the caller is a
* confirmation dialog, and a delete that quietly did nothing would leave the
* room on screen with no account of why.
*/
- async deleteRoom(serverId: string, roomId: string): Promise<void> {
- await rpc.switchServers.deleteRoom({ serverId, roomId });
+ async deleteRoom(workspaceId: string, roomId: string): Promise<void> {
+ await rpc.workspaces.deleteRoom({ workspaceId, roomId });
await this.refreshRoomState();
}
/**
- * The servers whose state is on screen: the active one, or all of them when
- * none is active (the same scope rule the room and location lists follow).
+ * The workspaces whose state is on screen: the active one, or all of them
+ * when none is active (the same scope rule the room and location lists
+ * follow).
*
- * Each server is its own world — its own rooms, its own agents, its own
- * connection. Reading or reporting on one you are not looking at is both
- * wasted work and, worse, someone else's problem presented as yours.
+ * Each workspace is its own world — its own rooms, its own agents. Reading or
+ * reporting on one you are not looking at is both wasted work and, worse,
+ * someone else's problem presented as yours.
*/
- private get serverIdsInScope(): string[] {
- const activeServerId = switchServersStore.activeServerId;
- if (activeServerId) return [activeServerId];
- return switchServersStore.servers.map((s) => s.id);
+ private get workspaceIdsInScope(): string[] {
+ const activeId = workspacesStore.activeId;
+ if (activeId) return [activeId];
+ return workspacesStore.workspaces.map((w) => w.id);
}
/**
- * Refresh the room catalogue for the servers on screen.
+ * Refresh the room catalogue for the workspaces on screen.
*
- * A server that cannot be read keeps its last-known rooms rather than losing
- * them, but the failure is recorded in {@link roomListErrors} instead of being
- * swallowed: last-known data rendered as if it were current is the one outcome
- * worse than showing nothing.
+ * A workspace that cannot be read keeps its last-known rooms rather than
+ * losing them, but the failure is recorded in {@link roomListErrors} instead
+ * of being swallowed: last-known data rendered as if it were current is the
+ * one outcome worse than showing nothing.
*/
async loadRoomNames(): Promise<void> {
- await this.loadRoomsFrom(this.serverIdsInScope);
+ await this.loadRoomsFrom(this.workspaceIdsInScope);
}
/**
- * Refresh the room catalogue for **every** server.
+ * Refresh the room catalogue for **every** workspace.
*
- * Only for cross-server search, which is deliberately not scoped — you search
- * because you do not know where a thing is. Everything else loads the servers
- * it is actually showing.
+ * Only for cross-workspace search, which is deliberately not scoped — you
+ * search because you do not know where a thing is. Everything else loads the
+ * workspaces it is actually showing.
*/
- async loadRoomsOnAllServers(): Promise<void> {
- await this.loadRoomsFrom(switchServersStore.servers.map((s) => s.id));
+ async loadRoomsInAllWorkspaces(): Promise<void> {
+ await this.loadRoomsFrom(workspacesStore.workspaces.map((w) => w.id));
}
- private async loadRoomsFrom(serverIds: string[]): Promise<void> {
- const servers = switchServersStore.servers.filter((s) => serverIds.includes(s.id));
- const connected = servers.filter((s) => switchServersStore.isConnected(s.id));
+ private async loadRoomsFrom(workspaceIds: string[]): Promise<void> {
+ const asked = workspacesStore.workspaces.filter((w) => workspaceIds.includes(w.id));
+ const connected = asked.filter((w) => switchServersStore.isConnected(w.serverId));
runInAction(() => {
// Not being connected is not a failure — there is simply nothing to ask
- // right now — but the rooms on that server are equally unknown, and the
+ // right now — but the rooms in that workspace are equally unknown, and the
// sidebar has to be able to say so.
- const asked = new Set(serverIds);
- this.unreachableServerIds = [
- ...this.unreachableServerIds.filter((id) => !asked.has(id)),
- ...servers.filter((s) => !switchServersStore.isConnected(s.id)).map((s) => s.id),
+ const askedIds = new Set(workspaceIds);
+ this.unreachableWorkspaceIds = [
+ ...this.unreachableWorkspaceIds.filter((id) => !askedIds.has(id)),
+ ...asked.filter((w) => !switchServersStore.isConnected(w.serverId)).map((w) => w.id),
];
});
await Promise.all(
- connected.map(async (server) => {
+ connected.map(async (workspace) => {
try {
- const rooms = await rpc.switchServers.listRemoteRooms(server.id);
+ const rooms = await rpc.workspaces.listRooms(workspace.id);
// Ownership is per server: the same person is a different user row on
// each gateway, so match against that server's signed-in identity.
- const signedInUserId = switchServersStore.statusFor(server.id)?.user?.id ?? null;
+ const signedInUserId = switchServersStore.statusFor(workspace.serverId)?.user?.id ?? null;
runInAction(() => {
- this.roomListErrors.delete(server.id);
+ this.roomListErrors.delete(workspace.id);
for (const room of rooms) {
this.roomNames.set(room.id, room.name);
- this.roomServerById.set(room.id, server.id);
+ this.roomWorkspaceById.set(room.id, workspace.id);
if (room.bridgeType) this.bridgeTypeByRoom.set(room.id, room.bridgeType);
else this.bridgeTypeByRoom.delete(room.id);
if (room.externalChannelUrl)
@@ -297,17 +314,17 @@ export class SwitchRoomsStore {
else this.channelUrlByRoom.delete(room.id);
}
const active = rooms.filter((r) => !r.archived);
- this.allRoomsByServer.set(server.id, active);
- this.ownedRoomsByServer.set(
- server.id,
+ this.allRoomsByWorkspace.set(workspace.id, active);
+ this.ownedRoomsByWorkspace.set(
+ workspace.id,
signedInUserId ? active.filter((r) => r.ownerId === signedInUserId) : []
);
});
} catch (cause) {
runInAction(() => {
this.roomListErrors.set(
- server.id,
- failureText(cause, `Could not load the rooms on ${server.name}.`)
+ workspace.id,
+ failureText(cause, `Could not load the rooms in ${workspace.name}.`)
);
});
}
@@ -324,42 +341,44 @@ export class SwitchRoomsStore {
* being asked to wait or to act.
*/
roomNameBlockedBySignIn(roomId: string): boolean {
- const serverId = this.roomServerById.get(roomId) ?? switchServersStore.activeServerId;
+ const workspaceId = this.roomWorkspaceById.get(roomId) ?? workspacesStore.activeId;
+ if (!workspaceId) return false;
+ const serverId = workspacesStore.serverIdFor(workspaceId);
if (!serverId) return false;
return serverAvailability(serverId) === 'signed-out';
}
/**
- * Servers on screen whose room list was asked for and failed.
+ * Workspaces on screen whose room list was asked for and failed.
*
- * Distinct from {@link serversNotSignedIn}: this is a fault, it may be
+ * Distinct from {@link workspacesNotSignedIn}: this is a fault, it may be
* transient, and retrying is a sensible thing to offer.
*/
- get serversThatFailedToLoad(): { id: string; name: string }[] {
- return this.namedServersInScope([...this.roomListErrors.keys()]);
+ get workspacesThatFailedToLoad(): { id: string; name: string }[] {
+ return this.namedWorkspacesInScope([...this.roomListErrors.keys()]);
}
/**
- * Servers on screen that were never asked because Switch Console is not signed in
- * to them.
+ * Workspaces on screen that were never asked because Switch Console is not
+ * signed in to their server.
*
* Not a fault and not retryable — the user has to sign in. Reporting it as a
* failure with a retry button offers an action that cannot work.
*/
- get serversNotSignedIn(): { id: string; name: string }[] {
- return this.namedServersInScope(
- this.unreachableServerIds.filter((id) => serverAvailability(id) === 'signed-out')
+ get workspacesNotSignedIn(): { id: string; name: string }[] {
+ return this.namedWorkspacesInScope(
+ this.unreachableWorkspaceIds.filter((id) => {
+ const serverId = workspacesStore.serverIdFor(id);
+ return serverId !== null && serverAvailability(serverId) === 'signed-out';
+ })
);
}
- private namedServersInScope(serverIds: string[]): { id: string; name: string }[] {
- const inScope = new Set(this.serverIdsInScope);
- return [...new Set(serverIds)]
+ private namedWorkspacesInScope(workspaceIds: string[]): { id: string; name: string }[] {
+ const inScope = new Set(this.workspaceIdsInScope);
+ return [...new Set(workspaceIds)]
.filter((id) => inScope.has(id))
- .map((id) => ({
- id,
- name: switchServersStore.servers.find((s) => s.id === id)?.name ?? id,
- }))
+ .map((id) => ({ id, name: workspacesStore.byId(id)?.name ?? id }))
.sort((a, b) => a.name.localeCompare(b.name));
}
@@ -371,15 +390,15 @@ export class SwitchRoomsStore {
*/
get agentsWithUnknownMembership(): number {
return this.trackedIdentities.filter(
- ({ serverId, switchAgentId }) =>
- this.roomsByAgent.get(key(serverId, switchAgentId)) === undefined &&
- !this.isLoading(serverId, switchAgentId)
+ ({ workspaceId, switchAgentId }) =>
+ this.roomsByAgent.get(key(workspaceId, switchAgentId)) === undefined &&
+ !this.isLoading(workspaceId, switchAgentId)
).length;
}
/** Cached membership, or undefined if never fetched. */
- roomsFor(serverId: string, switchAgentId: string): RemoteAgentRoom[] | undefined {
- return this.roomsByAgent.get(key(serverId, switchAgentId));
+ roomsFor(workspaceId: string, switchAgentId: string): RemoteAgentRoom[] | undefined {
+ return this.roomsByAgent.get(key(workspaceId, switchAgentId));
}
/**
@@ -436,23 +455,23 @@ export class SwitchRoomsStore {
* agent's at a time.
*/
async ensureMembershipsFor(
- agents: { serverId: string; switchAgentId: string }[],
+ agents: { workspaceId: string; switchAgentId: string }[],
options: { force?: boolean } = {}
): Promise<void> {
runInAction(() => {
this.trackedIdentities = agents;
});
await Promise.all(
- agents.map((a) => this.fetchAgentRooms(a.serverId, a.switchAgentId, options))
+ agents.map((a) => this.fetchAgentRooms(a.workspaceId, a.switchAgentId, options))
);
}
- isLoading(serverId: string, switchAgentId: string): boolean {
- return this.loading.has(key(serverId, switchAgentId));
+ isLoading(workspaceId: string, switchAgentId: string): boolean {
+ return this.loading.has(key(workspaceId, switchAgentId));
}
- errorFor(serverId: string, switchAgentId: string): string | null {
- return this.errors.get(key(serverId, switchAgentId)) ?? null;
+ errorFor(workspaceId: string, switchAgentId: string): string | null {
+ return this.errors.get(key(workspaceId, switchAgentId)) ?? null;
}
/**
@@ -460,11 +479,11 @@ export class SwitchRoomsStore {
* cache. Returns the membership, or null if the fetch failed.
*/
async fetchAgentRooms(
- serverId: string,
+ workspaceId: string,
switchAgentId: string,
options: { force?: boolean } = {}
): Promise<RemoteAgentRoom[] | null> {
- const k = key(serverId, switchAgentId);
+ const k = key(workspaceId, switchAgentId);
const cached = this.roomsByAgent.get(k);
if (cached && !options.force) return cached;
@@ -473,7 +492,7 @@ export class SwitchRoomsStore {
this.errors.delete(k);
});
try {
- const rooms = await rpc.switchServers.listAgentRooms({ serverId, agentId: switchAgentId });
+ const rooms = await rpc.workspaces.listAgentRooms({ workspaceId, agentId: switchAgentId });
runInAction(() => {
this.roomsByAgent.set(k, rooms);
});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.test.ts
index 7a6539c7a..36bafb7fc 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.test.ts
@@ -25,6 +25,9 @@ vi.mock('@renderer/lib/ipc', () => ({
},
},
}));
+vi.mock('@renderer/features/workspaces/workspaces-store', () => ({
+ workspacesStore: { refresh: vi.fn().mockResolvedValue(undefined) },
+}));
vi.mock('@renderer/features/remote-hosts/host-reachability-store', () => ({
hostReachabilityStore: { isBlocked: (sshHost: string) => blockedHosts.has(sshHost) },
}));
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.ts
index 053bb39aa..25c96500a 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.ts
@@ -1,5 +1,6 @@
import { makeAutoObservable, runInAction } from 'mobx';
import { hostReachabilityStore } from '@renderer/features/remote-hosts/host-reachability-store';
+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { describeFailure } from '@renderer/lib/errors/describe-failure';
import { rpc } from '@renderer/lib/ipc';
import { appState } from '@renderer/lib/stores/app-state';
@@ -140,6 +141,7 @@ export class SwitchServersStore {
const [servers, activeServerId] = await Promise.all([
rpc.switchServers.listServers(),
rpc.switchServers.getActiveServerId(),
+ workspacesStore.refresh(),
]);
runInAction(() => {
this.servers = servers;
@@ -331,6 +333,7 @@ export class SwitchServersStore {
const [servers, activeServerId] = await Promise.all([
rpc.switchServers.listServers(),
rpc.switchServers.getActiveServerId(),
+ workspacesStore.refresh(),
]);
runInAction(() => {
this.servers = servers;
@@ -416,6 +419,7 @@ export class SwitchServersStore {
const [servers, activeServerId] = await Promise.all([
rpc.switchServers.listServers(),
rpc.switchServers.getActiveServerId(),
+ workspacesStore.refresh(),
]);
runInAction(() => {
this.servers = servers;
@@ -440,6 +444,7 @@ export class SwitchServersStore {
this.clearError();
try {
await rpc.switchServers.setActiveServer(serverId);
+ await workspacesStore.refresh();
runInAction(() => {
this.activeServerId = serverId;
});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/use-my-identities.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/use-my-identities.ts
index 6e8a1fa2d..bc13dd5d9 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/use-my-identities.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/use-my-identities.ts
@@ -5,21 +5,21 @@ import type { LinkedIdentity } from '@shared/core/switch-servers/switch-servers'
/** Shared so every surface that claims or releases an identity refreshes the
* same cache entry the owner-only warning reads. */
-export function myIdentitiesQueryKey(serverId: string | null): unknown[] {
- return ['my-switch-identities', serverId];
+export function myIdentitiesQueryKey(workspaceId: string | null): unknown[] {
+ return ['my-switch-identities', workspaceId];
}
/**
- * The messaging accounts the signed-in user has claimed on a server
+ * The messaging accounts the signed-in user has claimed in a workspace
* (CHOO-2137).
*
- * `identities` is null while the answer is unknown — not signed in, no server
- * chosen, still loading, or the read failed. Callers must treat that as
+ * `identities` is null while the answer is unknown — not signed in, no
+ * workspace chosen, still loading, or the read failed. Callers must treat that as
* "unknown" rather than "none": warning that an owner-only agent is
* unreachable, on the strength of a list that has not arrived, is the same
* false alarm every time the page opens.
*/
-export function useMyIdentities(serverId: string | null): {
+export function useMyIdentities(workspaceId: string | null): {
identities: LinkedIdentity[] | null;
isLoading: boolean;
error: unknown;
@@ -27,14 +27,14 @@ export function useMyIdentities(serverId: string | null): {
} {
const queryClient = useQueryClient();
const query = useQuery({
- queryKey: myIdentitiesQueryKey(serverId),
- queryFn: () => rpc.switchServers.listMyIdentities(serverId as string),
- enabled: serverId !== null,
+ queryKey: myIdentitiesQueryKey(workspaceId),
+ queryFn: () => rpc.workspaces.listMyIdentities(workspaceId as string),
+ enabled: workspaceId !== null,
});
const refresh = useCallback(() => {
- void queryClient.invalidateQueries({ queryKey: myIdentitiesQueryKey(serverId) });
- }, [queryClient, serverId]);
+ void queryClient.invalidateQueries({ queryKey: myIdentitiesQueryKey(workspaceId) });
+ }, [queryClient, workspaceId]);
return {
identities: query.isSuccess ? query.data : null,
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/view.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/view.tsx
index 7cb17f9c0..e527a613d 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/view.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/view.tsx
@@ -16,6 +16,7 @@ import { agentsStore } from '@renderer/features/locations/stores/agents-store';
import { hostReachabilityStore } from '@renderer/features/remote-hosts/host-reachability-store';
import { HostUnreachablePanel } from '@renderer/features/remote-hosts/host-unreachable-panel';
import { useAppSettingsKey } from '@renderer/features/settings/use-app-settings-key';
+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { rpc } from '@renderer/lib/ipc';
import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';
import { useShowModal } from '@renderer/lib/modal/modal-provider';
@@ -119,12 +120,15 @@ const ServerMainPanel = observer(function ServerMainPanel() {
*/
const refreshEverything = async (): Promise<void> => {
setRefreshingPage(true);
+ // The three caches below are keyed by workspace, so a server id would
+ // invalidate nothing and the button would spin over stale cards.
+ const workspaceId = workspacesStore.soleIdOnServer(serverId);
try {
await Promise.all([
store.refreshServer(serverId),
- queryClient.invalidateQueries({ queryKey: ['remote-bridges', serverId] }),
- queryClient.invalidateQueries({ queryKey: myIdentitiesQueryKey(serverId) }),
- queryClient.invalidateQueries({ queryKey: ['owns-owner-addressed-agent', serverId] }),
+ queryClient.invalidateQueries({ queryKey: ['remote-bridges', workspaceId] }),
+ queryClient.invalidateQueries({ queryKey: myIdentitiesQueryKey(workspaceId) }),
+ queryClient.invalidateQueries({ queryKey: ['owns-owner-addressed-agent', workspaceId] }),
switchRoomsStore.refreshRoomState(),
agentsStore.load(),
new Promise((resolve) => setTimeout(resolve, MIN_REFRESH_FEEDBACK_MS)),
diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/agent-template-data.ts b/console/apps/switch-console-desktop/src/renderer/features/templates/agent-template-data.ts
index 133d4e935..d7d40cf3e 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/templates/agent-template-data.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/agent-template-data.ts
@@ -4,6 +4,7 @@ import type { TemplateSummary } from '@main/core/agent-templates/template-summar
import type { AgentTemplateOrigin } from '@main/core/agents/agent-config-file';
import type { ParsedTemplate } from '@main/core/room-templates/controller';
import type { StoredTemplateSummary } from '@main/core/switch-servers/gateway-client';
+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { rpc } from '@renderer/lib/ipc';
import { type BundledTemplate, bundledTemplates, findBundledTemplate } from './bundled-templates';
@@ -75,8 +76,9 @@ export async function loadAgentTemplateByOrigin(
}
if (!origin.serverId)
throw new Error(`"${origin.name}" came from a server this Console does not know.`);
- const detail = await rpc.switchServers.getTemplateDetail({
- serverId: origin.serverId,
+ const workspaceId = workspacesStore.requireSoleIdOnServer(origin.serverId);
+ const detail = await rpc.workspaces.getTemplateDetail({
+ workspaceId,
templateId: origin.id,
});
return agentTemplateFromContent(origin.name, detail.definition, null, origin);
@@ -84,7 +86,7 @@ export async function loadAgentTemplateByOrigin(
/** Resolve a listing entry (bundled or from the server's registry) into the agent it describes. */
export async function loadAgentTemplate(
- serverId: string,
+ workspaceId: string,
template: StoredTemplateSummary
): Promise<AgentTemplate> {
const bundled = findBundledTemplate(template.id);
@@ -95,12 +97,13 @@ export async function loadAgentTemplate(
source: 'bundled',
});
}
- const detail = await rpc.switchServers.getTemplateDetail({ serverId, templateId: template.id });
+ const detail = await rpc.workspaces.getTemplateDetail({ workspaceId, templateId: template.id });
+ const serverId = workspacesStore.serverIdFor(workspaceId);
return agentTemplateFromContent(detail.name, detail.definition, null, {
id: detail.id,
name: detail.name,
source: 'server',
- serverId,
+ ...(serverId ? { serverId } : {}),
});
}
@@ -135,7 +138,7 @@ export type LoadedTemplate = {
* owner, so someone else's template of the same name is not a copy.
*/
export async function loadTemplateById(
- serverId: string,
+ workspaceId: string,
templateId: string,
meId: string | null
): Promise<LoadedTemplate> {
@@ -148,7 +151,7 @@ export async function loadTemplateById(
let savedCopy: StoredTemplateSummary | null = null;
if (bundled) {
savedCopy =
- (await rpc.switchServers.listTemplates({ serverId }).catch(() => [])).find(
+ (await rpc.workspaces.listTemplates({ workspaceId }).catch(() => [])).find(
(t) => t.name === bundled.name && meId !== null && t.ownerId === meId
) ?? null;
name = bundled.name;
@@ -160,7 +163,7 @@ export async function loadTemplateById(
})
: bundled.yamlText;
} else {
- const detail = await rpc.switchServers.getTemplateDetail({ serverId, templateId });
+ const detail = await rpc.workspaces.getTemplateDetail({ workspaceId, templateId });
const { definition, ...summary } = detail;
name = detail.name;
description = detail.description;
diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/save-template-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/templates/save-template-modal.tsx
index 0d1a433ad..903c859c4 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/templates/save-template-modal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/save-template-modal.tsx
@@ -1,4 +1,5 @@
import { useId, useState } from 'react';
+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { failureText } from '@renderer/lib/errors/describe-failure';
import { toast } from '@renderer/lib/hooks/use-toast';
import { rpc } from '@renderer/lib/ipc';
@@ -57,8 +58,8 @@ export function SaveTemplateModal({
setSaving(true);
setError(null);
try {
- const saved = await rpc.switchServers.saveTemplate({
- serverId,
+ const saved = await rpc.workspaces.saveTemplate({
+ workspaceId: workspacesStore.requireSoleIdOnServer(serverId),
name: name.trim(),
description: description.trim(),
kind,
diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/template-detail-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/templates/template-detail-view.tsx
index a078cdabf..acedeb907 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/templates/template-detail-view.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/template-detail-view.tsx
@@ -15,6 +15,7 @@ import { useEffect, useState } from 'react';
import type { GuardResult, ViewDefinition } from '@renderer/app/view-registry';
import { ServerSectionTitlebar } from '@renderer/features/switch-servers/server-section-titlebar';
import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { PageHeader } from '@renderer/lib/components/page-header';
import { failureText } from '@renderer/lib/errors/describe-failure';
import { toast } from '@renderer/lib/hooks/use-toast';
@@ -155,6 +156,7 @@ const KIND_LABEL: Record<LoadedTemplate['kind'], string> = {
const TemplateDetailPanel = observer(function TemplateDetailPanel() {
const { serverId, templateId } = useViewParams();
+ const workspaceId = workspacesStore.soleIdOnServer(serverId);
const { navigate } = useNavigate();
const server = switchServersStore.servers.find((s) => s.id === serverId);
const me = switchServersStore.statusFor(serverId)?.user ?? null;
@@ -167,10 +169,18 @@ const TemplateDetailPanel = observer(function TemplateDetailPanel() {
const [showInstructions, setShowInstructions] = useState(false);
useEffect(() => {
+ // No workspace is an answer, not a wait. Returning with neither a template
+ // nor an error leaves the spinner below up forever, claiming something is
+ // on its way that nobody is fetching.
+ if (workspaceId === null) {
+ setLoaded(null);
+ setError('This server has no workspace yet, so its templates cannot be read.');
+ return;
+ }
let cancelled = false;
setLoaded(null);
setError(null);
- loadTemplateById(serverId, templateId, me?.id ?? null)
+ loadTemplateById(workspaceId, templateId, me?.id ?? null)
.then((t) => {
if (cancelled) return;
setLoaded(t);
@@ -183,7 +193,7 @@ const TemplateDetailPanel = observer(function TemplateDetailPanel() {
cancelled = true;
setCurrentName(null);
};
- }, [serverId, templateId, me?.id]);
+ }, [workspaceId, templateId, me?.id]);
const back = (
<Button
@@ -235,8 +245,8 @@ const TemplateDetailPanel = observer(function TemplateDetailPanel() {
if (!loaded.bundled) return;
setBusy('save');
try {
- const saved = await rpc.switchServers.saveTemplate({
- serverId,
+ const saved = await rpc.workspaces.saveTemplate({
+ workspaceId: workspacesStore.requireSoleIdOnServer(serverId),
name: loaded.bundled.name,
description: loaded.bundled.description,
kind: loaded.bundled.kind,
@@ -259,7 +269,10 @@ const TemplateDetailPanel = observer(function TemplateDetailPanel() {
if (!loaded.server) return;
setBusy('delete');
try {
- await rpc.switchServers.deleteTemplate({ serverId, templateId: loaded.server.id });
+ await rpc.workspaces.deleteTemplate({
+ workspaceId: workspacesStore.requireSoleIdOnServer(serverId),
+ templateId: loaded.server.id,
+ });
toast({ title: `"${loaded.name}" removed from ${server?.name ?? 'the workspace'}` });
navigate('templates', { serverId });
} catch (e) {
diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/template-use-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/templates/template-use-view.tsx
index 9a3822dc2..56a847467 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/templates/template-use-view.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/template-use-view.tsx
@@ -28,13 +28,17 @@ import { refreshSidebarRoomState } from '@renderer/features/sidebar/sidebar-tree
import { ServerSectionTitlebar } from '@renderer/features/switch-servers/server-section-titlebar';
import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
import { useMyIdentities } from '@renderer/features/switch-servers/use-my-identities';
+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { failureText } from '@renderer/lib/errors/describe-failure';
import { toast } from '@renderer/lib/hooks/use-toast';
import { rpc } from '@renderer/lib/ipc';
import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';
import { useModalContext } from '@renderer/lib/modal/modal-provider';
import { useAgentTypeAvailability } from '@renderer/lib/stores/use-agent-type-availability';
-import { remoteAgentsQueryKey, useRemoteAgents } from '@renderer/lib/stores/use-remote-agents';
+import {
+ useWorkspaceAgents,
+ workspaceAgentsQueryKey,
+} from '@renderer/lib/stores/use-workspace-agents';
import { Alert, AlertDescription } from '@renderer/lib/ui/alert';
import { Button } from '@renderer/lib/ui/button';
import { Switch } from '@renderer/lib/ui/switch';
@@ -119,7 +123,7 @@ type UsePageTemplate = {
warnings: string[];
};
-async function loadUsePageTemplate(serverId: string, params: Params): Promise<UsePageTemplate> {
+async function loadUsePageTemplate(workspaceId: string, params: Params): Promise<UsePageTemplate> {
let name: string;
let yamlText: string;
let instructions: string | null = null;
@@ -132,13 +136,19 @@ async function loadUsePageTemplate(serverId: string, params: Params): Promise<Us
instructions = bundled.instructions;
origin = { id: bundled.id, name: bundled.name, source: 'bundled' };
} else {
- const detail = await rpc.switchServers.getTemplateDetail({
- serverId,
+ const detail = await rpc.workspaces.getTemplateDetail({
+ workspaceId,
templateId: params.templateId,
});
name = detail.name;
yamlText = detail.definition;
- origin = { id: detail.id, name: detail.name, source: 'server', serverId };
+ const serverId = workspacesStore.serverIdFor(workspaceId);
+ origin = {
+ id: detail.id,
+ name: detail.name,
+ source: 'server',
+ ...(serverId ? { serverId } : {}),
+ };
}
} else if (params.yamlText) {
name = params.sourceName?.replace(/(\.template)?\.ya?ml$/i, '') ?? 'Pasted template';
@@ -158,7 +168,7 @@ async function loadUsePageTemplate(serverId: string, params: Params): Promise<Us
// Without the schema the form is built from the Console's own parse and
// the server validates on create, so an older server without the schema
// endpoint still gets a working page.
- const schema = await rpc.switchServers.fetchTemplateSchema(serverId).catch(() => null);
+ const schema = await rpc.workspaces.fetchTemplateSchema(workspaceId).catch(() => null);
const parsed = forForm
? await rpc.roomTemplates.parse({ yamlText: forForm, schema: schema ?? undefined })
: null;
@@ -237,6 +247,7 @@ type SlotSetup = {
const TemplateUsePanel = observer(function TemplateUsePanel() {
const params = useViewParams();
const { serverId, intoRoomId = null } = params;
+ const workspaceId = workspacesStore.soleIdOnServer(serverId);
const { navigate } = useNavigate();
const { showModal } = useModalContext();
const queryClient = useQueryClient();
@@ -255,7 +266,7 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {
// What the server returned for the room, kept so that a step failing after
// it does not make Retry create the room a second time.
const createdRoom = useRef<Awaited<
- ReturnType<typeof rpc.switchServers.createRoomFromTemplate>
+ ReturnType<typeof rpc.workspaces.createRoomFromTemplate>
> | null>(null);
const [roomStatus, setRoomStatus] = useState<SlotStatus>('idle');
const [createError, setCreateError] = useState<string | null>(null);
@@ -276,10 +287,18 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {
// render would reset the form.
const { templateId, yamlText: givenYaml, sourceName } = params;
useEffect(() => {
+ // No workspace is an answer, not a wait. Returning with neither a template
+ // nor an error leaves the page spinning forever, and Deploy reading
+ // "Loading…" for something nobody is fetching.
+ if (workspaceId === null) {
+ setLoaded(null);
+ setLoadError('This server has no workspace yet, so this template cannot be read.');
+ return;
+ }
let cancelled = false;
setLoaded(null);
setLoadError(null);
- loadUsePageTemplate(serverId, { serverId, templateId, yamlText: givenYaml, sourceName })
+ loadUsePageTemplate(workspaceId, { serverId, templateId, yamlText: givenYaml, sourceName })
.then((result) => {
if (cancelled) return;
setLoaded(result);
@@ -305,7 +324,7 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {
return () => {
cancelled = true;
};
- }, [serverId, templateId, givenYaml, sourceName]);
+ }, [serverId, workspaceId, templateId, givenYaml, sourceName]);
const parsed = loaded?.parsed ?? null;
// In the singular `agent:` form the room refers to the agent as `{agent}`.
@@ -364,20 +383,23 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {
const directoryParam = unboundOfType('directory');
// ── Server lists (pickers, identities, bridges) ─────────────────────────
- const agents = useRemoteAgents(serverId);
+ const agents = useWorkspaceAgents(workspaceId);
const roomsQuery = useQuery({
- queryKey: ['remote-rooms', serverId],
- queryFn: () => rpc.switchServers.listRemoteRooms(serverId),
+ queryKey: ['remote-rooms', workspaceId],
+ queryFn: () => rpc.workspaces.listRooms(workspaceId as string),
+ enabled: workspaceId !== null,
});
const bridgesQuery = useQuery({
- queryKey: ['remote-bridges', serverId],
- queryFn: () => rpc.switchServers.listRemoteBridges(serverId),
+ queryKey: ['remote-bridges', workspaceId],
+ queryFn: () => rpc.workspaces.listBridges(workspaceId as string),
+ enabled: workspaceId !== null,
});
const knownUsersQuery = useQuery({
- queryKey: ['remote-external-users', serverId],
- queryFn: () => rpc.switchServers.listRemoteExternalUsers(serverId),
+ queryKey: ['remote-external-users', workspaceId],
+ queryFn: () => rpc.workspaces.listExternalUsers(workspaceId as string),
+ enabled: workspaceId !== null,
});
- const { identities, refresh: refreshIdentities } = useMyIdentities(serverId);
+ const { identities, refresh: refreshIdentities } = useMyIdentities(workspaceId);
const bridges = useMemo(() => bridgesQuery.data ?? [], [bridgesQuery.data]);
const allowedHosts = useAllowedHosts(serverId);
const hostLabel = useCallback(
@@ -408,19 +430,20 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {
templateBridge !== null &&
identities !== null &&
creatorIdentity === null;
- const linkAccount = templateBridge
- ? () =>
- showModal('claimIdentityModal', {
- serverId,
- bridgeId: templateBridge.id,
- onSuccess: () => refreshIdentities(),
- })
- : null;
+ const linkAccount =
+ templateBridge && workspaceId !== null
+ ? () =>
+ showModal('claimIdentityModal', {
+ workspaceId,
+ bridgeId: templateBridge.id,
+ onSuccess: () => refreshIdentities(),
+ })
+ : null;
const noMessagingApp = parsed !== null && bridgesQuery.data !== undefined && bridges.length === 0;
const lists = useMemo(
(): EntityLists => ({
- serverId,
+ workspaceId,
agents: agents.data ?? [],
agentsLoading: agents.isLoading,
rooms: roomsQuery.data ?? [],
@@ -431,7 +454,7 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {
bridgeId: templateBridge?.id ?? null,
}),
[
- serverId,
+ workspaceId,
agents.data,
agents.isLoading,
roomsQuery.data,
@@ -740,19 +763,19 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {
}
return next;
});
- await rpc.switchServers.updateAddressingPolicy({
- serverId,
+ await rpc.workspaces.updateAddressingPolicy({
+ workspaceId: workspacesStore.requireSoleIdOnServer(serverId),
agentId: target.id,
policy: { rules },
});
}
- await queryClient.invalidateQueries({ queryKey: remoteAgentsQueryKey(serverId) });
+ await queryClient.invalidateQueries({ queryKey: workspaceAgentsQueryKey(workspaceId) });
} catch (e) {
toast({ title: failureText(e, 'Could not update the agents.'), variant: 'destructive' });
} finally {
setAllowingHandoffs(false);
}
- }, [agents.data, handoffBlocked, serverId, queryClient]);
+ }, [agents.data, handoffBlocked, serverId, workspaceId, queryClient]);
// ── Create ──────────────────────────────────────────────────────────────
const setSlot = (i: number, patch: Partial<AgentSlot>) =>
@@ -831,8 +854,8 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {
// must be written as the open policy; leaving the default would keep it closed.
if (switchAgentId && slot.entry.addressing) {
setSlot(i, { step: 'policy' });
- await rpc.switchServers.updateAddressingPolicy({
- serverId,
+ await rpc.workspaces.updateAddressingPolicy({
+ workspaceId: workspacesStore.requireSoleIdOnServer(serverId),
agentId: switchAgentId,
policy:
slot.entry.addressing === 'owner-agents'
@@ -855,7 +878,7 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {
// fails must not fail the run.
await agentsStore.load().catch(() => {});
await queryClient
- .invalidateQueries({ queryKey: remoteAgentsQueryKey(serverId) })
+ .invalidateQueries({ queryKey: workspaceAgentsQueryKey(workspaceId) })
.catch(() => {});
}
// A recent is used again from its own text, so a bundled template whose
@@ -911,8 +934,8 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {
setRoomStatus('creating');
try {
for (const [roomId, ids] of joinsByRoom) {
- await rpc.switchServers.addRoomAgents({
- serverId,
+ await rpc.workspaces.addRoomAgents({
+ workspaceId: workspacesStore.requireSoleIdOnServer(serverId),
roomId,
agentIds: [...new Set(ids)],
direction: 'agents_to_room',
@@ -995,7 +1018,11 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {
}
const result =
createdRoom.current ??
- (await rpc.switchServers.createRoomFromTemplate(serverId, coreYaml, inputs));
+ (await rpc.workspaces.createRoomFromTemplate(
+ workspacesStore.requireSoleIdOnServer(serverId),
+ coreYaml,
+ inputs
+ ));
createdRoom.current = result;
setRoomStatus('created');
// The room exists whether or not the sidebar refreshes.
diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/templates-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/templates/templates-view.tsx
index 21f5a9178..fadcf4691 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/templates/templates-view.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/templates-view.tsx
@@ -21,6 +21,7 @@ import type { GuardResult, ViewDefinition } from '@renderer/app/view-registry';
import { ServerPage } 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 { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { failureText } from '@renderer/lib/errors/describe-failure';
import { toast } from '@renderer/lib/hooks/use-toast';
import { rpc } from '@renderer/lib/ipc';
@@ -114,18 +115,18 @@ function summaryLine(s: TemplateSummary): string {
// template and keeps it for the session.
const summaryCache = new Map<string, Promise<TemplateSummary>>();
-function fetchSummary(serverId: string, item: TemplateListEntry): Promise<TemplateSummary> {
+function fetchSummary(workspaceId: string, item: TemplateListEntry): Promise<TemplateSummary> {
// The version is part of the key, so an edit made elsewhere refreshes the
// card as soon as the listing reports it.
- const key = `${serverId}:${item.id}:${item.server?.version ?? 0}`;
+ const key = `${workspaceId}:${item.id}:${item.server?.version ?? 0}`;
let pending = summaryCache.get(key);
if (!pending) {
pending = (async () => {
const yamlText =
item.content ??
(
- await rpc.switchServers.getTemplateDetail({
- serverId,
+ await rpc.workspaces.getTemplateDetail({
+ workspaceId,
templateId: item.id,
})
).definition;
@@ -137,11 +138,15 @@ function fetchSummary(serverId: string, item: TemplateListEntry): Promise<Templa
return pending;
}
-function useTemplateSummary(serverId: string, item: TemplateListEntry): TemplateSummary | null {
+function useTemplateSummary(
+ workspaceId: string | null,
+ item: TemplateListEntry
+): TemplateSummary | null {
const [summary, setSummary] = useState<TemplateSummary | null>(null);
useEffect(() => {
+ if (workspaceId === null) return;
let cancelled = false;
- fetchSummary(serverId, item)
+ fetchSummary(workspaceId, item)
.then((s) => {
if (!cancelled) setSummary(s);
})
@@ -151,7 +156,7 @@ function useTemplateSummary(serverId: string, item: TemplateListEntry): Template
return () => {
cancelled = true;
};
- }, [serverId, item]);
+ }, [workspaceId, item]);
return summary;
}
@@ -171,14 +176,14 @@ function OwnerRow({ name, mine }: { name: string; mine: boolean }) {
}
function TemplateCard({
- serverId,
+ workspaceId,
item,
meId,
busy,
onOpen,
onUse,
}: {
- serverId: string;
+ workspaceId: string | null;
item: TemplateListEntry;
meId: string | null;
busy: boolean;
@@ -186,7 +191,7 @@ function TemplateCard({
onUse: () => void;
}) {
const Icon = KIND_ICON[item.kind];
- const summary = useTemplateSummary(serverId, item);
+ const summary = useTemplateSummary(workspaceId, item);
const mine = item.server !== null && meId !== null && item.server.ownerId === meId;
return (
<div className="group relative flex min-h-[168px] flex-col rounded-[11px] border border-border bg-background transition-colors hover:border-border-1">
@@ -403,6 +408,7 @@ function RecentsSection({
const TemplatesPanel = observer(function TemplatesPanel() {
const serverId = useServerId();
+ const workspaceId = workspacesStore.soleIdOnServer(serverId);
const server = switchServersStore.servers.find((s) => s.id === serverId);
const meId = switchServersStore.statusFor(serverId)?.user?.id ?? null;
const { navigate } = useNavigate();
@@ -426,14 +432,14 @@ const TemplatesPanel = observer(function TemplatesPanel() {
const [searchHits, setSearchHits] = useState<StoredTemplateSummary[] | null>(null);
useEffect(() => {
const q = query.trim();
- if (q.length === 0) {
+ if (q.length === 0 || workspaceId === null) {
setSearchHits(null);
return;
}
let cancelled = false;
const timer = window.setTimeout(() => {
- rpc.switchServers
- .listTemplates({ serverId, q })
+ rpc.workspaces
+ .listTemplates({ workspaceId, q })
.then((hits) => {
if (!cancelled) setSearchHits(hits);
})
@@ -446,7 +452,7 @@ const TemplatesPanel = observer(function TemplatesPanel() {
cancelled = true;
window.clearTimeout(timer);
};
- }, [serverId, query, reloadKey]);
+ }, [workspaceId, query, reloadKey]);
// An agent template needs a coding agent where its agents will run, and
// this computer is the default run location. Say at the top of the listing
@@ -456,11 +462,19 @@ const TemplatesPanel = observer(function TemplatesPanel() {
const noProvider = availability !== undefined && !availability.some((a) => a.available);
useEffect(() => {
+ // No workspace is an answer, not a wait. The bundled templates below still
+ // render; leaving the spinner up would claim a list is on its way.
+ if (workspaceId === null) {
+ setTemplates([]);
+ setListError('This server has no workspace yet, so its templates cannot be read.');
+ setLoading(false);
+ return;
+ }
let cancelled = false;
setLoading(true);
setListError(null);
- rpc.switchServers
- .listTemplates({ serverId })
+ rpc.workspaces
+ .listTemplates({ workspaceId })
.then((result) => {
if (!cancelled) setTemplates(result);
})
@@ -478,7 +492,7 @@ const TemplatesPanel = observer(function TemplatesPanel() {
return () => {
cancelled = true;
};
- }, [serverId, reloadKey]);
+ }, [workspaceId, reloadKey]);
const { builtIn, onWorkspace } = useMemo(() => {
// A bundled card is always the bundled document. Saving it creates a
@@ -543,7 +557,7 @@ const TemplatesPanel = observer(function TemplatesPanel() {
const card = (item: TemplateListEntry) => (
<TemplateCard
key={item.id}
- serverId={serverId}
+ workspaceId={workspaceId}
item={item}
meId={meId}
busy={false}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspaces-store.ts b/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspaces-store.ts
new file mode 100644
index 000000000..3f5038edc
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspaces-store.ts
@@ -0,0 +1,92 @@
+import { makeAutoObservable, runInAction } from 'mobx';
+import { rpc } from '@renderer/lib/ipc';
+import type { Workspace } from '@shared/core/workspaces/workspaces';
+
+/**
+ * Renderer view of the workspaces this install knows about, and which one the
+ * window is scoped to.
+ *
+ * Everything that reads or writes what a workspace owns — rooms, agents,
+ * bridges, identities — is addressed by workspace id, so this is where a view
+ * holding a server or an agent gets the id to address it with. The server's own
+ * identity stays in the servers store: reachability, sign-in and the gateway
+ * URL are facts about a gateway, not about whose data it answers with.
+ *
+ * The selection itself lives in the main process, so this mirrors it rather
+ * than owning it — the servers store drives both through the same calls that
+ * change the active server.
+ */
+export class WorkspacesStore {
+ workspaces: Workspace[] = [];
+ activeId: string | null = null;
+
+ constructor() {
+ makeAutoObservable(this);
+ }
+
+ get active(): Workspace | null {
+ return this.workspaces.find((w) => w.id === this.activeId) ?? null;
+ }
+
+ async refresh(): Promise<void> {
+ const [workspaces, activeId] = await Promise.all([
+ rpc.workspaces.list(),
+ rpc.workspaces.getActiveId(),
+ ]);
+ runInAction(() => {
+ this.workspaces = workspaces;
+ this.activeId = activeId;
+ });
+ }
+
+ byId(workspaceId: string): Workspace | null {
+ return this.workspaces.find((w) => w.id === workspaceId) ?? null;
+ }
+
+ /** The server hosting a workspace, or null while the list is not loaded. */
+ serverIdFor(workspaceId: string): string | null {
+ return this.byId(workspaceId)?.serverId ?? null;
+ }
+
+ onServer(serverId: string): Workspace[] {
+ return this.workspaces.filter((w) => w.serverId === serverId);
+ }
+
+ /**
+ * The one workspace on a server, for a view that is about the server itself —
+ * its page, its cards, its pickers.
+ *
+ * Null on either edge rather than a guess. A server with none has not
+ * finished registering; a server with several means the view is the one that
+ * has to say which, and addressing the wrong one answers with somebody else's
+ * rooms while looking entirely correct. Callers render the absence; they must
+ * not substitute the server id, which would reach the gateway and succeed.
+ */
+ soleOnServer(serverId: string): Workspace | null {
+ const found = this.onServer(serverId);
+ return found.length === 1 ? found[0]! : null;
+ }
+
+ /**
+ * {@link soleOnServer} as an id, tolerating a server that has not been chosen
+ * — what a view still routed by server reads to address its workspace.
+ *
+ * Null means "no workspace to act in yet", and a view must hold its reads and
+ * writes until it is not: the list arrives asynchronously, so this answers
+ * null on the first render of every such page.
+ */
+ soleIdOnServer(serverId: string | null): string | null {
+ return serverId === null ? null : (this.soleOnServer(serverId)?.id ?? null);
+ }
+
+ /** {@link soleOnServer} as an id, for a call that cannot proceed without one. */
+ requireSoleIdOnServer(serverId: string): string {
+ const workspace = this.soleOnServer(serverId);
+ if (!workspace) {
+ throw new Error(`Switch server ${serverId} does not have exactly one workspace`);
+ }
+ return workspace.id;
+ }
+}
+
+export const workspacesStore = new WorkspacesStore();
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/agent-picker.tsx b/console/apps/switch-console-desktop/src/renderer/lib/components/agent-picker.tsx
index 38e8388d1..e1570e126 100644
--- a/console/apps/switch-console-desktop/src/renderer/lib/components/agent-picker.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/agent-picker.tsx
@@ -15,9 +15,13 @@ export type AgentPick = {
* type an agent is, not what provider drives it here; an agent registered from
* another Switch Console has no local record and reads as a plain "Agent".
*/
-export function agentProviderLabelFor(switchAgentId: string, serverId: string): string {
+export function agentProviderLabelFor(switchAgentId: string, workspaceId: string | null): string {
const local =
- agentsStore.agentsOnServer(serverId).find((a) => a.switchAgentId === switchAgentId) ?? null;
+ workspaceId === null
+ ? null
+ : (agentsStore
+ .agentsInWorkspace(workspaceId)
+ .find((a) => a.switchAgentId === switchAgentId) ?? null);
return agentProviderLabel(local?.providerId);
}
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/stores/use-remote-agents.ts b/console/apps/switch-console-desktop/src/renderer/lib/stores/use-workspace-agents.ts
similarity index 55%
rename from console/apps/switch-console-desktop/src/renderer/lib/stores/use-remote-agents.ts
rename to console/apps/switch-console-desktop/src/renderer/lib/stores/use-workspace-agents.ts
index 2b2b4798c..8a1859a96 100644
--- a/console/apps/switch-console-desktop/src/renderer/lib/stores/use-remote-agents.ts
+++ b/console/apps/switch-console-desktop/src/renderer/lib/stores/use-workspace-agents.ts
@@ -2,39 +2,39 @@ import { useQuery } from '@tanstack/react-query';
import { rpc } from '@renderer/lib/ipc';
import type { RemoteAgentSummary } from '@shared/core/switch-servers/switch-servers';
-/** The agent list a server holds, keyed so every surface shares one fetch.
+/** The agent list a workspace holds, keyed so every surface shares one fetch.
* Several unrelated views ask for this at once — the sidebar rows, the room
* panels, the agent page — and they must agree, so the key is defined once
* here rather than retyped at each call site. */
-export function remoteAgentsQueryKey(serverId: string | null) {
- return ['remote-agents', serverId] as const;
+export function workspaceAgentsQueryKey(workspaceId: string | null) {
+ return ['workspace-agents', workspaceId] as const;
}
/**
- * Every agent registered on `serverId`, or an idle query when there is no
- * server to ask.
+ * Every agent registered in `workspaceId`, or an idle query when there is no
+ * workspace to ask.
*/
-export function useRemoteAgents(serverId: string | null) {
+export function useWorkspaceAgents(workspaceId: string | null) {
return useQuery<RemoteAgentSummary[]>({
- queryKey: remoteAgentsQueryKey(serverId),
- queryFn: () => rpc.switchServers.listRemoteAgents(serverId as string),
- enabled: serverId !== null,
+ queryKey: workspaceAgentsQueryKey(workspaceId),
+ queryFn: () => rpc.workspaces.listAgents(workspaceId as string),
+ enabled: workspaceId !== null,
});
}
/**
- * An agent's chosen icon, or null when it has none, is not on this server, or
- * the list has not arrived yet.
+ * An agent's chosen icon, or null when it has none, is not in this workspace,
+ * or the list has not arrived yet.
*
* Null is not an error and callers must not treat it as one: `AgentAvatar`
* draws a bot from the agent's name instead, so a row renders the right
* picture on first paint and simply sharpens to a custom icon if there is one.
*/
export function useAgentIconUrl(
- serverId: string | null,
+ workspaceId: string | null,
switchAgentId: string | null
): string | null {
- const agents = useRemoteAgents(serverId);
+ const agents = useWorkspaceAgents(workspaceId);
if (switchAgentId === null) return null;
return agents.data?.find((agent) => agent.id === switchAgentId)?.iconUrl ?? null;
}
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/add-agent-settings-disclosure.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/add-agent-settings-disclosure.test.tsx
index 8b46dc958..7d90e5d75 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/add-agent-settings-disclosure.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/add-agent-settings-disclosure.test.tsx
@@ -31,12 +31,12 @@ vi.hoisted(() => {
vi.mock('@renderer/lib/ipc', () => ({
events: { on: vi.fn() },
rpc: {
- switchServers: {
- listRemoteRooms: () => Promise.resolve([]),
- listRemoteRoomGroups: () => Promise.resolve([]),
- listRemoteExternalUsers: () => Promise.resolve([]),
- listRemoteAgents: () => Promise.resolve([]),
- listRemoteBridges: () => Promise.resolve(remote.bridges),
+ workspaces: {
+ listRooms: () => Promise.resolve([]),
+ listRoomGroups: () => Promise.resolve([]),
+ listExternalUsers: () => Promise.resolve([]),
+ listAgents: () => Promise.resolve([]),
+ listBridges: () => Promise.resolve(remote.bridges),
listMyIdentities: () => Promise.resolve(remote.identities),
},
},
@@ -72,7 +72,7 @@ function Panel() {
return (
<AgentSettingsSection
form={form}
- serverId="srv-1"
+ workspaceId="ws-1"
onAddServer={() => {}}
onOpenMessagingApps={() => {}}
/>
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/messaging-app-row.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/messaging-app-row.test.tsx
index b5acc042d..430ecf91b 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/messaging-app-row.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/messaging-app-row.test.tsx
@@ -79,6 +79,7 @@ function row(
) {
return (
<MessagingAppRow
+ workspaceId="ws-1"
serverId="srv-1"
bridge={overrides.bridge ?? bridge()}
identities={overrides.identities === undefined ? [] : overrides.identities}
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/palette-agent-icon.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/palette-agent-icon.test.tsx
index d061e01f2..44be7df70 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/palette-agent-icon.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/palette-agent-icon.test.tsx
@@ -16,13 +16,14 @@ import { PaletteAgentItem } from '@renderer/features/command-palette/palette-age
import { agentsStore } from '@renderer/features/locations/stores/agents-store';
import { ThemeContext } from '@renderer/lib/providers/theme-provider';
import { AGENTS_METADATA_QUERY_KEY } from '@renderer/lib/stores/use-agents';
-import { remoteAgentsQueryKey } from '@renderer/lib/stores/use-remote-agents';
+import { workspaceAgentsQueryKey } from '@renderer/lib/stores/use-workspace-agents';
import type { Agent } from '@shared/core/agents/agents';
import type { SearchItem } from '@shared/core/search';
import type { RemoteAgentSummary } from '@shared/core/switch-servers/switch-servers';
const LOCATION_ID = 'loc-1';
const SERVER_ID = 'server-1';
+const WORKSPACE_ID = 'workspace-1';
const SWITCH_AGENT_ID = 'switch-agent-1';
const AGENT_NAME = 'reviewer';
@@ -33,7 +34,7 @@ const AGENT: Agent = {
providerId: 'claude',
switchAgentId: SWITCH_AGENT_ID,
apiEndpoint: 'https://switch.example',
- workspaceId: 'workspace-1',
+ workspaceId: WORKSPACE_ID,
serverId: SERVER_ID,
status: null,
autoApprove: false,
@@ -104,7 +105,7 @@ async function rowAvatarSrc(options: {
// test has no main process to answer.
defaultOptions: { queries: { retry: false, gcTime: 0, staleTime: Infinity } },
});
- client.setQueryData(remoteAgentsQueryKey(SERVER_ID), [remoteAgent(options.iconUrl)]);
+ client.setQueryData(workspaceAgentsQueryKey(WORKSPACE_ID), [remoteAgent(options.iconUrl)]);
// The provider mark beside the name reads its artwork from here. Seeded empty
// so it resolves to nothing rather than reaching for a main process the test
// does not have; the mark itself is the sidebar's, already covered there.
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/room-configuration-save.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/room-configuration-save.test.tsx
index 4cbc59f23..395dfe9a7 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/room-configuration-save.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/room-configuration-save.test.tsx
@@ -27,10 +27,10 @@ vi.hoisted(() => {
vi.mock('@renderer/lib/ipc', () => ({
events: { on: vi.fn() },
rpc: {
- switchServers: {
+ workspaces: {
updateRoom,
getRoomDetail,
- listRemoteAgents: vi.fn(() => Promise.resolve([])),
+ listAgents: vi.fn(() => Promise.resolve([])),
},
agents: { getAgents: vi.fn(() => Promise.resolve([])) },
},
@@ -38,7 +38,8 @@ vi.mock('@renderer/lib/ipc', () => ({
vi.mock('@renderer/features/switch-servers/switch-rooms-store', () => ({
switchRoomsStore: {
- roomServerId: () => 'srv-1',
+ roomWorkspaceId: () => 'ws-1',
+ roomServerId: () => 'server-1',
canDeleteRoom: () => false,
},
}));
@@ -156,7 +157,7 @@ describe('a room’s description and instructions', () => {
expect(updateRoom).toHaveBeenCalledTimes(1);
expect(updateRoom).toHaveBeenCalledWith({
- serverId: 'srv-1',
+ workspaceId: 'ws-1',
roomId: 'room-1',
description: 'The original description',
instructions: 'Be brief',
diff --git a/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts
index 655892b4f..5c39045f8 100644
--- a/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts
+++ b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts
@@ -265,7 +265,7 @@ export type RemoteRoomDetail = RemoteRoomSummary & {
/** The room fields Switch Console can change. Anything omitted is left alone;
* an empty string clears the field rather than leaving it. */
export type UpdateRoomParams = {
- serverId: string;
+ workspaceId: string;
roomId: string;
description?: string;
instructions?: string;
@@ -414,7 +414,7 @@ export type RemoteBridgeType = {
* never logged, and never sent back to the renderer.
*/
export type CreateBridgeParams = {
- serverId: string;
+ workspaceId: string;
bridgeType: string;
displayName: string;
connectionConfig: Record<string, string | boolean>;
@@ -450,7 +450,7 @@ export type CreateBridgeResult =
* own partial-update contract.
*/
export type UpdateBridgeParams = {
- serverId: string;
+ workspaceId: string;
bridgeId: string;
channelCreationEnabled?: boolean;
};
@@ -468,7 +468,7 @@ export type UpdateBridgeResult =
/** Parameters for disconnecting a bridge from a server
* (`DELETE /collaborations/{id}`). */
export type DeleteBridgeParams = {
- serverId: string;
+ workspaceId: string;
bridgeId: string;
};
@@ -555,7 +555,7 @@ export type BridgeDirectorySearchResult =
/** Claim a platform identity for the signed-in Switch user (CHOO-2137). */
export type ClaimIdentityParams = {
- serverId: string;
+ workspaceId: string;
bridgeId: string;
/** The platform's own id, not an `ExternalUser` row id — the row may not
* exist yet, and the server creates it on demand. */
@@ -669,7 +669,7 @@ export type AgentProviderKind = 'anthropic' | 'third-party';
* its credentials into the directory's `.claude/settings.local.json`.
*/
export type ProvisionAgentParams = {
- serverId: string;
+ workspaceId: string;
/** The agent's working directory; the settings file is written here and used
* as `repo_dir` so an offline-session command can `cd` into it. */
dir: string;
@@ -688,7 +688,7 @@ export type ProvisionAgentParams = {
* is no local directory: the agent's config lives entirely on the host.
*/
export type ProvisionRemoteAgentParams = {
- serverId: string;
+ workspaceId: string;
/** SSH alias of the onboarded host the agent runs on. */
sshHost: string;
/** The agent's working directory on the host; the settings file is written
@@ -741,7 +741,7 @@ export type ProvisionAgentResult =
* useful room, so there is no internal-only path here.
*/
export type CreateRoomParams = {
- serverId: string;
+ workspaceId: string;
name: string;
description: string;
/** Room-specific system prompt shown to agents on connect. Optional. */