Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
feat(console): move agents onto workspaces in the data layer
Petr Bauch154d08b27d2f
diff --git a/console/agents/architecture/data-model.md b/console/agents/architecture/data-model.mdindex e071bffc5..2fd1788bc 100644--- a/console/agents/architecture/data-model.md+++ b/console/agents/architecture/data-model.md@@ -23,7 +23,8 @@ The schema is defined in `apps/switch-console-desktop/src/main/db/schema.ts`.| **session** | `conversation` | One instantiation/run of an agent. The unit shown under an agent in the sidebar. || **message** | `message` | A message in a session (was keyed by `conversationId`, now `sessionId`). || *(removed)* | `session` (worktree-era) | The upstream parallel-run grouping. Removed — Switch Console runs every session in the location's directory, so the grouping layer is gone. |-| *(removed)* | `workspace` | The upstream execution-location abstraction (worktree / SSH / BYOI remote). Removed — see below. |+| *(removed)* | `workspace` | The upstream execution-location abstraction (worktree / SSH / BYOI remote). Removed — see below. Switch Console has a `workspaces` table again, but it names something unrelated: a tenant on a Switch server. |+| **workspace** | *(none)* — new | A tenant on a Switch server, and what the window is scoped to. An agent belongs to one; every gateway call is made in its name. The table is `workspaces`. |### Tables with no upstream equivalent@@ -32,6 +33,7 @@ These carry the Switch- and remote-specific state that upstream had no concept o| Table | What it is ||---|---|| `switch_servers` | A Switch server Switch Console talks to, managed or external. |+| `workspaces` | A tenant on one of those servers. Registering a server creates its first, tenant-less and named after the server. Agents reference it, and the active selection (`kv`, `activeWorkspaceId`) names one. || `remote_hosts` | An SSH host (keyed by its `~/.ssh/config` alias) that can run agents. || `remote_host_reachability` | The last observed reachability of a host. Separate from the host record so a probe result never masquerades as configuration — see the reachability note below. || `remote_host_setup_plans` | A host's onboarding plan (CHOO-1809). See "Remote host setup". |@@ -52,6 +54,11 @@ location (a working directory, local or on an SSH host)A location that lives on an SSH host references a `remote_hosts` row; that host carriesits own reachability and setup-plan rows alongside, not inside, the location hierarchy.+An agent also references the workspace it belongs to, which is not part of this+hierarchy: a location is where an agent runs, a workspace is who it runs as. One+directory can hold agents belonging to different workspaces, and a workspace's+agents can be spread across directories and hosts.+A session's room connection is a row keyed by `session_id` with`ON DELETE CASCADE`, so it cannot outlive the session (or the agent above it).It was previously a JSON blob in `app_settings`, which referenced nothing and so@@ -60,12 +67,14 @@ agents whose Switch server had been destroyed.## What we deliberately dropped from upstream, and why-- **The `workspaces` table and the workspace abstraction.** Upstream modelled+- **The upstream workspace abstraction.** (Not to be confused with Switch+ Console's own `workspaces` table above, which reuses the name for a tenant on+ a Switch server and has nothing to do with this.) Upstream modelled*where* a session runs (git worktree, project-SSH, BYOI remote). Switch Console hadalready gutted this before the rework — `workspace-config` reached v3 with thenote *"Switch Console has no git worktrees, branches, PRs, or BYOI: every sessionruns in the project root directory."* A workspace was therefore just "the- project directory" plus lifecycle scripts. We dropped the table (and+ project directory" plus lifecycle scripts. We dropped it (and`project.repositoryWorkspaceId` / `session.workspaceId`) and keep lifecyclescripts / fs access as a service hung off the location's directory.diff --git a/console/apps/switch-console-desktop/drizzle/0051_workspaces.sql b/console/apps/switch-console-desktop/drizzle/0051_workspaces.sqlindex ef9534803..9ecb019bf 100644--- a/console/apps/switch-console-desktop/drizzle/0051_workspaces.sql+++ b/console/apps/switch-console-desktop/drizzle/0051_workspaces.sql@@ -7,8 +7,9 @@-- read as a workspace id, so nothing has to be rewritten or reconciled. New-- workspaces discovered from a gateway get fresh ids.----- tenant_id stays NULL for these rows: the server reported no tenancy, so the--- workspace IS the whole server. A later reconcile fills it in if that changes.+-- tenant_id stays NULL for these rows: no gateway has been asked yet, and the+-- upgrade must not depend on one being reachable. The first reconcile matches+-- each row to a tenant, keeping the id so the agents pointing at it still do.CREATE TABLE `workspaces` (`id` text PRIMARY KEY NOT NULL,`server_id` text NOT NULL,@@ -23,6 +24,7 @@ CREATE TABLE `workspaces` (--> statement-breakpointCREATE INDEX `idx_workspaces_server_id` ON `workspaces` (`server_id`);--> statement-breakpointCREATE UNIQUE INDEX `idx_workspaces_server_tenant` ON `workspaces` (`server_id`,`tenant_id`);--> statement-breakpoint+CREATE UNIQUE INDEX `idx_workspaces_server_placeholder` ON `workspaces` (`server_id`) WHERE `tenant_id` IS NULL;--> statement-breakpointINSERT INTO `workspaces` (`id`, `server_id`, `name`, `tenant_id`, `slug`, `role`)SELECT `id`, `id`, `name`, NULL, NULL, NULL FROM `switch_servers`;--> statement-breakpoint@@ -31,7 +33,12 @@ INSERT INTO `workspaces` (`id`, `server_id`, `name`, `tenant_id`, `slug`, `role`-- drop a column named in one. Runs with foreign_keys=OFF inside the migration-- transaction, so dropping and renaming does not disturb the sessions FK, which-- tracks the table name. The workspace id equals the old server id, so the--- carry-over is a straight copy.+-- carry-over is a straight copy — except that `server_id` was added by+-- ALTER TABLE ADD COLUMN, which in SQLite cannot carry an ON DELETE clause, so+-- its set-null was never enforced by the engine and a row may point at a server+-- that is gone. Copying such a value would seed the new, real foreign key with a+-- violation that foreign_keys=OFF lets straight through, so it is dropped to+-- NULL here — the same "unlinked" state the app already handles.CREATE TABLE `__new_agents` (`id` text PRIMARY KEY NOT NULL,`location_id` text NOT NULL,@@ -50,7 +57,9 @@ CREATE TABLE `__new_agents` (FOREIGN KEY (`workspace_id`) REFERENCES `workspaces`(`id`) ON UPDATE no action ON DELETE set null);--> statement-breakpointINSERT INTO `__new_agents` (`id`, `location_id`, `name`, `provider_id`, `switch_agent_id`, `api_endpoint`, `workspace_id`, `status`, `auto_approve`, `owner_name`, `provider_config`, `created_at`, `updated_at`)- SELECT `id`, `location_id`, `name`, `provider_id`, `switch_agent_id`, `api_endpoint`, `server_id`, `status`, `auto_approve`, `owner_name`, `provider_config`, `created_at`, `updated_at` FROM `agents`;+ SELECT `id`, `location_id`, `name`, `provider_id`, `switch_agent_id`, `api_endpoint`,+ CASE WHEN `server_id` IN (SELECT `id` FROM `workspaces`) THEN `server_id` END,+ `status`, `auto_approve`, `owner_name`, `provider_config`, `created_at`, `updated_at` FROM `agents`;--> statement-breakpointDROP TABLE `agents`;--> statement-breakpointALTER TABLE `__new_agents` RENAME TO `agents`;--> statement-breakpointdiff --git a/console/apps/switch-console-desktop/drizzle/meta/0051_snapshot.json b/console/apps/switch-console-desktop/drizzle/meta/0051_snapshot.jsonindex 9e52e7a19..5f301abe2 100644--- a/console/apps/switch-console-desktop/drizzle/meta/0051_snapshot.json+++ b/console/apps/switch-console-desktop/drizzle/meta/0051_snapshot.json@@ -941,6 +941,12 @@"name": "idx_workspaces_server_tenant","columns": ["server_id", "tenant_id"],"isUnique": true+ },+ "idx_workspaces_server_placeholder": {+ "name": "idx_workspaces_server_placeholder",+ "columns": ["server_id"],+ "isUnique": true,+ "where": "`tenant_id` IS NULL"}},"foreignKeys": {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.tsindex d8fb24b63..cd31ca8a4 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@@ -104,6 +104,9 @@ 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}` })),+}));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.tsindex 81c4eed19..469f6a013 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,6 +10,7 @@ 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 { db } from '@main/db/client';import { agents as agentsTable } from '@main/db/schema';import { log } from '@main/lib/logger';@@ -191,6 +192,7 @@ async function runAddAgent(params: AddAgentParams): Promise<AddAgentResult> {message: `No Switch server with id ${params.serverId}`,});}+ const targetWorkspace = await requireSoleWorkspaceForServer(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@@ -312,7 +314,7 @@ async function runAddAgent(params: AddAgentParams): Promise<AddAgentResult> {providerId: params.providerId,switchAgentId: registered.id,apiEndpoint: server.apiUrl,- serverId: params.serverId,+ workspaceId: targetWorkspace.id,autoApprove: params.autoApprove,providerConfig: params.providerConfig ?? null,});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.tsindex d070f69de..7e3e46477 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,5 +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 type { AgentVerifyResult } from '@shared/core/switch-servers/switch-servers';import { getAgentById } from './getAgentById';import { updateAgent } from './updateAgent';@@ -38,7 +39,8 @@ export async function assignAgentServer(params: {}if (result === 'found') {- await updateAgent({ agentId: params.agentId, serverId: params.serverId });+ 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.tsindex bf6e13a6a..f39bba2c5 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@@ -46,10 +46,10 @@ const h = vi.hoisted(() => {const state: {workspace: PluginFs | null;/** Agent-row names already in the directory, per Switch server. */- agentNamesByServer: Record<string, string[]>;+ agentNamesByWorkspace: Record<string, string[]>;existsOnServer: boolean;existsThrows: Error | null;- } = { workspace: null, agentNamesByServer: {}, existsOnServer: true, existsThrows: null };+ } = { workspace: null, agentNamesByWorkspace: {}, existsOnServer: true, existsThrows: null };return {state,GatewayError,@@ -69,10 +69,13 @@ vi.mock('@main/core/locations/store', () => ({ensureLocation: vi.fn(async () => ({ id: 'loc-1' })),}));vi.mock('./getAgents', () => ({- getLocationAgentsOnServer: vi.fn(async (_locationId: string, serverId: string) =>- (h.state.agentNamesByServer[serverId] ?? []).map((name) => ({ name }))+ getLocationAgentsInWorkspace: vi.fn(async (_locationId: string, workspaceId: string) =>+ (h.state.agentNamesByWorkspace[workspaceId] ?? []).map((name) => ({ name }))),}));+vi.mock('@main/core/workspaces/workspaces-store', () => ({+ requireSoleWorkspaceForServer: vi.fn(async (serverId: string) => ({ id: `ws-${serverId}` })),+}));vi.mock('./agent-workspace-fs', () => ({resolveWorkspaceFsFor: vi.fn(async () => ({fs: h.state.workspace as PluginFs,@@ -115,7 +118,7 @@ function params(agents: Array<{ name: string; providerId: 'codex' | 'claude' }>)describe('attachConfiguredAgents', () => {beforeEach(() => {vi.clearAllMocks();- h.state.agentNamesByServer = {};+ h.state.agentNamesByWorkspace = {};h.state.existsOnServer = true;h.state.existsThrows = null;h.state.workspace = readOnlyFs({ '.switch/agents/theirs.json': creds('sw-theirs') });@@ -175,7 +178,7 @@ describe('attachConfiguredAgents', () => {});it('skips an agent this Switch Console already has', async () => {- h.state.agentNamesByServer = { 'srv-1': ['theirs'] };+ h.state.agentNamesByWorkspace = { 'ws-srv-1': ['theirs'] };const result = await attachConfiguredAgents(params([{ name: 'theirs', providerId: 'codex' }]));@@ -185,13 +188,13 @@ describe('attachConfiguredAgents', () => {it('attaches an agent already attached to a different server (CHOO-2044)', async () => {// Same directory, same name, other server — a separate agent, not a duplicate.- h.state.agentNamesByServer = { 'srv-other': ['theirs'] };+ h.state.agentNamesByWorkspace = { 'ws-srv-other': ['theirs'] };const result = await attachConfiguredAgents(params([{ name: 'theirs', providerId: 'codex' }]));expect(result.success).toBe(true);expect(h.createAgent).toHaveBeenCalledWith(- expect.objectContaining({ name: 'theirs', serverId: 'srv-1' })+ expect.objectContaining({ name: 'theirs', workspaceId: 'ws-srv-1' }));});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.tsindex a56bb053a..b81e989a9 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,6 +6,7 @@ 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 { log } from '@main/lib/logger';import type { Agent } from '@shared/core/agents/agents';import type { OnboardAgentError } from '@shared/core/agents/onboarding';@@ -70,6 +71,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 discovered = new Map((@@ -158,7 +160,7 @@ export async function attachConfiguredAgents(providerId,switchAgentId: found.switchAgentId,apiEndpoint: found.apiEndpoint,- serverId: params.serverId,+ workspaceId: targetWorkspace.id,autoApprove: params.sshHost !== null,ownerName: ownerName ?? null,});diff --git a/console/apps/switch-console-desktop/src/main/core/agents/createAgent.ts b/console/apps/switch-console-desktop/src/main/core/agents/createAgent.tsindex d6a28b0c3..f2ade07ab 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/createAgent.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/createAgent.ts@@ -2,7 +2,7 @@ import { sql } from 'drizzle-orm';import { db } from '@main/db/client';import { agents } from '@main/db/schema';import type { Agent, CreateAgentParams } from '@shared/core/agents/agents';-import { mapAgentRowToAgent } from './utils';+import { mapAgentRow } from './utils';/*** Insert an agent row. Main-process internal, and deliberately not an RPC@@ -21,7 +21,7 @@ export async function createAgent(params: CreateAgentParams): Promise<Agent> {providerId: params.providerId,switchAgentId: params.switchAgentId,apiEndpoint: params.apiEndpoint,- serverId: params.serverId,+ workspaceId: params.workspaceId,autoApprove: params.autoApprove,ownerName: params.ownerName ?? null,providerConfig: params.providerConfig ?? null,@@ -29,5 +29,5 @@ export async function createAgent(params: CreateAgentParams): Promise<Agent> {}).returning();- return mapAgentRowToAgent(row);+ return mapAgentRow(row);}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.tsindex e00083211..5b198be0a 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@@ -53,9 +53,14 @@ const h = vi.hoisted(() => {workspace: PluginFs | null;location: { id: string } | undefined;/** Agent-row names already in the directory, per Switch server. */- agentNamesByServer: Record<string, string[]>;+ agentNamesByWorkspace: Record<string, string[]>;claudeDefinitions: Array<{ name: string; description: string | null }>;- } = { workspace: null, location: { id: 'loc-1' }, agentNamesByServer: {}, claudeDefinitions: [] };+ } = {+ workspace: null,+ location: { id: 'loc-1' },+ agentNamesByWorkspace: {},+ claudeDefinitions: [],+ };return { state, warn: vi.fn() };});@@ -63,10 +68,13 @@ vi.mock('@main/core/locations/store', () => ({getLocationByHostDir: vi.fn(async () => h.state.location),}));vi.mock('./getAgents', () => ({- getLocationAgentsOnServer: vi.fn(async (_locationId: string, serverId: string) =>- (h.state.agentNamesByServer[serverId] ?? []).map((name) => ({ name }))+ getLocationAgentsInWorkspace: vi.fn(async (_locationId: string, workspaceId: string) =>+ (h.state.agentNamesByWorkspace[workspaceId] ?? []).map((name) => ({ name }))),}));+vi.mock('@main/core/workspaces/workspaces-store', () => ({+ requireSoleWorkspaceForServer: vi.fn(async (serverId: string) => ({ id: `ws-${serverId}` })),+}));vi.mock('./agent-workspace-fs', () => ({resolveWorkspaceFsFor: vi.fn(async () => ({fs: h.state.workspace as PluginFs,@@ -96,7 +104,7 @@ describe('discoverConfiguredAgents', () => {beforeEach(() => {vi.clearAllMocks();h.state.location = { id: 'loc-1' };- h.state.agentNamesByServer = {};+ h.state.agentNamesByWorkspace = {};h.state.claudeDefinitions = [];h.state.workspace = fakeFs();});@@ -161,7 +169,7 @@ describe('discoverConfiguredAgents', () => {});it('marks agents this Switch Console already has a row for', async () => {- h.state.agentNamesByServer = { 'srv-a': ['mine'] };+ h.state.agentNamesByWorkspace = { 'ws-srv-a': ['mine'] };h.state.workspace = fakeFs({'.switch/agents/mine.json': creds('sw-mine'),'.switch/agents/theirs.json': creds('sw-theirs'),@@ -176,7 +184,7 @@ describe('discoverConfiguredAgents', () => {// The directory is a place on disk, not one server's territory. An agent row// for server A says nothing about server B, and treating it as "already got// this" is what silently emptied the onboarding list.- h.state.agentNamesByServer = { 'srv-a': ['shared'] };+ h.state.agentNamesByWorkspace = { 'ws-srv-a': ['shared'] };h.state.workspace = fakeFs({ '.switch/agents/shared.json': creds('sw-shared') });expect((await scan('srv-a'))[0]).toMatchObject({ name: 'shared', alreadyAgent: true });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.tsindex 0682e4ac7..186969d3c 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,13 +1,14 @@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 { log } from '@main/lib/logger';import {isValidProviderId,type AgentProviderId,} from '@shared/core/providers/agent-provider-registry';import { resolveWorkspaceFsFor } from './agent-workspace-fs';-import { getLocationAgentsOnServer } from './getAgents';+import { getLocationAgentsInWorkspace } from './getAgents';import { SWITCH_AGENTS_DIR_RELATIVE } from './switch-settings-paths';/** How an agent's provider was inferred, so the UI can say whether to trust it. */@@ -122,9 +123,12 @@ 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 location = await getLocationByHostDir(params.sshHost, params.dir);const existing = location- ? new Set((await getLocationAgentsOnServer(location.id, params.serverId)).map((a) => a.name))+ ? new Set(+ (await getLocationAgentsInWorkspace(location.id, targetWorkspace.id)).map((a) => a.name)+ ): new Set<string>();const workspace = await resolveWorkspaceFsFor(params.sshHost, params.dir);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.tsindex a15565afe..0df24255a 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,8 +1,9 @@import { getLocationByHostDir } from '@main/core/locations/store';import { getPlugin } from '@main/core/providers/plugin-registry';+import { requireSoleWorkspaceForServer } from '@main/core/workspaces/workspaces-store';import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';import { resolveWorkspaceFsFor } from './agent-workspace-fs';-import { getLocationAgentsOnServer } from './getAgents';+import { getLocationAgentsInWorkspace } from './getAgents';export type DiscoveredLocationAgent = {/** The definition/launch name (`.claude/agents/<name>.md` stem, `--agent <name>`). */@@ -46,9 +47,12 @@ export async function discoverLocationAgents(params: {const behavior = getPlugin(params.providerId).behavior.repoAgents;if (!behavior) return [];+ const targetWorkspace = await requireSoleWorkspaceForServer(params.serverId);const location = await getLocationByHostDir(params.sshHost, params.dir);const existing = location- ? new Set((await getLocationAgentsOnServer(location.id, params.serverId)).map((a) => a.name))+ ? new Set(+ (await getLocationAgentsInWorkspace(location.id, targetWorkspace.id)).map((a) => a.name)+ ): new Set<string>();const workspace = await resolveWorkspaceFsFor(params.sshHost, params.dir);diff --git a/console/apps/switch-console-desktop/src/main/core/agents/getAgentById.ts b/console/apps/switch-console-desktop/src/main/core/agents/getAgentById.tsindex 9aeab349b..334f898e4 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/getAgentById.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/getAgentById.ts@@ -2,10 +2,10 @@ import { eq } from 'drizzle-orm';import { db } from '@main/db/client';import { agents } from '@main/db/schema';import type { Agent } from '@shared/core/agents/agents';-import { mapAgentRowToAgent } from './utils';+import { mapAgentRow } from './utils';export async function getAgentById(agentId: string): Promise<Agent | undefined> {const [row] = await db.select().from(agents).where(eq(agents.id, agentId)).limit(1);if (!row) return undefined;- return mapAgentRowToAgent(row);+ return mapAgentRow(row);}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/getAgents.ts b/console/apps/switch-console-desktop/src/main/core/agents/getAgents.tsindex 51edb0773..ef3e64ca6 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/getAgents.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/getAgents.ts@@ -1,37 +1,45 @@import { and, desc, eq } from 'drizzle-orm';import { db } from '@main/db/client';-import { agents } from '@main/db/schema';+import { agents, workspaces } from '@main/db/schema';import type { Agent } from '@shared/core/agents/agents';import { mapAgentRowToAgent } from './utils';+/**+ * Agents with the server hosting each one's workspace. Left-joined, because an+ * unlinked agent has no workspace and still has to be listed.+ */+function agentsWithServer() {+ return db+ .select({ agent: agents, serverId: workspaces.serverId })+ .from(agents)+ .leftJoin(workspaces, eq(agents.workspaceId, workspaces.id));+}+export async function getAgents(locationId?: string): Promise<Agent[]> {+ const query = agentsWithServer();const rows = locationId- ? await db- .select()- .from(agents)- .where(eq(agents.locationId, locationId))- .orderBy(desc(agents.updatedAt))- : await db.select().from(agents).orderBy(desc(agents.updatedAt));- return rows.map(mapAgentRowToAgent);+ ? await query.where(eq(agents.locationId, locationId)).orderBy(desc(agents.updatedAt))+ : await query.orderBy(desc(agents.updatedAt));+ return rows.map((row) => mapAgentRowToAgent(row.agent, row.serverId));}/**- * A directory's agents that belong to one Switch server.+ * A directory's agents that belong to one workspace.*- * A directory is a place on disk, not a server's territory: the same folder can- * hold agents registered against several servers. Anything answering "do I- * already have this agent" must therefore ask per server — asking per directory- * reports an agent on server A as already onboarded when the target is server B,- * and the candidate is silently dropped (CHOO-2044).+ * A directory is a place on disk, not a workspace's territory: the same folder+ * can hold agents belonging to several. Anything answering "do I already have+ * this agent" must therefore ask per workspace — asking per directory reports+ * an agent in workspace A as already onboarded when the target is workspace B,+ * and the candidate is silently dropped (CHOO-2044). Per workspace rather than+ * per server because an agent's name is unique per tenant on the gateway, so+ * two workspaces on one server can each hold a different agent of that name.*/-export async function getLocationAgentsOnServer(+export async function getLocationAgentsInWorkspace(locationId: string,- serverId: string+ workspaceId: string): Promise<Agent[]> {- const rows = await db- .select()- .from(agents)- .where(and(eq(agents.locationId, locationId), eq(agents.serverId, serverId)))+ const rows = await agentsWithServer()+ .where(and(eq(agents.locationId, locationId), eq(agents.workspaceId, workspaceId))).orderBy(desc(agents.updatedAt));- return rows.map(mapAgentRowToAgent);+ return rows.map((row) => mapAgentRowToAgent(row.agent, row.serverId));}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.tsindex fde36e2f4..00d98aa23 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@@ -44,6 +44,9 @@ vi.mock('@main/core/switch-rooms/switch-credentials', () => ({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}` })),+}));vi.mock('@main/core/switch-servers/gateway-client', () => {class GatewayError extends Error {constructor(readonly kind: string) {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.tsindex 8aa129be6..590a144eb 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,6 +9,7 @@ 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 { log } from '@main/lib/logger';import type {OnboardAgentError,@@ -185,6 +186,8 @@ export async function onboardAgent(params: OnboardAgentParams): Promise<OnboardA}}+ const targetWorkspace = await requireSoleWorkspaceForServer(params.serverId);+const location = await ensureLocation({ sshHost, dir: params.dir, name: params.name });const agent = await createAgent({@@ -194,7 +197,7 @@ export async function onboardAgent(params: OnboardAgentParams): Promise<OnboardAproviderId: params.providerId,switchAgentId: switchAgent.agentId,apiEndpoint: switchAgent.apiEndpoint,- serverId: params.serverId,+ workspaceId: targetWorkspace.id,// Honor an explicit choice from the add-agent modal; otherwise default by// run location — remote agents run unattended on their VM with no operator// to answer permission prompts, so default them to bypass, local off.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.tsindex 3c8e2304a..a5c1ed637 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@@ -9,7 +9,7 @@ const h = vi.hoisted(() => {}const state: {/** Agent-row names already in the directory, per Switch server. */- agentNamesByServer: Record<string, string[]>;+ agentNamesByWorkspace: Record<string, string[]>;definitions: Array<{name: string;description: string | null;@@ -20,7 +20,7 @@ const h = vi.hoisted(() => {local: Array<{ name: string; switchAgentId: string | null; apiEndpoint: string | null }>;/** Switch agent ids the target server admits to having. */idsOnServer: string[];- } = { agentNamesByServer: {}, definitions: [], local: [], idsOnServer: [] };+ } = { agentNamesByWorkspace: {}, definitions: [], local: [], idsOnServer: [] };return {state,GatewayError,@@ -44,10 +44,13 @@ vi.mock('@main/core/locations/store', () => ({ensureLocation: vi.fn(async () => ({ id: 'loc-1' })),}));vi.mock('./getAgents', () => ({- getLocationAgentsOnServer: vi.fn(async (_locationId: string, serverId: string) =>- (h.state.agentNamesByServer[serverId] ?? []).map((name) => ({ name }))+ getLocationAgentsInWorkspace: vi.fn(async (_locationId: string, workspaceId: string) =>+ (h.state.agentNamesByWorkspace[workspaceId] ?? []).map((name) => ({ name }))),}));+vi.mock('@main/core/workspaces/workspaces-store', () => ({+ requireSoleWorkspaceForServer: vi.fn(async (serverId: string) => ({ id: `ws-${serverId}` })),+}));vi.mock('./agent-workspace-fs', () => ({resolveWorkspaceFsFor: vi.fn(async () => ({fs: {} as PluginFs,@@ -115,7 +118,7 @@ function definition(name: string, registered: boolean) {describe('onboardLocationAgents identity resolution', () => {beforeEach(() => {vi.clearAllMocks();- h.state.agentNamesByServer = {};+ h.state.agentNamesByWorkspace = {};h.state.definitions = [];h.state.local = [];h.state.idsOnServer = [];@@ -174,7 +177,11 @@ describe('onboardLocationAgents identity resolution', () => {it('imports an identity the target server does have', async () => {h.state.definitions = [definition('mine', true)];h.state.local = [- { name: 'mine', switchAgentId: 'sw-on-b', apiEndpoint: 'https://b.example.com' },+ {+ name: 'mine',+ switchAgentId: 'sw-on-b',+ apiEndpoint: 'https://b.example.com',+ },];h.state.idsOnServer = ['sw-on-b'];@@ -184,7 +191,7 @@ describe('onboardLocationAgents identity resolution', () => {expect(h.registerAgentIdentity).not.toHaveBeenCalled();expect(h.writeNeutralAgentSettings).not.toHaveBeenCalled();expect(h.createAgent).toHaveBeenCalledWith(- expect.objectContaining({ name: 'mine', switchAgentId: 'sw-on-b', serverId: 'srv-b' })+ expect.objectContaining({ name: 'mine', switchAgentId: 'sw-on-b', workspaceId: 'ws-srv-b' }));});@@ -222,7 +229,7 @@ describe('onboardLocationAgents identity resolution', () => {it('offers a definition already onboarded onto another server', async () => {// Same directory, same name, different server — a separate agent.- h.state.agentNamesByServer = { 'srv-a': ['shared'] };+ h.state.agentNamesByWorkspace = { 'ws-srv-a': ['shared'] };h.state.definitions = [definition('shared', false)];h.state.local = [{ name: 'shared', switchAgentId: null, apiEndpoint: null }];@@ -230,7 +237,7 @@ describe('onboardLocationAgents identity resolution', () => {expect(result.success).toBe(true);expect(h.createAgent).toHaveBeenCalledWith(- expect.objectContaining({ name: 'shared', serverId: 'srv-b' })+ expect.objectContaining({ name: 'shared', workspaceId: 'ws-srv-b' }));});});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.tsindex e7a5d0218..27eeb1a53 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,6 +8,7 @@ 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 { log } from '@main/lib/logger';import { agentAvatarUrlForName } from '@shared/core/agents/agent-avatar';import type { Agent } from '@shared/core/agents/agents';@@ -18,7 +19,7 @@ import { basenameFromAnyPath } from '@shared/path-name';import { agentEvents } from './agent-events';import { resolveWorkspaceFsFor, type WorkspaceFs } from './agent-workspace-fs';import { createAgent } from './createAgent';-import { getLocationAgentsOnServer } from './getAgents';+import { getLocationAgentsInWorkspace } from './getAgents';import { registerAgentIdentity } from './register-agent-identity';import { reconcileAgentAutoSessionFromGateway } from './setAgentAutoSession';import { writeNeutralAgentSettingsFs } from './write-switch-settings';@@ -196,8 +197,9 @@ export async function onboardLocationAgents(name: params.locationName ?? basenameFromAnyPath(params.dir) ?? params.providerId,});+ const targetWorkspace = await requireSoleWorkspaceForServer(params.serverId);const existing = new Set(- (await getLocationAgentsOnServer(location.id, params.serverId)).map((a) => a.name)+ (await getLocationAgentsInWorkspace(location.id, targetWorkspace.id)).map((a) => a.name));const workspace = await resolveWorkspaceFsFor(params.sshHost, params.dir);@@ -247,7 +249,7 @@ export async function onboardLocationAgents(providerId: params.providerId,switchAgentId: resolved.identity.switchAgentId,apiEndpoint: resolved.identity.apiEndpoint,- serverId: params.serverId,+ workspaceId: targetWorkspace.id,autoApprove: params.sshHost !== null,});existing.add(def.name);diff --git a/console/apps/switch-console-desktop/src/main/core/agents/propagate-server-api-url.db.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/propagate-server-api-url.db.test.tsindex 39b884bd7..b943590f5 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/propagate-server-api-url.db.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/propagate-server-api-url.db.test.ts@@ -5,7 +5,7 @@ import { openFixture } from '@tooling/utils/db';import { eq } from 'drizzle-orm';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 { agents, locations, switchServers, workspaces } from '@main/db/schema';import { propagateServerApiUrl } from './propagate-server-api-url';import { agentSettingsRelativePath, SWITCH_SETTINGS_RELATIVE_PATH } from './switch-settings-paths';@@ -69,6 +69,13 @@ describe('propagateServerApiUrl', () => {apiUrl: 'https://other-api.example.com',},]);++ // Deliberately not the servers' ids: the cascade has to find agents through+ // their workspace, and identical ids would hide it not doing so.+ await fixture.db.insert(workspaces).values([+ { id: 'ws-pilot', serverId: 'pilot', name: 'Pilot' },+ { id: 'ws-other', serverId: 'other', name: 'Other' },+ ]);});afterEach(async () => {@@ -96,7 +103,7 @@ describe('propagateServerApiUrl', () => {switchAgentId: 'switch-agent-1',providerId: 'claude',apiEndpoint: 'https://old-api.example.com',- serverId: 'pilot',+ workspaceId: 'ws-pilot',});const results = await propagateServerApiUrl('pilot', 'https://new-api.example.com');@@ -152,7 +159,7 @@ describe('propagateServerApiUrl', () => {locationId: 'named-location',name: 'named-agent',providerId,- serverId: 'pilot',+ workspaceId: 'ws-pilot',apiEndpoint: env.SWITCH_API_ENDPOINT,});expect(await propagateServerApiUrl('pilot', 'https://new-api.example.com')).toMatchObject([@@ -185,7 +192,7 @@ describe('propagateServerApiUrl', () => {locationId: 'broken-location',name: 'broken-agent',providerId: 'codex',- serverId: 'pilot',+ workspaceId: 'ws-pilot',});expect(await propagateServerApiUrl('pilot', 'https://new-api.example.com')).toMatchObject([{ agentId: 'broken-agent', outcome: 'failed', error: expect.stringContaining('invalid') },@@ -211,7 +218,7 @@ describe('propagateServerApiUrl', () => {locationId: 'shared-location',name: 'agent-a',providerId: 'codex',- serverId: 'pilot',+ workspaceId: 'ws-pilot',switchAgentId: 'agent-a-identity',},{@@ -219,7 +226,7 @@ describe('propagateServerApiUrl', () => {locationId: 'shared-location',name: 'agent-b',providerId: 'claude',- serverId: 'other',+ workspaceId: 'ws-other',switchAgentId: 'agent-b-identity',},]);@@ -239,7 +246,7 @@ describe('propagateServerApiUrl', () => {name: 'bare-agent',providerId: 'claude',apiEndpoint: null,- serverId: 'pilot',+ workspaceId: 'ws-pilot',});const results = await propagateServerApiUrl('pilot', 'https://new-api.example.com');@@ -272,7 +279,7 @@ describe('propagateServerApiUrl', () => {name: 'other-agent',providerId: 'claude',apiEndpoint: 'https://other-api.example.com',- serverId: 'other',+ workspaceId: 'ws-other',});const results = await propagateServerApiUrl('pilot', 'https://new-api.example.com');diff --git a/console/apps/switch-console-desktop/src/main/core/agents/propagate-server-api-url.ts b/console/apps/switch-console-desktop/src/main/core/agents/propagate-server-api-url.tsindex 0e8d166a1..d98378ee8 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/propagate-server-api-url.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/propagate-server-api-url.ts@@ -6,7 +6,7 @@ import { FileSystemError, FileSystemErrorCodes } from '@main/core/fs/types';import { sshConnectionIdForHost } from '@main/core/locations/location-transport';import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';import { db } from '@main/db/client';-import { agents } from '@main/db/schema';+import { agents, workspaces } from '@main/db/schema';import { log } from '@main/lib/logger';import type { Agent } from '@shared/core/agents/agents';import type { AgentApiUrlPropagation } from '@shared/core/switch-servers/switch-servers';@@ -155,7 +155,8 @@ async function propagateToAgent(}/**- * Cascade a server's new API URL to every agent linked to it, rewriting each+ * Cascade a server's new API URL to every agent in any of its workspaces —+ * the URL is the server's, so all of them move together. Rewrites each* agent's on-disk `SWITCH_API_ENDPOINT` (local dir or remote SSH host) and the* DB mirror. Agents keep their token; unprovisioned agents are skipped, not* clobbered. Returns a per-agent summary — failures are reported, never@@ -166,10 +167,14 @@ export async function propagateServerApiUrl(serverId: string,apiEndpoint: string): Promise<AgentApiUrlPropagation[]> {- const rows = await db.select().from(agents).where(eq(agents.serverId, serverId));+ const rows = await db+ .select({ agent: agents })+ .from(agents)+ .innerJoin(workspaces, eq(agents.workspaceId, workspaces.id))+ .where(eq(workspaces.serverId, serverId));const results: AgentApiUrlPropagation[] = [];for (const row of rows) {- results.push(await propagateToAgent(mapAgentRowToAgent(row), apiEndpoint));+ results.push(await propagateToAgent(mapAgentRowToAgent(row.agent, serverId), apiEndpoint));}return results;}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/renameAgent.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/renameAgent.test.tsindex 373e53201..747a85b0b 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/renameAgent.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/renameAgent.test.ts@@ -74,6 +74,7 @@ vi.mock('@main/db/client', () => ({vi.mock('@main/db/schema', () => ({ agents: {} }));vi.mock('./utils', () => ({mapAgentRowToAgent: (row: Record<string, unknown>) => row,+ mapAgentRow: async (row: Record<string, unknown>) => row,}));const { renameAgent } = await import('./renameAgent');diff --git a/console/apps/switch-console-desktop/src/main/core/agents/renameAgent.ts b/console/apps/switch-console-desktop/src/main/core/agents/renameAgent.tsindex 0e3b3122f..d3d232f77 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/renameAgent.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/renameAgent.ts@@ -15,7 +15,7 @@ import { getAgentById } from './getAgentById';import { ensureRemoteWatcher } from './remote-watcher';import { removeAgentLaunchProfile } from './remove-launch-profile';import { agentSettingsRelativePath } from './switch-settings-paths';-import { mapAgentRowToAgent } from './utils';+import { mapAgentRow } from './utils';import { foreignCredentialsEndpoint } from './write-switch-settings';async function moveSidecarToNewName(_previous: Agent, renamed: Agent): Promise<void> {@@ -187,7 +187,7 @@ export async function renameAgent(.returning();if (!row) return err({ type: 'agent-not-found' });- const renamed = mapAgentRowToAgent(row);+ const renamed = await mapAgentRow(row);if (previous.name !== renamed.name) {await moveProvisionedFiles(previous, renamed);await moveSidecarToNewName(previous, renamed);diff --git a/console/apps/switch-console-desktop/src/main/core/agents/resolve-servers.db.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/resolve-servers.db.test.tsdeleted file mode 100644index 1bf6f9f3f..000000000--- a/console/apps/switch-console-desktop/src/main/core/agents/resolve-servers.db.test.ts+++ /dev/null@@ -1,128 +0,0 @@-import { openFixture } from '@tooling/utils/db';-import { eq } from 'drizzle-orm';-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 { resolveAgentServers } from './resolve-servers';--const mocks = vi.hoisted(() => ({- db: undefined as AppDb | undefined,-}));--vi.mock('@main/db/client', () => ({- get db() {- if (!mocks.db) throw new Error('Test database not initialized');- return mocks.db;- },-}));--// servers-store transitively constructs the encrypted-secrets singleton (which-// touches the real db at import). resolveAgentServers never reads cookies, so-// stub it out to keep this test to the agent↔server reconciliation path.-vi.mock('@main/core/secrets/encrypted-app-secrets-store', () => ({- encryptedAppSecretsStore: {- getSecret: vi.fn(),- setSecret: vi.fn(),- deleteSecret: vi.fn(),- },-}));--async function serverIdOf(db: AppDb, agentId: string): Promise<string | null> {- const [row] = await db- .select({ serverId: agents.serverId })- .from(agents)- .where(eq(agents.id, agentId))- .limit(1);- return row?.serverId ?? null;-}--describe('resolveAgentServers', () => {- let fixture: Awaited<ReturnType<typeof openFixture>>;-- beforeEach(async () => {- fixture = await openFixture('empty');- mocks.db = fixture.db;- // Mirror production: the app's main connection does not enforce foreign- // keys, so an agent can reference a server that has since been removed —- // exactly the dangling state resolveAgentServers cleans up.- fixture.sqlite.pragma('foreign_keys = OFF');-- await fixture.db- .insert(locations)- .values({ id: 'location-1', name: 'Location', sshHost: '', dir: '/repo/location-1' });- await fixture.db.insert(switchServers).values([- {- id: 'pilot',- name: 'Pilot',- gatewayUrl: 'https://pilot-gateway.example.com',- apiUrl: 'https://pilot-api.example.com',- },- {- id: 'local',- name: 'Local',- gatewayUrl: 'http://localhost:8080',- apiUrl: 'http://localhost:8081',- },- ]);- });-- afterEach(() => {- fixture.close();- mocks.db = undefined;- });-- it('keeps links to registered servers, unlinks dangling, leaves unassigned alone', async () => {- await fixture.db.insert(agents).values([- // Explicitly linked to a registered server -> kept (not re-derived).- {- id: 'agent-pilot',- locationId: 'location-1',- name: 'pilot',- providerId: 'claude',- apiEndpoint: 'https://pilot.example.com/agent-bridge',- serverId: 'pilot',- },- // Linked to a server that is no longer registered -> unlinked.- {- id: 'agent-dangling',- locationId: 'location-1',- name: 'dangling',- providerId: 'claude',- apiEndpoint: 'https://gone.example.com',- serverId: 'removed-server',- },- // Never assigned -> stays null.- {- id: 'agent-none',- locationId: 'location-1',- name: 'none',- providerId: 'claude',- apiEndpoint: null,- serverId: null,- },- ]);-- await resolveAgentServers();-- expect(await serverIdOf(fixture.db, 'agent-pilot')).toBe('pilot');- expect(await serverIdOf(fixture.db, 'agent-dangling')).toBeNull();- expect(await serverIdOf(fixture.db, 'agent-none')).toBeNull();- });-- it('does not re-link by endpoint origin (links are explicit, never inferred)', async () => {- // Endpoint origin matches the local server, but serverId is null: the old- // behavior would auto-link; the new behavior must leave it unassigned.- await fixture.db.insert(agents).values({- id: 'agent-origin-match',- locationId: 'location-1',- name: 'origin-match',- providerId: 'claude',- apiEndpoint: 'http://localhost:8080',- serverId: null,- });-- await resolveAgentServers();-- expect(await serverIdOf(fixture.db, 'agent-origin-match')).toBeNull();- });-});diff --git a/console/apps/switch-console-desktop/src/main/core/agents/resolve-servers.ts b/console/apps/switch-console-desktop/src/main/core/agents/resolve-servers.tsdeleted file mode 100644index 962379f33..000000000--- a/console/apps/switch-console-desktop/src/main/core/agents/resolve-servers.ts+++ /dev/null@@ -1,42 +0,0 @@-import { isNotNull, notInArray } from 'drizzle-orm';-import { listServers } from '@main/core/switch-servers/servers-store';-import { db } from '@main/db/client';-import { agents } from '@main/db/schema';-import { log } from '@main/lib/logger';--/**- * Drop agent → server links that point at a server no longer in the registry,- * so an agent never references a server that has been removed.- *- * Links are otherwise authoritative: an agent's `serverId` is chosen and- * verified explicitly at onboarding (or via the assign-server action), not- * inferred. This reconciliation only *unlinks* dangling references — it never- * re-derives or re-assigns a server — so an explicit choice is never clobbered.- * An agent left with a null `serverId` surfaces in the UI as "needs a server".- *- * Run at boot and whenever the server registry changes.- */-export async function resolveAgentServers(): Promise<void> {- const servers = await listServers();- const registeredIds = servers.map((s) => s.id);-- // No registered servers → every linked agent is dangling. Otherwise unlink- // only agents whose serverId is set and not among the registered ids.- // (`NOT IN` already excludes null rows, so unassigned agents stay untouched.)- const where =- registeredIds.length === 0- ? isNotNull(agents.serverId)- : notInArray(agents.serverId, registeredIds);-- const result = await db- .update(agents)- .set({ serverId: null })- .where(where)- .returning({ id: agents.id });-- if (result.length > 0) {- log.info('switch-agents: unlinked agents pointing at removed servers', {- unlinked: result.length,- });- }-}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/updateAgent.ts b/console/apps/switch-console-desktop/src/main/core/agents/updateAgent.tsindex 89073bec4..2285bb0af 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/updateAgent.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/updateAgent.ts@@ -4,14 +4,14 @@ import { agents } from '@main/db/schema';import type { AgentProviderConfig } from '@shared/core/agents/agent-provider-config';import type { Agent } from '@shared/core/agents/agents';import { agentEvents } from './agent-events';-import { mapAgentRowToAgent } from './utils';+import { mapAgentRow } from './utils';export type UpdateAgentParams = {agentId: string;status?: string | null;switchAgentId?: string | null;apiEndpoint?: string | null;- serverId?: string;+ workspaceId?: string;autoApprove?: boolean;/** Null clears the agent's specialization, putting it back on provider defaults. */providerConfig?: AgentProviderConfig | null;@@ -24,13 +24,13 @@ export async function updateAgent(params: UpdateAgentParams): Promise<Agent | unif (params.status !== undefined) set.status = params.status;if (params.switchAgentId !== undefined) set.switchAgentId = params.switchAgentId;if (params.apiEndpoint !== undefined) set.apiEndpoint = params.apiEndpoint;- if (params.serverId !== undefined) set.serverId = params.serverId;+ if (params.workspaceId !== undefined) set.workspaceId = params.workspaceId;if (params.autoApprove !== undefined) set.autoApprove = params.autoApprove;if (params.providerConfig !== undefined) set.providerConfig = params.providerConfig;const [row] = await db.update(agents).set(set).where(eq(agents.id, params.agentId)).returning();if (!row) return undefined;- const agent = mapAgentRowToAgent(row);+ const agent = await mapAgentRow(row);agentEvents._emit('agent:updated', agent);return agent;}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/utils.ts b/console/apps/switch-console-desktop/src/main/core/agents/utils.tsindex 801b36b72..7f8455a05 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/utils.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/utils.ts@@ -1,8 +1,14 @@+import { serverIdForWorkspace } from '@main/core/workspaces/workspaces-store';import type { AgentRow } from '@main/db/schema';import { noteAgentName } from '@main/lib/log-name-cache';import type { Agent } from '@shared/core/agents/agents';-export function mapAgentRowToAgent(row: AgentRow): Agent {+/**+ * `serverId` is the server hosting the agent's workspace. It is a join away+ * from the row rather than on it, so the caller resolves it — the list reads+ * join, the single-row reads use {@link mapAgentRow}.+ */+export function mapAgentRowToAgent(row: AgentRow, serverId: string | null): Agent {// Every read and write of an agent passes through here, so the log sink can// name an agent id without ever querying for it.noteAgentName(row.id, row.name);@@ -14,7 +20,8 @@ export function mapAgentRowToAgent(row: AgentRow): Agent {providerId: row.providerId,switchAgentId: row.switchAgentId ?? null,apiEndpoint: row.apiEndpoint ?? null,- serverId: row.serverId ?? null,+ workspaceId: row.workspaceId ?? null,+ serverId,status: row.status ?? null,autoApprove: row.autoApprove,ownerName: row.ownerName ?? null,@@ -23,3 +30,8 @@ export function mapAgentRowToAgent(row: AgentRow): Agent {updatedAt: row.updatedAt,};}++/** {@link mapAgentRowToAgent} for one row, looking its server up. */+export async function mapAgentRow(row: AgentRow): Promise<Agent> {+ return mapAgentRowToAgent(row, await serverIdForWorkspace(row.workspaceId));+}diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline-matrix-migration.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline-matrix-migration.test.tsindex 296037cbf..c6ee45465 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline-matrix-migration.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline-matrix-migration.test.ts@@ -63,7 +63,6 @@ vi.mock('@main/core/switch-servers/servers-store', () => ({vi.mock('@main/core/switch-servers/auth', () => ({passwordLogin: () => Promise.resolve({ success: true }),}));-vi.mock('@main/core/agents/resolve-servers', () => ({ resolveAgentServers: vi.fn() }));vi.mock('./managed-upgrade', () => ({prepareUpgrade: prepareUpgradeMock,finishUpgrade: finishUpgradeMock,diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline.test.tsindex f5e827c8e..135275606 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline.test.ts@@ -69,7 +69,6 @@ vi.mock('@main/core/switch-servers/servers-store', () => ({vi.mock('@main/core/switch-servers/auth', () => ({passwordLogin: () => Promise.resolve({ success: true }),}));-vi.mock('@main/core/agents/resolve-servers', () => ({ resolveAgentServers: vi.fn() }));vi.mock('./managed-upgrade', () => ({prepareUpgrade: prepareUpgradeMock,finishUpgrade: finishUpgradeMock,diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline.tsindex 0982bfa60..51ffc8064 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline.ts@@ -1,4 +1,3 @@-import { resolveAgentServers } from '@main/core/agents/resolve-servers';import { passwordLogin } from '@main/core/switch-servers/auth';import { ensureManagedServer, setActiveServerId } from '@main/core/switch-servers/servers-store';import { log } from '@main/lib/logger';@@ -272,7 +271,6 @@ export async function startStack(opts: StartStackOptions): Promise<StartLocalSer});}- await resolveAgentServers();if (upgrade) await finishUpgrade(host);return { kind: 'started', serverId: server.id, telemetryEnabled };}diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.test.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.test.tsindex b7a2dbe99..c762cc7cb 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.test.ts@@ -4,6 +4,7 @@ import { adoptSubagent } from './adopt-subagent';const mocks = vi.hoisted(() => ({local: vi.fn(),+ workspace: vi.fn(),server: vi.fn(),remote: vi.fn(),create: vi.fn(),@@ -12,16 +13,17 @@ const mocks = vi.hoisted(() => ({}));vi.mock('@main/core/agents/agent-events', () => ({ agentEvents: { _emit: mocks.emit } }));vi.mock('@main/core/agents/createAgent', () => ({ createAgent: mocks.create }));-vi.mock('@main/core/agents/getAgents', () => ({ getLocationAgentsOnServer: mocks.local }));+vi.mock('@main/core/agents/getAgents', () => ({ getLocationAgentsInWorkspace: mocks.local }));vi.mock('@main/core/agents/remote-session-reconciler', () => ({remoteSessionReconciler: { start: mocks.start },}));vi.mock('@main/core/switch-servers/gateway-client', () => ({ fetchAgentDetail: mocks.remote }));vi.mock('@main/core/switch-servers/servers-store', () => ({ getServer: mocks.server }));+vi.mock('@main/core/workspaces/workspaces-store', () => ({ requireWorkspace: mocks.workspace }));const parent = {id: 'parent',locationId: 'location',- serverId: 'server',+ workspaceId: 'workspace',apiEndpoint: 'https://example.test/agent',providerId: 'claude',autoApprove: false,@@ -31,6 +33,7 @@ const parent = {beforeEach(() => {vi.resetAllMocks();mocks.local.mockResolvedValue([]);+ mocks.workspace.mockResolvedValue({ id: 'workspace', serverId: 'server' });mocks.server.mockResolvedValue({ id: 'server' });mocks.remote.mockResolvedValue({ id: 'child', ownerName: 'Owner' });mocks.create.mockImplementation(async (value) => ({ ...value, id: 'local-child' }));@@ -44,7 +47,7 @@ it('adopts the child identity and discovers its sessions using its own credentianame: 'reviewer',switchAgentId: 'child',providerId: 'claude',- serverId: 'server',+ workspaceId: 'workspace',autoApprove: false,providerConfig: parent.providerConfig,})diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.tsindex d0f6552ee..d69d0f911 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.ts@@ -1,10 +1,11 @@import { randomUUID } from 'node:crypto';import { agentEvents } from '@main/core/agents/agent-events';import { createAgent } from '@main/core/agents/createAgent';-import { getLocationAgentsOnServer } from '@main/core/agents/getAgents';+import { getLocationAgentsInWorkspace } from '@main/core/agents/getAgents';import { remoteSessionReconciler } from '@main/core/agents/remote-session-reconciler';import { fetchAgentDetail } from '@main/core/switch-servers/gateway-client';import { getServer } from '@main/core/switch-servers/servers-store';+import { requireWorkspace } from '@main/core/workspaces/workspaces-store';import type { Agent } from '@shared/core/agents/agents';export async function adoptSubagent(@@ -12,8 +13,8 @@ export async function adoptSubagent(name: string,switchAgentId: string): Promise<void> {- if (!parent.serverId) throw new Error('The subagent’s Switch server is missing.');- const local = await getLocationAgentsOnServer(parent.locationId, parent.serverId);+ if (!parent.workspaceId) throw new Error('The subagent’s Switch workspace is missing.');+ const local = await getLocationAgentsInWorkspace(parent.locationId, parent.workspaceId);const existing = local.find((agent) => agent.switchAgentId === switchAgentId);if (existing) {if (existing.name !== name || existing.providerId !== parent.providerId)@@ -23,7 +24,8 @@ export async function adoptSubagent(}if (local.some((agent) => agent.name === name))throw new Error('This subagent name is already linked to a different Switch identity.');- const server = await getServer(parent.serverId);+ const workspace = await requireWorkspace(parent.workspaceId);+ const server = await getServer(workspace.serverId);if (!server) throw new Error('The subagent’s Switch server is missing.');const remote = await fetchAgentDetail(server, switchAgentId);if (remote.id !== switchAgentId)@@ -35,7 +37,7 @@ export async function adoptSubagent(providerId: parent.providerId,switchAgentId,apiEndpoint: parent.apiEndpoint,- serverId: parent.serverId,+ workspaceId: parent.workspaceId,autoApprove: parent.autoApprove,ownerName: remote.ownerName,providerConfig: parent.providerConfig,diff --git a/console/apps/switch-console-desktop/src/main/core/sessions/session-join.ts b/console/apps/switch-console-desktop/src/main/core/sessions/session-join.tsindex 21ab50987..bba4c1bde 100644--- a/console/apps/switch-console-desktop/src/main/core/sessions/session-join.ts+++ b/console/apps/switch-console-desktop/src/main/core/sessions/session-join.ts@@ -1,6 +1,6 @@import { eq } from 'drizzle-orm';import { db } from '@main/db/client';-import { agents, sessions, type SessionRow } from '@main/db/schema';+import { agents, sessions, type SessionRow, workspaces } from '@main/db/schema';import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';export type SessionWithAgent = {@@ -10,9 +10,9 @@ export type SessionWithAgent = {/** The owning agent's `name` — the session's identity source. The creds slug* and `--agent` launch name derive from it, read live, not from a frozen tag. */name: string;- /** The registered Switch server the agent belongs to; null once that server- * has been removed, which leaves the agent's endpoint and token pointing at- * something that no longer exists. */+ /** The server hosting the agent's workspace; null once that server has been+ * removed, which leaves the agent's endpoint and token pointing at something+ * that no longer exists. */serverId: string | null;};@@ -29,10 +29,12 @@ export async function loadSessionWithAgent(locationId: agents.locationId,providerId: agents.providerId,name: agents.name,- serverId: agents.serverId,+ serverId: workspaces.serverId,}).from(sessions).innerJoin(agents, eq(sessions.agentId, agents.id))+ // Left: an unlinked agent has no workspace and its sessions still load.+ .leftJoin(workspaces, eq(agents.workspaceId, workspaces.id)).where(eq(sessions.id, sessionId)).limit(1);if (!joined) return undefined;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.tsindex 44875ad81..8412beec6 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@@ -8,7 +8,6 @@ const managedServerHostBlocked = vi.hoisted(() => vi.fn((): unknown => null));const fetchAuthConfig = vi.hoisted(() => vi.fn());const trackEvent = vi.hoisted(() => vi.fn());const addServer = vi.hoisted(() => vi.fn());-const resolveAgentServers = vi.hoisted(() => vi.fn());const passwordLogin = vi.hoisted(() => vi.fn());const createRoomOnServer = vi.hoisted(() => vi.fn());const deleteBridge = vi.hoisted(() => vi.fn());@@ -22,7 +21,6 @@ const serverKindOf = vi.hoisted(() => vi.fn(() => 'remote_managed'));// ssh / agent side effects at load.vi.mock('@main/core/agents/agent-defaults', () => ({ suggestAgentDefaults: vi.fn() }));vi.mock('@main/core/agents/propagate-server-api-url', () => ({ propagateServerApiUrl: vi.fn() }));-vi.mock('@main/core/agents/resolve-servers', () => ({ resolveAgentServers }));vi.mock('@main/core/agents/write-remote-switch-settings', () => ({writeRemoteSwitchSettings: vi.fn(),}));@@ -287,16 +285,11 @@ describe('adding a server by URL', () => {beforeEach(() => {vi.clearAllMocks();- resolveAgentServers.mockResolvedValue(undefined);});- it('keeps the add that worked when reconciling the agent links does not', async () => {- // The row is in; unlinking agents from servers that are gone is bookkeeping- // after the fact. Rejecting here would show the user a failure for a server- // they now have, and a second press would register it twice.+ it('reports the add that worked', async () => {const added = server({ id: 'new' });addServer.mockResolvedValue(added);- resolveAgentServers.mockRejectedValue(new Error('database is locked'));await expect(switchServersController.addServer(params)).resolves.toBe(added);expect(trackEvent).toHaveBeenCalledExactlyOnceWith('server_added', {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.tsindex ff872e675..3da6c8e02 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts@@ -1,6 +1,5 @@import type { Result } from '@switch-console/shared';import { propagateServerApiUrl } from '@main/core/agents/propagate-server-api-url';-import { resolveAgentServers } from '@main/core/agents/resolve-servers';import { appService } from '@main/core/app/service';import {isManagedServerRunning,@@ -19,7 +18,6 @@ import type {} from '@main/core/telemetry/events';import { roomAgentsDirectionOf } from '@main/core/telemetry/narrow';import { trackEvent } from '@main/core/telemetry/telemetry-service';-import { log } from '@main/lib/logger';import { HostUnreachableError } from '@shared/core/remote-hosts/reachability';import type {AddressingPolicy,@@ -287,23 +285,12 @@ export const switchServersController = createRPCController({throw error;}trackEvent('server_added', { server_kind: 'external', outcome: 'success' });- // The row has landed, so the server is added whatever happens next — this- // reconciliation only unlinks agents pointing at servers that are gone.- // Rejecting for it would tell the user their add failed while the store has- // already reported it as done, and leave them to press Add again, which- // registers the same server a second time rather than retrying the first.- try {- await resolveAgentServers();- } catch (error) {- log.warn('switch-servers: could not reconcile agent links after adding a server', { error });- }return server;},updateServer: async (params: UpdateServerParams): Promise<UpdateServerResult> => {const previous = await requireServer(params.id);const server = await updateServer(params);- await resolveAgentServers();// The API URL is what an agent's SWITCH_API_ENDPOINT points at. When it// changes, cascade it to every member agent's stored config so they don'tdiff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/delete-server-agents.db.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/delete-server-agents.db.test.tsindex 12c9aa201..d4a78cab5 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/delete-server-agents.db.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/delete-server-agents.db.test.ts@@ -2,7 +2,7 @@ import { openFixture } from '@tooling/utils/db';import { eq } from 'drizzle-orm';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 { agents, locations, switchServers, workspaces } from '@main/db/schema';const mocks = vi.hoisted(() => ({db: undefined as AppDb | undefined,@@ -44,6 +44,11 @@ describe('deleteAgentsForServer', () => {gatewayUrl: `https://${id}.example.com`,apiUrl: `https://api-${id}.example.com`,});+ // Deliberately not the server's id: the query has to reach the server+ // through the workspace, and identical ids would hide it not doing so.+ await fixture.db+ .insert(workspaces)+ .values({ id: `ws-${id}`, serverId: id, name: `Workspace ${id}` });}});@@ -53,9 +58,13 @@ describe('deleteAgentsForServer', () => {});async function seedAgent(id: string, serverId: string | null): Promise<void> {- await fixture.db- .insert(agents)- .values({ id, locationId: 'loc-1', name: id, providerId: 'claude', serverId });+ await fixture.db.insert(agents).values({+ id,+ locationId: 'loc-1',+ name: id,+ providerId: 'claude',+ workspaceId: serverId ? `ws-${serverId}` : null,+ });}it('deletes only the agents belonging to the given server', async () => {@@ -121,7 +130,7 @@ describe('deleteAgentsForServer', () => {const remaining = await fixture.db.select({ id: agents.id }).from(agents)- .where(eq(agents.serverId, 'other-1'));+ .where(eq(agents.workspaceId, 'ws-other-1'));expect(remaining).toEqual([{ id: 'agent-other' }]);});});diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/delete-server-agents.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/delete-server-agents.tsindex 6fd47dbde..2f0a08cf5 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/delete-server-agents.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/delete-server-agents.ts@@ -1,11 +1,11 @@import { eq } from 'drizzle-orm';import { deleteAgent } from '@main/core/agents/deleteAgent';import { db } from '@main/db/client';-import { agents } from '@main/db/schema';+import { agents, workspaces } from '@main/db/schema';import { log } from '@main/lib/logger';/**- * Delete every agent that belongs to a managed Switch server, as part of+ * Delete every agent in every workspace of a managed Switch server, as part of* destroying that server's stack.** Wiping a managed stack destroys the server-side identity behind each of its@@ -33,7 +33,8 @@ export async function deleteAgentsForServer(const rows = await db.select({ id: agents.id, name: agents.name }).from(agents)- .where(eq(agents.serverId, serverId));+ .innerJoin(workspaces, eq(agents.workspaceId, workspaces.id))+ .where(eq(workspaces.serverId, serverId));const deleted: string[] = [];const failed: { agentId: string; error: string }[] = [];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.tsindex 2102d693d..2474f01b4 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@@ -2,7 +2,7 @@ import { openFixture } from '@tooling/utils/db';import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { AppDb } from '@main/db/client';-import { agents, kv, locations, switchServers } from '@main/db/schema';+import { agents, kv, locations, switchServers, workspaces } from '@main/db/schema';const mocks = vi.hoisted(() => ({db: undefined as AppDb | undefined,@@ -225,6 +225,10 @@ describe('servers-store: rename & delete', () => {});it('unlinks the server’s agents (keeps them), deletes the row, and clears the active pointer', async () => {+ // The unlink is two foreign keys deep — the server's workspaces cascade,+ // and their agents are set null — so this one test needs the engine to be+ // enforcing them.+ fixture.sqlite.pragma('foreign_keys = ON');await fixture.db.insert(locations).values({ id: 'loc-1', name: 'Loc', sshHost: '', dir: '/repo/loc-1' });@@ -234,25 +238,41 @@ describe('servers-store: rename & delete', () => {gatewayUrl: 'https://gw.example.com',apiUrl: 'https://api.example.com',});+ await fixture.db.insert(workspaces).values({ id: 'ws-1', serverId: 'srv-1', name: 'Server' });await fixture.db.insert(agents).values([- { id: 'agent-1', locationId: 'loc-1', name: 'A', providerId: 'claude', serverId: 'srv-1' },- { id: 'agent-2', locationId: 'loc-1', name: 'B', providerId: 'claude', serverId: 'srv-1' },+ {+ id: 'agent-1',+ locationId: 'loc-1',+ name: 'A',+ providerId: 'claude',+ workspaceId: 'ws-1',+ },+ {+ id: 'agent-2',+ locationId: 'loc-1',+ name: 'B',+ providerId: 'claude',+ workspaceId: 'ws-1',+ },]);- await fixture.db.insert(kv).values({ key: 'activeSwitchServerId', value: 'srv-1' });+ await fixture.db.insert(kv).values({ key: 'activeWorkspaceId', value: 'ws-1' });await removeServer('srv-1');const remainingServers = await fixture.db.select().from(switchServers);expect(remainingServers).toHaveLength(0);+ const remainingWorkspaces = await fixture.db.select().from(workspaces);+ expect(remainingWorkspaces).toHaveLength(0);+const remainingAgents = await fixture.db.select().from(agents);expect(remainingAgents).toHaveLength(2);- expect(remainingAgents.every((a) => a.serverId === null)).toBe(true);+ expect(remainingAgents.every((a) => a.workspaceId === null)).toBe(true);const [activePointer] = await fixture.db.select().from(kv)- .where(eq(kv.key, 'activeSwitchServerId'));+ .where(eq(kv.key, 'activeWorkspaceId'));expect(activePointer).toBeUndefined();expect(secretMocks.deleteSecret).toHaveBeenCalledWith('switch-server-cookie:srv-1');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.tsindex 9c027fa26..69d3852aa 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/servers-store.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/servers-store.ts@@ -3,8 +3,18 @@ import { and, desc, eq, isNull, ne, or, sql } from 'drizzle-orm';import { encryptedAppSecretsStore } from '@main/core/secrets/encrypted-app-secrets-store';import type { TelemetryEventMap } from '@main/core/telemetry/events';import { trackEvent } from '@main/core/telemetry/telemetry-service';+import {+ clearActiveWorkspaceOnServer,+ ensureServerWorkspace,+ getActiveWorkspaceId,+ insertServerWorkspace,+ renameServerWorkspaces,+ requireSoleWorkspaceForServer,+ serverIdForWorkspace,+ setActiveWorkspaceId,+} from '@main/core/workspaces/workspaces-store';import { db } from '@main/db/client';-import { agents, kv, type SwitchServerRow, switchServers } from '@main/db/schema';+import { type SwitchServerRow, switchServers } from '@main/db/schema';import {urlOrigin,type AddServerParams,@@ -14,8 +24,8 @@ import {type UpdateServerParams,} from '@shared/core/switch-servers/switch-servers';-const ACTIVE_SERVER_KV_KEY = 'activeSwitchServerId';-+// Keyed to the server, not the workspace: one gateway session cookie covers+// every workspace on a server.function cookieSecretKey(serverId: string): string {return `switch-server-cookie:${serverId}`;}@@ -142,7 +152,9 @@ export async function ensureManagedServer(}).where(eq(switchServers.id, existing.id)).returning();- return mapRow(row);+ const server = mapRow(row);+ await ensureServerWorkspace(server);+ return server;}const [row] = await db.insert(switchServers)@@ -157,13 +169,15 @@ export async function ensureManagedServer(updatedAt: sql`CURRENT_TIMESTAMP`,}).returning();+ const server = mapRow(row);+ await ensureServerWorkspace(server);// Only the insert: this function also runs on every restart of a stack that// already exists, and that is not a server being added.trackEvent('server_added', {server_kind: ref.kind === 'remote' ? 'remote_managed' : 'local',outcome: 'success',});- return mapRow(row);+ return server;}async function getServerByGatewayUrl(gatewayUrl: string): Promise<SwitchServer | null> {@@ -176,22 +190,28 @@ async function getServerByGatewayUrl(gatewayUrl: string): Promise<SwitchServer |}export async function addServer(params: AddServerParams): Promise<SwitchServer> {- const [row] = await db- .insert(switchServers)- .values({- id: randomUUID(),- name: params.name.trim(),- gatewayUrl: normaliseUrl(params.gatewayUrl),- apiUrl: normaliseUrl(params.apiUrl),- updatedAt: sql`CURRENT_TIMESTAMP`,- })- .returning();+ const server = db.transaction((tx) => {+ const [row] = tx+ .insert(switchServers)+ .values({+ id: randomUUID(),+ name: params.name.trim(),+ gatewayUrl: normaliseUrl(params.gatewayUrl),+ apiUrl: normaliseUrl(params.apiUrl),+ updatedAt: sql`CURRENT_TIMESTAMP`,+ })+ .returning()+ .all();+ const inserted = mapRow(row!);+ insertServerWorkspace(tx, inserted);+ return inserted;+ });// Not reported here, unlike the managed insert above: registering a URL is a// discrete action with one caller, so the controller reports both of its// outcomes together and a single Add cannot produce two events. The managed// kinds have no such single owner — two services call that path and so does// every restart — which is why it is reported at the insert instead.- return mapRow(row);+ return server;}export async function updateServer(params: UpdateServerParams): Promise<SwitchServer> {@@ -208,6 +228,7 @@ export async function updateServer(params: UpdateServerParams): Promise<SwitchSeif (!row) {throw new Error(`No Switch server with id ${params.id}`);}+ await renameServerWorkspaces(params.id, params.name.trim());return mapRow(row);}@@ -220,6 +241,7 @@ export async function renameServer(params: RenameServerParams): Promise<SwitchSeif (!row) {throw new Error(`No Switch server with id ${params.id}`);}+ await renameServerWorkspaces(params.id, params.name.trim());return mapRow(row);}@@ -229,13 +251,11 @@ export async function removeServer(id: string): Promise<void> {const server = await getServer(id).catch(() => null);await deleteSessionCookie(id);- // Unlink agents explicitly: SQLite's ALTER TABLE ADD COLUMN can't carry an- // ON DELETE clause, so the FK's set-null isn't enforced by the engine.- await db.update(agents).set({ serverId: null }).where(eq(agents.serverId, id));+ // Before the delete, while the server's workspaces are still readable.+ await clearActiveWorkspaceOnServer(id);+ // Deleting the server takes its workspaces with it and unlinks their agents,+ // both by foreign key: workspaces cascade, agents are set null.await db.delete(switchServers).where(eq(switchServers.id, id));- if ((await getActiveServerId()) === id) {- await db.delete(kv).where(eq(kv.key, ACTIVE_SERVER_KV_KEY));- }// Removing an already-absent server is not a server being removed.if (server) trackEvent('server_removed', { server_kind: serverKindOf(server) });@@ -249,23 +269,26 @@ 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 [row] = await db.select().from(kv).where(eq(kv.key, ACTIVE_SERVER_KV_KEY)).limit(1);- return row?.value ?? null;+ const activeWorkspaceId = await getActiveWorkspaceId();+ if (!activeWorkspaceId) return null;+ return serverIdForWorkspace(activeWorkspaceId);}+/** Select a server by selecting its workspace. */export async function setActiveServerId(id: string): Promise<void> {const server = await getServer(id);- if (!server) {- throw new Error(`No Switch server with id ${id}`);- }- await db- .insert(kv)- .values({ key: ACTIVE_SERVER_KV_KEY, value: id, updatedAt: sql`CURRENT_TIMESTAMP` })- .onConflictDoUpdate({- target: kv.key,- set: { value: id, updatedAt: sql`CURRENT_TIMESTAMP` },- });+ if (!server) throw new Error(`No Switch server with id ${id}`);+ const workspace = await requireSoleWorkspaceForServer(id);+ await setActiveWorkspaceId(workspace.id);}// ---------------------------------------------------------------------------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.tsnew file mode 100644index 000000000..1ab23794a--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/workspaces-store.db.test.ts@@ -0,0 +1,204 @@+import { openFixture } from '@tooling/utils/db';+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { AppDb } from '@main/db/client';+import { kv, switchServers, workspaces } from '@main/db/schema';++const mocks = vi.hoisted(() => ({+ db: undefined as AppDb | undefined,+}));++vi.mock('@main/db/client', () => ({+ get db() {+ if (!mocks.db) throw new Error('Test database not initialized');+ return mocks.db;+ },+}));++const {+ clearActiveWorkspaceOnServer,+ ensureServerWorkspace,+ getActiveWorkspaceId,+ listWorkspacesForServer,+ renameServerWorkspaces,+ requireSoleWorkspaceForServer,+ requireWorkspace,+ serverIdForWorkspace,+ setActiveWorkspaceId,+} = await import('./workspaces-store');++describe('workspaces-store', () => {+ let fixture: Awaited<ReturnType<typeof openFixture>>;++ beforeEach(async () => {+ fixture = await openFixture('empty');+ mocks.db = fixture.db;+ fixture.sqlite.pragma('foreign_keys = ON');+ });++ afterEach(() => {+ fixture.close();+ mocks.db = undefined;+ });++ async function seedServer(id: string, name: string): Promise<void> {+ await fixture.db.insert(switchServers).values({+ id,+ name,+ gatewayUrl: `https://${id}.example.com`,+ apiUrl: `https://api-${id}.example.com`,+ });+ }++ describe('ensureServerWorkspace', () => {+ it('gives a newly registered server one workspace, named after it', async () => {+ await seedServer('srv-1', 'Local dev');++ const workspace = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });++ expect(workspace.serverId).toBe('srv-1');+ expect(workspace.name).toBe('Local dev');+ expect(workspace.tenantId).toBeNull();+ expect(workspace.slug).toBeNull();+ expect(workspace.role).toBeNull();+ });++ // The managed-server paths run again on every restart of a stack that+ // already exists, and a second workspace would silently split its agents.+ it('returns the existing workspace instead of adding a second', async () => {+ await seedServer('srv-1', 'Local dev');+ const first = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });++ const again = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });++ expect(again.id).toBe(first.id);+ expect(await listWorkspacesForServer('srv-1')).toHaveLength(1);+ });++ /**+ * The table's other unique index is on (server_id, tenant_id), and SQLite+ * treats NULLs as distinct, so it lets a second tenant-less row through.+ * Reconcile repairs the one unmatched row it finds; a second would be left+ * behind belonging to no membership, and every call scoped to it refused.+ */+ it('refuses a second tenant-less workspace on the same server', async () => {+ await seedServer('srv-1', 'Local dev');+ await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });++ await expect(+ fixture.db.insert(workspaces).values({ id: 'ws-2', serverId: 'srv-1', name: 'Local dev' })+ ).rejects.toThrow(/UNIQUE/);+ });+ });++ describe('requireSoleWorkspaceForServer', () => {+ 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);+ });++ 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');+ });++ // 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 () => {+ 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 expect(requireSoleWorkspaceForServer('srv-1')).rejects.toThrow('must name one');+ });+ });++ describe('renameServerWorkspaces', () => {+ it('carries the new server name onto the workspace that took its name from it', async () => {+ await seedServer('srv-1', 'Old name');+ await ensureServerWorkspace({ id: 'srv-1', name: 'Old name' });++ await renameServerWorkspaces('srv-1', 'New name');++ expect((await listWorkspacesForServer('srv-1'))[0]!.name).toBe('New name');+ });++ // Once matched to a tenant the name is the gateway's, not the server's.+ it('leaves a tenant-bound workspace’s own name alone', async () => {+ await seedServer('srv-1', 'Old name');+ await fixture.db+ .insert(workspaces)+ .values({ id: 'ws-a', serverId: 'srv-1', name: 'Platform', tenantId: 'tenant-a' });++ await renameServerWorkspaces('srv-1', 'New name');++ expect((await listWorkspacesForServer('srv-1'))[0]!.name).toBe('Platform');+ });+ });++ describe('serverIdForWorkspace', () => {+ it('finds the server hosting a workspace', async () => {+ await seedServer('srv-1', 'Local dev');+ const created = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });++ expect(await serverIdForWorkspace(created.id)).toBe('srv-1');+ });++ it('answers null for an agent with no workspace', async () => {+ expect(await serverIdForWorkspace(null)).toBeNull();+ });+ });++ describe('the active selection', () => {+ it('round-trips a workspace id', async () => {+ await seedServer('srv-1', 'Local dev');+ const created = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });++ await setActiveWorkspaceId(created.id);++ expect(await getActiveWorkspaceId()).toBe(created.id);+ });++ it('refuses to select a workspace that does not exist', async () => {+ await expect(setActiveWorkspaceId('ws-missing')).rejects.toThrow('No workspace with id');+ });++ // The selection is a plain kv value; nothing cascades to it when the+ // server, and with it the workspace, is deleted.+ it('is cleared when the server holding the selected workspace goes', async () => {+ await seedServer('srv-1', 'Local dev');+ const created = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });+ await setActiveWorkspaceId(created.id);++ await clearActiveWorkspaceOnServer('srv-1');++ expect(await getActiveWorkspaceId()).toBeNull();+ expect(await fixture.db.select().from(kv).where(eq(kv.key, 'activeWorkspaceId'))).toEqual([]);+ });++ it('survives another server being removed', async () => {+ await seedServer('srv-1', 'Local dev');+ await seedServer('srv-2', 'Cloud');+ const created = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });+ await ensureServerWorkspace({ id: 'srv-2', name: 'Cloud' });+ await setActiveWorkspaceId(created.id);++ await clearActiveWorkspaceOnServer('srv-2');++ expect(await getActiveWorkspaceId()).toBe(created.id);+ });+ });++ describe('requireWorkspace', () => {+ it('names the id it could not find', async () => {+ await expect(requireWorkspace('ws-missing')).rejects.toThrow(+ 'No workspace with id ws-missing'+ );+ });+ });+});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.tsnew file mode 100644index 000000000..9fca13b7d--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/workspaces-store.ts@@ -0,0 +1,189 @@+import { randomUUID } from 'node:crypto';+import { and, asc, eq, isNull, sql } from 'drizzle-orm';+import { db, type DrizzleTx } from '@main/db/client';+import { kv, type WorkspaceRow, workspaces } from '@main/db/schema';+import type { Workspace } from '@shared/core/workspaces/workspaces';++const ACTIVE_WORKSPACE_KV_KEY = 'activeWorkspaceId';++function mapRow(row: WorkspaceRow): Workspace {+ return {+ id: row.id,+ serverId: row.serverId,+ name: row.name,+ tenantId: row.tenantId ?? null,+ slug: row.slug ?? null,+ role: row.role ?? null,+ createdAt: row.createdAt,+ updatedAt: row.updatedAt,+ };+}++export async function listWorkspaces(): Promise<Workspace[]> {+ const rows = await db.select().from(workspaces).orderBy(asc(workspaces.createdAt));+ return rows.map(mapRow);+}++export async function listWorkspacesForServer(serverId: string): Promise<Workspace[]> {+ const rows = await db+ .select()+ .from(workspaces)+ .where(eq(workspaces.serverId, serverId))+ .orderBy(asc(workspaces.createdAt));+ return rows.map(mapRow);+}++export async function getWorkspace(id: string): Promise<Workspace | null> {+ const [row] = await db.select().from(workspaces).where(eq(workspaces.id, id)).limit(1);+ return row ? mapRow(row) : null;+}++export async function requireWorkspace(id: string): Promise<Workspace> {+ const workspace = await getWorkspace(id);+ if (!workspace) throw new Error(`No workspace with id ${id}`);+ return workspace;+}++/**+ * The one workspace on a server, for a caller that knows only the server.+ *+ * 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.+ *+ * 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.+ */+export async function requireSoleWorkspaceForServer(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`);+ throw new Error(+ `Switch server ${serverId} has ${found.length} workspaces; the caller must name one`+ );+}++/**+ * Give a newly registered server its workspace, reusing the one it already has.+ *+ * Registering a server is what creates its first workspace — the gateway is+ * only asked which tenants the user belongs to afterwards, and the app has to+ * be usable before that answer arrives. The row starts tenant-less and named+ * after the server; a reconcile matches it to a tenant rather than replacing+ * it, so the agents pointing at it stay pointed at it.+ *+ * Idempotent, because the managed-server paths run again on every restart of a+ * stack that already exists. The read and the insert share one transaction, so+ * two of those restarts overlapping cannot each find no row and each create+ * one; the partial unique index on the table is the backstop for anything that+ * writes outside this function.+ */+export async function ensureServerWorkspace(server: {+ id: string;+ name: string;+}): Promise<Workspace> {+ return db.transaction((tx) => {+ const [existing] = tx+ .select()+ .from(workspaces)+ .where(eq(workspaces.serverId, server.id))+ .orderBy(asc(workspaces.createdAt))+ .limit(1)+ .all();+ return existing ? mapRow(existing) : insertServerWorkspace(tx, server);+ });+}++/**+ * The insert half of `ensureServerWorkspace`, so a caller registering a server+ * can create both rows in one transaction.+ *+ * A server row without a workspace cannot be used for anything — every path+ * that reaches a gateway resolves a workspace first — and nothing outside+ * registration creates one, so the two rows have to arrive together or not at+ * all.+ */+export function insertServerWorkspace(+ tx: DrizzleTx,+ server: { id: string; name: string }+): Workspace {+ const [row] = tx+ .insert(workspaces)+ .values({+ id: randomUUID(),+ serverId: server.id,+ name: server.name,+ updatedAt: sql`CURRENT_TIMESTAMP`,+ })+ .returning()+ .all();+ return mapRow(row!);+}++/**+ * Carry a server rename onto the workspaces that take their name from it.+ *+ * A tenant-less workspace has no name of its own — it was created named after+ * its server and nothing else has supplied one. Once matched to a tenant the+ * name is the gateway's, and a server rename must not overwrite it.+ */+export async function renameServerWorkspaces(serverId: string, name: string): Promise<void> {+ await db+ .update(workspaces)+ .set({ name, updatedAt: sql`CURRENT_TIMESTAMP` })+ .where(and(eq(workspaces.serverId, serverId), isNull(workspaces.tenantId)));+}++/**+ * The server hosting a workspace, or null when there is no workspace to ask+ * about — an agent that has not been attached to one.+ *+ * A workspace id that names no row is a different thing entirely, and raises:+ * the agents' foreign key means it cannot happen, so if it does the caller is+ * holding an id from somewhere the database does not know about, and answering+ * "no server" would send it on to fail somewhere further away.+ */+export async function serverIdForWorkspace(workspaceId: string | null): Promise<string | null> {+ if (!workspaceId) return null;+ const [row] = await db+ .select({ serverId: workspaces.serverId })+ .from(workspaces)+ .where(eq(workspaces.id, workspaceId))+ .limit(1);+ if (!row) throw new Error(`No workspace with id ${workspaceId}`);+ return row.serverId;+}++export async function getActiveWorkspaceId(): Promise<string | null> {+ const [row] = await db.select().from(kv).where(eq(kv.key, ACTIVE_WORKSPACE_KV_KEY)).limit(1);+ return row?.value ?? null;+}++export async function setActiveWorkspaceId(id: string): Promise<void> {+ await requireWorkspace(id);+ await db+ .insert(kv)+ .values({ key: ACTIVE_WORKSPACE_KV_KEY, value: id, updatedAt: sql`CURRENT_TIMESTAMP` })+ .onConflictDoUpdate({+ target: kv.key,+ set: { value: id, updatedAt: sql`CURRENT_TIMESTAMP` },+ });+}++/**+ * Drop the active selection if it names one of a server's workspaces.+ *+ * Removing a server takes its workspaces with it (the foreign key cascades),+ * and the selection is a plain `kv` value that nothing cascades to — so it has+ * to be cleared here, while the workspaces are still readable.+ */+export async function clearActiveWorkspaceOnServer(serverId: string): Promise<void> {+ const active = await getActiveWorkspaceId();+ if (!active) return;+ const onServer = (await listWorkspacesForServer(serverId)).some((w) => w.id === active);+ if (onServer) await db.delete(kv).where(eq(kv.key, ACTIVE_WORKSPACE_KV_KEY));+}diff --git a/console/apps/switch-console-desktop/src/main/db/schema.ts b/console/apps/switch-console-desktop/src/main/db/schema.tsindex 97855199a..d88ef167d 100644--- a/console/apps/switch-console-desktop/src/main/db/schema.ts+++ b/console/apps/switch-console-desktop/src/main/db/schema.ts@@ -4,6 +4,7 @@ import { versionedJsonColumn } from '@main/db/versioned-column';import { agentProviderConfig } from '@shared/core/agents/agent-provider-config';import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';import { sessionConfig } from '@shared/core/sessions/session-config';+import type { WorkspaceRole } from '@shared/core/workspaces/workspaces';// ---------------------------------------------------------------------------// Data model (Switch Console rework — diverges from upstream; see@@ -135,17 +136,21 @@ export const switchServers = sqliteTable(* in `kv` under `activeWorkspaceId`). Switching workspace swaps the whole* window — agents, rooms, sidebar — the way switching server used to.*- * `tenantId` is the workspace's id on the gateway, and is null when the server- * reports no tenancy: there the workspace *is* the whole server, which is every- * server registered before multi-tenancy and every self-hosted install that- * never turns it on. Workspaces are discovered from the gateway rather than- * created by hand, so a server that gains tenancy later fills in the ids on its- * next reconcile without the user doing anything.+ * `tenantId` is the workspace's id on the gateway. It is null only until the+ * gateway has been asked: a workspace is created locally the moment a server is+ * registered, because the app has to be usable before the answer arrives, and+ * the upgrade to workspaces created one per already-registered server the same+ * way. Every deployed Switch server has tenancy — the backend migration that+ * introduced it puts every existing user in a tenant — so a tenant-less row is+ * a workspace that has not reconciled yet, not a server without tenants.+ *+ * Reconcile therefore has to *match* that row to a tenant rather than insert+ * the real workspace beside it: the row's id is what every agent points at, and+ * the (server, tenant) unique index cannot catch a duplicate here because+ * SQLite treats NULLs as distinct.** `slug` is the gateway's handle for the workspace; null alongside a null- * `tenantId`. The (server, tenant) pair is unique so a reconcile can upsert on- * it, with tenant-less rows excluded from the index — SQLite treats NULLs as- * distinct, which is what lets the one-per-server legacy row coexist.+ * `tenantId`.*/export const workspaces = sqliteTable('workspaces',@@ -164,7 +169,7 @@ export const workspaces = sqliteTable(* (`owner` / `admin` / `member`). Null for a tenant-less workspace, where* the notion does not apply.*/- role: text('role'),+ role: text('role').$type<WorkspaceRole>(),createdAt: text('created_at').notNull().default(sql`CURRENT_TIMESTAMP`),@@ -175,6 +180,13 @@ export const workspaces = sqliteTable((table) => ({serverIdIdx: index('idx_workspaces_server_id').on(table.serverId),serverTenantIdx: uniqueIndex('idx_workspaces_server_tenant').on(table.serverId, table.tenantId),+ // A server has at most one unreconciled row. The index above cannot say so,+ // because SQLite treats NULLs as distinct, so two registrations racing on+ // the same server would each insert a placeholder and reconcile would only+ // ever repair the first one it found.+ serverPlaceholderIdx: uniqueIndex('idx_workspaces_server_placeholder')+ .on(table.serverId)+ .where(sql`tenant_id IS NULL`),}));@@ -185,12 +197,10 @@ export const workspaces = sqliteTable(* the location dir is configured as a Switch agent (detected from* `.claude/settings.local.json`); they are null for a plain local agent.*- * `workspaceId` binds the agent to the one workspace it belongs to. It is- * resolved by matching the detected `apiEndpoint` against the registered- * servers' origins and then the server's active workspace. It is nullable: an- * agent whose workspace is not (or no longer) registered is shown as "unlinked"- * rather than guessed, and removing a workspace sets its agents' `workspaceId`- * to null instead of deleting them.+ * `workspaceId` binds the agent to the one workspace it belongs to, chosen and+ * verified at onboarding rather than inferred. It is nullable: an agent whose+ * workspace is gone is shown as "unlinked" rather than guessed, and removing a+ * server sets its workspaces' agents to null instead of deleting them.*/export const agents = sqliteTable('agents',diff --git a/console/apps/switch-console-desktop/src/main/db/tests/migrations/0051-workspaces.test.ts b/console/apps/switch-console-desktop/src/main/db/tests/migrations/0051-workspaces.test.tsindex dd6d49361..34ca4f80d 100644--- a/console/apps/switch-console-desktop/src/main/db/tests/migrations/0051-workspaces.test.ts+++ b/console/apps/switch-console-desktop/src/main/db/tests/migrations/0051-workspaces.test.ts@@ -136,7 +136,9 @@ describe('migration 0051: workspaces', () => {expect(workspace!.id).toBe('srv-local');});- it('leaves the migrated workspaces tenant-less, since the server reported no tenancy', () => {+ // No gateway is asked during the upgrade — it must not depend on one being+ // reachable — so the tenant is filled in by the first reconcile, not here.+ it('leaves the migrated workspaces tenant-less for the first reconcile to match', () => {seedServer('srv-local', 'Local dev');applyMigration();@@ -179,6 +181,30 @@ describe('migration 0051: workspaces', () => {expect(row.workspace_id).toBeNull();});+ // The old server_id was added by ALTER TABLE ADD COLUMN, which in SQLite+ // cannot carry ON DELETE, so its set-null was never enforced and a row can+ // point at a server that is gone. Carrying that value over would seed the new,+ // engine-enforced foreign key with a violation, and the migration runs with+ // foreign_keys=OFF, so nothing would catch it until much later.+ it('drops an agent’s link to a server that no longer exists', () => {+ seedServer('srv-local', 'Local dev');+ seedAgent('agent-a', 'srv-local');+ // The dangling value has to be written with the constraint off, which is+ // how it arises: the real column was added by ALTER TABLE, so the engine+ // never enforced the clause this fixture's DDL can only state up front.+ db.exec('PRAGMA foreign_keys = OFF');+ db.prepare(`UPDATE agents SET server_id = 'srv-gone' WHERE id = 'agent-a'`).run();++ applyMigration();+ db.exec('PRAGMA foreign_keys = ON');++ const row = db.prepare(`SELECT workspace_id FROM agents WHERE id = 'agent-a'`).get() as {+ workspace_id: string | null;+ };+ expect(row.workspace_id).toBeNull();+ expect(db.prepare(`PRAGMA foreign_key_check`).all()).toEqual([]);+ });+it('carries every other agent column through the table rebuild', () => {seedServer('srv-local', 'Local dev');db.prepare(@@ -272,6 +298,22 @@ describe('migration 0051: workspaces', () => {expect(workspaces()).toEqual([]);});+ // Two foreign keys deep, and the one the old schema only claimed: the server's+ // workspaces cascade away, and their agents are unlinked rather than deleted.+ it('unlinks an agent when the server under its workspace is deleted', () => {+ seedServer('srv-local', 'Local dev');+ seedAgent('agent-a', 'srv-local');+ applyMigration();+ db.exec('PRAGMA foreign_keys = ON');++ db.prepare(`DELETE FROM switch_servers WHERE id = ?`).run('srv-local');++ const row = db.prepare(`SELECT workspace_id FROM agents WHERE id = 'agent-a'`).get() as {+ workspace_id: string | null;+ };+ expect(row.workspace_id).toBeNull();+ });+it('lets two servers each keep a tenant-less workspace', () => {seedServer('srv-a', 'A');seedServer('srv-b', 'B');diff --git a/console/apps/switch-console-desktop/src/main/index.ts b/console/apps/switch-console-desktop/src/main/index.tsindex a21936552..2dd171707 100644--- a/console/apps/switch-console-desktop/src/main/index.ts+++ b/console/apps/switch-console-desktop/src/main/index.ts@@ -13,7 +13,6 @@ import { createMainWindow, getMainWindow } from './app/window';import { bridgeAgentEventsToRenderer } from './core/agents/agent-events-renderer-bridge';import { migrateAgentStorage } from './core/agents/migrate-agent-storage';import { initializeRemoteDiscovery, initializeRemoteWatchers } from './core/agents/remote-watcher';-import { resolveAgentServers } from './core/agents/resolve-servers';import { appService } from './core/app/service';import { controlService } from './core/control-api/control-service';import { localDependencyManager } from './core/dependencies/dependency-managers';@@ -144,12 +143,6 @@ void app.whenReady().then(async () => {registerTelemetryListeners();trackEvent('app_launched', {});- try {- await resolveAgentServers();- } catch (e) {- log.warn('switch-agents: failed to reconcile agent → server links at boot', { error: e });- }-// Kept off the boot path: this can open an SSH/SFTP connection per remote// agent, so awaiting it here delayed the window opening. Session relaunch below// waits on it (it needs each agent's definitionName); nothing else does.diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/stores/location-manager.test.ts b/console/apps/switch-console-desktop/src/renderer/features/locations/stores/location-manager.test.tsindex 5954402f8..73e36e19b 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/stores/location-manager.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/stores/location-manager.test.ts@@ -74,6 +74,7 @@ function agent(overrides: Partial<Agent> = {}): Agent {providerId: 'claude',switchAgentId: 'sw-1',apiEndpoint: 'https://switch.example.com',+ workspaceId: 'workspace-1',serverId: 'server-1',status: null,autoApprove: false,diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/palette-agent-icon.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/palette-agent-icon.test.tsxindex 59b5e5d75..d061e01f2 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/palette-agent-icon.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/palette-agent-icon.test.tsx@@ -33,6 +33,7 @@ const AGENT: Agent = {providerId: 'claude',switchAgentId: SWITCH_AGENT_ID,apiEndpoint: 'https://switch.example',+ workspaceId: 'workspace-1',serverId: SERVER_ID,status: null,autoApprove: false,diff --git a/console/apps/switch-console-desktop/src/shared/core/agents/agents.ts b/console/apps/switch-console-desktop/src/shared/core/agents/agents.tsindex 58d073034..89bb53a83 100644--- a/console/apps/switch-console-desktop/src/shared/core/agents/agents.ts+++ b/console/apps/switch-console-desktop/src/shared/core/agents/agents.ts@@ -6,9 +6,8 @@ import type { AgentProviderId } from '@shared/core/providers/agent-provider-regi* location (a working directory on this machine or an SSH host). Many agents* may share a location. `switchAgentId` / `apiEndpoint` carry the Switch* identity detected from the location dir's `.claude/settings.local.json`.- * `serverId` is the registered Switch server the agent belongs to (resolved- * from `apiEndpoint`); null means unlinked — the server it points at is not- * registered in this app.+ * `workspaceId` is the workspace the agent belongs to; null means unlinked —+ * the workspace it was in is no longer registered in this app.*/export type Agent = {id: string;@@ -20,6 +19,12 @@ export type Agent = {providerId: AgentProviderId;switchAgentId: string | null;apiEndpoint: string | null;+ workspaceId: string | null;+ /**+ * The server hosting `workspaceId`, denormalised onto the agent: null exactly+ * when `workspaceId` is. Reaching an agent's gateway means reaching its+ * workspace's server, and this saves every caller repeating that one hop.+ */serverId: string | null;status: string | null;/** When true, Switch Console launches this agent's CLI with its auto-approve /@@ -43,10 +48,10 @@ export type CreateAgentParams = {providerId: AgentProviderId;switchAgentId: string | null;apiEndpoint: string | null;- /** The Switch server this agent belongs to. Every agent must have one — it is+ /** The workspace this agent belongs to. Every agent must have one — it is* chosen and verified at onboarding (legacy rows may still be null until the* user assigns one). */- serverId: string;+ workspaceId: string;/** Seed for the per-agent bypass-permissions flag: false for local agents,* true for remote agents. */autoApprove: boolean;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.tsnew file mode 100644index 000000000..ea228ca9f--- /dev/null+++ b/console/apps/switch-console-desktop/src/shared/core/workspaces/workspaces.ts@@ -0,0 +1,34 @@+/**+ * Shared types for workspaces: what a Switch Console window is scoped to, and+ * the thing agents belong to.+ *+ * A workspace sits one level below a registered server. On a server with+ * tenancy it mirrors a tenant the signed-in user is a member of; the server's+ * own identity (its URLs, its session cookie, its auth method) stays at the+ * server, because one session cookie covers every workspace on it.+ */++/** The caller's standing in a workspace, as the gateway reports it. */+export type WorkspaceRole = 'owner' | 'admin' | 'member';++/** A workspace on a registered Switch server. */+export type Workspace = {+ id: string;+ serverId: string;+ name: string;+ /**+ * The workspace's tenant id on the gateway.+ *+ * Null means the workspace has not been matched to a tenant yet — the state+ * every workspace starts in, since one is created locally the moment a server+ * is registered and the gateway is only asked afterwards. It is a transient+ * "not reconciled yet", not a description of the server.+ */+ 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. */+ role: WorkspaceRole | null;+ createdAt: string;+ updatedAt: string;+};