Skip to content

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

feat(console): switch workspaces from the sidebar, not just servers

Petr Bauch71b6391c02c4
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.ts
index 777dd23c4..44f2de0e1 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.ts
@@ -74,7 +74,10 @@ vi.mock('./agent-workdir-fs', () => ({
})),
}));
vi.mock('@main/core/switch-servers/servers-store', () => ({
- getServer: vi.fn(async () => ({ id: 'srv-1', apiUrl: 'https://switch.example.com' })),
+ getServer: vi.fn(async () => mockServer),
+}));
+vi.mock('@main/core/workspaces/workspace-session', () => ({
+ withWorkspaceSession: (_workspaceId: string, fn: (server: unknown) => unknown) => fn(mockServer),
}));
vi.mock('@main/core/locations/store', () => ({
ensureLocation: vi.fn(async () => ({ id: 'loc-1' })),
@@ -105,9 +108,11 @@ vi.mock('@main/db/client', () => ({
vi.mock('@main/db/schema', () => ({ agents: { id: 'id', switchAgentId: 'switchAgentId' } }));
vi.mock('drizzle-orm', () => ({ eq: vi.fn() }));
vi.mock('@main/core/workspaces/workspaces-store', () => ({
- requireSoleWorkspaceForServer: vi.fn(async (serverId: string) => ({ id: `ws-${serverId}` })),
+ requireWorkspaceForServer: vi.fn(async (serverId: string) => ({ id: `ws-${serverId}` })),
}));
+const mockServer = vi.hoisted(() => ({ id: 'srv-1', apiUrl: 'https://switch.example.com' }));
+
const { addAgent } = await import('./add-agent');
const { trackEvent } = await import('@main/core/telemetry/telemetry-service');
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.ts b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.ts
index 4e9d27df8..fb44dc57d 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.ts
@@ -10,7 +10,8 @@ import { agentTypeOf } from '@main/core/telemetry/agent-type';
import type { TelemetryAgentCreateFailure } from '@main/core/telemetry/events';
import { entryPointOf } from '@main/core/telemetry/narrow';
import { trackEvent } from '@main/core/telemetry/telemetry-service';
-import { requireSoleWorkspaceForServer } from '@main/core/workspaces/workspaces-store';
+import { withWorkspaceSession } from '@main/core/workspaces/workspace-session';
+import { requireWorkspaceForServer } from '@main/core/workspaces/workspaces-store';
import { db } from '@main/db/client';
import { agents as agentsTable } from '@main/db/schema';
import { log } from '@main/lib/logger';
@@ -192,7 +193,7 @@ async function runAddAgent(params: AddAgentParams): Promise<AddAgentResult> {
message: `No Switch server with id ${params.serverId}`,
});
}
- const targetWorkspace = await requireSoleWorkspaceForServer(params.serverId);
+ const targetWorkspace = await requireWorkspaceForServer(params.serverId);
// Before minting an identity: the gateway's uniqueness check is scoped to the
// Switch server, so it cannot see a name already taken in this directory. Two
@@ -258,15 +259,17 @@ async function runAddAgent(params: AddAgentParams): Promise<AddAgentResult> {
}
}
- const registered = await registerAgentIdentity(server, {
- name: params.name,
- description: params.description,
- displayName: params.displayName,
- repoDir: params.dir,
- autoSession: params.autoSession,
- agentType: knownAgentTypeForProvider(params.providerId),
- iconUrl: params.iconUrl ?? agentAvatarUrlForName(params.name),
- });
+ const registered = await withWorkspaceSession(targetWorkspace.id, (target) =>
+ registerAgentIdentity(target, {
+ name: params.name,
+ description: params.description,
+ displayName: params.displayName,
+ repoDir: params.dir,
+ autoSession: params.autoSession,
+ agentType: knownAgentTypeForProvider(params.providerId),
+ iconUrl: params.iconUrl ?? agentAvatarUrlForName(params.name),
+ })
+ );
if (registered.kind !== 'created') return reportFailedCreate(params, registered);
const behavior = getPlugin(params.providerId).behavior.repoAgents;
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-config-file.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-config-file.ts
index 4c3b06e1d..3368c75e0 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-config-file.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-config-file.ts
@@ -62,14 +62,28 @@ export type AgentTemplateOrigin = {
name: string;
source: 'bundled' | 'server';
serverId?: string;
+ /**
+ * The workspace the template was read from.
+ *
+ * A template registry belongs to a workspace, not to the server hosting it,
+ * so the server alone does not say where to look again once an account holds
+ * several on one. Absent on an origin written before this was recorded.
+ */
+ workspaceId?: string;
};
function parseTemplateOrigin(value: unknown): AgentTemplateOrigin | undefined {
if (!isPlainObject(value)) return undefined;
- const { id, name, source, serverId } = value;
+ const { id, name, source, serverId, workspaceId } = value;
if (typeof id !== 'string' || typeof name !== 'string') return undefined;
if (source !== 'bundled' && source !== 'server') return undefined;
- return { id, name, source, ...(typeof serverId === 'string' ? { serverId } : {}) };
+ return {
+ id,
+ name,
+ source,
+ ...(typeof serverId === 'string' ? { serverId } : {}),
+ ...(typeof workspaceId === 'string' ? { workspaceId } : {}),
+ };
}
/**
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/assignAgentServer.ts b/console/apps/switch-console-desktop/src/main/core/agents/assignAgentServer.ts
index 7e3e46477..cd7b884cc 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/assignAgentServer.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/assignAgentServer.ts
@@ -1,6 +1,6 @@
import { agentExistsOnServer, GatewayError } from '@main/core/switch-servers/gateway-client';
-import { getServer } from '@main/core/switch-servers/servers-store';
-import { requireSoleWorkspaceForServer } from '@main/core/workspaces/workspaces-store';
+import { withWorkspaceSession } from '@main/core/workspaces/workspace-session';
+import { requireWorkspaceForServer } from '@main/core/workspaces/workspaces-store';
import type { AgentVerifyResult } from '@shared/core/switch-servers/switch-servers';
import { getAgentById } from './getAgentById';
import { updateAgent } from './updateAgent';
@@ -23,14 +23,19 @@ export async function assignAgentServer(params: {
if (!agent.switchAgentId) {
throw new Error(`Agent ${params.agentId} has no Switch agent id to verify`);
}
- const server = await getServer(params.serverId);
- if (!server) {
- throw new Error(`No Switch server with id ${params.serverId}`);
- }
+ // Resolved before the call, not after it: the workspace the agent would be
+ // written into is the one the question has to be asked of, or a `found` here
+ // means found somewhere else.
+ const workspace = await requireWorkspaceForServer(params.serverId);
+ const switchAgentId = agent.switchAgentId;
let result: AgentVerifyResult;
try {
- result = (await agentExistsOnServer(server, agent.switchAgentId)) ? 'found' : 'not-found';
+ result = (await withWorkspaceSession(workspace.id, (server) =>
+ agentExistsOnServer(server, switchAgentId)
+ ))
+ ? 'found'
+ : 'not-found';
} catch (cause) {
if (cause instanceof GatewayError && cause.kind === 'unauthorized') {
return 'unauthenticated';
@@ -39,7 +44,6 @@ export async function assignAgentServer(params: {
}
if (result === 'found') {
- const workspace = await requireSoleWorkspaceForServer(params.serverId);
await updateAgent({ agentId: params.agentId, workspaceId: workspace.id });
}
return result;
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.test.ts
index 104079989..469fb15bb 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.test.ts
@@ -74,7 +74,16 @@ vi.mock('./getAgents', () => ({
),
}));
vi.mock('@main/core/workspaces/workspaces-store', () => ({
- requireSoleWorkspaceForServer: vi.fn(async (serverId: string) => ({ id: `ws-${serverId}` })),
+ requireWorkspaceForServer: vi.fn(async (serverId: string) => ({ id: `ws-${serverId}` })),
+}));
+
+const mockServer = vi.hoisted(() => ({
+ id: 'srv-1',
+ name: 'Switch',
+ apiUrl: 'https://switch.example.com',
+}));
+vi.mock('@main/core/workspaces/workspace-session', () => ({
+ withWorkspaceSession: (_workspaceId: string, fn: (server: unknown) => unknown) => fn(mockServer),
}));
vi.mock('./agent-workdir-fs', () => ({
resolveWorkdirFsFor: vi.fn(async () => ({
@@ -91,11 +100,7 @@ vi.mock('@main/core/switch-servers/gateway-client', () => ({
GatewayError: h.GatewayError,
}));
vi.mock('@main/core/switch-servers/servers-store', () => ({
- getServer: vi.fn(async () => ({
- id: 'srv-1',
- name: 'Switch',
- apiUrl: 'https://switch.example.com',
- })),
+ getServer: vi.fn(async () => mockServer),
}));
vi.mock('./createAgent', () => ({ createAgent: h.createAgent }));
vi.mock('@main/core/locations/path-utils', () => ({ checkIsValidDirectory: () => true }));
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.ts b/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.ts
index db4b6e7b0..c7a43a9fe 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.ts
@@ -6,7 +6,8 @@ import { checkIsValidDirectory } from '@main/core/locations/path-utils';
import { ensureLocation } from '@main/core/locations/store';
import { agentExistsOnServer, GatewayError } from '@main/core/switch-servers/gateway-client';
import { getServer } from '@main/core/switch-servers/servers-store';
-import { requireSoleWorkspaceForServer } from '@main/core/workspaces/workspaces-store';
+import { withWorkspaceSession } from '@main/core/workspaces/workspace-session';
+import { requireWorkspaceForServer } from '@main/core/workspaces/workspaces-store';
import { log } from '@main/lib/logger';
import type { Agent } from '@shared/core/agents/agents';
import type { OnboardAgentError } from '@shared/core/agents/onboarding';
@@ -71,7 +72,7 @@ export async function attachConfiguredAgents(
const server = await getServer(params.serverId);
if (!server) throw new Error(`No Switch server with id ${params.serverId}`);
- const targetWorkspace = await requireSoleWorkspaceForServer(params.serverId);
+ const targetWorkspace = await requireWorkspaceForServer(params.serverId);
const discovered = new Map(
(
@@ -118,7 +119,10 @@ export async function attachConfiguredAgents(
if (!found) continue;
try {
- if (!(await agentExistsOnServer(server, found.switchAgentId))) {
+ const exists = await withWorkspaceSession(targetWorkspace.id, (target) =>
+ agentExistsOnServer(target, found.switchAgentId)
+ );
+ if (!exists) {
return err({
type: 'switch-agent-not-on-server',
dir: params.dir,
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/discover-configured-agents.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/discover-configured-agents.test.ts
index a53f765b4..2fff3599b 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/discover-configured-agents.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/discover-configured-agents.test.ts
@@ -73,7 +73,7 @@ vi.mock('./getAgents', () => ({
),
}));
vi.mock('@main/core/workspaces/workspaces-store', () => ({
- requireSoleWorkspaceForServer: vi.fn(async (serverId: string) => ({ id: `ws-${serverId}` })),
+ requireWorkspaceForServer: vi.fn(async (serverId: string) => ({ id: `ws-${serverId}` })),
}));
vi.mock('./agent-workdir-fs', () => ({
resolveWorkdirFsFor: vi.fn(async () => ({
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/discover-configured-agents.ts b/console/apps/switch-console-desktop/src/main/core/agents/discover-configured-agents.ts
index 87bb5d308..fa38097ae 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/discover-configured-agents.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/discover-configured-agents.ts
@@ -1,7 +1,7 @@
import type { PluginFs } from '@switch-console/core/agents/plugins';
import { getLocationByHostDir } from '@main/core/locations/store';
import { listPlugins } from '@main/core/providers/plugin-registry';
-import { requireSoleWorkspaceForServer } from '@main/core/workspaces/workspaces-store';
+import { requireWorkspaceForServer } from '@main/core/workspaces/workspaces-store';
import { log } from '@main/lib/logger';
import {
isValidProviderId,
@@ -123,7 +123,7 @@ export async function discoverConfiguredAgents(params: {
* attached here already and still be attachable to another (CHOO-2044). */
serverId: string;
}): Promise<DiscoveredConfiguredAgent[]> {
- const targetWorkspace = await requireSoleWorkspaceForServer(params.serverId);
+ const targetWorkspace = await requireWorkspaceForServer(params.serverId);
const location = await getLocationByHostDir(params.sshHost, params.dir);
const existing = location
? new Set(
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/discover-location-agents.ts b/console/apps/switch-console-desktop/src/main/core/agents/discover-location-agents.ts
index 3c0814922..899f059f1 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/discover-location-agents.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/discover-location-agents.ts
@@ -1,6 +1,6 @@
import { getLocationByHostDir } from '@main/core/locations/store';
import { getPlugin } from '@main/core/providers/plugin-registry';
-import { requireSoleWorkspaceForServer } from '@main/core/workspaces/workspaces-store';
+import { requireWorkspaceForServer } from '@main/core/workspaces/workspaces-store';
import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';
import { resolveWorkdirFsFor } from './agent-workdir-fs';
import { getLocationAgentsInWorkspace } from './getAgents';
@@ -47,7 +47,7 @@ export async function discoverLocationAgents(params: {
const behavior = getPlugin(params.providerId).behavior.repoAgents;
if (!behavior) return [];
- const targetWorkspace = await requireSoleWorkspaceForServer(params.serverId);
+ const targetWorkspace = await requireWorkspaceForServer(params.serverId);
const location = await getLocationByHostDir(params.sshHost, params.dir);
const existing = location
? new Set(
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/onboard-agent.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/onboard-agent.test.ts
index 00d98aa23..144156fc5 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/onboard-agent.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/onboard-agent.test.ts
@@ -45,7 +45,10 @@ vi.mock('@main/core/switch-servers/servers-store', () => ({
getServer: vi.fn(async () => h.server),
}));
vi.mock('@main/core/workspaces/workspaces-store', () => ({
- requireSoleWorkspaceForServer: vi.fn(async (serverId: string) => ({ id: `ws-${serverId}` })),
+ requireWorkspaceForServer: vi.fn(async (serverId: string) => ({ id: `ws-${serverId}` })),
+}));
+vi.mock('@main/core/workspaces/workspace-session', () => ({
+ withWorkspaceSession: (_workspaceId: string, fn: (server: unknown) => unknown) => fn(h.server),
}));
vi.mock('@main/core/switch-servers/gateway-client', () => {
class GatewayError extends Error {
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/onboard-agent.ts b/console/apps/switch-console-desktop/src/main/core/agents/onboard-agent.ts
index 590a144eb..adb5c392c 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/onboard-agent.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/onboard-agent.ts
@@ -9,7 +9,8 @@ import { getServer } from '@main/core/switch-servers/servers-store';
import { agentTypeOf } from '@main/core/telemetry/agent-type';
import type { TelemetryAgentCreateFailure } from '@main/core/telemetry/events';
import { trackEvent } from '@main/core/telemetry/telemetry-service';
-import { requireSoleWorkspaceForServer } from '@main/core/workspaces/workspaces-store';
+import { withWorkspaceSession } from '@main/core/workspaces/workspace-session';
+import { requireWorkspaceForServer } from '@main/core/workspaces/workspaces-store';
import { log } from '@main/lib/logger';
import type {
OnboardAgentError,
@@ -85,33 +86,32 @@ async function verifyAgentOnServer(
agentId: string,
dir: string
): Promise<OnboardAgentError | null> {
- const server = await getServer(serverId);
- if (!server) {
- throw new Error(`No Switch server with id ${serverId}`);
- }
- try {
- const exists = await agentExistsOnServer(server, agentId);
- if (!exists) {
- return {
- type: 'switch-agent-not-on-server',
- dir,
- serverId: server.id,
- serverName: server.name,
- agentId,
- };
- }
- return null;
- } catch (cause) {
- if (cause instanceof GatewayError && cause.kind === 'unauthorized') {
- return {
- type: 'switch-server-unauthenticated',
- dir,
- serverId: server.id,
- serverName: server.name,
- };
+ const workspace = await requireWorkspaceForServer(serverId);
+ return withWorkspaceSession(workspace.id, async (server) => {
+ try {
+ const exists = await agentExistsOnServer(server, agentId);
+ if (!exists) {
+ return {
+ type: 'switch-agent-not-on-server',
+ dir,
+ serverId: server.id,
+ serverName: server.name,
+ agentId,
+ };
+ }
+ return null;
+ } catch (cause) {
+ if (cause instanceof GatewayError && cause.kind === 'unauthorized') {
+ return {
+ type: 'switch-server-unauthenticated',
+ dir,
+ serverId: server.id,
+ serverName: server.name,
+ };
+ }
+ throw cause;
}
- throw cause;
- }
+ });
}
/**
@@ -186,7 +186,7 @@ export async function onboardAgent(params: OnboardAgentParams): Promise<OnboardA
}
}
- const targetWorkspace = await requireSoleWorkspaceForServer(params.serverId);
+ const targetWorkspace = await requireWorkspaceForServer(params.serverId);
const location = await ensureLocation({ sshHost, dir: params.dir, name: params.name });
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/onboard-location-agents.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/onboard-location-agents.test.ts
index 9f9019727..c70ca5c4b 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/onboard-location-agents.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/onboard-location-agents.test.ts
@@ -49,7 +49,16 @@ vi.mock('./getAgents', () => ({
),
}));
vi.mock('@main/core/workspaces/workspaces-store', () => ({
- requireSoleWorkspaceForServer: vi.fn(async (serverId: string) => ({ id: `ws-${serverId}` })),
+ requireWorkspaceForServer: vi.fn(async (serverId: string) => ({ id: `ws-${serverId}` })),
+}));
+
+const mockServer = vi.hoisted(() => ({
+ id: 'srv-b',
+ name: 'Server B',
+ apiUrl: 'https://b.example.com',
+}));
+vi.mock('@main/core/workspaces/workspace-session', () => ({
+ withWorkspaceSession: (_workspaceId: string, fn: (server: unknown) => unknown) => fn(mockServer),
}));
vi.mock('./agent-workdir-fs', () => ({
resolveWorkdirFsFor: vi.fn(async () => ({
@@ -73,11 +82,7 @@ vi.mock('@main/core/switch-servers/gateway-client', () => ({
GatewayError: h.GatewayError,
}));
vi.mock('@main/core/switch-servers/servers-store', () => ({
- getServer: vi.fn(async () => ({
- id: 'srv-b',
- name: 'Server B',
- apiUrl: 'https://b.example.com',
- })),
+ getServer: vi.fn(async () => mockServer),
findServerByEndpoint: vi.fn(async (endpoint: string) =>
endpoint === 'https://a.example.com'
? { id: 'srv-a', name: 'Server A', apiUrl: 'https://a.example.com' }
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/onboard-location-agents.ts b/console/apps/switch-console-desktop/src/main/core/agents/onboard-location-agents.ts
index 6a9c81c9a..c9337fa9a 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/onboard-location-agents.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/onboard-location-agents.ts
@@ -8,7 +8,8 @@ import { ensureLocation } from '@main/core/locations/store';
import { getPlugin } from '@main/core/providers/plugin-registry';
import { agentExistsOnServer, GatewayError } from '@main/core/switch-servers/gateway-client';
import { findServerByEndpoint, getServer } from '@main/core/switch-servers/servers-store';
-import { requireSoleWorkspaceForServer } from '@main/core/workspaces/workspaces-store';
+import { withWorkspaceSession } from '@main/core/workspaces/workspace-session';
+import { requireWorkspaceForServer } from '@main/core/workspaces/workspaces-store';
import { log } from '@main/lib/logger';
import { agentAvatarUrlForName } from '@shared/core/agents/agent-avatar';
import type { Agent } from '@shared/core/agents/agents';
@@ -85,6 +86,8 @@ async function resolveIdentity(
description: string | null,
ctx: {
server: SwitchServer;
+ /** The workspace the agents are being onboarded into; every gateway call here is scoped to it. */
+ workspaceId: string;
workdir: WorkdirFs;
credsByName: Map<string, { switchAgentId: string | null; apiEndpoint: string | null }>;
dir: string;
@@ -92,11 +95,15 @@ async function resolveIdentity(
): Promise<{ ok: true; identity: ResolvedIdentity } | { ok: false; error: OnboardAgentError }> {
const creds = ctx.credsByName.get(name);
if (creds?.switchAgentId && creds.apiEndpoint) {
+ const switchAgentId = creds.switchAgentId;
try {
- if (await agentExistsOnServer(ctx.server, creds.switchAgentId)) {
+ const exists = await withWorkspaceSession(ctx.workspaceId, (target) =>
+ agentExistsOnServer(target, switchAgentId)
+ );
+ if (exists) {
return {
ok: true,
- identity: { switchAgentId: creds.switchAgentId, apiEndpoint: creds.apiEndpoint },
+ identity: { switchAgentId, apiEndpoint: creds.apiEndpoint },
};
}
} catch (cause) {
@@ -125,20 +132,22 @@ async function resolveIdentity(
// No usable credentials — adopt: mint a fresh identity and write its creds,
// keeping the existing definition file untouched.
- const registered = await registerAgentIdentity(ctx.server, {
- name,
- description: description ?? `Claude Code agent ${name}`,
- repoDir: ctx.dir,
- autoSession: true,
- // This path onboards `.claude/agents/*.md` definitions, so the identity is a
- // Claude Code one by construction.
- agentType: knownAgentTypeForProvider('claude'),
- // Nobody is at a form to choose one, so it starts with the avatar its name
- // generates — the same picture it would be shown with anyway.
- iconUrl: agentAvatarUrlForName(name),
- // The definition file carries no human label, so there is none to adopt.
- displayName: null,
- });
+ const registered = await withWorkspaceSession(ctx.workspaceId, (target) =>
+ registerAgentIdentity(target, {
+ name,
+ description: description ?? `Claude Code agent ${name}`,
+ repoDir: ctx.dir,
+ autoSession: true,
+ // This path onboards `.claude/agents/*.md` definitions, so the identity is a
+ // Claude Code one by construction.
+ agentType: knownAgentTypeForProvider('claude'),
+ // Nobody is at a form to choose one, so it starts with the avatar its name
+ // generates — the same picture it would be shown with anyway.
+ iconUrl: agentAvatarUrlForName(name),
+ // The definition file carries no human label, so there is none to adopt.
+ displayName: null,
+ })
+ );
if (registered.kind !== 'created') {
const message = 'message' in registered ? registered.message : '';
return {
@@ -197,7 +206,7 @@ export async function onboardLocationAgents(
name: params.locationName ?? basenameFromAnyPath(params.dir) ?? params.providerId,
});
- const targetWorkspace = await requireSoleWorkspaceForServer(params.serverId);
+ const targetWorkspace = await requireWorkspaceForServer(params.serverId);
const existing = new Set(
(await getLocationAgentsInWorkspace(location.id, targetWorkspace.id)).map((a) => a.name)
);
@@ -236,6 +245,7 @@ export async function onboardLocationAgents(
for (const def of selected) {
const resolved = await resolveIdentity(def.name, def.description, {
server,
+ workspaceId: targetWorkspace.id,
workdir,
credsByName,
dir: params.dir,
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 62aa2b17b..1bc7b26c1 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
@@ -61,7 +61,6 @@ vi.mock('./servers-store', () => ({
getServer,
addServer,
deleteSessionCookie: vi.fn(),
- getActiveServerId: vi.fn(),
listServers: vi.fn(),
removeServer: vi.fn(),
renameServer: vi.fn(),
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 71c16f306..7b9c8aea5 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
@@ -26,7 +26,6 @@ import { hostUnreachable, requireReachableServer, requireServer } from './requir
import {
addServer,
deleteSessionCookie,
- getActiveServerId,
getServer,
listServers,
removeServer,
@@ -124,8 +123,6 @@ export const switchServersController = createRPCController({
removeServer: (serverId: string): Promise<void> => removeServer(serverId),
- getActiveServerId: (): Promise<string | null> => getActiveServerId(),
-
setActiveServer: (serverId: string): Promise<void> => setActiveServerId(serverId),
getAuthConfig: async (serverId: string): Promise<SwitchAuthConfig> =>
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/servers-store.db.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/servers-store.db.test.ts
index 86e9935b9..fe5a08288 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/servers-store.db.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/servers-store.db.test.ts
@@ -37,14 +37,9 @@ vi.mock('@main/core/telemetry/telemetry-service', () => ({
}));
// Imported after the mocks so the module binds to the mocked db + secrets store.
-const {
- addServer,
- ensureManagedServer,
- getActiveServerId,
- removeServer,
- renameServer,
- setActiveServerId,
-} = await import('./servers-store');
+const { addServer, ensureManagedServer, removeServer, renameServer, setActiveServerId } =
+ await import('./servers-store');
+const { getActiveWorkspaceId } = await import('@main/core/workspaces/workspaces-store');
describe('servers-store: rename & delete', () => {
let fixture: Awaited<ReturnType<typeof openFixture>>;
@@ -306,8 +301,12 @@ describe('selecting a server', () => {
mocks.db = undefined;
});
- async function seedWorkspace(id: string, tenantId: string | null): Promise<void> {
- await fixture.db.insert(workspaces).values({ id, serverId: 'srv-1', name: id, tenantId });
+ async function seedWorkspace(
+ id: string,
+ tenantId: string | null,
+ role: 'owner' | 'member' | null = 'member'
+ ): Promise<void> {
+ await fixture.db.insert(workspaces).values({ id, serverId: 'srv-1', name: id, tenantId, role });
}
it('selects the one workspace a server has', async () => {
@@ -315,7 +314,7 @@ describe('selecting a server', () => {
await setActiveServerId('srv-1');
- expect(await getActiveServerId()).toBe('srv-1');
+ expect(await getActiveWorkspaceId()).toBe('ws-1');
});
/**
@@ -328,7 +327,7 @@ describe('selecting a server', () => {
await setActiveServerId('srv-1');
- expect(await getActiveServerId()).toBe('srv-1');
+ expect(await getActiveWorkspaceId()).toBe('ws-1');
});
// Re-selecting the server the user is already in must not move them to
@@ -345,6 +344,57 @@ describe('selecting a server', () => {
expect(pointer!.value).toBe('ws-2');
});
+ /**
+ * The oldest row is the one a withdrawn membership is most likely to be —
+ * the server's original workspace, whose membership was the first to be
+ * given up. Landing on it would scope the window to something the gateway
+ * refuses every call for.
+ */
+ it('skips a workspace this account is no longer a member of', async () => {
+ await seedWorkspace('ws-1', 't-gone', null);
+ await seedWorkspace('ws-2', 't-2');
+
+ await setActiveServerId('srv-1');
+
+ expect(await getActiveWorkspaceId()).toBe('ws-2');
+ });
+
+ /**
+ * The row the server was registered with, before the gateway was asked which
+ * workspaces the account has. It names no tenant, so a call scoped to it
+ * selects none and the gateway answers with whichever workspace the session
+ * last selected — under this one's name. On an upgraded install it is also
+ * the oldest row, and holds every agent.
+ */
+ it('skips a placeholder the reconcile could not match', async () => {
+ await seedWorkspace('ws-1', null, null);
+ await seedWorkspace('ws-2', 't-2');
+
+ await setActiveServerId('srv-1');
+
+ expect(await getActiveWorkspaceId()).toBe('ws-2');
+ });
+
+ // Every server's first workspace starts out like this and is matched to a
+ // membership afterwards; on its own there is nothing to confuse it with.
+ it('selects a lone workspace that has no tenant yet', async () => {
+ await seedWorkspace('ws-1', null, null);
+
+ await setActiveServerId('srv-1');
+
+ expect(await getActiveWorkspaceId()).toBe('ws-1');
+ });
+
+ // Nothing else to fall back to, and refusing here takes a healthy managed
+ // stack start down; the seam says why on the first call instead.
+ it('still picks one when every workspace on the server is withdrawn', async () => {
+ await seedWorkspace('ws-1', 't-gone', null);
+
+ await setActiveServerId('srv-1');
+
+ expect(await getActiveWorkspaceId()).toBe('ws-1');
+ });
+
it('refuses a server with no workspace at all', async () => {
await expect(setActiveServerId('srv-1')).rejects.toThrow('no workspace');
});
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 004fc1738..adf83d194 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
@@ -11,7 +11,6 @@ import {
insertServerWorkspace,
listWorkspacesForServer,
renameServerWorkspaces,
- serverIdForWorkspace,
setActiveWorkspaceId,
} from '@main/core/workspaces/workspaces-store';
import { db } from '@main/db/client';
@@ -24,6 +23,7 @@ import {
type SwitchServer,
type UpdateServerParams,
} from '@shared/core/switch-servers/switch-servers';
+import { workspaceUnavailability } from '@shared/core/workspaces/workspaces';
// Keyed to the server, not the workspace: one gateway session cookie covers
// every workspace on a server.
@@ -271,20 +271,6 @@ export function serverKindOf(
return server.managementKind === 'remote' ? 'remote_managed' : 'local';
}
-/**
- * The server whose workspace is active, for the parts of the app that still
- * scope themselves to a server.
- *
- * The selection itself is a workspace — see the workspaces store. This reads it
- * back as the server hosting it, and returns null when nothing is selected or
- * the selected workspace has since gone.
- */
-export async function getActiveServerId(): Promise<string | null> {
- const activeWorkspaceId = await getActiveWorkspaceId();
- if (!activeWorkspaceId) return null;
- return serverIdForWorkspace(activeWorkspaceId);
-}
-
/**
* Select a server by selecting one of its workspaces.
*
@@ -294,16 +280,27 @@ export async function getActiveServerId(): Promise<string | null> {
* from being corrected, while attaching an agent to it is neither. Refusing
* here would instead fail the managed stack start this runs inside, taking a
* healthy server down over a question about which of its workspaces to show.
+ *
+ * "First" means the first that can actually be opened, where there is one: a
+ * withdrawn membership and an unmatched placeholder are both refused by the
+ * gateway, and landing on either is not a wrong guess a click corrects. Where
+ * there is no such workspace it still picks, for the same reason it does not
+ * refuse a choice between several — the seam says why on the first call.
*/
export async function setActiveServerId(id: string): Promise<void> {
const server = await getServer(id);
if (!server) throw new Error(`No Switch server with id ${id}`);
const found = await listWorkspacesForServer(id);
- const workspace = found[0];
- if (!workspace) throw new Error(`Switch server ${id} has no workspace`);
+ if (found.length === 0) throw new Error(`Switch server ${id} has no workspace`);
const active = await getActiveWorkspaceId();
if (found.some((candidate) => candidate.id === active)) return;
- await setActiveWorkspaceId(workspace.id);
+ // The rows are oldest first, and the oldest is exactly the one a withdrawn
+ // membership or an unmatched placeholder is most likely to be — the row the
+ // server was registered with, before the gateway was ever asked.
+ const openable = found.find(
+ (candidate) => workspaceUnavailability(candidate, found.length) === null
+ );
+ await setActiveWorkspaceId((openable ?? found[0]!).id);
}
// ---------------------------------------------------------------------------
diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.db.test.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.db.test.ts
index b14bc0854..4a74aa61b 100644
--- a/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.db.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.db.test.ts
@@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { AppDb } from '@main/db/client';
import { agents, locations, switchServers } from '@main/db/schema';
import { workspacesChangedChannel } from '@shared/core/workspaces/workspaceEvents';
+import { isWithdrawnWorkspace } from '@shared/core/workspaces/workspaces';
const mocks = vi.hoisted(() => ({
db: undefined as AppDb | undefined,
@@ -333,13 +334,35 @@ describe('reconcile-workspaces', () => {
await reconcileServerWorkspaces('srv-1');
const found = await listWorkspacesForServer('srv-1');
- expect(found.some((w) => w.tenantId === 't-gone')).toBe(true);
+ const gone = found.find((w) => w.tenantId === 't-gone');
+ expect(gone).toBeDefined();
+ // The role is what the switcher reads to say so before the click, rather
+ // than leaving the log file as the only place it is said.
+ expect(gone!.role).toBeNull();
+ expect(isWithdrawnWorkspace(gone!)).toBe(true);
expect(warn).toHaveBeenCalledWith(expect.stringContaining('no longer a member'), {
server: 'srv-1',
workspace: expect.any(String),
});
});
+ it('restores the role when a withdrawn membership is granted again', async () => {
+ await createTenantWorkspace('srv-1', {
+ id: 't-back',
+ slug: 't-back',
+ name: 'Research',
+ role: 'admin',
+ });
+ fetchTenants.mockResolvedValue([tenant('t-1', 'Default')]);
+ await reconcileServerWorkspaces('srv-1');
+
+ fetchTenants.mockResolvedValue([tenant('t-1', 'Default'), tenant('t-back', 'Research')]);
+ await reconcileServerWorkspaces('srv-1');
+
+ const back = (await listWorkspacesForServer('srv-1')).find((w) => w.tenantId === 't-back');
+ expect(isWithdrawnWorkspace(back!)).toBe(false);
+ });
+
// An account in no workspace at all is a server the user cannot use; saying
// nothing and deleting the local row would look like it had never been set up.
it('leaves the rows alone when the gateway reports no membership', async () => {
@@ -353,6 +376,28 @@ describe('reconcile-workspaces', () => {
expect(warn).toHaveBeenCalled();
});
+ /**
+ * The short-circuit for "no memberships" used to return before the withdrawal
+ * pass, so the one case where every row has been withdrawn was the one case
+ * that never marked any. The switcher and the first-run picker went on
+ * offering them, and the refusal only arrived after the click.
+ */
+ it('marks every row withdrawn when the account is left in no workspace', async () => {
+ const held = await createTenantWorkspace('srv-1', {
+ id: 't-gone',
+ slug: 't-gone',
+ name: 'Research',
+ role: 'member',
+ });
+ fetchTenants.mockResolvedValue([]);
+
+ await reconcileServerWorkspaces('srv-1');
+
+ const found = await listWorkspacesForServer('srv-1');
+ expect(found.find((w) => w.id === held.id)!.role).toBeNull();
+ expect(found.find((w) => w.id === held.id)!.tenantId).toBe('t-gone');
+ });
+
it('is idempotent across launches', async () => {
const before = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });
fetchTenants.mockResolvedValue([tenant('t-1', 'Default')]);
diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.ts
index d8a6f92a8..4322263e0 100644
--- a/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.ts
+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.ts
@@ -12,6 +12,7 @@ import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';
import { workspacesChangedChannel } from '@shared/core/workspaces/workspaceEvents';
import type { Workspace } from '@shared/core/workspaces/workspaces';
import {
+ clearWorkspaceRole,
createTenantWorkspace,
discardEmptyWorkspace,
listWorkspacesForServer,
@@ -76,12 +77,19 @@ async function tenantToAdopt(
return null;
}
-/** Say so when a workspace is still held locally for a membership that has gone. */
-function reportWithdrawnMemberships(
+/**
+ * Mark the workspaces still held locally for a membership that has gone.
+ *
+ * The row is kept — deleting it would silently detach its agents — so the mark
+ * is what stops it reading as a workspace the user can still open. A log line
+ * alone would leave the switcher listing it exactly like the others, and the
+ * only sign would be the gateway refusing the call after the click.
+ */
+async function markWithdrawnMemberships(
serverId: string,
local: Workspace[],
tenants: RemoteTenant[]
-): void {
+): Promise<void> {
for (const workspace of local) {
if (!workspace.tenantId) continue;
if (tenants.some((tenant) => tenant.id === workspace.tenantId)) continue;
@@ -89,6 +97,7 @@ function reportWithdrawnMemberships(
'workspaces: this account is no longer a member of a workspace held locally; calls scoped to it will be refused',
{ server: serverId, workspace: workspace.id }
);
+ if (workspace.role !== null) await clearWorkspaceRole(workspace.id);
}
}
@@ -138,6 +147,13 @@ const inFlight = new Map<string, Promise<void>>();
async function reconcileOneServer(serverId: string): Promise<void> {
const server = await requireServer(serverId);
const tenants = await fetchTenants(server);
+ const local = await listWorkspacesForServer(serverId);
+ // Marked before the short-circuit below, not after it: an account that is in
+ // nothing has had every membership withdrawn, and that is precisely the case
+ // where a row still claiming one would go on being offered as somewhere to
+ // work.
+ await markWithdrawnMemberships(serverId, local, tenants);
+
if (tenants.length === 0) {
log.warn('workspaces: the gateway reports no workspace membership for this account', {
server: serverId,
@@ -145,9 +161,6 @@ async function reconcileOneServer(serverId: string): Promise<void> {
return;
}
- const local = await listWorkspacesForServer(serverId);
- reportWithdrawnMemberships(serverId, local, tenants);
-
const claimed = new Map(
local
.filter((workspace) => workspace.tenantId)
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
index 48fd068fe..73b302c86 100644
--- 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
@@ -2,7 +2,7 @@ import { decodeJwtTenantId, switchTenant } from '@main/core/switch-servers/gatew
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 type { Workspace } from '@shared/core/workspaces/workspaces';
+import { isUnmatchedWorkspace, type Workspace } from '@shared/core/workspaces/workspaces';
import { clearAssertedTenant, setAssertedTenant } from './asserted-tenant';
import { listWorkspacesForServer, requireWorkspace } from './workspaces-store';
@@ -116,7 +116,7 @@ async function requireAddressableWorkspace(workspaceId: string): Promise<Workspa
const workspace = await requireWorkspace(workspaceId);
if (workspace.tenantId) return workspace;
const onServer = await listWorkspacesForServer(workspace.serverId);
- if (onServer.length > 1) {
+ if (isUnmatchedWorkspace(workspace, onServer.length)) {
throw new Error(
// Not "sign in again": signing in re-runs the reconcile, which is what
// left the row unmatched in the first place and would do so again. The
diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/workspaces-store.db.test.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/workspaces-store.db.test.ts
index 1ab23794a..0abc22d39 100644
--- a/console/apps/switch-console-desktop/src/main/core/workspaces/workspaces-store.db.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/workspaces-store.db.test.ts
@@ -21,7 +21,7 @@ const {
getActiveWorkspaceId,
listWorkspacesForServer,
renameServerWorkspaces,
- requireSoleWorkspaceForServer,
+ requireWorkspaceForServer,
requireWorkspace,
serverIdForWorkspace,
setActiveWorkspaceId,
@@ -91,30 +91,46 @@ describe('workspaces-store', () => {
});
});
- describe('requireSoleWorkspaceForServer', () => {
+ describe('requireWorkspaceForServer', () => {
it('returns the one workspace a server has', async () => {
await seedServer('srv-1', 'Local dev');
const created = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });
- expect((await requireSoleWorkspaceForServer('srv-1')).id).toBe(created.id);
+ expect((await requireWorkspaceForServer('srv-1')).id).toBe(created.id);
});
it('raises for a server whose registration left it with none', async () => {
await seedServer('srv-1', 'Local dev');
- await expect(requireSoleWorkspaceForServer('srv-1')).rejects.toThrow('has no workspace');
+ await expect(requireWorkspaceForServer('srv-1')).rejects.toThrow('has no workspace');
+ });
+
+ // These callers run from screens showing the active workspace, so acting
+ // anywhere else would act somewhere the user is not looking.
+ it('takes the active one when a server has several', async () => {
+ await seedServer('srv-1', 'Cloud');
+ await fixture.db.insert(workspaces).values([
+ { id: 'ws-a', serverId: 'srv-1', name: 'A', tenantId: 'tenant-a' },
+ { id: 'ws-b', serverId: 'srv-1', name: 'B', tenantId: 'tenant-b' },
+ ]);
+ await setActiveWorkspaceId('ws-b');
+
+ expect((await requireWorkspaceForServer('srv-1')).id).toBe('ws-b');
});
// Picking one would attach the agent to a workspace the user never chose,
// and nothing would show them until it had already happened.
- it('raises rather than picking when a server has several', async () => {
+ it('raises when a server has several and the active one is elsewhere', async () => {
await seedServer('srv-1', 'Cloud');
+ await seedServer('srv-2', 'Local dev');
await fixture.db.insert(workspaces).values([
{ id: 'ws-a', serverId: 'srv-1', name: 'A', tenantId: 'tenant-a' },
{ id: 'ws-b', serverId: 'srv-1', name: 'B', tenantId: 'tenant-b' },
+ { id: 'ws-c', serverId: 'srv-2', name: 'C', tenantId: 'tenant-c' },
]);
+ await setActiveWorkspaceId('ws-c');
- await expect(requireSoleWorkspaceForServer('srv-1')).rejects.toThrow('must name one');
+ await expect(requireWorkspaceForServer('srv-1')).rejects.toThrow('must name one');
});
});
diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/workspaces-store.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/workspaces-store.ts
index 4a8c2cedc..98686313f 100644
--- a/console/apps/switch-console-desktop/src/main/core/workspaces/workspaces-store.ts
+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/workspaces-store.ts
@@ -54,25 +54,30 @@ export async function requireWorkspace(id: string): Promise<Workspace> {
}
/**
- * The one workspace on a server, for a caller that knows only the server.
+ * The workspace to act in on a server, for a caller that knows only the server
+ * — onboarding an agent, attaching one, discovering what a directory holds.
*
- * Servers currently carry exactly one workspace each: the row migration 0050
- * created, or the one `ensureServerWorkspace` creates when a server is
- * registered. Until the user can pick between them, callers that act on a
- * server — onboarding an agent, switching the active scope — resolve through
- * here rather than naming a workspace they have no way to choose.
+ * Most servers carry exactly one workspace, and then there is nothing to
+ * choose. Where there are several, the answer is the one the window is scoped
+ * to: these callers are all driven from screens showing that workspace, so
+ * anything else would act somewhere the user is not looking.
*
- * Raises on either edge instead of picking. A server with none is a registration
- * that half-succeeded; a server with several means the caller is the one that
- * has to say which, and attaching an agent to the wrong workspace is not
- * something the user would see until it had already happened.
+ * Raises rather than picking when neither applies. A server with no workspace
+ * is a registration that half-succeeded; a server with several, none of them
+ * the active one, means the caller is the one that has to say which — and
+ * attaching an agent to the wrong workspace is not something the user would see
+ * until it had already happened.
*/
-export async function requireSoleWorkspaceForServer(serverId: string): Promise<Workspace> {
+export async function requireWorkspaceForServer(serverId: string): Promise<Workspace> {
const found = await listWorkspacesForServer(serverId);
if (found.length === 1) return found[0]!;
if (found.length === 0) throw new Error(`Switch server ${serverId} has no workspace`);
+
+ const activeId = await getActiveWorkspaceId();
+ const active = found.find((workspace) => workspace.id === activeId);
+ if (active) return active;
throw new Error(
- `Switch server ${serverId} has ${found.length} workspaces; the caller must name one`
+ `Switch server ${serverId} has ${found.length} workspaces and none of them is the active one; the caller must name one`
);
}
@@ -163,6 +168,22 @@ export async function setWorkspaceTenant(
.where(eq(workspaces.id, workspaceId));
}
+/**
+ * Record that the account is no longer a member of a workspace it still holds a
+ * row for.
+ *
+ * The tenant id stays, because it is what the row's agents were registered
+ * against and what a restored membership would match it back to; only the role
+ * goes, since the gateway no longer reports one. A row naming a tenant with no
+ * role is what the switcher reads as withdrawn.
+ */
+export async function clearWorkspaceRole(workspaceId: string): Promise<void> {
+ await db
+ .update(workspaces)
+ .set({ role: null, updatedAt: sql`CURRENT_TIMESTAMP` })
+ .where(eq(workspaces.id, workspaceId));
+}
+
/**
* Whether any agent still belongs to a workspace.
*
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 f64a11142..ee6c0ebdf 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
@@ -16,7 +16,7 @@ import { useDebounce } from '@renderer/lib/hooks/useDebounce';
import { getEffectiveHotkey } from '@renderer/lib/hooks/useKeyboardShortcuts';
import { rpc } from '@renderer/lib/ipc';
import { useNavigate } from '@renderer/lib/layout/navigation-provider';
-import { scopeToLocationServer } from '@renderer/lib/layout/scope-to-server';
+import { scopeToLocationWorkspace } from '@renderer/lib/layout/scope-to-workspace';
import { type BaseModalProps } from '@renderer/lib/modal/modal-provider';
import { appState, sidebarStore } from '@renderer/lib/stores/app-state';
import { report } from '@renderer/lib/telemetry/report';
@@ -325,7 +325,7 @@ export function CommandPaletteModal({
if (!item.locationId) return;
const locationId = item.locationId;
handleClose();
- void scopeToLocationServer(locationId).then(() =>
+ void scopeToLocationWorkspace(locationId).then(() =>
navigate('session', { locationId, sessionId: item.id })
);
};
@@ -342,7 +342,7 @@ export function CommandPaletteModal({
if (!item.locationId) return;
const locationId = item.locationId;
handleClose();
- void scopeToLocationServer(locationId).then(() => {
+ void scopeToLocationWorkspace(locationId).then(() => {
sidebarStore.ensureGroupExpanded(agentExpandKey(item.id));
navigate('location', { locationId, agentName: item.title });
});
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 87d968d42..4ca49f85f 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
@@ -138,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 = useWorkspaceAgents(workspacesStore.soleIdOnServer(pickState.serverId));
+ const remoteAgents = useWorkspaceAgents(workspacesStore.idOnServerInScope(pickState.serverId));
const takenNames = useMemo(
() => new Set((remoteAgents.data ?? []).map((a) => a.name)),
[remoteAgents.data]
@@ -604,7 +604,7 @@ export const AddAgentModal = observer(function AddAgentModal({
{canConfigureAgent && (
<AgentSettingsSection
form={form}
- workspaceId={workspacesStore.soleIdOnServer(pickState.serverId)}
+ workspaceId={workspacesStore.idOnServerInScope(pickState.serverId)}
onAddServer={() => showAddServerModal({})}
onOpenMessagingApps={() => {
onClose();
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/stores/agents-store.test.ts b/console/apps/switch-console-desktop/src/renderer/features/locations/stores/agents-store.test.ts
index 1fb86772d..ea1004d6c 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/stores/agents-store.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/stores/agents-store.test.ts
@@ -4,70 +4,75 @@ import { agentsStore } from './agents-store';
vi.mock('@renderer/lib/ipc', () => ({ rpc: {} }));
-function agent(locationId: string, serverId: string | null, name: string): Agent {
- return { locationId, serverId, name } as Agent;
+function agent(locationId: string, workspaceId: string | null, name: string): Agent {
+ return { locationId, workspaceId, name } as Agent;
}
/**
* The premise these cover: a directory can hold agents registered against
- * several Switch servers at once, so "which server does this directory belong
+ * several workspaces at once, so "which workspace does this directory belong
* to" has no single answer and must not be asked (CHOO-2044).
*/
-describe('AgentsStore server scoping', () => {
+describe('AgentsStore workspace scoping', () => {
afterEach(() => {
agentsStore.byLocation.clear();
- agentsStore.optimisticServerByLocation.clear();
+ agentsStore.optimisticWorkspaceByLocation.clear();
});
- it('returns only the agents belonging to the given server', () => {
+ it('returns only the agents belonging to the given workspace', () => {
agentsStore.byLocation.set('shared', [
- agent('shared', 'server-1', 'a'),
- agent('shared', 'server-2', 'b'),
+ agent('shared', 'ws-1', 'a'),
+ agent('shared', 'ws-2', 'b'),
agent('shared', null, 'unlinked'),
]);
- expect(agentsStore.agentsOnServerAtLocation('shared', 'server-1').map((a) => a.name)).toEqual([
+ expect(agentsStore.agentsInWorkspaceAtLocation('shared', 'ws-1').map((a) => a.name)).toEqual([
'a',
]);
- expect(agentsStore.agentsOnServerAtLocation('shared', 'server-2').map((a) => a.name)).toEqual([
+ expect(agentsStore.agentsInWorkspaceAtLocation('shared', 'ws-2').map((a) => a.name)).toEqual([
'b',
]);
- expect(agentsStore.agentsOnServerAtLocation('shared', 'server-3')).toEqual([]);
+ expect(agentsStore.agentsInWorkspaceAtLocation('shared', 'ws-3')).toEqual([]);
});
- it('reports a shared directory as present on every server it has agents on', () => {
+ /**
+ * Two workspaces on the same server are still two scopes: the sidebar shows
+ * one of them at a time, so a directory present in both must answer for each
+ * separately rather than for the server they share.
+ */
+ it('separates two workspaces that live on the same server', () => {
agentsStore.byLocation.set('shared', [
- agent('shared', 'server-1', 'a'),
- agent('shared', 'server-2', 'b'),
+ agent('shared', 'ws-1', 'a'),
+ agent('shared', 'ws-2', 'b'),
]);
- expect(agentsStore.locationHasAgentsOnServer('shared', 'server-1')).toBe(true);
- expect(agentsStore.locationHasAgentsOnServer('shared', 'server-2')).toBe(true);
- expect(agentsStore.locationHasAgentsOnServer('shared', 'server-3')).toBe(false);
- expect(agentsStore.serverIdsForLocation('shared').sort()).toEqual(['server-1', 'server-2']);
+ expect(agentsStore.locationHasAgentsInWorkspace('shared', 'ws-1')).toBe(true);
+ expect(agentsStore.locationHasAgentsInWorkspace('shared', 'ws-2')).toBe(true);
+ expect(agentsStore.locationHasAgentsInWorkspace('shared', 'ws-3')).toBe(false);
+ expect(agentsStore.workspaceIdsForLocation('shared').sort()).toEqual(['ws-1', 'ws-2']);
});
it('keeps a just-created location in scope before its agent row lands', () => {
- agentsStore.noteLocationServer('fresh', 'server-1');
+ agentsStore.noteLocationWorkspace('fresh', 'ws-1');
- expect(agentsStore.locationHasAgentsOnServer('fresh', 'server-1')).toBe(true);
- expect(agentsStore.locationHasAgentsOnServer('fresh', 'server-2')).toBe(false);
- expect(agentsStore.serverIdsForLocation('fresh')).toEqual(['server-1']);
+ expect(agentsStore.locationHasAgentsInWorkspace('fresh', 'ws-1')).toBe(true);
+ expect(agentsStore.locationHasAgentsInWorkspace('fresh', 'ws-2')).toBe(false);
+ expect(agentsStore.workspaceIdsForLocation('fresh')).toEqual(['ws-1']);
});
it('ignores the optimistic note once real agents exist', () => {
- agentsStore.noteLocationServer('shared', 'server-9');
- agentsStore.byLocation.set('shared', [agent('shared', 'server-1', 'a')]);
+ agentsStore.noteLocationWorkspace('shared', 'ws-9');
+ agentsStore.byLocation.set('shared', [agent('shared', 'ws-1', 'a')]);
- expect(agentsStore.serverIdsForLocation('shared')).toEqual(['server-1']);
- expect(agentsStore.locationHasAgentsOnServer('shared', 'server-9')).toBe(false);
+ expect(agentsStore.workspaceIdsForLocation('shared')).toEqual(['ws-1']);
+ expect(agentsStore.locationHasAgentsInWorkspace('shared', 'ws-9')).toBe(false);
});
- it('treats a location with only unlinked agents as on no server', () => {
+ it('treats a location with only unlinked agents as in no workspace', () => {
agentsStore.byLocation.set('orphan', [agent('orphan', null, 'a')]);
- expect(agentsStore.serverIdsForLocation('orphan')).toEqual([]);
- expect(agentsStore.locationHasAgentsOnServer('orphan', 'server-1')).toBe(false);
+ expect(agentsStore.workspaceIdsForLocation('orphan')).toEqual([]);
+ expect(agentsStore.locationHasAgentsInWorkspace('orphan', 'ws-1')).toBe(false);
});
});
@@ -82,13 +87,13 @@ describe('AgentsStore server scoping', () => {
describe('resolving the agent a location route is about', () => {
afterEach(() => {
agentsStore.byLocation.clear();
- agentsStore.optimisticServerByLocation.clear();
+ agentsStore.optimisticWorkspaceByLocation.clear();
});
it('picks the named agent out of a shared directory', () => {
agentsStore.byLocation.set('dir', [
- agent('dir', 'server-1', 'charlie'),
- agent('dir', 'server-1', 'delta'),
+ agent('dir', 'ws-1', 'charlie'),
+ agent('dir', 'ws-1', 'delta'),
]);
expect(agentsStore.agentAtLocation('dir', 'charlie')?.name).toBe('charlie');
@@ -97,22 +102,22 @@ describe('resolving the agent a location route is about', () => {
it('resolves an unnamed route when the directory holds exactly one agent', () => {
// Nothing to choose between, so there is nothing to get wrong.
- agentsStore.byLocation.set('dir', [agent('dir', 'server-1', 'charlie')]);
+ agentsStore.byLocation.set('dir', [agent('dir', 'ws-1', 'charlie')]);
expect(agentsStore.agentAtLocation('dir', undefined)?.name).toBe('charlie');
});
it('refuses to guess between several agents', () => {
agentsStore.byLocation.set('dir', [
- agent('dir', 'server-1', 'charlie'),
- agent('dir', 'server-1', 'delta'),
+ agent('dir', 'ws-1', 'charlie'),
+ agent('dir', 'ws-1', 'delta'),
]);
expect(agentsStore.agentAtLocation('dir', undefined)).toBeNull();
});
it('is null for a name that is not there, rather than the first agent', () => {
- agentsStore.byLocation.set('dir', [agent('dir', 'server-1', 'charlie')]);
+ agentsStore.byLocation.set('dir', [agent('dir', 'ws-1', 'charlie')]);
expect(agentsStore.agentAtLocation('dir', 'nobody')).toBeNull();
});
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 8771222b6..3d446c8f7 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
@@ -4,26 +4,27 @@ import type { Agent } from '@shared/core/agents/agents';
/**
* Renderer cache of every agent across all locations. The sidebar scopes its tree
- * to the active server (see {@link switchServersStore.activeServerId}), so it needs
- * a reactive lookup that does not depend on each row's own react-query.
+ * to the active workspace (see {@link workspacesStore.activeId}), so it needs a
+ * reactive lookup that does not depend on each row's own react-query.
*
- * **A server belongs to an agent, not to a directory.** A directory is a place on
- * disk and can hold agents registered against several servers at once, so there is
- * no such thing as "the location's server" to scope on — asking for one drags every
- * agent in the directory under whichever answer came back first (CHOO-2044). Scope
- * on {@link agentsOnServerAtLocation}; a location is in scope when it has any.
+ * **A workspace belongs to an agent, not to a directory.** A directory is a place
+ * on disk and can hold agents registered in several workspaces at once, so there
+ * is no such thing as "the location's workspace" to scope on — asking for one
+ * drags every agent in the directory under whichever answer came back first
+ * (CHOO-2044). Scope on {@link agentsInWorkspaceAtLocation}; a location is in
+ * scope when it has any.
*/
export class AgentsStore {
/** All agents grouped by their location id. */
readonly byLocation = new Map<string, Agent[]>();
/**
- * Server id a just-created location's agent will belong to, recorded by the
+ * Workspace id a just-created location's agent will belong to, recorded by the
* add-agent modal before {@link load} has re-fetched the new agent. Used as a
- * fallback in {@link locationHasAgentsOnServer} so a freshly-created location does
- * not flicker out of the sidebar's server-scoped view during the gap between the
- * location mounting and the agent list refreshing.
+ * fallback in {@link locationHasAgentsInWorkspace} so a freshly-created location
+ * does not flicker out of the sidebar's workspace-scoped view during the gap
+ * between the location mounting and the agent list refreshing.
*/
- readonly optimisticServerByLocation = new Map<string, string>();
+ readonly optimisticWorkspaceByLocation = new Map<string, string>();
loaded = false;
constructor() {
@@ -41,16 +42,16 @@ export class AgentsStore {
}
// Drop optimistic notes now superseded by a real agent record.
for (const locationId of this.byLocation.keys()) {
- this.optimisticServerByLocation.delete(locationId);
+ this.optimisticWorkspaceByLocation.delete(locationId);
}
this.loaded = true;
});
}
- /** Record the server a location's agent will bind to, ahead of {@link load}. */
- noteLocationServer(locationId: string, serverId: string): void {
+ /** Record the workspace a location's agent will bind to, ahead of {@link load}. */
+ noteLocationWorkspace(locationId: string, workspaceId: string): void {
runInAction(() => {
- this.optimisticServerByLocation.set(locationId, serverId);
+ this.optimisticWorkspaceByLocation.set(locationId, workspaceId);
});
}
@@ -116,35 +117,41 @@ export class AgentsStore {
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. */
- agentsOnServerAtLocation(locationId: string, serverId: string): Agent[] {
- return (this.byLocation.get(locationId) ?? []).filter((a) => a.serverId === serverId);
+ /**
+ * A location's agents that belong to one workspace — what the sidebar renders
+ * under that workspace. Agents in the same directory registered elsewhere are
+ * not this workspace's to show.
+ *
+ * Unlike {@link agentsInWorkspace} this keeps agents with no Switch identity:
+ * an agent still being registered has a workspace and a row in the tree, and
+ * dropping it would make it disappear from the sidebar mid-onboarding.
+ */
+ agentsInWorkspaceAtLocation(locationId: string, workspaceId: string): Agent[] {
+ return (this.byLocation.get(locationId) ?? []).filter((a) => a.workspaceId === workspaceId);
}
- /** Whether a location has anything to show under `serverId`. */
- locationHasAgentsOnServer(locationId: string, serverId: string): boolean {
- return this.serverIdsForLocation(locationId).includes(serverId);
+ /** Whether a location has anything to show under `workspaceId`. */
+ locationHasAgentsInWorkspace(locationId: string, workspaceId: string): boolean {
+ return this.workspaceIdsForLocation(locationId).includes(workspaceId);
}
/**
- * The servers a location's agents belong to. A directory can span several, so
- * this is a list rather than the one answer callers used to ask for.
+ * The workspaces a location's agents belong to. A directory can span several,
+ * so this is a list rather than the one answer callers used to ask for.
*
* The optimistic note stands in only while the location has no agent rows at
* all — that is the gap it exists to cover. Letting it also speak for a location
- * that already has agents would have it claim a server the location is not on.
+ * that already has agents would have it claim a workspace the location is not in.
*/
- serverIdsForLocation(locationId: string): string[] {
+ workspaceIdsForLocation(locationId: string): string[] {
const agents = this.byLocation.get(locationId);
if (!agents || agents.length === 0) {
- const optimistic = this.optimisticServerByLocation.get(locationId);
+ const optimistic = this.optimisticWorkspaceByLocation.get(locationId);
return optimistic ? [optimistic] : [];
}
const ids = new Set<string>();
for (const agent of agents) {
- if (agent.serverId !== null) ids.add(agent.serverId);
+ if (agent.workspaceId !== null) ids.add(agent.workspaceId);
}
return [...ids];
}
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 627fed353..b731af82f 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
@@ -117,7 +117,7 @@ export const RemoteHostMainPanel = observer(function RemoteHostMainPanel() {
// 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 workspaceId = workspacesStore.idOnServerInScope(serverId);
const status = deriveHostStatus(reachability, plan.data ?? null);
const { prerequisites, agentTypes } = useMemo(
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 bb60498a3..59eedad2c 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
@@ -239,10 +239,9 @@ const CapturePanel = observer(function CapturePanel() {
let cancelled = false;
void (async () => {
try {
- const yaml = await rpc.workspaces.exportRoomYaml({
- workspaceId: workspacesStore.requireSoleIdOnServer(serverId),
- roomId,
- });
+ const workspaceId = workspacesStore.idOnServerInScope(serverId);
+ if (workspaceId === null) throw new Error('This server’s workspace is not known yet.');
+ const yaml = await rpc.workspaces.exportRoomYaml({ workspaceId, 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 5a11a022f..4adc99d46 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
@@ -289,8 +289,10 @@ 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 workspaceId = workspacesStore.idOnServerInScope(serverId);
+ if (workspaceId === null) throw new Error('This server’s workspace is not known yet.');
const saved = await rpc.workspaces.updateTemplate({
- workspaceId: workspacesStore.requireSoleIdOnServer(serverId),
+ workspaceId,
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/sidebar/sidebar-icon-backfill-toast.test.ts b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-icon-backfill-toast.test.ts
index dbf393f81..d21018db3 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
@@ -33,7 +33,7 @@ vi.mock('@renderer/features/locations/stores/agents-store', () => ({
agentsStore: {
load: vi.fn().mockResolvedValue(undefined),
byLocation: new Map([[LOCATION.id, [AGENT]]]),
- agentsOnServerAtLocation: () => [AGENT],
+ agentsInWorkspaceAtLocation: () => [AGENT],
},
}));
vi.mock('@renderer/features/switch-servers/switch-rooms-store', () => ({
@@ -42,8 +42,8 @@ vi.mock('@renderer/features/switch-servers/switch-rooms-store', () => ({
loadRoomNames: vi.fn().mockResolvedValue(undefined),
},
}));
-vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({
- switchServersStore: { activeServerId: 'server-1' },
+vi.mock('@renderer/features/workspaces/workspaces-store', () => ({
+ workspacesStore: { activeId: 'workspace-1' },
}));
vi.mock('@renderer/lib/stores/app-state', () => ({
sidebarStore: {
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-store.test.ts b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-store.test.ts
index 1d1d1eef9..2bcfdb4e8 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-store.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-store.test.ts
@@ -1,8 +1,9 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { agentsStore } from '@renderer/features/locations/stores/agents-store';
-import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import type { AgentConnectionKind } from '@shared/core/agents/agent-connection';
import type { Agent } from '@shared/core/agents/agents';
+import type { Workspace } from '@shared/core/workspaces/workspaces';
import {
agentExpandKey,
agentRoomGroupKey,
@@ -14,6 +15,19 @@ import {
type SidebarLocationManager = ConstructorParameters<typeof SidebarStore>[0];
+/**
+ * Scope the window to a workspace, the way choosing one in the switcher does.
+ * Both workspaces here sit on the same server, which is the case the scope has
+ * to tell apart: scoping by server would show them as one tree.
+ */
+function scopeToWorkspace(workspaceId: string | null): void {
+ workspacesStore.workspaces = [
+ { id: 'ws-1', serverId: 'server-1' } as Workspace,
+ { id: 'ws-2', serverId: 'server-1' } as Workspace,
+ ];
+ workspacesStore.activeId = workspaceId;
+}
+
vi.mock('@renderer/lib/ipc', () => ({
events: {
on: vi.fn(),
@@ -267,87 +281,88 @@ describe('SidebarStore grouping', () => {
});
});
-describe('SidebarStore active-server scoping', () => {
- function linkAgent(locationId: string, serverId: string | null) {
- agentsStore.byLocation.set(locationId, [{ locationId, serverId } as Agent]);
+describe('SidebarStore active-workspace scoping', () => {
+ function linkAgent(locationId: string, workspaceId: string | null) {
+ agentsStore.byLocation.set(locationId, [{ locationId, workspaceId } as Agent]);
}
afterEach(() => {
- switchServersStore.activeServerId = null;
+ scopeToWorkspace(null);
agentsStore.byLocation.clear();
});
- it("shows only the active server's locations", () => {
+ it("shows only the active workspace's locations", () => {
const store = new SidebarStore(
locationManager([
{ id: 'a', createdAt: '2026-01-01T00:00:00.000Z' },
{ id: 'b', createdAt: '2026-01-02T00:00:00.000Z' },
])
);
- linkAgent('a', 'server-1');
- linkAgent('b', 'server-2');
- switchServersStore.activeServerId = 'server-1';
+ linkAgent('a', 'ws-1');
+ linkAgent('b', 'ws-2');
+ scopeToWorkspace('ws-1');
expect(store.orderedLocations.map((p) => p.id)).toEqual(['a']);
expect(store.isEmpty).toBe(false);
});
- it('shows all locations when no server is active', () => {
+ it('shows all locations when no workspace is active', () => {
const store = new SidebarStore(
locationManager([
{ id: 'a', createdAt: '2026-01-01T00:00:00.000Z' },
{ id: 'b', createdAt: '2026-01-02T00:00:00.000Z' },
])
);
- linkAgent('a', 'server-1');
- linkAgent('b', 'server-2');
+ linkAgent('a', 'ws-1');
+ linkAgent('b', 'ws-2');
expect(store.orderedLocations.map((p) => p.id).sort()).toEqual(['a', 'b']);
});
- it('hides unlinked locations when a server is active', () => {
+ it('hides unlinked locations when a workspace is active', () => {
const store = new SidebarStore(
locationManager([{ id: 'a', createdAt: '2026-01-01T00:00:00.000Z' }])
);
linkAgent('a', null);
- switchServersStore.activeServerId = 'server-1';
+ scopeToWorkspace('ws-1');
expect(store.orderedLocations).toEqual([]);
expect(store.isEmpty).toBe(true);
});
- it('shows a directory shared between servers under both (CHOO-2044)', () => {
- // A directory is a place on disk, not one server's territory. Resolving it to
- // a single server filed it under whichever agent came back first, and the
- // other server's agents vanished from the tree.
+ it('shows a directory shared between workspaces under both (CHOO-2044)', () => {
+ // A directory is a place on disk, not one workspace's territory. Resolving it
+ // to a single one filed it under whichever agent came back first, and the
+ // other workspace's agents vanished from the tree. The two here share a
+ // server, so a server-scoped tree would not tell them apart at all.
const store = new SidebarStore(
locationManager([{ id: 'shared', createdAt: '2026-01-01T00:00:00.000Z' }])
);
agentsStore.byLocation.set('shared', [
- { locationId: 'shared', serverId: 'server-1' } as Agent,
- { locationId: 'shared', serverId: 'server-2' } as Agent,
+ { locationId: 'shared', workspaceId: 'ws-1' } as Agent,
+ { locationId: 'shared', workspaceId: 'ws-2' } as Agent,
]);
- switchServersStore.activeServerId = 'server-1';
+ scopeToWorkspace('ws-1');
expect(store.orderedLocations.map((p) => p.id)).toEqual(['shared']);
- switchServersStore.activeServerId = 'server-2';
+ scopeToWorkspace('ws-2');
expect(store.orderedLocations.map((p) => p.id)).toEqual(['shared']);
- switchServersStore.activeServerId = 'server-3';
+ scopeToWorkspace('ws-3');
expect(store.orderedLocations).toEqual([]);
});
- it('describes a shared directory by an agent on the active server (CHOO-2044)', () => {
+ it('describes a shared directory by an agent in the active workspace (CHOO-2044)', () => {
const store = new SidebarStore(
locationManager([{ id: 'shared', createdAt: '2026-01-01T00:00:00.000Z' }])
);
agentsStore.byLocation.set('shared', [
- { locationId: 'shared', serverId: 'server-1', providerId: 'claude' } as Agent,
- { locationId: 'shared', serverId: 'server-2', providerId: 'codex' } as Agent,
+ { locationId: 'shared', workspaceId: 'ws-1', providerId: 'claude' } as Agent,
+ { locationId: 'shared', workspaceId: 'ws-2', providerId: 'codex' } as Agent,
]);
- switchServersStore.activeServerId = 'server-2';
+ scopeToWorkspace('ws-2');
expect(store.locationProviderId('shared')).toBe('codex');
});
});
@@ -408,12 +423,12 @@ describe('SidebarStore filters', () => {
}
function linkAgent(locationId: string, fields: { providerId?: Agent['providerId'] }) {
- agentsStore.byLocation.set(locationId, [{ locationId, serverId: null, ...fields } as Agent]);
+ agentsStore.byLocation.set(locationId, [{ locationId, workspaceId: null, ...fields } as Agent]);
}
afterEach(() => {
agentsStore.byLocation.clear();
- switchServersStore.activeServerId = null;
+ scopeToWorkspace(null);
});
it('returns all locations unfiltered when no filter is active', () => {
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-store.ts b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-store.ts
index 8a5725397..5e2d0501a 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-store.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-store.ts
@@ -8,7 +8,7 @@ import {
unregisteredSessionData,
type SessionStore,
} from '@renderer/features/sessions/stores/session-store';
-import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import type { Snapshottable } from '@renderer/lib/stores/snapshottable';
import type { AgentConnectionKind } from '@shared/core/agents/agent-connection';
import {
@@ -237,27 +237,27 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {
}
/**
- * Whether a location has anything to show under the active server. The whole
- * sidebar tree is scoped to one server at a time: a location shows when it holds
- * at least one agent linked to {@link switchServersStore.activeServerId}.
- * Unregistered locations (mid-onboarding, no agent row yet) always show so the
- * user sees progress. When no server is active, nothing is hidden.
+ * Whether a location has anything to show under the active workspace. The whole
+ * sidebar tree is scoped to one workspace at a time: a location shows when it
+ * holds at least one agent in {@link workspacesStore.activeId}. Unregistered
+ * locations (mid-onboarding, no agent row yet) always show so the user sees
+ * progress. When no workspace is active, nothing is hidden.
*
- * A directory can hold agents for several servers, so this is "has any here",
+ * A directory can hold agents for several workspaces, so this is "has any here",
* not "belongs to". Which of its agents are then drawn is
* {@link scopedAgents}' business — a location being in scope does not put every
- * agent in it on this server's tree (CHOO-2044).
+ * agent in it on this workspace's tree (CHOO-2044).
*/
isLocationInActiveScope(locationId: string): boolean {
- const activeServerId = switchServersStore.activeServerId;
- if (!activeServerId) return true;
+ const activeWorkspaceId = workspacesStore.activeId;
+ if (!activeWorkspaceId) return true;
const location = this.locationManager.locations.get(locationId);
if (location && location.state === 'unregistered') return true;
- return agentsStore.locationHasAgentsOnServer(locationId, activeServerId);
+ return agentsStore.locationHasAgentsInWorkspace(locationId, activeWorkspaceId);
}
/**
- * Server-scoped locations, newest first. Locations are no longer a level of
+ * Workspace-scoped locations, newest first. Locations are no longer a level of
* the sidebar tree — the manual order the user drags lives on agents and
* rooms — so this is the plain default order the agent list is built from.
*/
@@ -271,12 +271,12 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {
/** The representative agent of a location (the agent shown on its sidebar row):
* the first real (non-definition) agent, not a former subagent's row. Restricted
- * to the active server, so a directory shared with another server does not
- * describe itself by an agent this tree is not showing. */
+ * to the active workspace, so a directory shared with another does not describe
+ * itself by an agent this tree is not showing. */
private parentAgent(locationId: string) {
- const activeServerId = switchServersStore.activeServerId;
- const agents = activeServerId
- ? agentsStore.agentsOnServerAtLocation(locationId, activeServerId)
+ const activeWorkspaceId = workspacesStore.activeId;
+ const agents = activeWorkspaceId
+ ? agentsStore.agentsInWorkspaceAtLocation(locationId, activeWorkspaceId)
: (agentsStore.byLocation.get(locationId) ?? []);
return agents[0] ?? (agentsStore.byLocation.get(locationId) ?? [])[0];
}
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 6bf725275..a5e875889 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
@@ -2,7 +2,7 @@ import { agentsStore } from '@renderer/features/locations/stores/agents-store';
import type { LocationStore } from '@renderer/features/locations/stores/location';
import type { SessionStore } from '@renderer/features/sessions/stores/session-store';
import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
-import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { toast } from '@renderer/lib/hooks/use-toast';
import { rpc } from '@renderer/lib/ipc';
import { sidebarStore } from '@renderer/lib/stores/app-state';
@@ -20,22 +20,26 @@ import type { AgentIconBackfill } from '@shared/core/switch-servers/switch-serve
export type AgentEntry = { agent: Agent; location: LocationStore };
/**
- * A location's agents that the active server's tree should draw.
+ * A location's agents that the active workspace's tree should draw.
*
- * A location is in scope when *some* of its agents are on the active server, but a
- * directory can hold agents for several servers at once — so scope has to be
+ * A location is in scope when *some* of its agents are in the active workspace,
+ * but a directory can hold agents for several at once — so scope has to be
* re-applied per agent here. Taking the location's whole list instead drew agents
- * belonging to another server under this one, which read as "onboarding brought
+ * belonging to another workspace under this one, which read as "onboarding brought
* them across" when nothing had been onboarded at all (CHOO-2044).
+ *
+ * The workspace and not its server: two workspaces on one server are two separate
+ * trees, and scoping on the server would draw both of them under whichever name
+ * the sidebar is showing.
*/
function agentsAtLocationInScope(location: LocationStore): Agent[] {
- const activeServerId = switchServersStore.activeServerId;
- if (!activeServerId) return agentsStore.byLocation.get(location.id) ?? [];
- return agentsStore.agentsOnServerAtLocation(location.id, activeServerId);
+ const activeWorkspaceId = workspacesStore.activeId;
+ if (!activeWorkspaceId) return agentsStore.byLocation.get(location.id) ?? [];
+ return agentsStore.agentsInWorkspaceAtLocation(location.id, activeWorkspaceId);
}
/**
- * The flat list of agents in the active-server scope. Switch Console shows agents
+ * The flat list of agents in the active-workspace scope. Switch Console shows agents
* as a flat list — not grouped by directory (CHOO-1440).
*
* Newest first, then overlaid with the user's manual drag order: an agent they
@@ -57,7 +61,7 @@ export function scopedAgents(): AgentEntry[] {
}
/**
- * Every agent on the active server, ignoring the agent filters.
+ * Every agent in the active workspace, ignoring the agent filters.
*
* Room membership is a fact about a room, so the agents a room lists — and the
* agents whose membership is fetched at all — must not depend on which filters
@@ -151,7 +155,7 @@ export async function refreshSidebarRoomStateAfterOnboarding(): Promise<void> {
/**
* Fill in the avatar of any of this user's agents registered before icons
- * existed (CHOO-2171). The main process does it once per server per run, so
+ * existed (CHOO-2171). The main process does it once per workspace per run, so
* calling it on every refresh costs nothing after the first.
*
* Not awaited by the caller and never allowed to throw: the sidebar must paint
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/open-room.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/open-room.ts
index 05981eb11..7c59190c3 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/open-room.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/open-room.ts
@@ -1,4 +1,4 @@
-import { scopeToRoomServer } from '@renderer/lib/layout/scope-to-server';
+import { scopeToRoomWorkspace } from '@renderer/lib/layout/scope-to-workspace';
import { appState, sidebarStore } from '@renderer/lib/stores/app-state';
/**
@@ -12,7 +12,7 @@ import { appState, sidebarStore } from '@renderer/lib/stores/app-state';
* findable in the tree it belongs to.
*/
export async function openRoom(roomId: string): Promise<void> {
- await scopeToRoomServer(roomId);
+ await scopeToRoomWorkspace(roomId);
sidebarStore.setGrouping('room');
sidebarStore.ensureRoomExpanded(roomId);
appState.navigation.navigate('room', { roomId });
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/session-deeplink-listener.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/session-deeplink-listener.tsx
index d699ea9c9..211cc0891 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/session-deeplink-listener.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/session-deeplink-listener.tsx
@@ -4,7 +4,7 @@ import { agentsStore } from '@renderer/features/locations/stores/agents-store';
import { getLocationManagerStore } from '@renderer/features/locations/stores/location-selectors';
import { getSessionManagerStore } from '@renderer/features/sessions/stores/session-selectors';
import { events } from '@renderer/lib/ipc';
-import { scopeToLocationServer } from '@renderer/lib/layout/scope-to-server';
+import { scopeToLocationWorkspace } from '@renderer/lib/layout/scope-to-workspace';
import { appState } from '@renderer/lib/stores/app-state';
import { report } from '@renderer/lib/telemetry/report';
import { sessionDeeplinkChannel } from '@shared/core/switch-rooms/switchRoomEvents';
@@ -95,7 +95,7 @@ export function SessionDeeplinkListener(): null {
// is filtered out of the server-scoped tree and there is no row to
// reveal. Navigating is all the sidebar needs — it expands and scrolls
// to whatever the open view selects, from any origin.
- await scopeToLocationServer(match.locationId);
+ await scopeToLocationWorkspace(match.locationId);
appState.navigation.navigate('session', match);
})();
}
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 0728fdcf3..f76278d93 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
@@ -56,7 +56,7 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppMod
const { setCloseGuard } = useModalContext();
const serverId = overrideServerId ?? switchServersStore.activeServerId ?? '';
- const workspaceId = workspacesStore.soleIdOnServer(serverId || null);
+ const workspaceId = workspacesStore.idOnServerInScope(serverId || null);
const server = switchServersStore.servers.find((s) => s.id === serverId) ?? null;
const isAdmin = switchServersStore.statusFor(serverId)?.user?.role === 'admin';
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 cbf5dc9e9..c16adda19 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
@@ -50,7 +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 workspaceId = workspacesStore.idOnServerInScope(serverId || null);
const server = switchServersStore.servers.find((s) => s.id === serverId) ?? null;
const [name, setName] = useState('');
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 798eae8aa..8bf8f73fe 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
@@ -91,7 +91,7 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({
const showConnectMessagingApp = useShowModal('connectMessagingAppModal');
const showClaimIdentity = useShowModal('claimIdentityModal');
const showDisconnectMessagingApp = useShowModal('disconnectMessagingAppModal');
- const workspaceId = workspacesStore.soleIdOnServer(serverId);
+ const workspaceId = workspacesStore.idOnServerInScope(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.
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 4405821ce..e28b9d554 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
@@ -51,7 +51,7 @@ export const AgentServerPicker = observer(function AgentServerPicker({
const servers = switchServersStore.servers;
- const workspaceId = workspacesStore.soleIdOnServer(serverId);
+ const workspaceId = workspacesStore.idOnServerInScope(serverId);
const verifyQuery = useQuery({
queryKey: ['verifyAgent', workspaceId, switchAgentId],
queryFn: () =>
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 37cfeff94..03844e40b 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
@@ -44,7 +44,7 @@ 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 workspaceId = workspacesStore.idOnServerInScope(serverId);
const bridgesQuery = useQuery({
queryKey: ['remote-bridges', workspaceId],
queryFn: () => rpc.workspaces.listBridges(workspaceId as string),
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 4b7676344..0dda4c543 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
@@ -44,7 +44,7 @@ const ServerRoomsPanel = observer(function ServerRoomsPanel() {
void refreshSidebarRoomState(false);
}, [serverId]);
- const workspaceId = workspacesStore.soleIdOnServer(serverId);
+ const workspaceId = workspacesStore.idOnServerInScope(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);
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 013426d19..1f1c299f8 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
@@ -19,7 +19,7 @@ export const ServerStatTiles = observer(function ServerStatTiles({
}: {
serverId: string;
}) {
- const workspaceId = workspacesStore.soleIdOnServer(serverId);
+ const workspaceId = workspacesStore.idOnServerInScope(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.
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 a1de9818b..80995b7de 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
@@ -181,7 +181,7 @@ export class SwitchRoomsStore {
* 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
+ * `scopeToRoomWorkspace`), so the sidebar follows you there rather than
* filtering the room back out.
*/
get listedRoomsInAllWorkspaces(): RemoteRoomSummary[] {
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 36bafb7fc..f7d5521de 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
@@ -4,8 +4,9 @@ import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';
const getAuthConfig = vi.hoisted(() => vi.fn());
const getConnectionStatus = vi.hoisted(() => vi.fn());
const listServers = vi.hoisted(() => vi.fn());
-const getActiveServerId = vi.hoisted(() => vi.fn());
const setActiveServer = vi.hoisted(() => vi.fn());
+/** The workspace selection as the main process holds it, by the server it is on. */
+const selection = vi.hoisted(() => ({ serverId: null as string | null }));
const removeServer = vi.hoisted(() => vi.fn());
const addServer = vi.hoisted(() => vi.fn());
/** SSH hosts the reachability manager currently considers down. */
@@ -18,15 +19,40 @@ vi.mock('@renderer/lib/ipc', () => ({
getAuthConfig,
getConnectionStatus,
listServers,
- getActiveServerId,
setActiveServer,
removeServer,
addServer,
},
},
}));
+/**
+ * Stands in for the workspace selection this store now reads its active server
+ * off, faithfully enough that the selection logic is still being tested rather
+ * than asserted against a constant.
+ *
+ * Each server gets one workspace, which is the state every install is in, so
+ * `listServers` and {@link selectServer} stay the knobs a test turns. A
+ * selection naming a server that is no longer listed resolves to no workspace —
+ * which is exactly what happens for real once the removed server takes its
+ * workspace row with it.
+ */
vi.mock('@renderer/features/workspaces/workspaces-store', () => ({
- workspacesStore: { refresh: vi.fn().mockResolvedValue(undefined) },
+ workspacesStore: {
+ workspaces: [] as { id: string; serverId: string }[],
+ activeId: null as string | null,
+ get active(): { id: string; serverId: string } | null {
+ return this.workspaces.find((w) => w.id === this.activeId) ?? null;
+ },
+ get activeServerId(): string | null {
+ return this.active?.serverId ?? null;
+ },
+ async refresh(): Promise<void> {
+ const servers: SwitchServer[] = await listServers();
+ const activeServerId = selection.serverId;
+ this.workspaces = servers.map((s) => ({ id: `ws-${s.id}`, serverId: s.id }));
+ this.activeId = activeServerId === null ? null : `ws-${activeServerId}`;
+ },
+ },
}));
vi.mock('@renderer/features/remote-hosts/host-reachability-store', () => ({
hostReachabilityStore: { isBlocked: (sshHost: string) => blockedHosts.has(sshHost) },
@@ -38,6 +64,11 @@ vi.mock('@renderer/lib/stores/app-state', () => ({
const { SwitchServersStore } = await import('./switch-servers-store');
+/** Scope the window to a server, the way choosing one of its workspaces does. */
+function selectServer(serverId: string | null): void {
+ selection.serverId = serverId;
+}
+
const authConfig = { passwordLoginEnabled: true, oidcEnabled: false, oidcProviderLabel: null };
function server(id: string, overrides: Partial<SwitchServer> = {}): SwitchServer {
@@ -94,6 +125,9 @@ beforeEach(() => {
user: null,
}));
getAuthConfig.mockResolvedValue(authConfig);
+ listServers.mockResolvedValue([]);
+ selectServer(null);
+ setActiveServer.mockImplementation(async (serverId: string) => selectServer(serverId));
});
describe('fetching sign-in options', () => {
@@ -199,7 +233,7 @@ describe('recovering when connectivity returns', () => {
getAuthConfig.mockRejectedValueOnce(new Error('offline'));
await store.ensureAuthConfig('srv-a');
listServers.mockResolvedValue([]);
- getActiveServerId.mockResolvedValue(null);
+ selectServer(null);
removeServer.mockResolvedValue(undefined);
await store.removeServer('srv-a');
@@ -214,7 +248,7 @@ describe('a page left on a server that is gone', () => {
it('is revalidated when the server is removed', async () => {
const store = newStore([server('srv-a')]);
listServers.mockResolvedValue([]);
- getActiveServerId.mockResolvedValue(null);
+ selectServer(null);
removeServer.mockResolvedValue(undefined);
await store.removeServer('srv-a');
@@ -227,7 +261,7 @@ describe('a page left on a server that is gone', () => {
expect(store.loaded).toBe(false);
listServers.mockResolvedValue([server('srv-a')]);
- getActiveServerId.mockResolvedValue('srv-a');
+ selectServer('srv-a');
await store.init();
expect(store.loaded).toBe(true);
@@ -446,14 +480,14 @@ describe('a server that cannot be reached', () => {
});
/**
- * A server is a workspace: the switcher, the sidebar and the sessions under it
- * all read the active one, so "servers exist but none is active" is a state the
- * UI cannot render. Nothing on the main side picks one, so the store must.
+ * The switcher, the sidebar and the sessions under it all read the active
+ * workspace, so "servers exist but none is active" is a state the UI cannot
+ * render. Nothing on the main side picks one, so the store must.
*/
describe('keeping a server active', () => {
it('selects the first server when nothing was active', async () => {
listServers.mockResolvedValue([server('srv-a'), server('srv-b')]);
- getActiveServerId.mockResolvedValue(null);
+ selectServer(null);
const store = new SwitchServersStore();
await store.init();
@@ -463,7 +497,7 @@ describe('keeping a server active', () => {
it('keeps the server the user last chose', async () => {
listServers.mockResolvedValue([server('srv-a'), server('srv-b')]);
- getActiveServerId.mockResolvedValue('srv-b');
+ selectServer('srv-b');
const store = new SwitchServersStore();
await store.init();
@@ -477,7 +511,7 @@ describe('keeping a server active', () => {
// workspace at all — no switcher, no destinations, no sidebar tree — while
// a perfectly good server sat in the list.
listServers.mockResolvedValue([server('srv-b')]);
- getActiveServerId.mockResolvedValue('srv-gone');
+ selectServer('srv-gone');
const store = new SwitchServersStore();
await store.init();
@@ -491,7 +525,7 @@ describe('keeping a server active', () => {
// the very first one left the app with no workspace to show — the sidebar
// stayed on "Add a server" until the next launch.
listServers.mockResolvedValue([]);
- getActiveServerId.mockResolvedValue(null);
+ selectServer(null);
const store = new SwitchServersStore();
await store.init();
@@ -506,7 +540,7 @@ describe('keeping a server active', () => {
it('does not move the workspace when a second server is added', async () => {
listServers.mockResolvedValue([server('srv-a')]);
- getActiveServerId.mockResolvedValue('srv-a');
+ selectServer('srv-a');
const store = new SwitchServersStore();
await store.init();
@@ -521,7 +555,7 @@ describe('keeping a server active', () => {
it('leaves nothing active when there are no servers at all', async () => {
listServers.mockResolvedValue([]);
- getActiveServerId.mockResolvedValue(null);
+ selectServer(null);
const store = new SwitchServersStore();
await store.init();
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 943b65a27..a8e41855e 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
@@ -22,7 +22,6 @@ import type {
*/
export class SwitchServersStore {
servers: SwitchServer[] = [];
- activeServerId: string | null = null;
/** Connection status per server id, refreshed on focus / select / manually. */
readonly statuses = new Map<string, ServerConnectionStatus>();
@@ -83,8 +82,24 @@ export class SwitchServersStore {
return hostReachabilityStore.isBlocked(server.sshHost);
}
+ /**
+ * The server the window is scoped to.
+ *
+ * Read off the active workspace rather than held here, so the two cannot
+ * disagree. What the user selects is a workspace; the server is whichever one
+ * hosts it, and the main process resolves it the same way.
+ */
+ get activeServerId(): string | null {
+ return workspacesStore.activeServerId;
+ }
+
get activeServer(): SwitchServer | null {
- return this.servers.find((s) => s.id === this.activeServerId) ?? null;
+ return this.serverById(this.activeServerId);
+ }
+
+ serverById(serverId: string | null): SwitchServer | null {
+ if (!serverId) return null;
+ return this.servers.find((s) => s.id === serverId) ?? null;
}
statusFor(serverId: string): ServerConnectionStatus | null {
@@ -138,14 +153,12 @@ export class SwitchServersStore {
this.errorDetail = null;
});
try {
- const [servers, activeServerId] = await Promise.all([
+ const [servers] = await Promise.all([
rpc.switchServers.listServers(),
- rpc.switchServers.getActiveServerId(),
workspacesStore.refresh(),
]);
runInAction(() => {
this.servers = servers;
- this.activeServerId = activeServerId;
this.loaded = true;
});
// A page restored onto a server that has since been deleted can only be
@@ -164,18 +177,22 @@ export class SwitchServersStore {
}
/**
- * A server is a workspace: the switcher, the sidebar and the sessions under
- * it all read the active one, so one must be selected whenever any server
- * exists. Nothing on the main side picks it — adding the first server leaves
- * the active id null — so every path that changes the list ends here.
+ * The switcher, the sidebar and the sessions under it all read the active
+ * workspace, so one must be selected whenever any exists. Nothing on the main
+ * side picks it — adding the first server leaves the selection empty — so
+ * every path that changes the list ends here.
*
- * A stored id that no longer names a server counts as no selection. It is not
- * hypothetical: removing the active server and adding another leaves the id
- * pointing at the removed one, and treating that as a selection left the app
- * with no workspace at all — no switcher, no sidebar tree, no way back.
+ * A stored selection that no longer names a workspace counts as none. It is
+ * not hypothetical: removing the active server and adding another leaves the
+ * id pointing at the removed one, and treating that as a selection left the
+ * app with no workspace at all — no switcher, no sidebar tree, no way back.
+ *
+ * Which one it lands on is expressed over servers rather than workspaces,
+ * because a server is what the user just added or removed, and its own
+ * workspaces are then the main process's to choose between.
*/
private async ensureActiveServer(): Promise<void> {
- if (this.activeServerId && this.servers.some((s) => s.id === this.activeServerId)) return;
+ if (workspacesStore.active) return;
const first = this.servers[0];
if (first) await this.setActive(first.id);
}
@@ -330,14 +347,12 @@ export class SwitchServersStore {
this.clearError();
try {
const created = await rpc.switchServers.addServer({ name, gatewayUrl, apiUrl });
- const [servers, activeServerId] = await Promise.all([
+ const [servers] = await Promise.all([
rpc.switchServers.listServers(),
- rpc.switchServers.getActiveServerId(),
workspacesStore.refresh(),
]);
runInAction(() => {
this.servers = servers;
- this.activeServerId = activeServerId;
});
await this.ensureActiveServer();
await this.refreshStatus(created.id);
@@ -416,14 +431,12 @@ export class SwitchServersStore {
this.clearError();
try {
await rpc.switchServers.removeServer(serverId);
- const [servers, activeServerId] = await Promise.all([
+ const [servers] = await Promise.all([
rpc.switchServers.listServers(),
- rpc.switchServers.getActiveServerId(),
workspacesStore.refresh(),
]);
runInAction(() => {
this.servers = servers;
- this.activeServerId = activeServerId;
this.statuses.delete(serverId);
this.authConfigs.delete(serverId);
this.authConfigWanted.delete(serverId);
@@ -440,14 +453,20 @@ export class SwitchServersStore {
}
}
+ /**
+ * Scope the window to a server, for the callers that know only one — adding
+ * a server, and following a navigation onto another server's room or agent.
+ *
+ * Which of its workspaces that lands on is the main process's to decide: it
+ * keeps the current selection if it is already on this server, and otherwise
+ * picks one. Picking here instead would make this store the second place that
+ * answers the same question.
+ */
async setActive(serverId: string): Promise<void> {
this.clearError();
try {
await rpc.switchServers.setActiveServer(serverId);
await workspacesStore.refresh();
- runInAction(() => {
- this.activeServerId = serverId;
- });
} catch (cause) {
this.setError(cause, 'Could not switch to that server.');
}
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 e527a613d..be2a5b807 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
@@ -122,7 +122,7 @@ const ServerMainPanel = observer(function ServerMainPanel() {
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);
+ const workspaceId = workspacesStore.idOnServerInScope(serverId);
try {
await Promise.all([
store.refreshServer(serverId),
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-switcher.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-switcher.tsx
index aaa72a706..adf6b5bb1 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-switcher.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-switcher.tsx
@@ -1,6 +1,8 @@
import { ChevronsUpDown, Plus } from 'lucide-react';
import { observer } from 'mobx-react-lite';
import { useEffect } from 'react';
+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
+import { useToast } from '@renderer/lib/hooks/use-toast';
import { useNavigate } from '@renderer/lib/layout/navigation-provider';
import { useShowModal } from '@renderer/lib/modal/modal-provider';
import { SwitchConsoleMark } from '@renderer/lib/switch-console-mark';
@@ -16,6 +18,11 @@ import {
import { Spinner } from '@renderer/lib/ui/spinner';
import { cn } from '@renderer/utils/utils';
import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';
+import {
+ type Workspace,
+ type WorkspaceUnavailability,
+ workspaceUnavailability,
+} from '@shared/core/workspaces/workspaces';
import { localServerStore } from './local-server-store';
import { remoteServerStore } from './remote-server-store';
import { serverIcon } from './server-icon';
@@ -30,15 +37,33 @@ import {
} from './server-presentation';
import { switchServersStore } from './switch-servers-store';
+/**
+ * How the button names where you are.
+ *
+ * A server registered before its workspaces are known names its only workspace
+ * after itself, and until the account has been asked the two names are the same
+ * — saying both would read as a stutter. Where they differ the server is the
+ * more important half of the answer, since the same workspace name can exist on
+ * two of them.
+ */
+function switcherSubtitle(workspace: Workspace, server: SwitchServer): string {
+ const status = serverSubtitleLabel(server);
+ return workspace.name === server.name ? status : `${server.name} · ${status}`;
+}
+
/**
* The workspace switcher at the top of the sidebar.
*
- * A server is a workspace: the sidebar, its sessions and everything under them
- * are scoped to whichever one is active, so exactly one is on screen at a time
- * and the rest live behind this control. Before it, all servers were listed
- * side by side and the scoping was left to be inferred from a highlighted row.
+ * The window is scoped to one workspace: the sidebar, its sessions and
+ * everything under them show that workspace's world and nothing else, so
+ * exactly one is on screen at a time and the rest live behind this control.
+ *
+ * Workspaces are listed under the server hosting them rather than in one flat
+ * list. A workspace only means anything on its server — two servers can each
+ * have a "Default" — and the server is also what carries reachability, so the
+ * group heading is where it is said once instead of on every row.
*
- * With no servers there is nothing to switch between, so it collapses to the
+ * With no workspace there is nothing to switch between, so it collapses to the
* one action that leads anywhere.
*/
export const WorkspaceSwitcher = observer(function WorkspaceSwitcher() {
@@ -59,9 +84,10 @@ export const WorkspaceSwitcher = observer(function WorkspaceSwitcher() {
};
}, [store]);
- const active = store.activeServer;
+ const active = workspacesStore.active;
+ const activeServer = active ? store.serverById(active.serverId) : null;
- if (!active) {
+ if (!active || !activeServer) {
return (
<div className="px-2">
<LocalServerPendingButton />
@@ -79,8 +105,8 @@ export const WorkspaceSwitcher = observer(function WorkspaceSwitcher() {
);
}
- const ActiveIcon = serverIcon(active);
- const drift = serverDrift(active);
+ const ActiveIcon = serverIcon(activeServer);
+ const drift = serverDrift(activeServer);
return (
<div className="px-2">
@@ -89,18 +115,18 @@ export const WorkspaceSwitcher = observer(function WorkspaceSwitcher() {
render={
<button
type="button"
- aria-label="Switch server"
+ aria-label="Switch workspace"
className="flex w-full items-center gap-[10px] rounded-lg px-2 py-1.5 text-left hover:bg-[var(--sel-soft)]"
>
- <ServerAvatar server={active} size="md" />
+ <ServerAvatar server={activeServer} size="md" />
<span className="min-w-0 flex-1">
<span className="block truncate text-sm font-medium text-foreground">
{active.name}
</span>
<span className="flex items-center gap-1.5 text-xs text-foreground-muted">
<ActiveIcon className="size-3 shrink-0" />
- <span className="truncate">{serverSubtitleLabel(active)}</span>
- <ServerStatusDot server={active} />
+ <span className="truncate">{switcherSubtitle(active, activeServer)}</span>
+ <ServerStatusDot server={activeServer} />
{drift && <ServerDriftIndicator drift={drift} />}
</span>
</span>
@@ -109,14 +135,9 @@ export const WorkspaceSwitcher = observer(function WorkspaceSwitcher() {
}
/>
<DropdownMenuContent align="start" className="min-w-72">
- <DropdownMenuGroup>
- <DropdownMenuLabel className="text-xs font-medium text-foreground-passive">
- Servers
- </DropdownMenuLabel>
- {store.servers.map((server) => (
- <ServerMenuItem key={server.id} server={server} />
- ))}
- </DropdownMenuGroup>
+ {store.servers.map((server) => (
+ <ServerWorkspaceGroup key={server.id} server={server} />
+ ))}
<DropdownMenuSeparator />
<DropdownMenuItem onClick={() => showAddServerModal({})}>
<Plus className="size-4" />
@@ -164,44 +185,130 @@ const LocalServerPendingButton = observer(function LocalServerPendingButton() {
);
});
-const ServerMenuItem = observer(function ServerMenuItem({ server }: { server: SwitchServer }) {
- const store = switchServersStore;
- const { navigate } = useNavigate();
+/** One server, as a heading over the workspaces the account has on it. */
+const ServerWorkspaceGroup = observer(function ServerWorkspaceGroup({
+ server,
+}: {
+ server: SwitchServer;
+}) {
const Icon = serverIcon(server);
const placement = serverPlacementLabel(server);
const drift = serverDrift(server);
- const isActive = store.activeServerId === server.id;
+ const workspaces = workspacesStore.onServer(server.id);
+
+ return (
+ <DropdownMenuGroup>
+ <DropdownMenuLabel className="flex items-center gap-2 py-1.5">
+ <ServerAvatar server={server} size="sm" />
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-xs font-medium text-foreground">{server.name}</span>
+ <span className="flex min-w-0 items-center gap-1.5 text-xs font-normal text-foreground-muted">
+ <Icon className="size-3 shrink-0" />
+ <span className="truncate">{serverStatusLabel(server)}</span>
+ {/* Beside the words it qualifies rather than at the row's right edge,
+ where it read as a property of the row instead of of the status. */}
+ <ServerStatusDot server={server} />
+ {placement && (
+ <span className="shrink-0 rounded bg-background-tertiary px-1 py-px text-[10px] font-medium tracking-wide text-foreground-muted uppercase">
+ {placement}
+ </span>
+ )}
+ </span>
+ </span>
+ {drift && <ServerDriftIndicator drift={drift} />}
+ </DropdownMenuLabel>
+ {workspaces.length === 0 ? (
+ // Registering a server is what creates its first workspace, so a server
+ // with none did not finish being registered. Saying so beats an empty
+ // heading, which reads as a rendering fault.
+ <div className="px-2 py-1.5 pl-9 text-xs text-foreground-muted">
+ No workspace yet — this server has not finished being set up.
+ </div>
+ ) : (
+ workspaces.map((workspace) => (
+ <WorkspaceMenuItem
+ key={workspace.id}
+ workspace={workspace}
+ server={server}
+ onServerCount={workspaces.length}
+ />
+ ))
+ )}
+ </DropdownMenuGroup>
+ );
+});
+
+const UNAVAILABLE_BADGE: Record<WorkspaceUnavailability, string> = {
+ withdrawn: 'No longer a member',
+ unmatched: 'Not matched',
+};
+
+/**
+ * What to do about a workspace that cannot be opened — said on the row rather
+ * than after the click, since the app already knows.
+ *
+ * The unmatched case deliberately does not say "sign in again": signing in
+ * re-runs the reconcile, which is what left the row unmatched, and would do so
+ * again. The row only survives because it holds agents, so the way out is the
+ * workspace beside it plus adding those agents there.
+ */
+const UNAVAILABLE_REASON: Record<WorkspaceUnavailability, (name: string) => string> = {
+ withdrawn: (name) =>
+ `This account is no longer a member of ${name}. Its agents are still here; ask an admin to add you back to open it.`,
+ unmatched: (name) =>
+ `${name} was never matched to a workspace on this server, so there is no way to tell which one to ask for. Open one of the others; the agents left here have to be added again in the workspace they belong to.`,
+};
+
+const WorkspaceMenuItem = observer(function WorkspaceMenuItem({
+ workspace,
+ server,
+ onServerCount,
+}: {
+ workspace: Workspace;
+ server: SwitchServer;
+ onServerCount: number;
+}) {
+ const { navigate } = useNavigate();
+ const { toast } = useToast();
+ const isActive = workspacesStore.activeId === workspace.id;
+ // Kept in the list rather than hidden: its agents are still here and the row
+ // is the only thing that says where they went. Disabled, because the gateway
+ // refuses every call scoped to it — offering it would turn a fact the app
+ // already knows into an error after the click.
+ const unavailable = workspaceUnavailability(workspace, onServerCount);
return (
<DropdownMenuItem
- // The active server is shown by filling its row rather than by a tick in
- // the right margin, so the row you are on reads at a glance instead of
+ // The active workspace is shown by filling its row rather than by a tick
+ // in the right margin, so the row you are on reads at a glance instead of
// needing the eye to travel to the end of it. `aria-current` carries the
// same fact for anything that cannot see the fill.
aria-current={isActive ? 'true' : undefined}
- className={cn(isActive && 'bg-[var(--sel)]')}
+ className={cn('pl-9', isActive && 'bg-[var(--sel)]')}
+ disabled={unavailable !== null}
+ title={unavailable ? UNAVAILABLE_REASON[unavailable](workspace.name) : undefined}
onClick={() => {
- void store.setActive(server.id);
- navigate('server', { serverId: server.id });
+ void workspacesStore
+ .setActive(workspace.id)
+ .then(() => navigate('server', { serverId: server.id }))
+ .catch(() => {
+ // Said out loud rather than swallowed: the sidebar would otherwise
+ // keep showing the workspace you left, under the name of the one
+ // you picked.
+ toast({
+ title: 'Could not switch workspace',
+ description: `${workspace.name} is still there; the app stayed where it was.`,
+ variant: 'destructive',
+ });
+ });
}}
>
- <ServerAvatar server={server} size="md" />
- <span className="min-w-0 flex-1">
- <span className="block truncate text-sm font-medium text-foreground">{server.name}</span>
- <span className="flex min-w-0 items-center gap-1.5 text-xs text-foreground-muted">
- <Icon className="size-3 shrink-0" />
- <span className="truncate">{serverStatusLabel(server)}</span>
- {/* Beside the words it qualifies rather than at the row's right edge,
- where it read as a property of the row instead of of the status. */}
- <ServerStatusDot server={server} />
- {placement && (
- <span className="shrink-0 rounded bg-background-tertiary px-1 py-px text-[10px] font-medium tracking-wide text-foreground-muted uppercase">
- {placement}
- </span>
- )}
+ <span className="min-w-0 flex-1 truncate text-sm text-foreground">{workspace.name}</span>
+ {(unavailable || workspace.role) && (
+ <span className="shrink-0 rounded bg-background-tertiary px-1 py-px text-[10px] font-medium tracking-wide text-foreground-muted uppercase">
+ {unavailable ? UNAVAILABLE_BADGE[unavailable] : workspace.role}
</span>
- </span>
- {drift && <ServerDriftIndicator drift={drift} />}
+ )}
</DropdownMenuItem>
);
});
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 d7d40cf3e..67af9d2e8 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
@@ -74,16 +74,34 @@ export async function loadAgentTemplateByOrigin(
if (!bundled) throw new Error(`This Console no longer bundles "${origin.name}".`);
return agentTemplateFromContent(origin.name, bundled.yamlText, bundled.instructions, origin);
}
- if (!origin.serverId)
- throw new Error(`"${origin.name}" came from a server this Console does not know.`);
- const workspaceId = workspacesStore.requireSoleIdOnServer(origin.serverId);
const detail = await rpc.workspaces.getTemplateDetail({
- workspaceId,
+ workspaceId: templateWorkspaceId(origin),
templateId: origin.id,
});
return agentTemplateFromContent(origin.name, detail.definition, null, origin);
}
+/**
+ * The workspace to ask for a server template, from what the origin recorded.
+ *
+ * A registry belongs to a workspace, so an origin naming only a server is
+ * answerable exactly while that server holds one. Where it holds several the
+ * window's own workspace is not an answer: it would load a different template
+ * of the same id, or none, and offer it as this agent's.
+ */
+function templateWorkspaceId(origin: AgentTemplateOrigin): string {
+ if (origin.workspaceId) return origin.workspaceId;
+ if (!origin.serverId)
+ throw new Error(`"${origin.name}" came from a server this Console does not know.`);
+ const onServer = workspacesStore.onServer(origin.serverId);
+ if (onServer.length === 1) return onServer[0]!.id;
+ if (onServer.length === 0)
+ throw new Error(`The workspace "${origin.name}" came from is not known yet.`);
+ throw new Error(
+ `"${origin.name}" was recorded before this Console kept which workspace a template came from, and its Switch server now has ${onServer.length}. Open it from that workspace's template list instead.`
+ );
+}
+
/** Resolve a listing entry (bundled or from the server's registry) into the agent it describes. */
export async function loadAgentTemplate(
workspaceId: string,
@@ -103,6 +121,7 @@ export async function loadAgentTemplate(
id: detail.id,
name: detail.name,
source: 'server',
+ workspaceId,
...(serverId ? { serverId } : {}),
});
}
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 903c859c4..285d7646a 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
@@ -54,12 +54,18 @@ export function SaveTemplateModal({
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
+ const workspaceId = workspacesStore.idOnServerInScope(serverId);
+
const save = async () => {
+ if (workspaceId === null) {
+ setError('This server’s workspace is not known yet.');
+ return;
+ }
setSaving(true);
setError(null);
try {
const saved = await rpc.workspaces.saveTemplate({
- workspaceId: workspacesStore.requireSoleIdOnServer(serverId),
+ workspaceId,
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 acedeb907..9df654e55 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
@@ -156,7 +156,7 @@ const KIND_LABEL: Record<LoadedTemplate['kind'], string> = {
const TemplateDetailPanel = observer(function TemplateDetailPanel() {
const { serverId, templateId } = useViewParams();
- const workspaceId = workspacesStore.soleIdOnServer(serverId);
+ const workspaceId = workspacesStore.idOnServerInScope(serverId);
const { navigate } = useNavigate();
const server = switchServersStore.servers.find((s) => s.id === serverId);
const me = switchServersStore.statusFor(serverId)?.user ?? null;
@@ -242,11 +242,11 @@ const TemplateDetailPanel = observer(function TemplateDetailPanel() {
const use = () => navigate('templateUse', { serverId, templateId });
const saveToServer = async () => {
- if (!loaded.bundled) return;
+ if (!loaded.bundled || workspaceId === null) return;
setBusy('save');
try {
const saved = await rpc.workspaces.saveTemplate({
- workspaceId: workspacesStore.requireSoleIdOnServer(serverId),
+ workspaceId,
name: loaded.bundled.name,
description: loaded.bundled.description,
kind: loaded.bundled.kind,
@@ -266,13 +266,10 @@ const TemplateDetailPanel = observer(function TemplateDetailPanel() {
};
const remove = async () => {
- if (!loaded.server) return;
+ if (!loaded.server || workspaceId === null) return;
setBusy('delete');
try {
- await rpc.workspaces.deleteTemplate({
- workspaceId: workspacesStore.requireSoleIdOnServer(serverId),
- templateId: loaded.server.id,
- });
+ await rpc.workspaces.deleteTemplate({ workspaceId, 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 56a847467..308e81388 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
@@ -147,6 +147,7 @@ async function loadUsePageTemplate(workspaceId: string, params: Params): Promise
id: detail.id,
name: detail.name,
source: 'server',
+ workspaceId,
...(serverId ? { serverId } : {}),
};
}
@@ -247,7 +248,7 @@ type SlotSetup = {
const TemplateUsePanel = observer(function TemplateUsePanel() {
const params = useViewParams();
const { serverId, intoRoomId = null } = params;
- const workspaceId = workspacesStore.soleIdOnServer(serverId);
+ const workspaceId = workspacesStore.idOnServerInScope(serverId);
const { navigate } = useNavigate();
const { showModal } = useModalContext();
const queryClient = useQueryClient();
@@ -697,7 +698,7 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {
const blockedReason: string | null =
phase !== 'form'
? null
- : loaded === null
+ : loaded === null || workspaceId === null
? 'Loading…'
: missing.length > 0
? `Fill in ${missing.map(paramLabel).join(', ')}`
@@ -742,6 +743,7 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {
}, [parsed, editedAgents, templateParams, values, slots, agents.data]);
const [allowingHandoffs, setAllowingHandoffs] = useState(false);
const allowHandoffs = useCallback(async () => {
+ if (workspaceId === null) return;
const byName = new Map((agents.data ?? []).map((a) => [a.name, a]));
setAllowingHandoffs(true);
try {
@@ -764,7 +766,7 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {
return next;
});
await rpc.workspaces.updateAddressingPolicy({
- workspaceId: workspacesStore.requireSoleIdOnServer(serverId),
+ workspaceId,
agentId: target.id,
policy: { rules },
});
@@ -775,14 +777,14 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {
} finally {
setAllowingHandoffs(false);
}
- }, [agents.data, handoffBlocked, serverId, workspaceId, queryClient]);
+ }, [agents.data, handoffBlocked, workspaceId, queryClient]);
// ── Create ──────────────────────────────────────────────────────────────
const setSlot = (i: number, patch: Partial<AgentSlot>) =>
setSlots((prev) => prev.map((s, j) => (j === i ? { ...s, ...patch } : s)));
const createAll = async () => {
- if (!loaded || blockedReason !== null) return;
+ if (!loaded || workspaceId === null || blockedReason !== null) return;
setPhase('creating');
setCreateError(null);
setFieldErrors({});
@@ -855,7 +857,7 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {
if (switchAgentId && slot.entry.addressing) {
setSlot(i, { step: 'policy' });
await rpc.workspaces.updateAddressingPolicy({
- workspaceId: workspacesStore.requireSoleIdOnServer(serverId),
+ workspaceId,
agentId: switchAgentId,
policy:
slot.entry.addressing === 'owner-agents'
@@ -935,7 +937,7 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {
try {
for (const [roomId, ids] of joinsByRoom) {
await rpc.workspaces.addRoomAgents({
- workspaceId: workspacesStore.requireSoleIdOnServer(serverId),
+ workspaceId,
roomId,
agentIds: [...new Set(ids)],
direction: 'agents_to_room',
@@ -1018,11 +1020,7 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {
}
const result =
createdRoom.current ??
- (await rpc.workspaces.createRoomFromTemplate(
- workspacesStore.requireSoleIdOnServer(serverId),
- coreYaml,
- inputs
- ));
+ (await rpc.workspaces.createRoomFromTemplate(workspaceId, 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 fadcf4691..7399728a7 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
@@ -408,7 +408,7 @@ function RecentsSection({
const TemplatesPanel = observer(function TemplatesPanel() {
const serverId = useServerId();
- const workspaceId = workspacesStore.soleIdOnServer(serverId);
+ const workspaceId = workspacesStore.idOnServerInScope(serverId);
const server = switchServersStore.servers.find((s) => s.id === serverId);
const meId = switchServersStore.statusFor(serverId)?.user?.id ?? null;
const { navigate } = useNavigate();
diff --git a/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspaces-store.test.ts b/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspaces-store.test.ts
index 698084808..59f9e3163 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspaces-store.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspaces-store.test.ts
@@ -1,74 +1,184 @@
-/**
- * The store mirrors a list the main process owns, and the reconcile moves that
- * list without a window having asked. These cover the seam that carries such a
- * change across, which is otherwise only exercised by a running app.
- */
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type { Workspace } from '@shared/core/workspaces/workspaces';
-const list = vi.hoisted(() => vi.fn<() => Promise<unknown[]>>(async () => []));
-const getActiveId = vi.hoisted(() => vi.fn<() => Promise<string | null>>(async () => null));
+const list = vi.hoisted(() => vi.fn());
+const getActiveId = vi.hoisted(() => vi.fn());
+const setActive = vi.hoisted(() => vi.fn());
const subscribers = vi.hoisted(() => new Map<string, (data: unknown) => void>());
vi.mock('@renderer/lib/ipc', () => ({
- rpc: { workspaces: { list, getActiveId } },
events: {
on: (event: { name: string }, cb: (data: unknown) => void) => {
subscribers.set(event.name, cb);
return () => subscribers.delete(event.name);
},
},
+ rpc: { workspaces: { list, getActiveId, setActive } },
}));
const { WorkspacesStore } = await import('./workspaces-store');
const { workspacesChangedChannel } = await import('@shared/core/workspaces/workspaceEvents');
-function workspace(id: string, name: string) {
+function workspace(id: string, serverId: string, name = id): Workspace {
return {
id,
- serverId: 'srv-1',
+ serverId,
name,
tenantId: `tenant-${id}`,
- slug: name.toLowerCase(),
- role: 'member' as const,
+ slug: id,
+ role: 'member',
createdAt: '2026-01-01T00:00:00Z',
updatedAt: '2026-01-01T00:00:00Z',
};
}
-describe('WorkspacesStore', () => {
- beforeEach(() => {
- subscribers.clear();
- list.mockReset().mockResolvedValue([]);
- getActiveId.mockReset().mockResolvedValue(null);
- });
+/** A store holding the given workspaces, scoped to one of them. */
+async function loaded(workspaces: Workspace[], activeId: string | null) {
+ list.mockResolvedValue(workspaces);
+ getActiveId.mockResolvedValue(activeId);
+ const store = new WorkspacesStore();
+ await store.refresh();
+ return store;
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ subscribers.clear();
+ setActive.mockResolvedValue(undefined);
+});
+
+/** Fire the main process's "the list moved" event at whoever subscribed. */
+function announceChange(): void {
+ const notify = subscribers.get(workspacesChangedChannel.name);
+ expect(notify, 'nothing subscribed to the workspaces-changed event').toBeDefined();
+ notify!(undefined);
+}
+describe('keeping up with the main process', () => {
+ /**
+ * The reconcile adds and matches rows without a window having asked — the
+ * boot sweep, and every sign-in. Nothing else would tell an open window, so a
+ * membership gained since the last launch would stay invisible for the whole
+ * session.
+ */
it('re-reads the list when the main process says it changed', async () => {
- const store = new WorkspacesStore();
- list.mockResolvedValue([workspace('ws-1', 'Acme')]);
- await store.refresh();
+ const store = await loaded([workspace('ws-a', 'srv-1')], 'ws-a');
+
+ list.mockResolvedValue([workspace('ws-a', 'srv-1'), workspace('ws-b', 'srv-1')]);
+ announceChange();
- list.mockResolvedValue([workspace('ws-1', 'Acme'), workspace('ws-2', 'Skunkworks')]);
- subscribers.get(workspacesChangedChannel.name)!(undefined);
await vi.waitFor(() => expect(store.workspaces).toHaveLength(2));
});
/**
- * The reconcile drops the placeholder a server was registered with once every
+ * The sweep drops the placeholder a server was registered with once every
* membership has a row of its own. A window still listing it offers a
- * workspace that no longer exists, and the only thing it can report on the
- * click is that the switch failed — not that the row went.
+ * workspace that is not there, and the only thing it can report on the click
+ * is that the switch failed — not that the row went.
*/
it('drops a workspace the main process no longer has', async () => {
- const store = new WorkspacesStore();
- list.mockResolvedValue([workspace('ws-1', 'Acme'), workspace('ws-2', 'Skunkworks')]);
- getActiveId.mockResolvedValue('ws-1');
- await store.refresh();
+ const store = await loaded([workspace('ws-a', 'srv-1'), workspace('ws-b', 'srv-1')], 'ws-a');
+
+ list.mockResolvedValue([workspace('ws-b', 'srv-1')]);
+ getActiveId.mockResolvedValue('ws-b');
+ announceChange();
+
+ await vi.waitFor(() => expect(store.byId('ws-a')).toBeNull());
+ expect(store.activeId).toBe('ws-b');
+ });
+});
+
+describe('what the window is scoped to', () => {
+ it('reads the server off the workspace rather than holding its own', async () => {
+ const store = await loaded([workspace('ws-a', 'srv-1'), workspace('ws-b', 'srv-2')], 'ws-b');
+
+ expect(store.active?.id).toBe('ws-b');
+ expect(store.activeServerId).toBe('srv-2');
+ });
+
+ // Every install has this moment: the list arrives before anything has chosen.
+ it('is scoped to nothing while no workspace is selected', async () => {
+ const store = await loaded([workspace('ws-a', 'srv-1')], null);
+
+ expect(store.active).toBeNull();
+ expect(store.activeServerId).toBeNull();
+ });
+
+ /**
+ * Removing a server takes its workspaces with it, leaving the stored
+ * selection naming one that is gone. Reading that as a selection would scope
+ * the window to a server that is no longer there.
+ */
+ it('is scoped to nothing when the selection names a workspace that has gone', async () => {
+ const store = await loaded([workspace('ws-a', 'srv-1')], 'ws-removed');
+
+ expect(store.active).toBeNull();
+ expect(store.activeServerId).toBeNull();
+ });
+
+ it('moves the scope when a workspace is chosen', async () => {
+ const store = await loaded([workspace('ws-a', 'srv-1'), workspace('ws-b', 'srv-1')], 'ws-a');
+
+ await store.setActive('ws-b');
+
+ expect(setActive).toHaveBeenCalledWith('ws-b');
+ expect(store.activeId).toBe('ws-b');
+ });
+
+ /**
+ * A switch that failed quietly would leave the sidebar listing one
+ * workspace's rooms under another one's name — indistinguishable from the
+ * rooms having disappeared.
+ */
+ it('raises and stays put when the selection cannot be saved', async () => {
+ const store = await loaded([workspace('ws-a', 'srv-1'), workspace('ws-b', 'srv-1')], 'ws-a');
+ setActive.mockRejectedValue(new Error('database is locked'));
+
+ await expect(store.setActive('ws-b')).rejects.toThrow('database is locked');
+ expect(store.activeId).toBe('ws-a');
+ });
+});
+
+describe('the workspace a server-routed view acts in', () => {
+ it('is the active one when the window is scoped to that server', async () => {
+ const store = await loaded(
+ [workspace('ws-a', 'srv-1'), workspace('ws-b', 'srv-1'), workspace('ws-c', 'srv-2')],
+ 'ws-b'
+ );
+
+ expect(store.onServerInScope('srv-1')?.id).toBe('ws-b');
+ });
+
+ // A server with one workspace has nothing to choose between, so a page for it
+ // works whether or not the window is scoped there.
+ it('falls back to the only workspace on another server', async () => {
+ const store = await loaded([workspace('ws-a', 'srv-1'), workspace('ws-c', 'srv-2')], 'ws-a');
+
+ expect(store.onServerInScope('srv-2')?.id).toBe('ws-c');
+ });
+
+ // Addressing the wrong one answers with somebody else's rooms while looking
+ // entirely correct, so the view has to render the absence instead.
+ it('answers nothing for another server with several workspaces', async () => {
+ const store = await loaded(
+ [workspace('ws-a', 'srv-1'), workspace('ws-b', 'srv-2'), workspace('ws-c', 'srv-2')],
+ 'ws-a'
+ );
+
+ expect(store.onServerInScope('srv-2')).toBeNull();
+ expect(store.idOnServerInScope('srv-2')).toBeNull();
+ });
+
+ it('answers nothing for a server whose registration left it with none', async () => {
+ const store = await loaded([workspace('ws-a', 'srv-1')], 'ws-a');
+
+ expect(store.idOnServerInScope('srv-2')).toBeNull();
+ });
- list.mockResolvedValue([workspace('ws-2', 'Skunkworks')]);
- getActiveId.mockResolvedValue('ws-2');
- subscribers.get(workspacesChangedChannel.name)!(undefined);
+ // Every page routed by server reads this before its server is known.
+ it('answers nothing before a server has been chosen', async () => {
+ const store = await loaded([workspace('ws-a', 'srv-1')], 'ws-a');
- await vi.waitFor(() => expect(store.byId('ws-1')).toBeNull());
- expect(store.activeId).toBe('ws-2');
+ expect(store.idOnServerInScope(null)).toBeNull();
});
});
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
index f6d054f98..8d86acd2d 100644
--- 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
@@ -13,16 +13,19 @@ import type { Workspace } from '@shared/core/workspaces/workspaces';
* 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.
+ * The selection is persisted by the main process, so this mirrors it rather
+ * than owning it — but the window is scoped to a workspace, so this is where
+ * the scope is read and changed, and the servers store derives its own notion
+ * of "which server" from it.
*/
export class WorkspacesStore {
workspaces: Workspace[] = [];
activeId: string | null = null;
+ /** Ordinal of the most recent {@link setActive}; nothing renders it. */
+ lastSwitch = 0;
constructor() {
- makeAutoObservable(this);
+ makeAutoObservable(this, { lastSwitch: false });
// The reconcile adds, matches and drops rows without a window asking, so
// the calls the servers store makes are not the only times this list moves.
@@ -38,6 +41,40 @@ export class WorkspacesStore {
return this.workspaces.find((w) => w.id === this.activeId) ?? null;
}
+ /**
+ * The server the window is scoped to, for the parts of the app still keyed by
+ * one.
+ *
+ * Derived rather than stored alongside the workspace: the server is simply
+ * the one hosting the selection, and the main process reads it back the same
+ * way, so the two cannot come to disagree about which server the app is on.
+ */
+ get activeServerId(): string | null {
+ return this.active?.serverId ?? null;
+ }
+
+ /**
+ * Scope the window to a workspace.
+ *
+ * Raises if the selection does not take. The caller shows it: a switch that
+ * failed quietly would leave the sidebar listing one workspace's rooms under
+ * another one's name, which looks like data loss rather than a failed click.
+ *
+ * Only the last switch started may write the mirror. Two clicks in quick
+ * succession are two round trips that can finish in either order, and the
+ * slower one landing second would leave this pointing at a workspace the main
+ * process has already moved off — every read after it addressed under a name
+ * the window is no longer showing.
+ */
+ async setActive(workspaceId: string): Promise<void> {
+ const request = ++this.lastSwitch;
+ await rpc.workspaces.setActive(workspaceId);
+ if (request !== this.lastSwitch) return;
+ runInAction(() => {
+ this.activeId = workspaceId;
+ });
+ }
+
async refresh(): Promise<void> {
const [workspaces, activeId] = await Promise.all([
rpc.workspaces.list(),
@@ -63,39 +100,38 @@ export class WorkspacesStore {
}
/**
- * The one workspace on a server, for a view that is about the server itself —
- * its page, its cards, its pickers.
+ * The workspace a view about a server acts in — its page, its cards, its
+ * pickers.
+ *
+ * The active one when the window is scoped to that server, which is the
+ * ordinary case: choosing a workspace in the switcher is how you reach its
+ * pages at all. A view about some other server falls back to its only
+ * workspace, since then there is nothing to choose.
*
- * 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.
+ * Null rather than a guess where neither applies. A server with no workspace
+ * has not finished registering; a server with several, none of them active,
+ * 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 {
+ onServerInScope(serverId: string | null): Workspace | null {
+ if (serverId === null) return null;
+ const active = this.active;
+ if (active?.serverId === serverId) return active;
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.
+ * {@link onServerInScope} as an id, for a view still routed by server.
*
* 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;
+ idOnServerInScope(serverId: string | null): string | null {
+ return this.onServerInScope(serverId)?.id ?? null;
}
}
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/layout/scope-to-server.ts b/console/apps/switch-console-desktop/src/renderer/lib/layout/scope-to-server.ts
deleted file mode 100644
index fe047b200..000000000
--- a/console/apps/switch-console-desktop/src/renderer/lib/layout/scope-to-server.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-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';
-
-/**
- * Make a target's Switch server the active one before navigating to it.
- *
- * The active server scopes the whole sidebar — `sidebarStore.isLocationInActiveScope`
- * and `switchRoomsStore.listedRoomsInActiveScope` both filter on it. Navigating
- * to something on another server without this opens the view but leaves the
- * sidebar showing a tree the target is not in, so the row you just opened is
- * nowhere to be seen.
- *
- * A no-op when the target is already on the active server, when its server
- * cannot be resolved (an unlinked location), or when no server is active.
- */
-async function activateServer(serverId: string | null): Promise<void> {
- if (!serverId) return;
- if (switchServersStore.activeServerId === serverId) return;
- await switchServersStore.setActive(serverId);
-}
-
-/**
- * Scope to a server that shows `locationId` — for agents and sessions.
- *
- * A directory can hold agents for several servers, so there may be more than one
- * right answer. If the active server is already one of them there is nothing to do;
- * switching away would hide the row the caller is navigating to (CHOO-2044).
- */
-export async function scopeToLocationServer(locationId: string): Promise<void> {
- if (!agentsStore.loaded) await agentsStore.load();
- const serverIds = agentsStore.serverIdsForLocation(locationId);
- if (serverIds.length === 0) return;
- const active = switchServersStore.activeServerId;
- if (active && serverIds.includes(active)) return;
- await activateServer(serverIds[0]);
-}
-
-/** Scope to the server owning `roomId`. */
-export async function scopeToRoomServer(roomId: string): Promise<void> {
- await activateServer(switchRoomsStore.roomServerId(roomId));
-}
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/layout/scope-to-workspace.ts b/console/apps/switch-console-desktop/src/renderer/lib/layout/scope-to-workspace.ts
new file mode 100644
index 000000000..219acde55
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/lib/layout/scope-to-workspace.ts
@@ -0,0 +1,44 @@
+import { agentsStore } from '@renderer/features/locations/stores/agents-store';
+import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
+
+/**
+ * Make a target's workspace the active one before navigating to it.
+ *
+ * The active workspace scopes the whole sidebar — `sidebarStore.isLocationInActiveScope`
+ * and `switchRoomsStore.listedRoomsInActiveScope` both filter on it. Navigating
+ * to something in another workspace without this opens the view but leaves the
+ * sidebar showing a tree the target is not in, so the row you just opened is
+ * nowhere to be seen. Scoping to the *server* is not enough: its other workspace
+ * filters the target out just as surely as another server would.
+ *
+ * A no-op when the target is already in the active workspace, or when its
+ * workspace cannot be resolved (an unlinked location).
+ */
+async function activateWorkspace(workspaceId: string | null): Promise<void> {
+ if (!workspaceId) return;
+ if (workspacesStore.activeId === workspaceId) return;
+ await workspacesStore.setActive(workspaceId);
+}
+
+/**
+ * Scope to a workspace that shows `locationId` — for agents and sessions.
+ *
+ * A directory can hold agents for several workspaces, so there may be more than
+ * one right answer. If the active workspace is already one of them there is
+ * nothing to do; switching away would hide the row the caller is navigating to
+ * (CHOO-2044).
+ */
+export async function scopeToLocationWorkspace(locationId: string): Promise<void> {
+ if (!agentsStore.loaded) await agentsStore.load();
+ const workspaceIds = agentsStore.workspaceIdsForLocation(locationId);
+ if (workspaceIds.length === 0) return;
+ const active = workspacesStore.activeId;
+ if (active && workspaceIds.includes(active)) return;
+ await activateWorkspace(workspaceIds[0]!);
+}
+
+/** Scope to the workspace owning `roomId`. */
+export async function scopeToRoomWorkspace(roomId: string): Promise<void> {
+ await activateWorkspace(switchRoomsStore.roomWorkspaceId(roomId));
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/workspace-switcher.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/workspace-switcher.test.tsx
new file mode 100644
index 000000000..e0462ff50
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/workspace-switcher.test.tsx
@@ -0,0 +1,295 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';
+import type { Workspace, WorkspaceRole } from '@shared/core/workspaces/workspaces';
+
+vi.hoisted(() => {
+ window.electronAPI ??= {
+ invoke: () => Promise.resolve(undefined),
+ eventOn: () => () => {},
+ eventSend: () => {},
+ } as unknown as typeof window.electronAPI;
+});
+
+const state = vi.hoisted(() => ({
+ servers: [] as { id: string; name: string }[],
+ workspaces: [] as {
+ id: string;
+ serverId: string;
+ name: string;
+ tenantId: string | null;
+ role: string | null;
+ }[],
+ activeId: null as string | null,
+ setActive: vi.fn(),
+ navigate: vi.fn(),
+}));
+
+vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({
+ switchServersStore: {
+ init: () => Promise.resolve(),
+ recoverStale: () => Promise.resolve(),
+ get servers() {
+ return state.servers;
+ },
+ serverById: (id: string) => state.servers.find((s) => s.id === id) ?? null,
+ },
+}));
+
+vi.mock('@renderer/features/workspaces/workspaces-store', () => ({
+ workspacesStore: {
+ get activeId() {
+ return state.activeId;
+ },
+ get active() {
+ return state.workspaces.find((w) => w.id === state.activeId) ?? null;
+ },
+ onServer: (serverId: string) => state.workspaces.filter((w) => w.serverId === serverId),
+ setActive: state.setActive,
+ },
+}));
+
+vi.mock('@renderer/features/switch-servers/local-server-store', () => ({
+ localServerStore: { init: () => Promise.resolve(), dispose: () => {}, phase: 'stopped' },
+}));
+
+vi.mock('@renderer/features/switch-servers/remote-server-store', () => ({
+ remoteServerStore: { init: () => Promise.resolve(), dispose: () => {} },
+}));
+
+// Presentation of a server — its avatar, icon, status words and drift — is the
+// server's business and tested with it. Stubbed so this test is about which
+// workspaces the switcher offers and which it refuses.
+vi.mock('@renderer/features/switch-servers/server-presentation', () => ({
+ ServerAvatar: () => null,
+ ServerDriftIndicator: () => null,
+ ServerStatusDot: () => null,
+ serverDrift: () => null,
+ serverPlacementLabel: () => null,
+ serverStatusLabel: (server: SwitchServer) => `${server.name} status`,
+ serverSubtitleLabel: (server: SwitchServer) => `${server.name} status`,
+}));
+
+vi.mock('@renderer/features/switch-servers/server-icon', () => ({
+ serverIcon: () => () => null,
+}));
+
+vi.mock('@renderer/lib/layout/navigation-provider', () => ({
+ useNavigate: () => ({ navigate: state.navigate }),
+}));
+
+vi.mock('@renderer/lib/modal/modal-provider', () => ({
+ useShowModal: () => () => {},
+}));
+
+vi.mock('@renderer/lib/hooks/use-toast', () => ({
+ useToast: () => ({ toast: () => {} }),
+}));
+
+import { WorkspaceSwitcher } from '@renderer/features/switch-servers/workspace-switcher';
+
+let container: HTMLDivElement | null = null;
+let root: Root | null = null;
+
+function server(id: string, name: string): SwitchServer {
+ return {
+ id,
+ name,
+ gatewayUrl: `https://${id}.example.invalid`,
+ apiUrl: `https://${id}.example.invalid/api`,
+ managed: false,
+ managementKind: null,
+ sshHost: null,
+ createdAt: '2026-01-01T00:00:00Z',
+ updatedAt: '2026-01-01T00:00:00Z',
+ };
+}
+
+function workspace(
+ id: string,
+ serverId: string,
+ patch: { tenantId?: string | null; role?: WorkspaceRole | null } = {}
+): Workspace {
+ const tenantId = patch.tenantId === undefined ? `tenant-${id}` : patch.tenantId;
+ return {
+ id,
+ serverId,
+ name: id,
+ tenantId,
+ slug: tenantId === null ? null : id,
+ role: patch.role === undefined ? 'member' : patch.role,
+ createdAt: '2026-01-01T00:00:00Z',
+ updatedAt: '2026-01-01T00:00:00Z',
+ };
+}
+
+/** Mount the switcher on the given servers and workspaces, and open its menu. */
+async function openSwitcher(
+ servers: SwitchServer[],
+ workspaces: Workspace[],
+ activeId: string
+): Promise<void> {
+ state.servers = servers;
+ state.workspaces = workspaces;
+ state.activeId = activeId;
+
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ await act(async () => root!.render(<WorkspaceSwitcher />));
+
+ const trigger = container.querySelector<HTMLElement>('[aria-label="Switch workspace"]');
+ expect(trigger, 'the switcher did not render its trigger').not.toBeNull();
+ await act(async () => trigger!.click());
+}
+
+/** The menu row offering a workspace, by the name shown on it. */
+function row(name: string): HTMLElement {
+ const found = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find((item) =>
+ item.textContent?.startsWith(name)
+ );
+ expect(found, `no row for ${name}`).toBeDefined();
+ return found!;
+}
+
+beforeEach(() => {
+ state.setActive.mockReset().mockResolvedValue(undefined);
+ state.navigate.mockReset();
+});
+
+afterEach(async () => {
+ if (root) await act(async () => root!.unmount());
+ container?.remove();
+ container = null;
+ root = null;
+});
+
+describe('the workspaces the switcher offers', () => {
+ // A workspace only means anything on its server — two servers can each have a
+ // "Default" — so a flat list would offer two rows that read identically.
+ it('lists the workspaces on a server under that server', async () => {
+ await openSwitcher(
+ [server('srv-1', 'Acme'), server('srv-2', 'Local dev')],
+ [workspace('ws-a', 'srv-1'), workspace('ws-b', 'srv-1'), workspace('ws-c', 'srv-2')],
+ 'ws-a'
+ );
+
+ const groups = [...document.querySelectorAll<HTMLElement>('[data-slot="dropdown-menu-group"]')];
+ const listed = groups.map((group) => [
+ group.querySelector('[data-slot="dropdown-menu-label"]')?.textContent,
+ // The first span on a row is its name; a second one, where there is one,
+ // is the role or the reason it cannot be opened.
+ [...group.querySelectorAll('[role="menuitem"]')].map(
+ (item) => item.querySelector('span')?.textContent
+ ),
+ ]);
+
+ expect(listed[0]?.[0]).toContain('Acme');
+ expect(listed[0]?.[1]).toEqual(['ws-a', 'ws-b']);
+ expect(listed[1]?.[0]).toContain('Local dev');
+ expect(listed[1]?.[1]).toEqual(['ws-c']);
+ });
+
+ it('marks the one the window is scoped to', async () => {
+ await openSwitcher(
+ [server('srv-1', 'Acme')],
+ [workspace('ws-a', 'srv-1'), workspace('ws-b', 'srv-1')],
+ 'ws-b'
+ );
+
+ expect(row('ws-a').getAttribute('aria-current')).toBeNull();
+ expect(row('ws-b').getAttribute('aria-current')).toBe('true');
+ });
+
+ it('switches to the one clicked', async () => {
+ await openSwitcher(
+ [server('srv-1', 'Acme')],
+ [workspace('ws-a', 'srv-1'), workspace('ws-b', 'srv-1')],
+ 'ws-a'
+ );
+
+ await act(async () => row('ws-b').click());
+
+ expect(state.setActive).toHaveBeenCalledWith('ws-b');
+ });
+});
+
+/**
+ * Two rows the gateway will refuse every call scoped to. Both are kept in the
+ * list rather than hidden, because their agents are still here and the row is
+ * the only thing that says where they went — so both have to be unclickable and
+ * both have to say why, or the app turns a fact it already knows into an error
+ * after the click.
+ */
+describe('a workspace that cannot be opened', () => {
+ it('refuses one this account is no longer a member of', async () => {
+ await openSwitcher(
+ [server('srv-1', 'Acme')],
+ [workspace('ws-a', 'srv-1'), workspace('ws-gone', 'srv-1', { role: null })],
+ 'ws-a'
+ );
+
+ const gone = row('ws-gone');
+ expect(gone.getAttribute('aria-disabled')).toBe('true');
+ expect(gone.textContent).toContain('No longer a member');
+ expect(gone.title).toContain('no longer a member');
+ });
+
+ /**
+ * The row every server is registered with, before the gateway has been asked
+ * which workspaces the account has. Once the account turns out to have more
+ * than one, nothing can say which this row meant — and a call scoped to it
+ * selects no tenant at all, so the gateway answers under whichever workspace
+ * the session last selected.
+ */
+ it('refuses a placeholder the reconcile could not match', async () => {
+ await openSwitcher(
+ [server('srv-1', 'Acme')],
+ [
+ workspace('ws-placeholder', 'srv-1', { tenantId: null, role: null }),
+ workspace('ws-a', 'srv-1'),
+ ],
+ 'ws-a'
+ );
+
+ const placeholder = row('ws-placeholder');
+ expect(placeholder.getAttribute('aria-disabled')).toBe('true');
+ expect(placeholder.textContent).toContain('Not matched');
+ });
+
+ /**
+ * The same state on a server holding one workspace is ordinary rather than
+ * broken: there is nothing to confuse it with, and the gateway resolves the
+ * account's sole membership to exactly that row. Refusing it would lock the
+ * window out of a freshly registered server until a reconcile had run.
+ */
+ it('still offers a lone workspace that has no tenant yet', async () => {
+ await openSwitcher(
+ [server('srv-1', 'Acme')],
+ [workspace('ws-only', 'srv-1', { tenantId: null, role: null })],
+ 'ws-only'
+ );
+
+ const only = row('ws-only');
+ expect(only.getAttribute('aria-disabled')).toBeNull();
+ expect(only.textContent).toBe('ws-only');
+ });
+
+ it('says what to do instead of sending you back through sign-in', async () => {
+ await openSwitcher(
+ [server('srv-1', 'Acme')],
+ [
+ workspace('ws-placeholder', 'srv-1', { tenantId: null, role: null }),
+ workspace('ws-a', 'srv-1'),
+ ],
+ 'ws-a'
+ );
+
+ // Signing in re-runs the reconcile, which is what left the row unmatched and
+ // would do so again — so the row must not offer it as the way out.
+ const reason = row('ws-placeholder').title;
+ expect(reason).toContain('Open one of the others');
+ expect(reason).not.toMatch(/sign in/i);
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/shared/core/workspaces/workspaces.ts b/console/apps/switch-console-desktop/src/shared/core/workspaces/workspaces.ts
index ea228ca9f..3c97fe80f 100644
--- a/console/apps/switch-console-desktop/src/shared/core/workspaces/workspaces.ts
+++ b/console/apps/switch-console-desktop/src/shared/core/workspaces/workspaces.ts
@@ -27,8 +27,58 @@ export type Workspace = {
tenantId: string | null;
/** The gateway's slug for the workspace; null alongside a null `tenantId`. */
slug: string | null;
- /** Null alongside a null `tenantId`, where the notion does not apply yet. */
+ /**
+ * Null alongside a null `tenantId`, where the notion does not apply yet — and
+ * null beside a tenant id once the membership has been withdrawn, which is
+ * what {@link isWithdrawnWorkspace} reads.
+ */
role: WorkspaceRole | null;
createdAt: string;
updatedAt: string;
};
+
+/**
+ * Whether this account has lost its membership of a workspace still held here.
+ *
+ * The row is kept so the agents registered through it stay attached to
+ * something, but nothing scoped to it can be answered any more: the gateway
+ * refuses a session selecting a tenant the account does not belong to. Views
+ * say so rather than offering it, so the refusal is read before the click
+ * rather than after it.
+ */
+export function isWithdrawnWorkspace(workspace: Workspace): boolean {
+ return workspace.tenantId !== null && workspace.role === null;
+}
+
+/**
+ * Whether a row that names no tenant is one nothing can answer for.
+ *
+ * Every server's first workspace is created tenant-less and matched to a
+ * membership by the reconcile, so on a server holding one workspace this state
+ * is ordinary: there is nothing to confuse it with, and the gateway resolves
+ * the account's sole membership to exactly that row. Beside siblings it is the
+ * placeholder the reconcile could not match, kept only because it holds agents
+ * — and a call scoped to it selects no tenant, so the gateway answers with
+ * whichever workspace the session last selected, under this one's name.
+ *
+ * `onSameServer` is every workspace on the server, this one included.
+ */
+export function isUnmatchedWorkspace(workspace: Workspace, onSameServer: number): boolean {
+ return workspace.tenantId === null && onSameServer > 1;
+}
+
+/** Why a workspace cannot be opened, or null when it can. */
+export type WorkspaceUnavailability = 'withdrawn' | 'unmatched';
+
+/**
+ * The two ways a workspace held here can be one nothing scoped to it will be
+ * answered for, as one question — so a view offering workspaces cannot rule out
+ * the first and go on offering the second.
+ */
+export function workspaceUnavailability(
+ workspace: Workspace,
+ onSameServer: number
+): WorkspaceUnavailability | null {
+ if (isWithdrawnWorkspace(workspace)) return 'withdrawn';
+ return isUnmatchedWorkspace(workspace, onSameServer) ? 'unmatched' : null;
+}