Skip to content

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

feat(console): match a server's workspaces to the account's memberships

Petr Bauch2fd226d86a13
diff --git a/console/.gitignore b/console/.gitignore
index a8e608708..234ec9fc2 100644
--- a/console/.gitignore
+++ b/console/.gitignore
@@ -115,4 +115,5 @@ apps/*/tooling/node-deps/node_modules/
# Vitest / Browser testing
.vitest-attachments/
+.vitest/
**/__screenshots__/
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.test.ts
index c92c0f62f..62aa2b17b 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.test.ts
@@ -9,6 +9,7 @@ const fetchAuthConfig = vi.hoisted(() => vi.fn());
const trackEvent = vi.hoisted(() => vi.fn());
const addServer = vi.hoisted(() => vi.fn());
const passwordLogin = vi.hoisted(() => vi.fn());
+const reconcileServerWorkspaces = vi.hoisted(() => vi.fn());
// Stubbed rather than reimplemented: what the tests below assert is that the
// kind reaches the event, not how a row is read as one.
const serverKindOf = vi.hoisted(() => vi.fn(() => 'remote_managed'));
@@ -30,6 +31,10 @@ vi.mock('@main/core/managed-switch-server/managed-server-status', () => ({
isManagedServerRunning,
managedServerHostBlocked,
}));
+// Reads this install's own workspace rows, and through them the database client.
+vi.mock('@main/core/workspaces/reconcile-workspaces', () => ({
+ reconcileServerWorkspaces,
+}));
// Writes to the app's log file, which a test has no business creating.
vi.mock('@main/lib/logger', () => ({
log: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() },
@@ -196,6 +201,58 @@ describe('an action a server whose host has gone down cannot take', () => {
});
});
+/**
+ * Signing in is the first moment the gateway will say which workspaces the
+ * account belongs to — before it, the server's only workspace is the
+ * placeholder its registration created.
+ */
+describe('reading the account’s workspaces once it is signed in', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getServer.mockResolvedValue(server({}));
+ managedServerHostBlocked.mockReturnValue(null);
+ });
+
+ it('matches the workspaces after a sign-in that succeeded', async () => {
+ passwordLogin.mockResolvedValue({ success: true, value: { id: 'u1' } });
+
+ await switchServersController.passwordLogin({
+ serverId: 'srv',
+ email: '[email protected]',
+ password: 'hunter2',
+ });
+
+ expect(reconcileServerWorkspaces).toHaveBeenCalledWith('srv');
+ });
+
+ it('does not after one that failed', async () => {
+ passwordLogin.mockResolvedValue({ success: false, error: { kind: 'invalid_credentials' } });
+
+ await switchServersController.passwordLogin({
+ serverId: 'srv',
+ email: '[email protected]',
+ password: 'hunter2',
+ });
+
+ expect(reconcileServerWorkspaces).not.toHaveBeenCalled();
+ });
+
+ // The sign-in itself worked; reporting it as a failure would send the user
+ // back to a form with nothing left to do.
+ it('still reports the sign-in when the workspaces cannot be read', async () => {
+ passwordLogin.mockResolvedValue({ success: true, value: { id: 'u1' } });
+ reconcileServerWorkspaces.mockRejectedValue(new Error('gateway too old'));
+
+ const result = await switchServersController.passwordLogin({
+ serverId: 'srv',
+ email: '[email protected]',
+ password: 'hunter2',
+ });
+
+ expect(result.success).toBe(true);
+ });
+});
+
describe('adding a server by URL', () => {
const params = { name: 'S', gatewayUrl: 'http://gateway', apiUrl: 'http://api' };
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts
index 3752d42e6..71c16f306 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
@@ -4,6 +4,8 @@ import { appService } from '@main/core/app/service';
import { isManagedServerRunning } from '@main/core/managed-switch-server/managed-server-status';
import type { TelemetryAuthMethod, TelemetrySignInFailure } from '@main/core/telemetry/events';
import { trackEvent } from '@main/core/telemetry/telemetry-service';
+import { reconcileServerWorkspaces } from '@main/core/workspaces/reconcile-workspaces';
+import { log } from '@main/lib/logger';
import type {
AddServerParams,
BundledChatSignIn,
@@ -45,6 +47,26 @@ function signInFailureReason(result: Result<unknown, LoginError>): TelemetrySign
return result.success ? 'none' : SIGN_IN_FAILURE[result.error.kind];
}
+/**
+ * Match the server's workspaces to the memberships the account turns out to
+ * have. Signing in is the first moment the gateway will answer that, and the
+ * renderer reloads its workspace list straight afterwards — so it is awaited,
+ * to be there when it does.
+ *
+ * Logged rather than raised: the sign-in itself succeeded, and reporting it as
+ * a failure would send the user back to a form that has nothing left to do.
+ */
+async function adoptWorkspaces(server: SwitchServer): Promise<void> {
+ try {
+ await reconcileServerWorkspaces(server.id);
+ } catch (error) {
+ log.warn('workspaces: signed in, but could not read the account’s workspaces', {
+ server: server.id,
+ error: String(error),
+ });
+ }
+}
+
/**
* Reported by reason rather than by outcome: the two are the same fact, and a
* sign-in that never left this machine — the server's host is down — has a
@@ -121,6 +143,7 @@ export const switchServersController = createRPCController({
}
const result = await passwordLogin(server, params.email, params.password);
reportSignIn('password', server, signInFailureReason(result));
+ if (result.success) await adoptWorkspaces(server);
return result;
},
@@ -133,6 +156,7 @@ export const switchServersController = createRPCController({
}
const result = await oidcLogin(server);
reportSignIn('oidc', server, signInFailureReason(result));
+ if (result.success) await adoptWorkspaces(server);
return result;
},
diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.test.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.test.ts
index 8f2fc597f..e6b84d82b 100644
--- a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.test.ts
@@ -10,6 +10,7 @@ const fetchBridges = vi.hoisted(() => vi.fn());
const getServer = vi.hoisted(() => vi.fn());
const getSessionCookie = vi.hoisted(() => vi.fn());
const requireWorkspace = vi.hoisted(() => vi.fn());
+const listWorkspacesForServer = vi.hoisted(() => vi.fn(async () => [{ id: 'ws' }]));
const switchTenant = vi.hoisted(() => vi.fn());
// Stubbed rather than reimplemented: what the tests below assert is that the
// kind reaches the event, not how a row is read as one.
@@ -88,6 +89,7 @@ vi.mock('@main/core/switch-servers/servers-store', () => ({
vi.mock('./workspaces-store', () => ({
getActiveWorkspaceId: vi.fn(),
listWorkspaces: vi.fn(),
+ listWorkspacesForServer,
requireWorkspace,
setActiveWorkspaceId: vi.fn(),
}));
@@ -240,7 +242,7 @@ describe('selecting the workspace’s tenant before the call', () => {
expect(switchTenant).not.toHaveBeenCalled();
});
- it('asserts nothing for a workspace with no tenant of its own', async () => {
+ it('asserts nothing for a workspace with no tenant, where its server has only the one', async () => {
requireWorkspace.mockResolvedValue(workspace(null));
await workspacesController.listBridges('ws');
@@ -248,4 +250,12 @@ describe('selecting the workspace’s tenant before the call', () => {
expect(switchTenant).not.toHaveBeenCalled();
expect(getSessionCookie).not.toHaveBeenCalled();
});
+
+ it('refuses a workspace with no tenant where its server has several', async () => {
+ requireWorkspace.mockResolvedValue(workspace(null));
+ listWorkspacesForServer.mockResolvedValueOnce([{ id: 'ws' }, { id: 'ws-2' }]);
+
+ await expect(workspacesController.listBridges('ws')).rejects.toThrow('has not been matched');
+ expect(fetchBridges).not.toHaveBeenCalled();
+ });
});
diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.db.test.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.db.test.ts
new file mode 100644
index 000000000..b14bc0854
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.db.test.ts
@@ -0,0 +1,402 @@
+import { openFixture } from '@tooling/utils/db';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { AppDb } from '@main/db/client';
+import { agents, locations, switchServers } from '@main/db/schema';
+import { workspacesChangedChannel } from '@shared/core/workspaces/workspaceEvents';
+
+const mocks = vi.hoisted(() => ({
+ db: undefined as AppDb | undefined,
+}));
+
+const fetchTenants = vi.hoisted(() => vi.fn());
+const decodeJwtTenantId = vi.hoisted(() => vi.fn((_jwt: string): string | null => null));
+const getSessionCookie = vi.hoisted(() => vi.fn(async (): Promise<string | null> => null));
+const listServers = vi.hoisted(() => vi.fn(async (): Promise<{ id: string }[]> => []));
+const warn = vi.hoisted(() => vi.fn());
+const emit = vi.hoisted(() => vi.fn());
+
+vi.mock('@main/db/client', () => ({
+ get db() {
+ if (!mocks.db) throw new Error('Test database not initialized');
+ return mocks.db;
+ },
+}));
+vi.mock('@main/core/managed-switch-server/managed-server-status', () => ({
+ isManagedServerRunning: () => true,
+}));
+vi.mock('@main/core/switch-servers/gateway-client', () => ({ decodeJwtTenantId, fetchTenants }));
+vi.mock('@main/core/switch-servers/require-server', () => ({
+ requireServer: async (id: string) => ({ id, name: id }),
+}));
+vi.mock('@main/lib/events', () => ({ events: { emit } }));
+vi.mock('@main/lib/logger', () => {
+ const logger = { debug: vi.fn(), info: vi.fn(), warn, error: vi.fn(), child: () => logger };
+ return { log: logger };
+});
+
+// Mocked whole rather than in part: the module builds the encrypted secrets
+// store at import, which a test has no key for.
+vi.mock('@main/core/switch-servers/servers-store', () => ({ getSessionCookie, listServers }));
+
+const { reconcileAllWorkspaces, reconcileServerWorkspaces } =
+ await import('./reconcile-workspaces');
+const { createTenantWorkspace, ensureServerWorkspace, listWorkspacesForServer } =
+ await import('./workspaces-store');
+
+function tenant(id: string, name: string, role = 'member') {
+ return { id, slug: id, name, role };
+}
+
+describe('reconcile-workspaces', () => {
+ let fixture: Awaited<ReturnType<typeof openFixture>>;
+
+ beforeEach(async () => {
+ vi.clearAllMocks();
+ decodeJwtTenantId.mockReturnValue(null);
+ getSessionCookie.mockResolvedValue(null);
+ fixture = await openFixture('empty');
+ mocks.db = fixture.db;
+ fixture.sqlite.pragma('foreign_keys = ON');
+ await fixture.db.insert(switchServers).values({
+ id: 'srv-1',
+ name: 'Local dev',
+ gatewayUrl: 'https://srv-1.example.com',
+ apiUrl: 'https://api-srv-1.example.com',
+ });
+ listServers.mockResolvedValue([{ id: 'srv-1' }]);
+ });
+
+ afterEach(() => {
+ fixture.close();
+ mocks.db = undefined;
+ });
+
+ /** An agent in a workspace, which is the one thing that makes it unguessable. */
+ async function attachAgent(workspaceId: string): Promise<void> {
+ await fixture.db
+ .insert(locations)
+ .values({ id: 'loc-1', name: 'repo', dir: '/repo' })
+ .onConflictDoNothing();
+ await fixture.db.insert(agents).values({
+ id: `agent-${workspaceId}`,
+ locationId: 'loc-1',
+ name: 'a',
+ providerId: 'claude',
+ workspaceId,
+ });
+ }
+
+ /**
+ * The case every install upgrading into tenancy is in: one workspace carrying
+ * every agent, and one membership it turns out to be.
+ */
+ it('claims the server’s existing workspace for its sole membership', async () => {
+ const before = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });
+ fetchTenants.mockResolvedValue([tenant('t-1', 'Default', 'owner')]);
+
+ await reconcileServerWorkspaces('srv-1');
+
+ const found = await listWorkspacesForServer('srv-1');
+ expect(found).toHaveLength(1);
+ // Same row: the agents, the active selection and the saved navigation all
+ // name this id, and a replacement would detach every one of them.
+ expect(found[0]!.id).toBe(before.id);
+ expect(found[0]!.tenantId).toBe('t-1');
+ expect(found[0]!.role).toBe('owner');
+ });
+
+ /**
+ * A row is named after its server only until it is matched. After that the
+ * workspace is a tenant, the gateway is the only place it can be named or
+ * renamed, and nothing in this app offers to name one — so a local label kept
+ * here is one neither side can ever correct.
+ */
+ it('takes the gateway’s name for a workspace it has matched', async () => {
+ await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });
+ fetchTenants.mockResolvedValue([tenant('t-1', 'Default')]);
+
+ await reconcileServerWorkspaces('srv-1');
+
+ expect((await listWorkspacesForServer('srv-1'))[0]!.name).toBe('Default');
+ });
+
+ /**
+ * Also how a name typed into the create form survives the round trip that
+ * records it failing. The workspace exists on the gateway under that name and
+ * the local row does not have it yet; the next reconcile is what closes the
+ * gap, so the name is late rather than lost.
+ */
+ it('carries a later rename on the gateway onto the row it already matched', async () => {
+ await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });
+ fetchTenants.mockResolvedValue([tenant('t-1', 'Default')]);
+ await reconcileServerWorkspaces('srv-1');
+
+ fetchTenants.mockResolvedValue([tenant('t-1', 'Acme Robotics')]);
+ await reconcileServerWorkspaces('srv-1');
+
+ expect((await listWorkspacesForServer('srv-1'))[0]!.name).toBe('Acme Robotics');
+ });
+
+ it('adds a workspace for a membership this install has no row for', async () => {
+ await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });
+ getSessionCookie.mockResolvedValue('cookie');
+ decodeJwtTenantId.mockReturnValue('t-1');
+ fetchTenants.mockResolvedValue([tenant('t-1', 'Default'), tenant('t-2', 'Research')]);
+
+ await reconcileServerWorkspaces('srv-1');
+
+ const found = await listWorkspacesForServer('srv-1');
+ expect(found).toHaveLength(2);
+ expect(found.find((w) => w.tenantId === 't-1')!.name).toBe('Default');
+ expect(found.find((w) => w.tenantId === 't-2')!.name).toBe('Research');
+ });
+
+ /**
+ * What every multi-membership sign-in used to produce: the gateway refuses a
+ * scoped call from a session with several memberships and no selection, so
+ * this server has never answered one and its row holds nothing. Left behind
+ * while a row was added per membership, it appeared in the switcher as a
+ * workspace belonging to no membership at all.
+ */
+ it('gives the registration row a membership rather than leaving it belonging to none', async () => {
+ const before = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });
+ fetchTenants.mockResolvedValue([tenant('t-1', 'Default')]);
+
+ await reconcileServerWorkspaces('srv-1');
+
+ const found = await listWorkspacesForServer('srv-1');
+ expect(found).toHaveLength(1);
+ // The same row, so the active selection and the saved navigation still name
+ // something that exists.
+ expect(found[0]!.id).toBe(before.id);
+ expect(found[0]!.tenantId).toBe('t-1');
+ });
+
+ /**
+ * Which membership inherits the id the agents, the active selection and the
+ * saved navigation point at is not something to decide by coin toss. Every
+ * membership gets its own row instead, and the placeholder nothing was ever
+ * put in is dropped — the same list, arrived at the same way every time.
+ */
+ it('refuses to pick one of several memberships for the registration row', async () => {
+ const before = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });
+ fetchTenants.mockResolvedValue([tenant('t-1', 'Default'), tenant('t-2', 'Research')]);
+
+ await reconcileServerWorkspaces('srv-1');
+
+ const found = await listWorkspacesForServer('srv-1');
+ expect(found).toHaveLength(2);
+ expect(found.some((w) => w.id === before.id)).toBe(false);
+ expect(found.map((w) => w.name).toSorted()).toEqual(['Default', 'Research']);
+ });
+
+ /**
+ * The cookie says which membership this row's calls have been reaching, so
+ * there is nothing to guess and the row keeps its agents and its id.
+ */
+ it('adopts the membership the session already resolves to', async () => {
+ const before = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });
+ getSessionCookie.mockResolvedValue('cookie');
+ decodeJwtTenantId.mockReturnValue('t-2');
+ fetchTenants.mockResolvedValue([tenant('t-1', 'Default'), tenant('t-2', 'Research')]);
+
+ await reconcileServerWorkspaces('srv-1');
+
+ const found = await listWorkspacesForServer('srv-1');
+ expect(found).toHaveLength(2);
+ expect(found.find((w) => w.id === before.id)!.tenantId).toBe('t-2');
+ });
+
+ /**
+ * The one case that cannot be answered: agents were registered through this
+ * row, so it stands for wherever they live, and naming it the wrong
+ * membership would move them somewhere the user cannot see.
+ */
+ it('refuses to guess which membership a workspace with agents holds', async () => {
+ const before = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });
+ await attachAgent(before.id);
+ fetchTenants.mockResolvedValue([tenant('t-1', 'Default'), tenant('t-2', 'Research')]);
+
+ await reconcileServerWorkspaces('srv-1');
+
+ const found = await listWorkspacesForServer('srv-1');
+ expect(found.find((w) => w.id === before.id)!.tenantId).toBeNull();
+ // Both memberships are still recorded — only the question of which one the
+ // existing row holds is left open.
+ expect(found).toHaveLength(3);
+ expect(found.some((w) => w.tenantId === 't-1')).toBe(true);
+ expect(found.some((w) => w.tenantId === 't-2')).toBe(true);
+ expect(warn).toHaveBeenCalled();
+ });
+
+ /**
+ * The repair the short-circuit used to make impossible: once every membership
+ * has a row, the leftover registration row could never be revisited, and no
+ * later boot or sign-in could clear it.
+ */
+ it('drops an empty registration row left over once every membership has one', async () => {
+ const before = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });
+ await createTenantWorkspace('srv-1', {
+ id: 't-1',
+ slug: 't-1',
+ name: 'Default',
+ role: 'owner',
+ });
+ await createTenantWorkspace('srv-1', {
+ id: 't-2',
+ slug: 't-2',
+ name: 'Research',
+ role: 'member',
+ });
+ fetchTenants.mockResolvedValue([tenant('t-1', 'Default'), tenant('t-2', 'Research')]);
+
+ await reconcileServerWorkspaces('srv-1');
+
+ const found = await listWorkspacesForServer('srv-1');
+ expect(found).toHaveLength(2);
+ expect(found.some((w) => w.id === before.id)).toBe(false);
+ });
+
+ /**
+ * The boot sweep runs behind an open window that read its list before it
+ * started, and nothing else tells that window the list moved. Without this a
+ * membership gained or lost between launches stays invisible for the whole
+ * session, and the row dropped above goes on being offered in the switcher
+ * after it has gone.
+ */
+ it('announces the change so an open window re-reads the list', async () => {
+ await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });
+ fetchTenants.mockResolvedValue([tenant('t-1', 'Default')]);
+
+ await reconcileServerWorkspaces('srv-1');
+
+ expect(emit).toHaveBeenCalledWith(workspacesChangedChannel, undefined);
+ });
+
+ /**
+ * The boot sweep is not awaited, so a sign-in lands in the middle of it. Read
+ * together, both passes see a membership with no row and both create one; the
+ * unique index then turns the loser into an error that abandons the rest of
+ * its pass, leaving the tenants it had not reached yet unmatched.
+ */
+ it('runs two passes on one server one after the other', async () => {
+ await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });
+ getSessionCookie.mockResolvedValue('cookie');
+ decodeJwtTenantId.mockReturnValue('t-1');
+ fetchTenants.mockResolvedValue([
+ tenant('t-1', 'Default'),
+ tenant('t-2', 'Research'),
+ tenant('t-3', 'Ops'),
+ ]);
+
+ await Promise.all([reconcileServerWorkspaces('srv-1'), reconcileServerWorkspaces('srv-1')]);
+
+ const found = await listWorkspacesForServer('srv-1');
+ expect(found).toHaveLength(3);
+ expect(found.map((w) => w.tenantId).toSorted((a, b) => a!.localeCompare(b!))).toEqual([
+ 't-1',
+ 't-2',
+ 't-3',
+ ]);
+ });
+
+ it('carries a role change on a workspace it already matched', async () => {
+ const existing = await createTenantWorkspace('srv-1', {
+ id: 't-1',
+ slug: 't-1',
+ name: 'Research',
+ role: 'member',
+ });
+ fetchTenants.mockResolvedValue([tenant('t-1', 'Research', 'admin')]);
+
+ await reconcileServerWorkspaces('srv-1');
+
+ const found = await listWorkspacesForServer('srv-1');
+ expect(found).toHaveLength(1);
+ expect(found[0]!.id).toBe(existing.id);
+ expect(found[0]!.role).toBe('admin');
+ });
+
+ /**
+ * Deleting it would silently detach that workspace's agents. Kept, so the
+ * next call scoped to it fails and says why — and said out loud now.
+ */
+ it('keeps a workspace whose membership has been withdrawn, and says so', async () => {
+ await createTenantWorkspace('srv-1', {
+ id: 't-gone',
+ slug: 't-gone',
+ name: 'Research',
+ role: 'member',
+ });
+ fetchTenants.mockResolvedValue([tenant('t-1', 'Default')]);
+
+ await reconcileServerWorkspaces('srv-1');
+
+ const found = await listWorkspacesForServer('srv-1');
+ expect(found.some((w) => w.tenantId === 't-gone')).toBe(true);
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('no longer a member'), {
+ server: 'srv-1',
+ workspace: expect.any(String),
+ });
+ });
+
+ // An account in no workspace at all is a server the user cannot use; saying
+ // nothing and deleting the local row would look like it had never been set up.
+ it('leaves the rows alone when the gateway reports no membership', async () => {
+ const before = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });
+ fetchTenants.mockResolvedValue([]);
+
+ await reconcileServerWorkspaces('srv-1');
+
+ const found = await listWorkspacesForServer('srv-1');
+ expect(found).toEqual([before]);
+ expect(warn).toHaveBeenCalled();
+ });
+
+ it('is idempotent across launches', async () => {
+ const before = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });
+ fetchTenants.mockResolvedValue([tenant('t-1', 'Default')]);
+
+ await reconcileServerWorkspaces('srv-1');
+ await reconcileServerWorkspaces('srv-1');
+
+ const found = await listWorkspacesForServer('srv-1');
+ expect(found).toHaveLength(1);
+ expect(found[0]!.id).toBe(before.id);
+ });
+
+ describe('the boot sweep', () => {
+ // Asking costs a round trip that can only be refused, and the answer would
+ // be thrown away.
+ it('skips a server this install is not signed in to', async () => {
+ await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });
+
+ await reconcileAllWorkspaces();
+
+ expect(fetchTenants).not.toHaveBeenCalled();
+ });
+
+ // One server being down must not stop the rest from being reconciled.
+ it('carries on past a server that cannot be reached', async () => {
+ await fixture.db.insert(switchServers).values({
+ id: 'srv-2',
+ name: 'Staging',
+ gatewayUrl: 'https://srv-2.example.com',
+ apiUrl: 'https://api-srv-2.example.com',
+ });
+ await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });
+ await ensureServerWorkspace({ id: 'srv-2', name: 'Staging' });
+ listServers.mockResolvedValue([{ id: 'srv-1' }, { id: 'srv-2' }]);
+ getSessionCookie.mockResolvedValue('cookie');
+ fetchTenants
+ .mockRejectedValueOnce(new Error('no route to host'))
+ .mockResolvedValue([tenant('t-2', 'Default')]);
+
+ await reconcileAllWorkspaces();
+
+ expect((await listWorkspacesForServer('srv-1'))[0]!.tenantId).toBeNull();
+ expect((await listWorkspacesForServer('srv-2'))[0]!.tenantId).toBe('t-2');
+ expect(warn).toHaveBeenCalled();
+ });
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.ts
new file mode 100644
index 000000000..d8a6f92a8
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.ts
@@ -0,0 +1,213 @@
+import { isManagedServerRunning } from '@main/core/managed-switch-server/managed-server-status';
+import {
+ decodeJwtTenantId,
+ fetchTenants,
+ type RemoteTenant,
+} from '@main/core/switch-servers/gateway-client';
+import { requireServer } from '@main/core/switch-servers/require-server';
+import { getSessionCookie, listServers } from '@main/core/switch-servers/servers-store';
+import { events } from '@main/lib/events';
+import { log } from '@main/lib/logger';
+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';
+import { workspacesChangedChannel } from '@shared/core/workspaces/workspaceEvents';
+import type { Workspace } from '@shared/core/workspaces/workspaces';
+import {
+ createTenantWorkspace,
+ discardEmptyWorkspace,
+ listWorkspacesForServer,
+ setWorkspaceTenant,
+ workspaceHasAgents,
+} from './workspaces-store';
+
+/**
+ * The tenant this server's session resolves to — the one whose data every call
+ * made against it so far has actually reached.
+ *
+ * The gateway resolves a session to the tenant its cookie selects, or to the
+ * sole membership when nothing is selected; with several memberships and no
+ * selection it refuses the request instead of guessing. So a server that has
+ * ever answered has exactly one answer here, and when there is none nothing has
+ * been attached to a workspace yet and there is nothing to get wrong.
+ */
+async function resolvedTenant(
+ server: SwitchServer,
+ tenants: RemoteTenant[]
+): Promise<RemoteTenant | null> {
+ const cookie = await getSessionCookie(server.id);
+ const selected = cookie ? decodeJwtTenantId(cookie) : null;
+ // A claim naming a membership the account no longer holds answers nothing, so
+ // it falls through rather than standing in the way of the sole-membership
+ // answer below — which is what the gateway itself would resolve the next call
+ // to.
+ const claimed = selected ? tenants.find((tenant) => tenant.id === selected) : undefined;
+ if (claimed) return claimed;
+ return tenants.length === 1 ? tenants[0]! : null;
+}
+
+/**
+ * The membership to give the tenant-less row a server is registered with, or
+ * null when it cannot be told and must not be guessed.
+ *
+ * Every server starts with one such row, and until it is matched it belongs to
+ * nothing: a call scoped to it selects no tenant, so the gateway answers under
+ * whatever the session last selected — another workspace's rooms and agents,
+ * under this one's name, with no error anywhere. Leaving one behind while
+ * creating a row per membership is how that used to happen on every
+ * multi-membership sign-in.
+ */
+async function tenantToAdopt(
+ server: SwitchServer,
+ unclaimed: Workspace,
+ tenants: RemoteTenant[],
+ unmatched: RemoteTenant[]
+): Promise<RemoteTenant | null> {
+ // The one this row's calls have been reaching all along, when no other row
+ // holds it already.
+ const resolved = await resolvedTenant(server, tenants);
+ if (resolved && unmatched.some((tenant) => tenant.id === resolved.id)) return resolved;
+ // Only where there is nothing to choose between. Nothing was ever registered
+ // through the row, so there is no data to put anywhere, and a membership the
+ // user can see and switch away from beats a row belonging to none of them.
+ // With several it would be a coin toss deciding which membership inherits the
+ // id the saved navigation and the active selection point at; left unadopted,
+ // every membership gets its own row and the empty placeholder is dropped
+ // further down, which reaches the same list without the toss.
+ if (unmatched.length === 1 && !(await workspaceHasAgents(unclaimed.id))) return unmatched[0]!;
+ return null;
+}
+
+/** Say so when a workspace is still held locally for a membership that has gone. */
+function reportWithdrawnMemberships(
+ serverId: string,
+ local: Workspace[],
+ tenants: RemoteTenant[]
+): void {
+ for (const workspace of local) {
+ if (!workspace.tenantId) continue;
+ if (tenants.some((tenant) => tenant.id === workspace.tenantId)) continue;
+ log.warn(
+ 'workspaces: this account is no longer a member of a workspace held locally; calls scoped to it will be refused',
+ { server: serverId, workspace: workspace.id }
+ );
+ }
+}
+
+/**
+ * Match this install's workspaces for a server against the memberships the
+ * gateway reports.
+ *
+ * A server registers before anyone asks which workspaces its account belongs
+ * to, so its first row is created tenant-less and named after the server. This
+ * is what later gives that row its tenant — claiming it rather than replacing
+ * it, so the agents registered through it stay where they are — and adds a row
+ * for every other membership.
+ *
+ * A row whose membership has been withdrawn is kept, not deleted. Deleting it
+ * would silently detach that workspace's agents; leaving it means the next call
+ * scoped to it fails and says why.
+ */
+export async function reconcileServerWorkspaces(serverId: string): Promise<void> {
+ // The boot sweep is not awaited and a sign-in can land in the middle of it.
+ // Two passes that both read the rows before either writes create the same
+ // tenant twice, and the unique index turns the loser into an error that
+ // abandons the rest of its pass — so they run one after the other instead.
+ const queued = (inFlight.get(serverId) ?? Promise.resolve())
+ .then(
+ () => reconcileOneServer(serverId),
+ () => reconcileOneServer(serverId)
+ )
+ // An open window read its list before this ran, and nothing else tells it
+ // the list moved. Without this a membership added or withdrawn between
+ // launches stays invisible for the session, and a placeholder dropped below
+ // goes on being offered in the switcher after the row it names has gone.
+ .then(() => {
+ events.emit(workspacesChangedChannel, undefined);
+ });
+ inFlight.set(
+ serverId,
+ queued.then(
+ () => {},
+ () => {}
+ )
+ );
+ return queued;
+}
+
+const inFlight = new Map<string, Promise<void>>();
+
+async function reconcileOneServer(serverId: string): Promise<void> {
+ const server = await requireServer(serverId);
+ const tenants = await fetchTenants(server);
+ if (tenants.length === 0) {
+ log.warn('workspaces: the gateway reports no workspace membership for this account', {
+ server: serverId,
+ });
+ return;
+ }
+
+ const local = await listWorkspacesForServer(serverId);
+ reportWithdrawnMemberships(serverId, local, tenants);
+
+ const claimed = new Map(
+ local
+ .filter((workspace) => workspace.tenantId)
+ .map((workspace) => [workspace.tenantId!, workspace])
+ );
+ for (const tenant of tenants) {
+ const workspace = claimed.get(tenant.id);
+ if (workspace) await setWorkspaceTenant(workspace.id, tenant);
+ }
+
+ const unmatched = tenants.filter((tenant) => !claimed.has(tenant.id));
+ const unclaimed = local.find((workspace) => !workspace.tenantId) ?? null;
+ const adopting = unclaimed ? await tenantToAdopt(server, unclaimed, tenants, unmatched) : null;
+ if (unclaimed && adopting) await setWorkspaceTenant(unclaimed.id, adopting);
+
+ for (const tenant of unmatched) {
+ if (tenant.id === adopting?.id) continue;
+ await createTenantWorkspace(serverId, tenant);
+ }
+
+ if (!unclaimed || adopting) return;
+
+ // Reached when every membership is held by another row and this one is left
+ // over. Empty, it is a placeholder the reconcile has overtaken and dropping
+ // it is the whole repair; holding agents, it is the only record of where they
+ // live and is kept, unmatched, so the next call scoped to it is refused and
+ // says why rather than answering as some other workspace.
+ if (await workspaceHasAgents(unclaimed.id)) {
+ log.warn(
+ 'workspaces: cannot tell which workspace this server’s existing agents belong to; leaving it unmatched, and calls scoped to it will be refused',
+ { server: serverId, workspace: unclaimed.id, memberships: tenants.length }
+ );
+ return;
+ }
+ await discardEmptyWorkspace(unclaimed.id);
+}
+
+/**
+ * Reconcile every server this install holds a session for.
+ *
+ * Run at boot and left unawaited: a workspace list that is one launch stale is
+ * cosmetic, and a server that is slow or down must not hold up the window. A
+ * managed server whose stack is not running is skipped rather than probed —
+ * its gateway port is not listening, so the attempt only produces a network
+ * error in the log (CHOO-1657).
+ */
+export async function reconcileAllWorkspaces(): Promise<void> {
+ for (const server of await listServers()) {
+ // The cookie read is inside the guard with everything else: it opens the
+ // keychain, and a machine that refuses to unlock it would otherwise take
+ // the whole sweep down on the first server and skip the rest in silence.
+ try {
+ if (server.managed && !isManagedServerRunning(server)) continue;
+ if (!(await getSessionCookie(server.id))) continue;
+ await reconcileServerWorkspaces(server.id);
+ } catch (error: unknown) {
+ log.warn('workspaces: could not reconcile a server’s workspaces', {
+ server: server.id,
+ error: String(error),
+ });
+ }
+ }
+}
diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/workspace-session.test.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/workspace-session.test.ts
index 716f64940..a11e13d03 100644
--- a/console/apps/switch-console-desktop/src/main/core/workspaces/workspace-session.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/workspace-session.test.ts
@@ -135,6 +135,25 @@ describe('withWorkspaceSession', () => {
expect(switchTenant).not.toHaveBeenCalled();
});
+ /**
+ * The same row on a server that turns out to hold several. The call would
+ * still succeed — the gateway answers for whatever the session last selected
+ * — and would answer with another workspace's rooms and agents under this
+ * one's name. There is no way to tell which is meant, so it is refused rather
+ * than guessed.
+ */
+ it('refuses a tenant-less workspace on a server holding several', async () => {
+ workspace('ws-stale', null);
+ workspace('ws-b', 'tenant-b');
+ const ran = vi.fn();
+
+ await expect(withWorkspaceSession('ws-stale', ran)).rejects.toThrow(
+ /has not been matched to one of the 2/
+ );
+ expect(ran).not.toHaveBeenCalled();
+ expect(switchTenant).not.toHaveBeenCalled();
+ });
+
it('runs calls on the same tenant at the same time', async () => {
workspace('ws-a', 'tenant-a');
const first = deferred<void>();
diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/workspace-session.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/workspace-session.ts
index c4334a21d..48fd068fe 100644
--- a/console/apps/switch-console-desktop/src/main/core/workspaces/workspace-session.ts
+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/workspace-session.ts
@@ -2,8 +2,9 @@ import { decodeJwtTenantId, switchTenant } from '@main/core/switch-servers/gatew
import { hostUnreachable, requireServer } from '@main/core/switch-servers/require-server';
import { getSessionCookie } from '@main/core/switch-servers/servers-store';
import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';
+import type { Workspace } from '@shared/core/workspaces/workspaces';
import { clearAssertedTenant, setAssertedTenant } from './asserted-tenant';
-import { requireWorkspace } from './workspaces-store';
+import { listWorkspacesForServer, requireWorkspace } from './workspaces-store';
/**
* Calls in flight on a server's current tenant selection, and the queue that
@@ -101,6 +102,33 @@ async function acquire(server: SwitchServer, tenantId: string | null): Promise<S
return session;
}
+/**
+ * The workspace, refusing one that names no tenant on a server holding several.
+ *
+ * A row without a tenant asserts nothing, so the call goes out under whatever
+ * the session last selected and the gateway answers for that — another
+ * workspace's rooms and agents, under this one's name, with no error anywhere.
+ * Refusing costs nothing where a server holds one workspace: there is nothing
+ * to confuse it with, and the gateway resolves the account's sole membership to
+ * exactly that row.
+ */
+async function requireAddressableWorkspace(workspaceId: string): Promise<Workspace> {
+ const workspace = await requireWorkspace(workspaceId);
+ if (workspace.tenantId) return workspace;
+ const onServer = await listWorkspacesForServer(workspace.serverId);
+ if (onServer.length > 1) {
+ throw new Error(
+ // Not "sign in again": signing in re-runs the reconcile, which is what
+ // left the row unmatched in the first place and would do so again. The
+ // row only survives because it holds agents, so the way out is to open
+ // one of the workspaces the account does belong to and add those agents
+ // there.
+ `This workspace has not been matched to one of the ${onServer.length} this account belongs to on its Switch server, so there is no way to tell which one to ask. Switch to one of the others on this server; the agents left here have to be added again in the workspace they belong to.`
+ );
+ }
+ return workspace;
+}
+
/**
* The server hosting a workspace, with no session work done.
*
@@ -126,14 +154,15 @@ export async function workspaceServer(workspaceId: string): Promise<SwitchServer
*
* A workspace that has not been matched to a tenant yet asserts nothing — there
* is no id to select, and the call goes out against whatever the session
- * resolves, which is the single membership that produced the row. It still
+ * resolves. That is the right answer only while the server holds one workspace,
+ * which is why the rest are refused; see `requireAddressableWorkspace`. It still
* takes a lease, so it cannot straddle another workspace's switch.
*/
export async function withWorkspaceSession<T>(
workspaceId: string,
fn: (server: SwitchServer) => Promise<T>
): Promise<T> {
- const workspace = await requireWorkspace(workspaceId);
+ const workspace = await requireAddressableWorkspace(workspaceId);
const server = await requireServer(workspace.serverId);
const session = await acquire(server, workspace.tenantId);
try {
@@ -154,7 +183,7 @@ export async function withReachableWorkspaceSession<T>(
workspaceId: string,
fn: (server: SwitchServer) => Promise<T>
): Promise<T> {
- const workspace = await requireWorkspace(workspaceId);
+ const workspace = await requireAddressableWorkspace(workspaceId);
const server = await requireServer(workspace.serverId);
const unreachable = hostUnreachable(server);
if (unreachable) throw unreachable;
diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/workspaces-store.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/workspaces-store.ts
index 9fca13b7d..4a8c2cedc 100644
--- a/console/apps/switch-console-desktop/src/main/core/workspaces/workspaces-store.ts
+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/workspaces-store.ts
@@ -1,8 +1,8 @@
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';
+import { agents, kv, type WorkspaceRow, workspaces } from '@main/db/schema';
+import type { Workspace, WorkspaceRole } from '@shared/core/workspaces/workspaces';
const ACTIVE_WORKSPACE_KV_KEY = 'activeWorkspaceId';
@@ -19,8 +19,17 @@ function mapRow(row: WorkspaceRow): Workspace {
};
}
+// `createdAt` is a one-second-granularity timestamp and a reconcile writes a
+// server's rows in one loop, so ties are the norm rather than the exception. The
+// id breaks them, because callers that take the first row — the one the window
+// falls back to — must land on the same one every launch.
+const workspaceOrder = [asc(workspaces.createdAt), asc(workspaces.id)];
+
export async function listWorkspaces(): Promise<Workspace[]> {
- const rows = await db.select().from(workspaces).orderBy(asc(workspaces.createdAt));
+ const rows = await db
+ .select()
+ .from(workspaces)
+ .orderBy(...workspaceOrder);
return rows.map(mapRow);
}
@@ -29,7 +38,7 @@ export async function listWorkspacesForServer(serverId: string): Promise<Workspa
.select()
.from(workspaces)
.where(eq(workspaces.serverId, serverId))
- .orderBy(asc(workspaces.createdAt));
+ .orderBy(...workspaceOrder);
return rows.map(mapRow);
}
@@ -91,7 +100,7 @@ export async function ensureServerWorkspace(server: {
.select()
.from(workspaces)
.where(eq(workspaces.serverId, server.id))
- .orderBy(asc(workspaces.createdAt))
+ .orderBy(...workspaceOrder)
.limit(1)
.all();
return existing ? mapRow(existing) : insertServerWorkspace(tx, server);
@@ -124,6 +133,94 @@ export function insertServerWorkspace(
return mapRow(row!);
}
+/**
+ * Match a workspace row to the tenant it holds, and keep what the gateway owns
+ * about that tenant up to date.
+ *
+ * An update rather than a replacement, because the row's id is what the agents,
+ * the active selection and the saved navigation all point at — a new row for
+ * the same workspace would detach every one of them.
+ *
+ * The name comes over with the rest. A matched workspace is a tenant, the
+ * gateway is where it is named and renamed, and nothing in this app offers to
+ * name one — so the alternative is a local label that can never be corrected
+ * from either side. The row a server is registered with is named after the
+ * server only for as long as it belongs to no tenant.
+ */
+export async function setWorkspaceTenant(
+ workspaceId: string,
+ tenant: { id: string; slug: string; name: string; role: WorkspaceRole }
+): Promise<void> {
+ await db
+ .update(workspaces)
+ .set({
+ tenantId: tenant.id,
+ slug: tenant.slug,
+ name: tenant.name,
+ role: tenant.role,
+ updatedAt: sql`CURRENT_TIMESTAMP`,
+ })
+ .where(eq(workspaces.id, workspaceId));
+}
+
+/**
+ * Whether any agent still belongs to a workspace.
+ *
+ * Asked of the tenant-less row a server is registered with, to tell a
+ * placeholder nothing was ever put in from the record of where a set of agents
+ * lives. The first can be given a membership or dropped; the second cannot be
+ * guessed at, because moving it would move those agents somewhere the user has
+ * no way to see.
+ */
+export async function workspaceHasAgents(workspaceId: string): Promise<boolean> {
+ const [row] = await db
+ .select({ id: agents.id })
+ .from(agents)
+ .where(eq(agents.workspaceId, workspaceId))
+ .limit(1);
+ return row !== undefined;
+}
+
+/**
+ * Drop a workspace nothing points at, moving the active selection off it first.
+ *
+ * Only ever the placeholder row a server is registered with, and only once a
+ * reconcile has found that every membership the account holds is already held
+ * by another row — leaving it would put a workspace in the switcher that
+ * belongs to no membership at all. The caller checks it is empty first; the
+ * selection is a plain `kv` value that no foreign key reaches, so it has to be
+ * moved here rather than left pointing at a row that has gone.
+ */
+export async function discardEmptyWorkspace(workspaceId: string): Promise<void> {
+ const workspace = await requireWorkspace(workspaceId);
+ const sibling = (await listWorkspacesForServer(workspace.serverId)).find(
+ (candidate) => candidate.id !== workspaceId
+ );
+ if (!sibling) throw new Error(`Workspace ${workspaceId} is the only one on its Switch server`);
+ if ((await getActiveWorkspaceId()) === workspaceId) await setActiveWorkspaceId(sibling.id);
+ await db.delete(workspaces).where(eq(workspaces.id, workspaceId));
+}
+
+/** Record a workspace the user belongs to that this install has no row for. */
+export async function createTenantWorkspace(
+ serverId: string,
+ tenant: { id: string; slug: string; name: string; role: WorkspaceRole }
+): Promise<Workspace> {
+ const [row] = await db
+ .insert(workspaces)
+ .values({
+ id: randomUUID(),
+ serverId,
+ name: tenant.name,
+ tenantId: tenant.id,
+ slug: tenant.slug,
+ role: tenant.role,
+ updatedAt: sql`CURRENT_TIMESTAMP`,
+ })
+ .returning();
+ return mapRow(row!);
+}
+
/**
* Carry a server rename onto the workspaces that take their name from it.
*
diff --git a/console/apps/switch-console-desktop/src/main/index.ts b/console/apps/switch-console-desktop/src/main/index.ts
index 2dd171707..d5b8fb0a6 100644
--- a/console/apps/switch-console-desktop/src/main/index.ts
+++ b/console/apps/switch-console-desktop/src/main/index.ts
@@ -35,6 +35,7 @@ import { registerTelemetryListeners } from './core/telemetry/telemetry-listeners
import { trackEvent } from './core/telemetry/telemetry-service';
import { updateService } from './core/updates/update-service';
import { viewStateService } from './core/view-state/view-state-service';
+import { reconcileAllWorkspaces } from './core/workspaces/reconcile-workspaces';
import { initializeDatabase } from './db/initialize';
import { logAppExit, logAppStart, registerAppDiagnostics } from './lib/app-diagnostics';
import {
@@ -158,6 +159,14 @@ void app.whenReady().then(async () => {
void reconcileResourceSampler();
+ // A server registered before its account's memberships were known carries one
+ // tenant-less workspace; this is what gives it its tenant, and what notices a
+ // membership added or withdrawn since the last launch. Unawaited: it talks to
+ // every signed-in server, and the window must not wait on any of them.
+ void reconcileAllWorkspaces().catch((error: unknown) => {
+ log.error('Workspace reconcile could not run; every server was left as it was:', error);
+ });
+
// Reflect a managed local Switch stack that survived the last quit, so the UI
// shows it running without the user restarting it.
void localServerService.initialize();
diff --git a/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspaces-store.test.ts b/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspaces-store.test.ts
new file mode 100644
index 000000000..698084808
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspaces-store.test.ts
@@ -0,0 +1,74 @@
+/**
+ * The store mirrors a list the main process owns, and the reconcile moves that
+ * list without a window having asked. These cover the seam that carries such a
+ * change across, which is otherwise only exercised by a running app.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const list = vi.hoisted(() => vi.fn<() => Promise<unknown[]>>(async () => []));
+const getActiveId = vi.hoisted(() => vi.fn<() => Promise<string | null>>(async () => null));
+const subscribers = vi.hoisted(() => new Map<string, (data: unknown) => void>());
+
+vi.mock('@renderer/lib/ipc', () => ({
+ rpc: { workspaces: { list, getActiveId } },
+ events: {
+ on: (event: { name: string }, cb: (data: unknown) => void) => {
+ subscribers.set(event.name, cb);
+ return () => subscribers.delete(event.name);
+ },
+ },
+}));
+
+const { WorkspacesStore } = await import('./workspaces-store');
+const { workspacesChangedChannel } = await import('@shared/core/workspaces/workspaceEvents');
+
+function workspace(id: string, name: string) {
+ return {
+ id,
+ serverId: 'srv-1',
+ name,
+ tenantId: `tenant-${id}`,
+ slug: name.toLowerCase(),
+ role: 'member' as const,
+ createdAt: '2026-01-01T00:00:00Z',
+ updatedAt: '2026-01-01T00:00:00Z',
+ };
+}
+
+describe('WorkspacesStore', () => {
+ beforeEach(() => {
+ subscribers.clear();
+ list.mockReset().mockResolvedValue([]);
+ getActiveId.mockReset().mockResolvedValue(null);
+ });
+
+ it('re-reads the list when the main process says it changed', async () => {
+ const store = new WorkspacesStore();
+ list.mockResolvedValue([workspace('ws-1', 'Acme')]);
+ await store.refresh();
+
+ list.mockResolvedValue([workspace('ws-1', 'Acme'), workspace('ws-2', 'Skunkworks')]);
+ subscribers.get(workspacesChangedChannel.name)!(undefined);
+ await vi.waitFor(() => expect(store.workspaces).toHaveLength(2));
+ });
+
+ /**
+ * The reconcile drops the placeholder a server was registered with once every
+ * membership has a row of its own. A window still listing it offers a
+ * workspace that no longer exists, and the only thing it can report on the
+ * click is that the switch failed — not that the row went.
+ */
+ it('drops a workspace the main process no longer has', async () => {
+ const store = new WorkspacesStore();
+ list.mockResolvedValue([workspace('ws-1', 'Acme'), workspace('ws-2', 'Skunkworks')]);
+ getActiveId.mockResolvedValue('ws-1');
+ await store.refresh();
+
+ list.mockResolvedValue([workspace('ws-2', 'Skunkworks')]);
+ getActiveId.mockResolvedValue('ws-2');
+ subscribers.get(workspacesChangedChannel.name)!(undefined);
+
+ await vi.waitFor(() => expect(store.byId('ws-1')).toBeNull());
+ expect(store.activeId).toBe('ws-2');
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspaces-store.ts b/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspaces-store.ts
index 3f5038edc..f6d054f98 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspaces-store.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspaces-store.ts
@@ -1,5 +1,6 @@
import { makeAutoObservable, runInAction } from 'mobx';
-import { rpc } from '@renderer/lib/ipc';
+import { events, rpc } from '@renderer/lib/ipc';
+import { workspacesChangedChannel } from '@shared/core/workspaces/workspaceEvents';
import type { Workspace } from '@shared/core/workspaces/workspaces';
/**
@@ -22,6 +23,15 @@ export class WorkspacesStore {
constructor() {
makeAutoObservable(this);
+
+ // The reconcile adds, matches and drops rows without a window asking, so
+ // the calls the servers store makes are not the only times this list moves.
+ // A membership gained or lost since the last launch would otherwise stay
+ // invisible until the next one, and a row the boot sweep deleted would go
+ // on being offered here after it had gone.
+ events.on(workspacesChangedChannel, () => {
+ void this.refresh();
+ });
}
get active(): Workspace | null {
diff --git a/console/apps/switch-console-desktop/src/shared/core/workspaces/workspaceEvents.ts b/console/apps/switch-console-desktop/src/shared/core/workspaces/workspaceEvents.ts
new file mode 100644
index 000000000..6591daeb3
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/shared/core/workspaces/workspaceEvents.ts
@@ -0,0 +1,13 @@
+import { defineEvent } from '@shared/lib/ipc/events';
+
+/**
+ * The set of workspaces this install holds changed in the main process.
+ *
+ * Fired by the reconcile, which is the one thing that adds, matches and drops
+ * workspace rows without a window having asked for it — the boot sweep, and
+ * every sign-in. Without it a membership added or withdrawn since the last
+ * launch stays invisible for the whole session, and a placeholder the sweep
+ * deleted goes on being offered in the switcher by a renderer holding the list
+ * it read at startup.
+ */
+export const workspacesChangedChannel = defineEvent<void>('workspaces:changed');
diff --git a/console/apps/switch-console-desktop/tooling/fixtures/baseline.db b/console/apps/switch-console-desktop/tooling/fixtures/baseline.db
index 23caa2637..c1759e17b 100644
Binary files a/console/apps/switch-console-desktop/tooling/fixtures/baseline.db and b/console/apps/switch-console-desktop/tooling/fixtures/baseline.db differ
diff --git a/console/apps/switch-console-desktop/tooling/fixtures/baseline.db-shm b/console/apps/switch-console-desktop/tooling/fixtures/baseline.db-shm
new file mode 100644
index 000000000..fe9ac2845
Binary files /dev/null and b/console/apps/switch-console-desktop/tooling/fixtures/baseline.db-shm differ
diff --git a/console/apps/switch-console-desktop/tooling/fixtures/baseline.db-wal b/console/apps/switch-console-desktop/tooling/fixtures/baseline.db-wal
new file mode 100644
index 000000000..e69de29bb
diff --git a/console/apps/switch-console-desktop/tooling/fixtures/empty.db b/console/apps/switch-console-desktop/tooling/fixtures/empty.db
index 3bf798903..ef513691c 100644
Binary files a/console/apps/switch-console-desktop/tooling/fixtures/empty.db and b/console/apps/switch-console-desktop/tooling/fixtures/empty.db differ
diff --git a/console/apps/switch-console-desktop/tooling/fixtures/empty.db-shm b/console/apps/switch-console-desktop/tooling/fixtures/empty.db-shm
new file mode 100644
index 000000000..fe9ac2845
Binary files /dev/null and b/console/apps/switch-console-desktop/tooling/fixtures/empty.db-shm differ
diff --git a/console/apps/switch-console-desktop/tooling/fixtures/empty.db-wal b/console/apps/switch-console-desktop/tooling/fixtures/empty.db-wal
new file mode 100644
index 000000000..e69de29bb