Skip to content

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

Put agent management, Switch Cloud, cloud machines and first run behind feature flags (CHOO-3441) (#751)

Louis Amaudruzd4e7cb030efd
diff --git a/.env.example b/.env.example
index edd70dd9a..3e4c88f03 100644
--- a/.env.example
+++ b/.env.example
@@ -144,12 +144,24 @@ AGENT_REGISTRATION_TOKEN=
# ── Agent management (experimental) ──────────────────────────────────────────
# Machines running an agents controller, and the agents placed on them (the
-# gateway's Machines page). Off by default. When on, CONTROLLER_TOKEN_SECRET
-# is required: at least 32 random characters, separate from SECRET_KEYS,
-# e.g. `openssl rand -base64 48`.
-AGENT_MANAGEMENT_ENABLED=false
+# gateway's Machines page). Off unless FEATURE_FLAGS_ENABLED below lists
+# `agent_management`. When on, CONTROLLER_TOKEN_SECRET is required: at least
+# 32 random characters, separate from SECRET_KEYS, e.g. `openssl rand -base64 48`.
CONTROLLER_TOKEN_SECRET=
+# ── Feature flags ────────────────────────────────────────────────────────────
+# Flags turned on for this deployment, comma-separated (e.g.
+# `ecosystem.show_owners`). Every other flag is off. They are fixed at deploy
+# time: no one can change them while the server runs. An unknown flag stops
+# startup. Known flags:
+# ecosystem.show_owners owners on the ecosystem graph
+# agent_management managed agents and the machines that run them
+# switch_cloud Switch Cloud
+# hosted_agents offers cloud machines in Switch Console; this
+# server runs them only with HOSTED_LAUNCH_CAPACITY
+# above 0 (which needs agent_management)
+FEATURE_FLAGS_ENABLED=
+
# ── Server keys ──────────────────────────────────────────────────────────────
# Master keys every signing and encryption key is derived from:
# "<id>:<secret>" comma-separated, current first, secrets of 32+ characters.
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration-service.test.ts b/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration-service.test.ts
index 71099c46d..d61f2504a 100644
--- a/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration-service.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration-service.test.ts
@@ -900,6 +900,21 @@ describe('moving every agent automatically', () => {
expect(tries()).toBe(4);
});
+ it('asks again at once about agents left alone once told to recheck them all', async () => {
+ all = [PARENT];
+ world.eligibility = { management: false, owner: null, ownedByMe: false };
+ const migration = service();
+ await migration.migrateEverything();
+ expect(adopted()).toHaveLength(0);
+ expect((await migration.overview()).leftAlone).toBe(1);
+ world.eligibility = { management: true, owner: 'Ada', ownedByMe: true };
+ await migration.migrateEverything();
+ expect(adopted()).toHaveLength(0);
+ migration.recheckAll();
+ await migration.migrateEverything();
+ expect(adopted()).toHaveLength(1);
+ });
+
it('counts what it left alone and what it could not ask about', async () => {
const base = deps().management;
const migration = service({
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration-service.ts b/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration-service.ts
index 8567f41da..4fa331495 100644
--- a/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration-service.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration-service.ts
@@ -400,6 +400,14 @@ export class AgentMigrationService {
};
}
+ /**
+ * Forgets every agent that could not be managed, so the next pass asks Switch
+ * about each again: a server that has just turned agent management on.
+ */
+ recheckAll(): void {
+ for (const agentId of this.unmanageableUntil.keys()) this.recheck(agentId);
+ }
+
/** Forgets that an agent could not be managed, so the next pass asks Switch again. */
recheck(agentId: string): void {
this.unmanageableUntil.delete(agentId);
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration.ts b/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration.ts
index 208bbec67..dcad2327a 100644
--- a/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration.ts
@@ -16,6 +16,7 @@ import {
embeddedControllerDataDir,
embeddedControllerService,
} from '@main/core/embedded-controller/embedded-controllers';
+import { featureFlagsService } from '@main/core/feature-flags/feature-flags';
import { hostControllerDataDir } from '@main/core/host-controllers/host-controller-service';
import { hostControllerService } from '@main/core/host-controllers/host-controllers';
import { locationManager } from '@main/core/locations/location-manager';
@@ -770,6 +771,9 @@ export const agentMigrationService = new AgentMigrationService({
const AUTO_MIGRATION_INTERVAL_MS = 60_000;
let autoMigrationTimer: NodeJS.Timeout | null = null;
+// Agents asked about while their server had agent management off are not asked
+// again for a while; a server turning it on is the moment to ask at once.
+let stopFollowingFlags: (() => void) | null = null;
function migrateEverythingLogged(): void {
agentMigrationService.migrateEverything().catch((error: unknown) => {
@@ -788,9 +792,16 @@ export function startAutoMigration(): void {
if (autoMigrationTimer) return;
migrateEverythingLogged();
autoMigrationTimer = setInterval(migrateEverythingLogged, AUTO_MIGRATION_INTERVAL_MS);
+ stopFollowingFlags = featureFlagsService.subscribe((state) => {
+ if (!state.flags.agent_management) return;
+ agentMigrationService.recheckAll();
+ migrateEverythingLogged();
+ });
}
export function stopAutoMigration(): void {
if (autoMigrationTimer) clearInterval(autoMigrationTimer);
autoMigrationTimer = null;
+ stopFollowingFlags?.();
+ stopFollowingFlags = null;
}
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-migration/controller.ts b/console/apps/switch-console-desktop/src/main/core/agent-migration/controller.ts
index ec61ec6b7..55f72f7fb 100644
--- a/console/apps/switch-console-desktop/src/main/core/agent-migration/controller.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agent-migration/controller.ts
@@ -20,8 +20,11 @@ export const agentMigrationController = createRPCController({
/** Where the automatic move stands, per machine and server, from what its passes found. */
getOverview: (): Promise<MigrationOverview> => agentMigrationService.overview(),
- /** Runs a pass of the automatic move now rather than at the next minute. */
- runNow: (): Promise<void> => agentMigrationService.migrateEverything(),
+ /** Runs a pass of the automatic move now, asking Switch afresh about every agent. */
+ runNow: (): Promise<void> => {
+ agentMigrationService.recheckAll();
+ return agentMigrationService.migrateEverything();
+ },
/** Runs the automatic move again now, asking Switch afresh about the agent. */
retry: (agentId: string): Promise<void> => {
diff --git a/console/apps/switch-console-desktop/src/main/core/dependencies/core-dependencies.test.ts b/console/apps/switch-console-desktop/src/main/core/dependencies/core-dependencies.test.ts
index ec8483812..c2947cfca 100644
--- a/console/apps/switch-console-desktop/src/main/core/dependencies/core-dependencies.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/dependencies/core-dependencies.test.ts
@@ -1,3 +1,4 @@
+import { readFileSync } from 'node:fs';
import { pickInstallOption } from '@switch-console/core/deps/runtime';
import { describe, expect, it } from 'vitest';
import { CORE_DEPENDENCIES } from './core-dependencies';
@@ -16,3 +17,27 @@ describe('CORE_DEPENDENCIES on Windows', () => {
expect(pickInstallOption(descriptor(id), 'windows')?.command).toBe(command);
});
});
+
+/** The `>=x.y` floor a console package declares for Node, as [major, minor]. */
+function nodeFloor(pkg: string): [number, number] {
+ const url = new URL(`../../../../../../packages/${pkg}/package.json`, import.meta.url);
+ const engines = (JSON.parse(readFileSync(url, 'utf8')) as { engines: { node: string } }).engines;
+ const [major, minor = '0'] = engines.node.replace('>=', '').split('.');
+ return [Number(major), Number(minor)];
+}
+
+describe('the Node a remote host needs', () => {
+ it('is at least what the agent runtime and the agents controller run on', () => {
+ const [major, minor] = (descriptor('node').minVersion ?? '').split('.').map(Number);
+ for (const pkg of ['switch-agent-runtime', 'agent-controller']) {
+ const [needMajor, needMinor] = nodeFloor(pkg);
+ expect(major > needMajor || (major === needMajor && minor >= needMinor), pkg).toBe(true);
+ }
+ });
+
+ it('upgrades a Homebrew Node that is already there rather than leaving it', () => {
+ expect(pickInstallOption(descriptor('node'), 'macos')?.command).toBe(
+ 'brew upgrade node 2>/dev/null || brew install node'
+ );
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/dependencies/core-dependencies.ts b/console/apps/switch-console-desktop/src/main/core/dependencies/core-dependencies.ts
index f031ce9d8..22bf66a1d 100644
--- a/console/apps/switch-console-desktop/src/main/core/dependencies/core-dependencies.ts
+++ b/console/apps/switch-console-desktop/src/main/core/dependencies/core-dependencies.ts
@@ -62,11 +62,20 @@ export const CORE_DEPENDENCIES: DependencyDescriptor[] = [
category: 'core',
commands: ['node'],
versionArgs: ['--version'],
- // Persistent SDK hosts require AbortSignal.any.
- minVersion: '20.3.0',
+ // The agent runtime connects over Node's built-in WebSocket (Node 22), and
+ // the agents controller Console installs for managed agents needs 22.13.
+ // A host below this shows as needing setup, and the install below upgrades it.
+ minVersion: '22.13.0',
docUrl: 'https://nodejs.org/en/download',
installCommands: {
- macos: [{ method: 'homebrew', command: 'brew install node', recommended: true }],
+ macos: [
+ {
+ method: 'homebrew',
+ // `brew install` leaves an old Node in place; upgrade one that is there.
+ command: 'brew upgrade node 2>/dev/null || brew install node',
+ recommended: true,
+ },
+ ],
linux: [
{
// Distro `apt install nodejs` ships ancient Node on LTS Ubuntu (v12 on
diff --git a/console/apps/switch-console-desktop/src/main/core/feature-flags/controller.ts b/console/apps/switch-console-desktop/src/main/core/feature-flags/controller.ts
new file mode 100644
index 000000000..f36951242
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/feature-flags/controller.ts
@@ -0,0 +1,24 @@
+import { err, ok } from '@switch-console/shared';
+import { getServer } from '@main/core/switch-servers/servers-store';
+import type { FeatureFlagKey } from '@shared/core/feature-flags/feature-flags';
+import { createRPCController } from '@shared/lib/ipc/rpc';
+import { featureFlagsService } from './feature-flags';
+
+export const featureFlagsController = createRPCController({
+ /** A server's feature flags as last read from its gateway. */
+ get: (serverId: string) => ok(featureFlagsService.get(serverId)),
+
+ /** A server's feature flags, read now if they never have been. */
+ current: async (serverId: string) => {
+ const server = await getServer(serverId);
+ if (!server) return err(`No Switch server ${serverId}`);
+ return ok(await featureFlagsService.current(server));
+ },
+ /** Whether any connected server turns `key` on, as last read. */
+ anyEnabled: (key: FeatureFlagKey) => ok(featureFlagsService.anyEnabled(key)),
+ /** Read every server's flags now rather than waiting for the next poll. */
+ refresh: async () => {
+ await featureFlagsService.refreshAll();
+ return ok();
+ },
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/feature-flags/feature-flags-service.test.ts b/console/apps/switch-console-desktop/src/main/core/feature-flags/feature-flags-service.test.ts
new file mode 100644
index 000000000..6ca9be850
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/feature-flags/feature-flags-service.test.ts
@@ -0,0 +1,139 @@
+import { describe, expect, it, vi } from 'vitest';
+import {
+ allFeatureFlagsOff,
+ type RemoteFeatureFlag,
+ type ServerFeatureFlags,
+} from '@shared/core/feature-flags/feature-flags';
+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';
+import { FeatureFlagsService } from './feature-flags-service';
+
+const server = (id: string) => ({ id }) as SwitchServer;
+
+function harness(servers: SwitchServer[]) {
+ const responses = new Map<string, RemoteFeatureFlag[] | Error>();
+ const changes: ServerFeatureFlags[] = [];
+ const warn = vi.fn();
+ const service = new FeatureFlagsService({
+ listServers: async () => servers,
+ fetchFlags: async (s) => {
+ const response = responses.get(s.id);
+ if (response instanceof Error) throw response;
+ return response ?? [];
+ },
+ onChange: (state) => changes.push(state),
+ warn,
+ intervalMs: 60_000,
+ });
+ return { service, responses, changes, warn, servers };
+}
+
+describe('FeatureFlagsService', () => {
+ it('reads every server separately', async () => {
+ const h = harness([server('a'), server('b')]);
+ h.responses.set('a', [{ key: 'ecosystem.show_owners', enabled: true }]);
+ h.responses.set('b', [{ key: 'ecosystem.show_owners', enabled: false }]);
+ await h.service.refreshAll();
+ expect(h.service.get('a').flags['ecosystem.show_owners']).toBe(true);
+ expect(h.service.get('b').flags['ecosystem.show_owners']).toBe(false);
+ });
+
+ it('ignores keys it does not know and treats missing keys as off', async () => {
+ const h = harness([server('a')]);
+ h.responses.set('a', [{ key: 'not.a.console.flag', enabled: true }]);
+ await h.service.refreshAll();
+ expect(h.service.get('a').flags).toEqual(allFeatureFlagsOff());
+ expect(h.service.get('a').flags).not.toHaveProperty('not.a.console.flag');
+ });
+
+ it('reports a change seen on a later poll, and nothing when nothing changed', async () => {
+ const h = harness([server('a')]);
+ await h.service.refreshAll();
+ expect(h.changes).toHaveLength(1);
+ await h.service.refreshAll();
+ expect(h.changes).toHaveLength(1);
+ h.responses.set('a', [{ key: 'ecosystem.show_owners', enabled: true }]);
+ await h.service.refreshAll();
+ expect(h.changes).toHaveLength(2);
+ expect(h.changes[1].flags['ecosystem.show_owners']).toBe(true);
+ });
+
+ it('keeps the last values read when a read fails, and says why', async () => {
+ const h = harness([server('a')]);
+ h.responses.set('a', [{ key: 'ecosystem.show_owners', enabled: true }]);
+ await h.service.refreshAll();
+ h.responses.set('a', new Error('unreachable'));
+ await h.service.refreshAll();
+ await h.service.refreshAll();
+ const state = h.service.get('a');
+ expect(state.flags['ecosystem.show_owners']).toBe(true);
+ expect(state.error).toBe('unreachable');
+ expect(h.warn).toHaveBeenCalledTimes(1);
+ });
+
+ it('has every flag off for a server never read', async () => {
+ const h = harness([server('a')]);
+ h.responses.set('a', new Error('signed out'));
+ await h.service.refreshAll();
+ expect(h.service.get('a')).toMatchObject({
+ flags: { 'ecosystem.show_owners': false },
+ fetchedAt: null,
+ error: 'signed out',
+ });
+ });
+
+ it('reads a server never read before answering for it, and only then', async () => {
+ const h = harness([server('a')]);
+ h.responses.set('a', [{ key: 'agent_management', enabled: true }]);
+ expect((await h.service.current(server('a'))).flags.agent_management).toBe(true);
+ h.responses.set('a', [{ key: 'agent_management', enabled: false }]);
+ expect((await h.service.current(server('a'))).flags.agent_management).toBe(true);
+ });
+
+ it('says whether any server turns a flag on', async () => {
+ const h = harness([server('a'), server('b')]);
+ expect(h.service.anyEnabled('agent_management')).toBe(false);
+ h.responses.set('b', [{ key: 'agent_management', enabled: true }]);
+ await h.service.refreshAll();
+ expect(h.service.anyEnabled('agent_management')).toBe(true);
+ expect(h.service.anyEnabled('hosted_agents')).toBe(false);
+ });
+
+ it('tells subscribers of a change, until they stop', async () => {
+ const h = harness([server('a')]);
+ const seen: boolean[] = [];
+ const stop = h.service.subscribe((state) => seen.push(state.flags.agent_management));
+ h.responses.set('a', [{ key: 'agent_management', enabled: true }]);
+ await h.service.refreshAll();
+ await h.service.refreshAll();
+ stop();
+ h.responses.set('a', []);
+ await h.service.refreshAll();
+ expect(seen).toEqual([true]);
+ });
+
+ it('forgets a server that was removed', async () => {
+ const h = harness([server('a')]);
+ h.responses.set('a', [{ key: 'ecosystem.show_owners', enabled: true }]);
+ await h.service.refreshAll();
+ h.servers.length = 0;
+ await h.service.refreshAll();
+ expect(h.service.get('a').fetchedAt).toBeNull();
+ });
+
+ it('polls on the interval once started', async () => {
+ vi.useFakeTimers();
+ try {
+ const h = harness([server('a')]);
+ const read = vi.spyOn(h.service, 'refreshAll');
+ h.service.start();
+ expect(read).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(read).toHaveBeenCalledTimes(2);
+ h.service.stop();
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(read).toHaveBeenCalledTimes(2);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/feature-flags/feature-flags-service.ts b/console/apps/switch-console-desktop/src/main/core/feature-flags/feature-flags-service.ts
new file mode 100644
index 000000000..cb4e3eff2
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/feature-flags/feature-flags-service.ts
@@ -0,0 +1,141 @@
+import {
+ allFeatureFlagsOff,
+ type FeatureFlagKey,
+ resolveFeatureFlags,
+ sameFeatureFlags,
+ type RemoteFeatureFlag,
+ type ServerFeatureFlags,
+} from '@shared/core/feature-flags/feature-flags';
+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';
+
+/** How often every server's flags are read again. Flags only change when a
+ * server is redeployed, so a minute is plenty. */
+export const FEATURE_FLAGS_POLL_INTERVAL_MS = 60_000;
+
+export type FeatureFlagsServiceDeps = {
+ listServers: () => Promise<SwitchServer[]>;
+ fetchFlags: (server: SwitchServer) => Promise<RemoteFeatureFlag[]>;
+ onChange: (state: ServerFeatureFlags) => void;
+ warn: (message: string, error?: unknown) => void;
+ intervalMs: number;
+};
+
+/**
+ * Keeps the feature flags of every connected Switch server, reading each from
+ * its gateway on a schedule and reporting a change as soon as it is seen.
+ *
+ * A failed read keeps the last values read and records the error, so a server
+ * that is briefly unreachable does not flip its flags off; one never read
+ * successfully has every flag off, with the reason it could not be read.
+ */
+export class FeatureFlagsService {
+ private readonly states = new Map<string, ServerFeatureFlags>();
+ private readonly listeners = new Set<(state: ServerFeatureFlags) => void>();
+ private timer: ReturnType<typeof setInterval> | null = null;
+ private inflight: Promise<void> | null = null;
+
+ constructor(private readonly deps: FeatureFlagsServiceDeps) {}
+
+ start(): void {
+ if (this.timer) return;
+ this.timer = setInterval(() => void this.refreshAll(), this.deps.intervalMs);
+ void this.refreshAll();
+ }
+
+ stop(): void {
+ if (this.timer) clearInterval(this.timer);
+ this.timer = null;
+ }
+
+ /** The server's flags as last read; every flag off if they have not been. */
+ get(serverId: string): ServerFeatureFlags {
+ return (
+ this.states.get(serverId) ?? {
+ serverId,
+ flags: allFeatureFlagsOff(),
+ fetchedAt: null,
+ error: 'Not read yet',
+ }
+ );
+ }
+
+ /**
+ * The server's flags, read now if they never have been: a server just added
+ * or just signed in to has not been read yet, and the next poll may be a
+ * minute away.
+ */
+ async current(server: SwitchServer): Promise<ServerFeatureFlags> {
+ if (this.states.get(server.id)?.fetchedAt == null) await this.readOne(server);
+ return this.get(server.id);
+ }
+
+ /**
+ * Calls `listener` whenever a server's flags change, as `onChange` is, for
+ * the main process's own consumers. Returns the way to stop.
+ */
+ subscribe(listener: (state: ServerFeatureFlags) => void): () => void {
+ this.listeners.add(listener);
+ return () => this.listeners.delete(listener);
+ }
+
+ /** Whether any server read so far turns `key` on. */
+ anyEnabled(key: FeatureFlagKey): boolean {
+ return [...this.states.values()].some((state) => state.flags[key]);
+ }
+
+ /** Read every server's flags now. Concurrent calls share one pass. */
+ refreshAll(): Promise<void> {
+ this.inflight ??= this.readAll().finally(() => {
+ this.inflight = null;
+ });
+ return this.inflight;
+ }
+
+ private async readAll(): Promise<void> {
+ let servers: SwitchServer[];
+ try {
+ servers = await this.deps.listServers();
+ } catch (error) {
+ this.deps.warn('feature-flags: could not list servers; flags left as they were', error);
+ return;
+ }
+ const known = new Set(servers.map((server) => server.id));
+ for (const serverId of [...this.states.keys()]) {
+ if (!known.has(serverId)) this.states.delete(serverId);
+ }
+ await Promise.all(servers.map((server) => this.readOne(server)));
+ }
+
+ private async readOne(server: SwitchServer): Promise<void> {
+ const previous = this.states.get(server.id);
+ let next: ServerFeatureFlags;
+ try {
+ const flags = resolveFeatureFlags(await this.deps.fetchFlags(server));
+ next = { serverId: server.id, flags, fetchedAt: Date.now(), error: null };
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ next = {
+ serverId: server.id,
+ flags: previous?.flags ?? allFeatureFlagsOff(),
+ fetchedAt: previous?.fetchedAt ?? null,
+ error: message,
+ };
+ if (previous?.error !== message) {
+ this.deps.warn(
+ `feature-flags: could not read the flags of server ${server.id}; ` +
+ (previous?.fetchedAt ? 'keeping the last values read' : 'every flag is off'),
+ error
+ );
+ }
+ }
+ this.states.set(server.id, next);
+ if (
+ !previous ||
+ !sameFeatureFlags(previous.flags, next.flags) ||
+ previous.error !== next.error
+ ) {
+ this.deps.onChange(next);
+ for (const listener of this.listeners) listener(next);
+ }
+ }
+}
diff --git a/console/apps/switch-console-desktop/src/main/core/feature-flags/feature-flags.ts b/console/apps/switch-console-desktop/src/main/core/feature-flags/feature-flags.ts
new file mode 100644
index 000000000..072f7a004
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/feature-flags/feature-flags.ts
@@ -0,0 +1,14 @@
+import { fetchFeatureFlags } from '@main/core/switch-servers/gateway-client';
+import { listServers } from '@main/core/switch-servers/servers-store';
+import { events } from '@main/lib/events';
+import { log } from '@main/lib/logger';
+import { featureFlagsChangedChannel } from '@shared/events/featureFlagEvents';
+import { FEATURE_FLAGS_POLL_INTERVAL_MS, FeatureFlagsService } from './feature-flags-service';
+
+export const featureFlagsService = new FeatureFlagsService({
+ listServers,
+ fetchFlags: fetchFeatureFlags,
+ onChange: (state) => events.emit(featureFlagsChangedChannel, state),
+ warn: (message, error) => log.warn(message, error),
+ intervalMs: FEATURE_FLAGS_POLL_INTERVAL_MS,
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.test.ts
index 59c7acb38..07bf2b988 100644
--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.test.ts
@@ -133,6 +133,10 @@ describe('buildEnvFile', () => {
// controller token secret generated for the stack.
'AGENT_MANAGEMENT_ENABLED',
'CONTROLLER_TOKEN_SECRET',
+ // Every feature flag is off unless a deployment lists it, and a managed
+ // stack lists none: agent management and cloud agents, the flags a
+ // server would turn on, are not offered from a loopback stack yet.
+ 'FEATURE_FLAGS_ENABLED',
// Private hosts Switch may reach at a tenant- or agent-supplied URL. The
// compose file always allows the bundled Mattermost; a managed stack
// allows nothing more until its operator says so.
diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml
index 761bc62ae..186281228 100644
--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml
+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml
@@ -235,8 +235,11 @@ services:
# The bundled Mattermost is on the compose network, a private address,
# so it is always allowed; .env adds to it rather than replacing it.
OUTBOUND_ALLOWED_PRIVATE_HOSTS: mattermost,${OUTBOUND_ALLOWED_PRIVATE_HOSTS:-}
+ # Replaced by the agent_management feature flag. Still passed through so
+ # switch-core refuses a .env that turns it on, rather than ignoring it.
AGENT_MANAGEMENT_ENABLED: ${AGENT_MANAGEMENT_ENABLED:-false}
CONTROLLER_TOKEN_SECRET: ${CONTROLLER_TOKEN_SECRET:-}
+ FEATURE_FLAGS_ENABLED: ${FEATURE_FLAGS_ENABLED:-}
GATEWAY_ADMIN_EMAIL: ${GATEWAY_ADMIN_EMAIL}
GATEWAY_ADMIN_PASSWORD: ${GATEWAY_ADMIN_PASSWORD}
FRONTEND_BASE_URL: ${FRONTEND_BASE_URL}
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 69f0939fb..eb96e81cc 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
@@ -1,4 +1,5 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type * as WorkspaceSession from '@main/core/workspaces/workspace-session';
import { HostUnreachableError } from '@shared/core/remote-hosts/reachability';
const fetchMe = vi.hoisted(() => vi.fn());
@@ -21,6 +22,9 @@ const serverKindOf = vi.hoisted(() => vi.fn(() => 'remote_managed'));
const updateServer = vi.hoisted(() => vi.fn());
const propagateServerApiUrl = vi.hoisted(() => vi.fn());
const followServerApiUrl = vi.hoisted(() => vi.fn());
+const listCloudMachines = vi.hoisted(() => vi.fn());
+const ensureCloudMachine = vi.hoisted(() => vi.fn());
+const serverFlags = vi.hoisted(() => ({ hosted_agents: true }));
// Stub the modules the controller imports that would otherwise pull electron /
// ssh / agent side effects at load.
@@ -59,8 +63,20 @@ vi.mock('./backfill-agent-icons', () => ({ backfillAgentIcons: vi.fn() }));
vi.mock('./bundled-chat-sign-in', () => ({ bundledChatSignInFor: vi.fn() }));
vi.mock('./managed-claude-credential', () => ({ deleteManagedClaudeCredential: vi.fn() }));
vi.mock('./gateway-web', () => ({ openAuthenticatedGatewayPage: vi.fn() }));
+vi.mock('@main/core/feature-flags/feature-flags', () => ({
+ featureFlagsService: { current: vi.fn(async () => ({ flags: serverFlags })) },
+}));
+vi.mock('@main/core/workspaces/workspace-session', async (importOriginal) => ({
+ ...(await importOriginal<typeof WorkspaceSession>()),
+ withServerWorkspaceSession: async (serverId: string, fn: (s: unknown) => unknown) =>
+ fn({ id: serverId, name: 'S' }),
+ withReachableServerWorkspaceSession: async (serverId: string, fn: (s: unknown) => unknown) =>
+ fn({ id: serverId, name: 'S' }),
+}));
vi.mock('./gateway-client', () => ({
fetchMe,
+ listCloudMachines,
+ ensureCloudMachine,
agentExistsOnServer: vi.fn(),
fetchAgentDetail: vi.fn(),
fetchAgentRooms: vi.fn(),
@@ -732,3 +748,31 @@ describe('finding the server an invite link is for', () => {
).resolves.toEqual({ kind: 'unknown', origin: 'https://cloud.example.com' });
});
});
+
+describe('cloud machines', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ serverFlags['hosted_agents'] = true;
+ });
+
+ it('lists and claims them on a server that turns them on', async () => {
+ listCloudMachines.mockResolvedValue([]);
+ ensureCloudMachine.mockResolvedValue({ machine_id: 'm' });
+ expect(await switchServersController.cloudMachines('srv')).toEqual([]);
+ expect(await switchServersController.ensureCloudMachine('srv')).toEqual({ machine_id: 'm' });
+ });
+
+ it('answers that there are none, without asking, when the server turns them off', async () => {
+ serverFlags['hosted_agents'] = false;
+ expect(await switchServersController.cloudMachines('srv')).toBeNull();
+ expect(listCloudMachines).not.toHaveBeenCalled();
+ });
+
+ it('refuses to claim one when the server turns them off', async () => {
+ serverFlags['hosted_agents'] = false;
+ await expect(switchServersController.ensureCloudMachine('srv')).rejects.toThrow(
+ 'does not have cloud machines turned on'
+ );
+ expect(ensureCloudMachine).not.toHaveBeenCalled();
+ });
+});
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 5326e4594..43d2fcf91 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
@@ -3,6 +3,7 @@ import { z } from 'zod';
import { propagateServerApiUrl } from '@main/core/agents/propagate-server-api-url';
import { appService } from '@main/core/app/service';
import { embeddedControllerService } from '@main/core/embedded-controller/embedded-controllers';
+import { featureFlagsService } from '@main/core/feature-flags/feature-flags';
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';
@@ -49,6 +50,7 @@ import {
joinWorkspaceByDomain,
createTenant,
fetchAuthConfig,
+ fetchCanCreateWorkspace,
fetchMe,
fetchJoinableWorkspaces,
fetchPendingInvitations,
@@ -179,15 +181,25 @@ async function registerSwitchCloud({ url }: SwitchCloudEndpoint): Promise<Switch
return server;
}
+/** Whether the server turns cloud machines on (its `hosted_agents` flag). */
+async function hostedAgentsOn(server: SwitchServer): Promise<boolean> {
+ return (await featureFlagsService.current(server)).flags['hosted_agents'];
+}
+
export const switchServersController = createRPCController({
/** The icons the server generates for an agent called `name`, one page at a time. */
agentIconChoices: (params: { serverId: string; name: string; page: number }) =>
withReachableServerWorkspaceSession(params.serverId, (server) =>
fetchAgentIconChoices(server, params.name, params.page)
),
+ /** Whether the signed-in account may create a workspace on the server. */
+ canCreateWorkspace: (serverId: string) =>
+ withServerWorkspaceSession(serverId, (server) => fetchCanCreateWorkspace(server)),
/** The caller's cloud machines, or null when the server offers none. */
cloudMachines: (serverId: string) =>
- withServerWorkspaceSession(serverId, (server) => listCloudMachines(server)),
+ withServerWorkspaceSession(serverId, async (server) =>
+ (await hostedAgentsOn(server)) ? listCloudMachines(server) : null
+ ),
cloudMachineLifecycle: (
serverId: string,
machineId: string,
@@ -458,7 +470,12 @@ export const switchServersController = createRPCController({
},
ensureCloudMachine: (serverId: string) =>
- withReachableServerWorkspaceSession(serverId, (server) => ensureCloudMachine(server)),
+ withReachableServerWorkspaceSession(serverId, async (server) => {
+ if (!(await hostedAgentsOn(server))) {
+ throw new Error(`${server.name} does not have cloud machines turned on.`);
+ }
+ return ensureCloudMachine(server);
+ }),
logout: async (serverId: string): Promise<void> => {
// Read before the cookie goes, so the kind of server is still knowable — and
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts
index d6123561a..7043716ef 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts
@@ -75,6 +75,7 @@ const {
removeBridgeTeam,
createInvitation,
fetchInvitations,
+ fetchCanCreateWorkspace,
fetchInviteEmailEnabled,
createRoom,
deleteBridge,
@@ -1211,6 +1212,13 @@ describe('sign-up support', () => {
await expect(listCloudMachines(SERVER)).resolves.toBeNull();
});
+ it('reads no cloud machines where the server says this workspace cannot claim one', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse({ available: false, machines: [] }));
+ await expect(listCloudMachines(SERVER)).resolves.toBeNull();
+ fetchMock.mockResolvedValueOnce(jsonResponse({ available: true, machines: [] }));
+ await expect(listCloudMachines(SERVER)).resolves.toEqual([]);
+ });
+
it('raises the server’s explanation when no machine can be had', async () => {
fetchMock.mockResolvedValueOnce(
errorResponse(503, JSON.stringify({ detail: 'Cloud machines are not offered here.' }))
@@ -2006,6 +2014,20 @@ describe('workspace invitations', () => {
await expect(fetchInviteEmailEnabled(SERVER)).resolves.toBeNull();
});
+ it('reads whether the server lets the account create a workspace', async () => {
+ fetchMock.mockResolvedValue(jsonResponse({ can_create_workspace: false }) as never);
+ await expect(fetchCanCreateWorkspace(SERVER)).resolves.toBe(false);
+
+ fetchMock.mockResolvedValue(jsonResponse({ can_create_workspace: true }) as never);
+ await expect(fetchCanCreateWorkspace(SERVER)).resolves.toBe(true);
+
+ // Older servers refused nothing up front, so nothing is hidden on them.
+ fetchMock.mockResolvedValue(jsonResponse({ state: 'ready' }) as never);
+ await expect(fetchCanCreateWorkspace(SERVER)).resolves.toBe(true);
+ fetchMock.mockResolvedValue(errorResponse(404, '{"detail":"Not Found"}') as never);
+ await expect(fetchCanCreateWorkspace(SERVER)).resolves.toBe(true);
+ });
+
it('keeps the link when an older server says nothing about the e-mail', async () => {
fetchMock.mockResolvedValue(jsonResponse({ ...ROW, token: 'tok-1' }) as never);
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
index ff59275fd..de141a012 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
@@ -9,6 +9,7 @@ import {
} from '@main/core/managed-switch-server/managed-server-status';
import { assertedTenant } from '@main/core/workspaces/asserted-tenant';
import { type CloudMachine, cloudMachineSchema } from '@shared/core/cloud-agents/cloud-agents';
+import type { RemoteFeatureFlag } from '@shared/core/feature-flags/feature-flags';
import type {
AdvancedConfigField,
ManagedMachine,
@@ -399,6 +400,16 @@ function mapUser(json: UserResponseJson): SwitchUser {
};
}
+const featureFlagsResponseSchema = z.object({
+ flags: z.array(z.object({ key: z.string(), enabled: z.boolean() })),
+});
+
+/** The server's feature flags, which its deployment sets and nothing can change. */
+export async function fetchFeatureFlags(server: SwitchServer): Promise<RemoteFeatureFlag[]> {
+ const res = await gatewayFetch(server, '/feature-flags', { authenticated: true });
+ return featureFlagsResponseSchema.parse(await res.json()).flags;
+}
+
export async function fetchMe(server: SwitchServer): Promise<SwitchUser> {
const res = await gatewayFetch(server, '/auth/me', { authenticated: true });
return mapUser((await res.json()) as UserResponseJson);
@@ -794,6 +805,33 @@ export async function fetchInviteEmailEnabled(server: SwitchServer): Promise<boo
return json.invite_email_enabled;
}
+/**
+ * Whether the signed-in account may create a workspace on this server: the
+ * server's own answer, which covers its sign-up mode, the per-person cap, and
+ * a deployment that keeps to one workspace because it is not isolating them.
+ *
+ * True on a server older than the answer (no session route, or no field): it
+ * refused nothing up front either.
+ */
+export async function fetchCanCreateWorkspace(server: SwitchServer): Promise<boolean> {
+ let res: Response;
+ try {
+ res = await gatewayFetch(server, '/auth/session', { authenticated: true });
+ } catch (cause) {
+ if (cause instanceof GatewayError && cause.status === 404) return true;
+ throw cause;
+ }
+ const json = (await res.json()) as { can_create_workspace?: unknown };
+ if (json.can_create_workspace === undefined) return true;
+ if (typeof json.can_create_workspace !== 'boolean') {
+ throw new GatewayError(
+ 'http',
+ `${server.name} reported an unreadable can_create_workspace: ${String(json.can_create_workspace)}`
+ );
+ }
+ return json.can_create_workspace;
+}
+
/** Options for `registerKnownAgent`, matching the gateway's
* `RegisterKnownAgentRequest.options`. The gateway validates these against the
* options schema of the `agent_type` being registered and ignores keys that type
@@ -2564,8 +2602,9 @@ export async function createRoom(
}
/**
- * The caller's cloud machines, or null when the server offers none: a server
- * without cloud machines answers the route with 404.
+ * The caller's cloud machines, or null when the server offers none: it says
+ * this workspace cannot claim one (`available: false`), or, from before it
+ * said so, answers the route with 404.
*/
export async function listCloudMachines(server: SwitchServer): Promise<CloudMachine[] | null> {
let response: Response;
@@ -2575,7 +2614,10 @@ export async function listCloudMachines(server: SwitchServer): Promise<CloudMach
if (error instanceof GatewayError && error.kind === 'http' && error.status === 404) return null;
throw error;
}
- return z.object({ machines: z.array(cloudMachineSchema) }).parse(await response.json()).machines;
+ const listed = z
+ .object({ available: z.boolean().optional(), machines: z.array(cloudMachineSchema) })
+ .parse(await response.json());
+ return listed.available === false ? null : listed.machines;
}
export async function cloudMachineLifecycle(
@@ -2715,7 +2757,7 @@ export async function disconnectGitHub(server: SwitchServer) {
/**
* The server does not run agent management: its `/gateway/management` routes
- * are not mounted (`AGENT_MANAGEMENT_ENABLED` is off), so they answer a bare
+ * are not mounted (its `agent_management` flag is off), so they answer a bare
* 404 rather than one in the management error envelope.
*/
export class AgentManagementUnavailableError extends Error {
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/switch-cloud.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/switch-cloud.test.ts
index 1571e584a..92bfcaec0 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/switch-cloud.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/switch-cloud.test.ts
@@ -1,8 +1,10 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
+import { BUILD_FEATURE_FLAGS } from '@shared/core/feature-flags/feature-flags';
import { requireSwitchCloudEndpoint, switchCloudEndpoint } from './switch-cloud';
afterEach(() => {
vi.unstubAllEnvs();
+ BUILD_FEATURE_FLAGS.switch_cloud = true;
});
function runWith(value: string | undefined) {
@@ -11,6 +13,13 @@ function runWith(value: string | undefined) {
}
describe('switchCloudEndpoint', () => {
+ it('is null when the build turns Switch Cloud off, even with a URL', () => {
+ runWith('https://cloud.example.com');
+ BUILD_FEATURE_FLAGS.switch_cloud = false;
+ expect(switchCloudEndpoint()).toBeNull();
+ expect(() => requireSwitchCloudEndpoint()).toThrow('switch_cloud flag is off');
+ });
+
it('is null when nothing names a Cloud', () => {
runWith(undefined);
expect(switchCloudEndpoint()).toBeNull();
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/switch-cloud.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/switch-cloud.ts
index 050dacdb8..da4e694a4 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/switch-cloud.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/switch-cloud.ts
@@ -1,3 +1,4 @@
+import { BUILD_FEATURE_FLAGS } from '@shared/core/feature-flags/feature-flags';
import type { SwitchCloudEndpoint } from '@shared/core/switch-servers/switch-cloud';
/** Read at run time, so a dev run can be pointed at a deployment without a rebuild. */
@@ -6,7 +7,8 @@ const RUNTIME_VARIABLE = 'SWITCH_CLOUD_URL';
const BUILD_VARIABLE = 'MAIN_VITE_SWITCH_CLOUD_URL';
/**
- * Where Switch Cloud is, or null when neither this run nor this build names it.
+ * Where Switch Cloud is, or null when this build does not offer it: its
+ * `switch_cloud` flag is off, or neither this run nor this build names it.
*
* Supplied from outside rather than written here, because this repository is
* public and which deployment a build treats as the Cloud is a choice made per
@@ -17,6 +19,7 @@ const BUILD_VARIABLE = 'MAIN_VITE_SWITCH_CLOUD_URL';
* stand in for the Cloud while testing (`just local-cloud`).
*/
export function switchCloudEndpoint(): SwitchCloudEndpoint | null {
+ if (!BUILD_FEATURE_FLAGS.switch_cloud) return null;
const fromRun = process.env[RUNTIME_VARIABLE]?.trim();
if (fromRun) return { url: parseCloudUrl(fromRun, RUNTIME_VARIABLE) };
const fromBuild = import.meta.env.MAIN_VITE_SWITCH_CLOUD_URL?.trim();
@@ -28,7 +31,9 @@ export function requireSwitchCloudEndpoint(): SwitchCloudEndpoint {
const endpoint = switchCloudEndpoint();
if (!endpoint) {
throw new Error(
- `Switch Cloud is not configured for this build. Set ${RUNTIME_VARIABLE} to its https URL.`
+ BUILD_FEATURE_FLAGS.switch_cloud
+ ? `Switch Cloud is not configured for this build. Set ${RUNTIME_VARIABLE} to its https URL.`
+ : 'Switch Cloud is not offered by this build: its switch_cloud flag is off.'
);
}
return endpoint;
diff --git a/console/apps/switch-console-desktop/src/main/index.ts b/console/apps/switch-console-desktop/src/main/index.ts
index 5fd66ec96..44a8a7bba 100644
--- a/console/apps/switch-console-desktop/src/main/index.ts
+++ b/console/apps/switch-console-desktop/src/main/index.ts
@@ -19,6 +19,7 @@ import { appService } from './core/app/service';
import { controlService } from './core/control-api/control-service';
import { localDependencyManager } from './core/dependencies/dependency-managers';
import { embeddedControllerService } from './core/embedded-controller/embedded-controllers';
+import { featureFlagsService } from './core/feature-flags/feature-flags';
import { locationManager } from './core/locations/location-manager';
import { locationSettingsService } from './core/locations/settings/location-settings-service';
import { localServerService } from './core/managed-switch-server/local-server-service';
@@ -200,6 +201,13 @@ void app.whenReady().then(async () => {
log.error('Workspace reconcile could not run; every server was left as it was:', error);
});
+ // Each server's feature flags, read on a schedule so a redeploy that changes
+ // them reaches the window without a restart. Started once the managed stacks
+ // report themselves, for the same reason as the reconcile above.
+ void Promise.allSettled([localServerReady, remoteServerReady]).then(() =>
+ featureFlagsService.start()
+ );
+
const dependenciesReady = localDependencyManager.probeAll().catch((e: unknown) => {
log.error('Failed to probe dependencies:', e);
});
@@ -290,6 +298,7 @@ app.on('before-quit', (event) => {
controlService.dispose();
stopAutoMigration();
stopResourceSampler();
+ featureFlagsService.stop();
localServerService.dispose();
remoteServerService.dispose();
updateService.dispose();
diff --git a/console/apps/switch-console-desktop/src/main/rpc.ts b/console/apps/switch-console-desktop/src/main/rpc.ts
index e716ff01c..7a3890347 100644
--- a/console/apps/switch-console-desktop/src/main/rpc.ts
+++ b/console/apps/switch-console-desktop/src/main/rpc.ts
@@ -5,6 +5,7 @@ import { agentTypesController } from './core/agent-types/controller';
import { agentsController } from './core/agents/controller';
import { appController } from './core/app/controller';
import { embeddedControllerController } from './core/embedded-controller/controller';
+import { featureFlagsController } from './core/feature-flags/controller';
import { filesController } from './core/fs/controller';
import { hostControllersController } from './core/host-controllers/controller';
import { locationsController } from './core/locations/controller';
@@ -54,6 +55,7 @@ export const rpcRouter = createRPCRouter({
agentMigration: agentMigrationController,
hostControllers: hostControllersController,
managedAgents: managedAgentsController,
+ featureFlags: featureFlagsController,
fs: createRPCNamespace({
watch: filesController,
}),
diff --git a/console/apps/switch-console-desktop/src/renderer/app/shell-shape.test.ts b/console/apps/switch-console-desktop/src/renderer/app/shell-shape.test.ts
index 204e09326..73ebfb1da 100644
--- a/console/apps/switch-console-desktop/src/renderer/app/shell-shape.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/app/shell-shape.test.ts
@@ -19,6 +19,7 @@ function shape(differences: Partial<Parameters<typeof shellShape>[0]>) {
installIsEmpty: true,
viewWorksWithoutServer: false,
onboardingInProgress: false,
+ onboardingEnabled: true,
...differences,
});
}
@@ -34,6 +35,15 @@ describe('what fills the window', () => {
expect(shape({})).toBe('onboarding');
});
+ it('opens the workspace on a fresh install when the build has no first-run pages', () => {
+ expect(shape({ onboardingEnabled: false })).toBe('workspace');
+ expect(shape({ onboardingEnabled: false, onboardingInProgress: true })).toBe('workspace');
+ });
+
+ it('still waits for the read when the build has no first-run pages', () => {
+ expect(shape({ onboardingEnabled: false, loaded: false })).toBe('loading');
+ });
+
/**
* "Something to show" is not "a server". Removing one says in as many words
* that its agents are kept and can be re-linked elsewhere, so an install left
diff --git a/console/apps/switch-console-desktop/src/renderer/app/shell-shape.ts b/console/apps/switch-console-desktop/src/renderer/app/shell-shape.ts
index 5f9d0aec8..fc4c1e61f 100644
--- a/console/apps/switch-console-desktop/src/renderer/app/shell-shape.ts
+++ b/console/apps/switch-console-desktop/src/renderer/app/shell-shape.ts
@@ -19,6 +19,7 @@ export function shellShape({
installIsEmpty,
viewWorksWithoutServer,
onboardingInProgress,
+ onboardingEnabled,
}: {
loaded: boolean;
/**
@@ -52,6 +53,11 @@ export function shellShape({
viewWorksWithoutServer: boolean;
/** Whether the first-run flow has been started and not yet finished. */
onboardingInProgress: boolean;
+ /**
+ * Whether this build shows the first-run pages at all. Without them a fresh
+ * install opens the workspace, and the first server is added from there.
+ */
+ onboardingEnabled: boolean;
}): ShellShape {
// Checked before the read, not after. Such a view needs nothing from this
// install to draw, and a first read that failed is exactly when Settings —
@@ -61,6 +67,7 @@ export function shellShape({
// in hand is still the list, and a later refresh failing is not a reason to
// take the app away.
if (!loaded) return listError === null ? 'loading' : 'failed';
+ if (!onboardingEnabled) return 'workspace';
// A flow in progress outranks what the install holds, because the flow is
// what changes it: the server is added several pages before the user has
// signed in to it, and going by the contents alone would throw them out of
diff --git a/console/apps/switch-console-desktop/src/renderer/app/workspace.tsx b/console/apps/switch-console-desktop/src/renderer/app/workspace.tsx
index cb2f395c4..545ae3e94 100644
--- a/console/apps/switch-console-desktop/src/renderer/app/workspace.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/app/workspace.tsx
@@ -15,6 +15,7 @@ import { useWorkspaceSlots } from '@renderer/lib/layout/workspace-slots';
import { Button } from '@renderer/lib/ui/button';
import { Spinner } from '@renderer/lib/ui/spinner';
import { Toaster } from '@renderer/lib/ui/toaster';
+import { BUILD_FEATURE_FLAGS } from '@shared/core/feature-flags/feature-flags';
import { shellShape } from './shell-shape';
import { viewWorksWithoutServer } from './view-registry';
@@ -65,6 +66,7 @@ const Shell = observer(function Shell({ mainContent }: { mainContent: ReactNode
installIsEmpty: switchServersStore.installIsEmpty,
viewWorksWithoutServer: viewWorksWithoutServer(currentViewId),
onboardingInProgress: onboardingStore.inProgress,
+ onboardingEnabled: BUILD_FEATURE_FLAGS.onboarding,
});
switch (shape) {
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/new-agent-form.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/new-agent-form.tsx
index 589e7864c..ce57ff1d2 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/new-agent-form.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/new-agent-form.tsx
@@ -3,6 +3,7 @@ import { useQuery, useQueryClient } from '@tanstack/react-query';
import { Cloud, Monitor, Server } from 'lucide-react';
import { observer } from 'mobx-react-lite';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useCloudMachines } from '@renderer/features/cloud-agents/use-cloud-agents';
import { agentsStore } from '@renderer/features/locations/stores/agents-store';
import { getLocationManagerStore } from '@renderer/features/locations/stores/location-selectors';
import { MANAGED_AGENTS_KEY } from '@renderer/features/managed-agents/use-managed-agents';
@@ -14,12 +15,12 @@ import {
} from '@renderer/features/remote-hosts/host-readiness-notice';
import { useAppSettingsKey } from '@renderer/features/settings/use-app-settings-key';
import { policyHasDeadRule } from '@renderer/features/switch-servers/addressing-policy-editor';
-import { isSwitchCloudServer } from '@renderer/features/switch-servers/switch-cloud-origin';
import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { ProviderConnectionStatus } from '@renderer/lib/components/provider-connection-status';
import { describeFailure, failureText } from '@renderer/lib/errors/describe-failure';
import { toast } from '@renderer/lib/hooks/use-toast';
+import { useFeatureFlags } from '@renderer/lib/hooks/useFeatureFlags';
import { rpc } from '@renderer/lib/ipc';
import { useNavigate } from '@renderer/lib/layout/navigation-provider';
import { useModalContext, useShowModal } from '@renderer/lib/modal/modal-provider';
@@ -133,9 +134,17 @@ export const NewAgentForm = observer(function NewAgentForm({
const selectedServer = switchServersStore.servers.find(
(server) => server.id === selectedServerId
);
- // Switch Cloud offers everything any server does, and running in the cloud besides.
- const cloudAvailable = !!selectedServer && isSwitchCloudServer(selectedServer);
+ // Running in the cloud is offered where the server's flag offers it, and can
+ // be chosen only where the server says this workspace can claim a machine:
+ // its cloud machine list is null where it cannot, and undefined until read.
+ const serverFlags = useFeatureFlags(selectedServerId);
+ const cloudOffered = !!selectedServer && serverFlags['hosted_agents'];
+ const cloudMachines = useCloudMachines(cloudOffered ? selectedServerId : null);
+ const cloudAvailable = cloudOffered && Array.isArray(cloudMachines.data);
+ const cloudNotSetUp = cloudOffered && cloudMachines.data === null;
const isCloudRun = runHost === 'cloud';
+ // Why the form moved off Switch cloud by itself, said under the picker.
+ const [cloudFallback, setCloudFallback] = useState<string | null>(null);
// On a server with agent management the server lists where agents can run:
// every machine the user owns there. Null when it does not run management.
@@ -246,6 +255,17 @@ export const NewAgentForm = observer(function NewAgentForm({
}
}, [allowedHosts, runHost]);
+ // Switch cloud was chosen (or preset) on a server that turns out not to run
+ // cloud machines: run here instead, and say why rather than leave the form
+ // unable to add the agent.
+ useEffect(() => {
+ if (runHost !== 'cloud' || !cloudNotSetUp) return;
+ setRunHost(LOCAL_RUN_LOCATION);
+ setCloudFallback(
+ 'Cloud agents are not set up on this server, so this agent will run on this computer.'
+ );
+ }, [cloudNotSetUp, runHost]);
+
// The cloud machine's controller is online: the agent goes on it, as on any machine.
useEffect(() => {
if (cloudController?.state === 'online') setRunHost(machineRunLocation(cloudController.id));
@@ -759,11 +779,17 @@ export const NewAgentForm = observer(function NewAgentForm({
<span className="text-xs text-foreground-muted">local</span>
</SelectItem>
)}
- {cloudAvailable && !cloudMachineListed && (
- <SelectItem value="cloud">
+ {cloudOffered && !cloudMachineListed && (
+ <SelectItem value="cloud" disabled={!cloudAvailable}>
<Cloud className="size-4 text-foreground-muted" />
<span className="flex-1">Switch cloud</span>
- <span className="text-xs text-foreground-muted">preview</span>
+ <span className="text-xs text-foreground-muted">
+ {cloudAvailable
+ ? 'preview'
+ : cloudNotSetUp
+ ? 'not set up on this server'
+ : 'checking…'}
+ </span>
</SelectItem>
)}
{allowedHosts
@@ -779,6 +805,12 @@ export const NewAgentForm = observer(function NewAgentForm({
))}
</SelectContent>
</Select>
+ {cloudFallback && !isCloudRun && (
+ <p className="flex items-start gap-1.5 text-xs text-foreground-muted" role="status">
+ <Cloud className="mt-0.5 size-3.5 shrink-0" />
+ <span>{cloudFallback}</span>
+ </p>
+ )}
{!isCloudRun && !management && runLocationConstrained && (
<p className="text-xs text-foreground-muted">
{targetServer?.managementKind === 'remote'
diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-list.tsx b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-list.tsx
index e3d76491f..013cc94dd 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-list.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-list.tsx
@@ -6,7 +6,7 @@ import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider
import { useWorkspaceSlots } from '@renderer/lib/layout/workspace-slots';
import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';
import { isCloudMachine, type ManagedAgentView } from '@shared/core/managed-agents/managed-agents';
-import { isValidProviderId } from '@shared/core/providers/agent-provider-registry';
+import { getProvider, isValidProviderId } from '@shared/core/providers/agent-provider-registry';
import { type AgentPresence, SidebarAgentRow } from '../sidebar/agent-row';
import {
type ManagedAgentState,
@@ -33,13 +33,22 @@ export const ManagedAgentList = observer(function ManagedAgentList() {
if (!agents.data?.length) return null;
return (
<div className="flex flex-col gap-[2px]" aria-label="Managed agents">
- {agents.data.map((agent) => (
+ {attentionFirst(agents.data).map((agent) => (
<ManagedAgentRow key={agent.agentId} agent={agent} />
))}
</div>
);
});
+/**
+ * The agents that need looking at first — a failed agent, or one whose machine
+ * is gone — and the rest in the order the server listed them.
+ */
+export function attentionFirst(agents: ManagedAgentView[]): ManagedAgentView[] {
+ const needsAttention = (agent: ManagedAgentView) => managedAgentState(agent).tone === 'problem';
+ return [...agents.filter(needsAttention), ...agents.filter((agent) => !needsAttention(agent))];
+}
+
const ManagedAgentRow = observer(function ManagedAgentRow({ agent }: { agent: ManagedAgentView }) {
const { navigate } = useNavigate();
const { currentView } = useWorkspaceSlots();
@@ -52,6 +61,7 @@ const ManagedAgentRow = observer(function ManagedAgentRow({ agent }: { agent: Ma
machines.data?.find((machine) => machine.id === agent.machine?.id)?.local?.kind ===
'this-computer';
const machineDown = agent.machine !== null && agent.machine.state !== 'online';
+ const providerName = isValidProviderId(provider) ? getProvider(provider)?.name : null;
return (
<SidebarAgentRow
label={label}
@@ -66,7 +76,9 @@ const ManagedAgentRow = observer(function ManagedAgentRow({ agent }: { agent: Ma
tone: PRESENCE_TONE[state.tone],
label: state.detail ? `${state.label}: ${state.detail}` : state.label,
}}
- dimmed={machineDown}
+ dimmed={machineDown || state.tone === 'idle'}
+ showProviderMark={false}
+ title={providerName ? `${label} · ${providerName}` : label}
marks={
!thisComputer && (
<Tooltip>
diff --git a/console/apps/switch-console-desktop/src/renderer/features/settings/components/ReplayOnboardingRow.tsx b/console/apps/switch-console-desktop/src/renderer/features/settings/components/ReplayOnboardingRow.tsx
index 68071216f..cc89039dd 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/settings/components/ReplayOnboardingRow.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/settings/components/ReplayOnboardingRow.tsx
@@ -2,6 +2,7 @@ import { onboardingStore } from '@renderer/features/onboarding/onboarding-store'
import { showDevTools } from '@renderer/lib/dev-tools';
import { useNavigate } from '@renderer/lib/layout/navigation-provider';
import { Button } from '@renderer/lib/ui/button';
+import { BUILD_FEATURE_FLAGS } from '@shared/core/feature-flags/feature-flags';
import { SettingRow } from './SettingRow';
/**
@@ -13,7 +14,7 @@ import { SettingRow } from './SettingRow';
*/
export function ReplayOnboardingRow() {
const { navigate } = useNavigate();
- if (!showDevTools()) return null;
+ if (!showDevTools() || !BUILD_FEATURE_FLAGS.onboarding) return null;
return (
<SettingRow
title="Replay first-run pages"
diff --git a/console/apps/switch-console-desktop/src/renderer/features/settings/components/SettingsPage.tsx b/console/apps/switch-console-desktop/src/renderer/features/settings/components/SettingsPage.tsx
index c826c37f4..459866762 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/settings/components/SettingsPage.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/settings/components/SettingsPage.tsx
@@ -3,6 +3,7 @@ import { MigrationSettingsPage } from '@renderer/features/agent-migration/migrat
import { RemoteHostsSettingsPage } from '@renderer/features/remote-hosts/views/remote-hosts-view';
import { PageHeader } from '@renderer/lib/components/page-header';
import { PageContent, PageLayout, PageSidebarMenu } from '@renderer/lib/components/page-layout';
+import { useAnyServerFeatureFlag } from '@renderer/lib/hooks/useFeatureFlags';
import { openExternalUrl } from '@renderer/lib/open-external';
import { SWITCH_CONSOLE_DOCS_URL } from '@shared/urls';
import { AgentsSettingsPage } from '../agents-page/AgentsSettingsPage';
@@ -100,15 +101,19 @@ export function SettingsPage({
tab: SettingsPageTab;
onTabChange: (tab: SettingsPageTab) => void;
}) {
+ // Only offered while some server runs agent management: elsewhere there is
+ // nothing to move to managed and nothing managed to look after.
+ const agentManagement = useAnyServerFeatureFlag('agent_management');
const handleDocsClick = useCallback(() => {
void openExternalUrl(SWITCH_CONSOLE_DOCS_URL, 'Could not open the documentation');
}, []);
- const tabs: Array<{
+ type Tab = {
id: SettingsPageTab;
label: string;
isExternal?: boolean;
- }> = [
+ };
+ const allTabs: Tab[] = [
// Switch Console v0 hides Account, Integrations, Connections (SSH), and Browser tabs.
{ id: 'general', label: 'General' },
{ id: 'clis-models', label: 'Agent providers' },
@@ -117,8 +122,10 @@ export function SettingsPage({
{ id: 'interface', label: 'Interface' },
{ id: 'docs', label: 'Docs', isExternal: true },
];
+ const tabs = allTabs.filter((tab) => agentManagement || tab.id !== 'managed-agents');
- const currentContent = TAB_CONTENT[activeTab]?.();
+ const shownTab = !agentManagement && activeTab === 'managed-agents' ? 'general' : activeTab;
+ const currentContent = TAB_CONTENT[shownTab]?.();
return (
<PageLayout
@@ -126,7 +133,7 @@ export function SettingsPage({
sidebar={
<PageSidebarMenu
items={tabs}
- activeId={activeTab}
+ activeId={shownTab}
onSelect={(item) => {
if (item.isExternal) {
handleDocsClick();
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-row.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-row.tsx
index 947ae69a5..3043b5b0d 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-row.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-row.tsx
@@ -29,6 +29,8 @@ export const SidebarAgentRow = observer(function SidebarAgentRow({
marks,
status,
actions,
+ showProviderMark = true,
+ title,
}: {
label: string;
iconUrl: string | null;
@@ -46,12 +48,17 @@ export const SidebarAgentRow = observer(function SidebarAgentRow({
status: ReactNode;
/** The row's buttons, shown on hover. */
actions: ReactNode;
+ /** Whether the provider's mark follows the name. Managed rows leave it to the hover text. */
+ showProviderMark?: boolean;
+ /** Hover text for the row. */
+ title?: string;
}) {
return (
<SidebarMenuRow
- className="group/row flex justify-between"
+ className="group/row flex h-[30px] justify-between py-0 text-[13px]"
data-active={isActive || undefined}
isActive={isActive}
+ title={title}
onMouseDown={(e) => e.preventDefault()}
onClick={onOpen}
>
@@ -78,11 +85,12 @@ export const SidebarAgentRow = observer(function SidebarAgentRow({
className="flex-initial truncate select-none"
>
<span className="flex min-w-0 items-center gap-1.5">
- <span className={cn('truncate', dimmed && 'text-foreground-muted')}>{label}</span>
+ <span className={cn('truncate font-medium', dimmed && 'opacity-60')}>{label}</span>
{/* What the agent runs on. The avatar took the leading slot, so
without this the row no longer says. Hideable from the Sessions
menu for a reader who only cares about identity. */}
- {!sidebarStore.hideProviderMark &&
+ {showProviderMark &&
+ !sidebarStore.hideProviderMark &&
(providerId ? (
<AgentIcon id={providerId} size={12} className="h-3 w-3 shrink-0" />
) : (
@@ -105,11 +113,14 @@ export type AgentPresence = {
label: string;
};
+// Running reads green, on its way (starting, connecting) amber, stopped grey
+// and in trouble red: amber is for something still happening, not for an
+// agent at rest.
const DOT_COLOR: Record<AgentPresence['tone'], string> = {
running: 'bg-foreground-success',
- stopped: 'bg-foreground-warning',
+ stopped: 'bg-[var(--fg-passive)]',
problem: 'bg-foreground-destructive',
- pending: 'bg-foreground-muted',
+ pending: 'bg-foreground-warning',
};
/**
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/left-sidebar.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/left-sidebar.tsx
index 0e1b067f8..50dc93de0 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/left-sidebar.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/left-sidebar.tsx
@@ -13,7 +13,7 @@ import { WorkspaceSwitcher } from '../switch-servers/workspace-switcher';
import { SidebarPinnedSessionList } from './pinned-session-list';
import { SessionDiscoveryStatus } from './session-discovery-status';
import { SessionsSectionHeader } from './sessions-section-header';
-import { SidebarGroupedList } from './sidebar-grouped-list';
+import { SidebarGroupedList, useAgentManagementMode } from './sidebar-grouped-list';
import {
SidebarContainer,
SidebarContent,
@@ -34,6 +34,7 @@ export const LeftSidebar: React.FC = observer(function LeftSidebar() {
const { currentView } = useWorkspaceSlots();
const { isDragOver, onDragOver, onDragEnter, onDragLeave, onDrop } = useSidebarDrop();
+ const managementMode = useAgentManagementMode();
return (
<div
@@ -65,8 +66,10 @@ export const LeftSidebar: React.FC = observer(function LeftSidebar() {
<WorkspaceNav />
</div>
<SidebarGroup className="mt-0 mb-0 flex min-h-0 flex-1 flex-col">
- <SessionsSectionHeader />
- <SessionDiscoveryStatus />
+ {/* With agent management the sections draw their own headings,
+ inside the list, so they scroll with it. */}
+ {!managementMode && <SessionsSectionHeader />}
+ {!managementMode && <SessionDiscoveryStatus />}
<SidebarGroupContent className="flex min-h-0 flex-1 flex-col">
<SidebarMenu className="flex min-h-0 flex-1 flex-col">
<SidebarGroupedList />
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/main-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/main-section.tsx
new file mode 100644
index 000000000..b555c0b2f
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/main-section.tsx
@@ -0,0 +1,133 @@
+import { DoorOpen, MessageCircle, X } from 'lucide-react';
+import { observer } from 'mobx-react-lite';
+import { useState } from 'react';
+import { ManagedAgentList } from '@renderer/features/managed-agents/managed-agent-list';
+import { useManagedAgents } from '@renderer/features/managed-agents/use-managed-agents';
+import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
+import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
+import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';
+import { SegmentedControl } from '@renderer/lib/ui/segmented-control';
+import type { RemoteRoomSummary } from '@shared/core/switch-servers/switch-servers';
+import { SidebarMenuRow } from './sidebar-primitives';
+import { isRoomViewActive, openRoomView } from './sidebar-room-grouping';
+
+type MainTab = 'agents' | 'rooms';
+
+const TAB_KEY = 'sidebar.mainTab';
+const CHATS_TEASER_KEY = 'sidebar.chatsTeaserDismissed';
+
+const TABS: { value: MainTab; label: string }[] = [
+ { value: 'agents', label: 'Agents' },
+ { value: 'rooms', label: 'Rooms' },
+];
+
+function storedTab(): MainTab {
+ return localStorage.getItem(TAB_KEY) === 'rooms' ? 'rooms' : 'agents';
+}
+
+/**
+ * The sidebar's main section on a server that runs agent management: its
+ * managed agents or its rooms, one row each, behind an Agents / Rooms switch.
+ *
+ * Shown only once the server has a managed agent. Until then everything is
+ * still under the legacy Sessions section, and a switch over an empty list
+ * would be the first thing on screen with nothing behind it.
+ */
+export const SidebarMainSection = observer(function SidebarMainSection() {
+ const [tab, setTab] = useState<MainTab>(storedTab);
+ const agents = useManagedAgents(switchServersStore.activeServerId);
+ const rooms = switchRoomsStore.listedRoomsInActiveScope;
+ const count = tab === 'agents' ? (agents.data?.length ?? 0) : rooms.length;
+
+ return (
+ <section aria-label={tab === 'agents' ? 'Agents' : 'Rooms'} className="flex flex-col">
+ <div className="flex items-center justify-between px-[9px] pt-4 pb-1.5">
+ <SegmentedControl
+ value={tab}
+ onChange={(next) => {
+ setTab(next);
+ localStorage.setItem(TAB_KEY, next);
+ }}
+ options={TABS}
+ ariaLabel="Show agents or rooms"
+ quiet
+ />
+ <span className="text-[11.5px] text-[var(--fg-passive)] tabular-nums">{count}</span>
+ </div>
+ {tab === 'agents' ? (
+ <>
+ <ManagedAgentList />
+ {agents.data?.length === 0 && (
+ <p className="px-[9px] py-2 text-xs text-foreground-muted">No agents yet.</p>
+ )}
+ <ChatsTeaser />
+ </>
+ ) : (
+ <RoomList rooms={rooms} />
+ )}
+ </section>
+ );
+});
+
+/** One row per room: its messaging app and its name. Nothing is nested under it. */
+const RoomList = observer(function RoomList({ rooms }: { rooms: RemoteRoomSummary[] }) {
+ if (rooms.length === 0) {
+ return <p className="px-[9px] py-2 text-xs text-foreground-muted">No rooms on this server.</p>;
+ }
+ return (
+ <div className="flex flex-col gap-[2px]" aria-label="Rooms">
+ {rooms.map((room) => (
+ <SidebarMenuRow
+ key={room.id}
+ isActive={isRoomViewActive(room.id)}
+ title={room.bridgeDisplayName ? `${room.name} · ${room.bridgeDisplayName}` : room.name}
+ onMouseDown={(event) => event.preventDefault()}
+ onClick={() => openRoomView(room.id)}
+ className="h-[30px] py-0 text-[13px]"
+ >
+ {hasBridgeIcon(room.bridgeType) ? (
+ <BridgeIcon bridgeType={room.bridgeType} size={17} className="shrink-0" />
+ ) : (
+ <DoorOpen className="size-[17px] shrink-0 text-[var(--fg-icon)]" />
+ )}
+ <span className="min-w-0 flex-1 truncate">{room.name}</span>
+ </SidebarMenuRow>
+ ))}
+ </div>
+ );
+});
+
+/**
+ * One sentence about what is coming for these agents, under them, closed for
+ * good with its ×.
+ */
+function ChatsTeaser() {
+ const [dismissed, setDismissed] = useState(() => localStorage.getItem(CHATS_TEASER_KEY) === '1');
+ if (dismissed) return null;
+ return (
+ <div className="mx-[2px] mt-3 flex gap-2.5 rounded-[10px] border-[0.5px] border-[var(--hair)] bg-[var(--menu-faint)] p-2.5">
+ <span className="flex size-6 shrink-0 items-center justify-center rounded-[7px] bg-[rgb(79_160_94_/_0.14)] text-[#8fcb9e]">
+ <MessageCircle className="size-3.5" />
+ </span>
+ <div className="min-w-0 flex-1">
+ <p className="text-[12.5px] font-medium text-[var(--fg-name)]">
+ Chats with agents are coming
+ </p>
+ <p className="mt-0.5 text-xs leading-snug text-[var(--fg-dim)]">
+ Soon you&rsquo;ll talk to any of these agents directly, not only in rooms.
+ </p>
+ </div>
+ <button
+ type="button"
+ aria-label="Dismiss"
+ className="flex size-5 shrink-0 items-center justify-center rounded-md text-[var(--fg-icon)] hover:bg-[var(--sel-soft)] hover:text-foreground"
+ onClick={() => {
+ localStorage.setItem(CHATS_TEASER_KEY, '1');
+ setDismissed(true);
+ }}
+ >
+ <X className="size-3.5" />
+ </button>
+ </div>
+ );
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sessions-section-header.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sessions-section-header.tsx
index 0e4ccdb3f..09542aa83 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sessions-section-header.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sessions-section-header.tsx
@@ -206,7 +206,15 @@ const AgentFilterSections = observer(function AgentFilterSections() {
* setting, which is why it previously sat under a "Group by" caption; keeping
* it beside "Sessions" says the same thing without spending a second row.
*/
-export const SessionsSectionHeader = observer(function SessionsSectionHeader() {
+export const SessionsSectionHeader = observer(function SessionsSectionHeader({
+ legacy = false,
+}: {
+ /**
+ * Under the Agents / Rooms section of a server that runs agent management:
+ * tagged Legacy, grouped by agent only, since rooms have their own tab.
+ */
+ legacy?: boolean;
+}) {
const showAddLocationModal = useShowModal('addAgentModal');
const showCreateRoomModal = useShowModal('createRoomModal');
const showCreateSessionModal = useShowModal('sessionModal');
@@ -215,16 +223,22 @@ export const SessionsSectionHeader = observer(function SessionsSectionHeader() {
// Which grouping you are looking at says how you want the list arranged, not
// which thing you next want to make, and reaching the other action used to
// mean switching view first.
- const roomMode = sidebarStore.grouping === 'room';
+ const roomMode = !legacy && sidebarStore.grouping === 'room';
return (
<>
{/* Label, its overflow menu and the grouping toggle share one line. The
three icon buttons that used to sit on a second line — sort, filter,
add — are all in the menu now; the actions are unchanged. */}
- <div className="group/sessions flex items-center justify-between px-5 pt-[18px] pb-2">
+ <div
+ className={cn(
+ 'group/sessions flex items-center justify-between',
+ legacy ? 'px-[9px] pt-4 pb-1.5' : 'px-5 pt-[18px] pb-2'
+ )}
+ >
<div className="flex items-center gap-[6px]">
<SectionLabel>Sessions</SectionLabel>
+ {legacy && <LegacyTag />}
<DropdownMenu onOpenChange={setOptionsOpen}>
<Tooltip>
<DropdownMenuTrigger
@@ -333,10 +347,10 @@ export const SessionsSectionHeader = observer(function SessionsSectionHeader() {
</DropdownMenuContent>
</DropdownMenu>
</div>
- <ViewGroupingToggle />
+ {!legacy && <ViewGroupingToggle />}
</div>
{/* Outside the tree's scroller, so it stays put as the list scrolls. */}
- <div className="px-2 pb-1">
+ <div className={legacy ? 'pb-1' : 'px-2 pb-1'}>
<button
type="button"
onClick={() => showCreateSessionModal({ entryPoint: 'sidebar' })}
@@ -349,3 +363,25 @@ export const SessionsSectionHeader = observer(function SessionsSectionHeader() {
</>
);
});
+
+/**
+ * Says the section below is the old way agents run, without alarm: no colour,
+ * a hairline, and the why on hover.
+ */
+function LegacyTag() {
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <span className="ml-[1px] inline-flex h-4 items-center rounded-[5px] border-[0.5px] border-[var(--hair-strong)] px-1.5 text-[10px] font-medium tracking-[0.02em] text-[var(--fg-passive)]">
+ Legacy
+ </span>
+ }
+ />
+ <TooltipContent className="max-w-60">
+ Agents this Console still runs itself, with their sessions. Console moves each one to a
+ managed machine; once it has moved it shows under Agents above.
+ </TooltipContent>
+ </Tooltip>
+ );
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx
index f1ea2b645..dc9a3d71b 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx
@@ -8,13 +8,17 @@ import { hostReachabilityStore } from '@renderer/features/remote-hosts/host-reac
import { switchRoomsStore as roomConnectionsStore } from '@renderer/features/switch-rooms/switch-rooms-store';
import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
+import { useFeatureFlags } from '@renderer/lib/hooks/useFeatureFlags';
import { useNavigate } from '@renderer/lib/layout/navigation-provider';
import { sidebarStore } from '@renderer/lib/stores/app-state';
import { AgentTree } from './agent-tree';
+import { SidebarMainSection } from './main-section';
import { RoomTree } from './room-tree';
+import { SessionDiscoveryStatus } from './session-discovery-status';
+import { SessionsSectionHeader } from './sessions-section-header';
import { useScrollSelectionIntoView } from './sidebar-auto-scroll';
import { sidebarEmptyState } from './sidebar-empty-state';
-import { refreshSidebarRoomState } from './sidebar-tree-data';
+import { agentsInActiveScope, refreshSidebarRoomState } from './sidebar-tree-data';
/**
* How often the room state is reconciled against the servers while the window
@@ -89,6 +93,7 @@ export const SidebarGroupedList = observer(function SidebarGroupedList() {
const managedAgents = useManagedAgents(switchServersStore.activeServerId);
const activeServerId = switchServersStore.activeServerId;
+ const managementMode = useAgentManagementMode();
const managedAgentCount = activeServerId && managedAgents.data ? managedAgents.data.length : 0;
const emptyState = sidebarEmptyState({
grouping: sidebarStore.grouping,
@@ -100,6 +105,32 @@ export const SidebarGroupedList = observer(function SidebarGroupedList() {
serverListedAgentCount: managedAgentCount,
});
+ if (managementMode) {
+ const managedIds = new Set((managedAgents.data ?? []).map((agent) => agent.agentId));
+ const legacyCount = agentsInActiveScope().filter(
+ (entry) => entry.agent.switchAgentId === null || !managedIds.has(entry.agent.switchAgentId)
+ ).length;
+ return (
+ <div
+ ref={scrollerRef}
+ className="flex min-h-0 flex-1 flex-col gap-[2px] overflow-y-auto px-2.5 pt-0 pb-3"
+ >
+ <RoomStateDisclosure />
+ {/* Agents / Rooms once anything is managed, or on an install with no
+ agents yet, where there is nothing legacy to show. Sessions only
+ while some agent still runs the old way, and gone once none does. */}
+ {(managedAgentCount > 0 || legacyCount === 0) && <SidebarMainSection />}
+ {legacyCount > 0 && (
+ <>
+ <SessionsSectionHeader legacy />
+ <SessionDiscoveryStatus />
+ <AgentTree />
+ </>
+ )}
+ </div>
+ );
+ }
+
return (
<div
ref={scrollerRef}
@@ -122,6 +153,15 @@ export const SidebarGroupedList = observer(function SidebarGroupedList() {
);
});
+/**
+ * Whether the server on screen runs agent management, which is what turns the
+ * sidebar into Agents / Rooms with the old Sessions list below as legacy. A
+ * server without it keeps the sidebar it always had.
+ */
+export function useAgentManagementMode(): boolean {
+ return useFeatureFlags(switchServersStore.activeServerId).agent_management;
+}
+
/**
* Says so when the room state on screen is known to be incomplete.
*
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/AddServerModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/AddServerModal.tsx
index 101535054..b1f619f84 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/AddServerModal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/AddServerModal.tsx
@@ -24,9 +24,10 @@ import type {
AddServerChoiceName,
AddServerStepName,
} from '@shared/core/switch-servers/add-server-steps';
-import type {
- ServerApiUrlPropagation,
- SwitchServer,
+import {
+ type ServerApiUrlPropagation,
+ type SwitchServer,
+ urlOrigin,
} from '@shared/core/switch-servers/switch-servers';
import { ConnectionsStep } from './connections-step';
import { LinkAccountsStep } from './link-accounts-step';
@@ -86,6 +87,16 @@ type Props = BaseModalProps<void> & {
mode?: 'local' | 'remoteHost' | 'external';
};
+/**
+ * Where signing in to Switch Cloud leads: on to setting up cloud agents when
+ * the Cloud offers them (its `hosted_agents` flag), otherwise to the step any
+ * other server ends on.
+ */
+async function stepAfterCloudSignIn(serverId: string): Promise<Step> {
+ const flags = await rpc.featureFlags.current(serverId);
+ return flags.success && flags.data.flags.hosted_agents ? 'managedGitHub' : 'linkAccounts';
+}
+
type Step =
| 'managedAgent'
| 'managedGitHub'
@@ -209,8 +220,10 @@ export const AddServerModal = observer(function AddServerModal(props: Props) {
* chooser rather than to a connect-by-URL form it never passed through. An
* account already signed in goes on to setting up its cloud agents.
*/
- const enterCloud = (server: SwitchServer) => {
- const next: Step = switchServersStore.isConnected(server.id) ? 'managedGitHub' : 'signIn';
+ const enterCloud = async (server: SwitchServer) => {
+ const next: Step = switchServersStore.isConnected(server.id)
+ ? await stepAfterCloudSignIn(server.id)
+ : 'signIn';
setConnected(server);
setChoice('cloud');
setStep(next);
@@ -293,7 +306,8 @@ export const AddServerModal = observer(function AddServerModal(props: Props) {
onClose={props.onClose}
onSignedIn={(signedIn) => {
setMachineUnavailable(machineUnavailableReason(signedIn));
- goToStep(choice === 'cloud' ? 'managedGitHub' : 'linkAccounts');
+ if (choice === 'cloud') void stepAfterCloudSignIn(connected.id).then(goToStep);
+ else goToStep('linkAccounts');
}}
/>
);
@@ -331,7 +345,7 @@ export const AddServerModal = observer(function AddServerModal(props: Props) {
// Step 1 — choose where the server lives
// ---------------------------------------------------------------------------
-function ChooseStep({
+export const ChooseStep = observer(function ChooseStep({
onLocal,
onRemoteHost,
onExternal,
@@ -345,6 +359,13 @@ function ChooseStep({
onClose: () => void;
}) {
const cloud = useSwitchCloud();
+ // Switch Cloud is one server: once it is added, its workspaces are in the
+ // switcher, and offering to add it again would only lead back to it.
+ const cloudAdded =
+ cloud.kind === 'open' &&
+ switchServersStore.servers.some(
+ (server) => urlOrigin(server.gatewayUrl) === urlOrigin(cloud.url)
+ );
const [cloudAttempt, setCloudAttempt] = useState<{ connecting: boolean; error: string | null }>({
connecting: false,
error: null,
@@ -374,7 +395,7 @@ function ChooseStep({
<div className="grid gap-3">
{/* Offered only when this build knows where the Cloud is. A failed read
is shown rather than dropped, since it means the build is broken. */}
- {cloud.kind === 'open' && (
+ {cloud.kind === 'open' && !cloudAdded && (
<ChoiceCard
icon={
cloudAttempt.connecting ? (
@@ -424,7 +445,7 @@ function ChooseStep({
</div>
</WizardFrame>
);
-}
+});
export function ChoiceCard({
icon,
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-sign-in.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-sign-in.tsx
index dfbee658a..416c66ca6 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-sign-in.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-sign-in.tsx
@@ -82,11 +82,13 @@ export type ServerSignIn = {
* Warm the signed-in user's cloud machine on Switch Cloud, so it
* is starting while they set up their first agent. Not awaited: sign-in is
* done whether or not the machine starts, so a refusal is a notice rather than
- * a failed sign-in.
+ * a failed sign-in. Skipped when the server does not turn cloud machines on.
*/
function warmCloudMachine(serverId: string): void {
- void loadSwitchCloudOrigin().then(() => {
+ void loadSwitchCloudOrigin().then(async () => {
if (serverId !== managedCloudServerId()) return;
+ const flags = await rpc.featureFlags.current(serverId);
+ if (!flags.success || !flags.data.flags['hosted_agents']) return;
rpc.switchServers.ensureCloudMachine(serverId).catch((cause: unknown) => {
toast({
title: 'Your cloud machine did not start',
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-switcher.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-switcher.tsx
index be6844f6d..4d5cf6f82 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-switcher.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-switcher.tsx
@@ -1,5 +1,5 @@
-import { useQueryClient } from '@tanstack/react-query';
-import { Check, ChevronsUpDown, LogIn, Plus, Search, Server, UserPlus } from 'lucide-react';
+import { useQuery, useQueryClient } from '@tanstack/react-query';
+import { Check, ChevronsUpDown, Plus, Search, Server, UserPlus } from 'lucide-react';
import { observer } from 'mobx-react-lite';
import { useEffect, useState } from 'react';
import {
@@ -17,6 +17,7 @@ import { WorkspaceAvatar } from '@renderer/features/workspaces/workspace-avatar'
import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { failureText } from '@renderer/lib/errors/describe-failure';
import { useToast } from '@renderer/lib/hooks/use-toast';
+import { rpc } from '@renderer/lib/ipc';
import { useNavigate } from '@renderer/lib/layout/navigation-provider';
import { useShowModal } from '@renderer/lib/modal/modal-provider';
import { SwitchConsoleMark } from '@renderer/lib/switch-console-mark';
@@ -49,6 +50,7 @@ import {
ServerStatusDot,
serverDrift,
serverPlacementLabel,
+ serverState,
serverStatusLabel,
serverSubtitleLabel,
} from './server-presentation';
@@ -134,11 +136,7 @@ export const WorkspaceSwitcher = observer(function WorkspaceSwitcher() {
return showsServers(cloud.kind) ? (
<ServerMenu activeServer={activeServer} />
) : (
- <WorkspaceMenu
- active={active}
- activeServer={activeServer}
- cloudOrigin={cloud.kind === 'open' ? cloud.url : null}
- />
+ <WorkspaceMenu active={active} activeServer={activeServer} />
);
});
@@ -294,6 +292,16 @@ const ServerMenuItem = observer(function ServerMenuItem({
);
});
+// The workspace menu's rows, as one place to read the sizes off: workspace
+// rows a little denser than the app's default menu row, action rows a fixed
+// height, and the small buttons on a row light enough not to compete with it.
+const WORKSPACE_ROW =
+ 'gap-2.5 rounded-[7px] px-[9px] py-[5px] text-[13px] focus:bg-[var(--sel-soft)]';
+const ACTION_ROW =
+ 'h-[30px] gap-2.5 rounded-[7px] px-[9px] py-0 text-[13px] text-[var(--fg-action)] focus:bg-[var(--sel-soft)] [&_svg]:text-[var(--fg-icon)]';
+const ROW_BUTTON =
+ 'inline-flex h-[22px] shrink-0 items-center gap-1 rounded-[6px] px-[9px] text-[11.5px] text-[var(--fg-action)] disabled:opacity-60';
+
/**
* Workspaces listed under the server hosting them rather than in one flat
* list. A workspace only means anything on its server — two servers can each
@@ -306,18 +314,13 @@ const ServerMenuItem = observer(function ServerMenuItem({
const WorkspaceMenu = observer(function WorkspaceMenu({
active,
activeServer,
- cloudOrigin,
}: {
active: Workspace;
activeServer: SwitchServer;
- /** Switch Cloud's origin when this build knows it, to mark its server as the official one. */
- cloudOrigin: string | null;
}) {
const store = switchServersStore;
const { navigate } = useNavigate();
const showAddServerModal = useShowModal('addServerModal');
- const showCreateWorkspaceModal = useShowModal('createWorkspaceModal');
- const showInvitePeopleModal = useShowModal('invitePeopleModal');
const [query, setQuery] = useState('');
const drift = serverDrift(activeServer);
@@ -341,7 +344,7 @@ const WorkspaceMenu = observer(function WorkspaceMenu({
<button
type="button"
aria-label="Switch workspace"
- className="flex w-full items-center gap-[10px] rounded-lg px-2 py-1.5 text-left hover:bg-[var(--sel-soft)]"
+ className="flex w-full items-center gap-[10px] rounded-[9px] px-2 py-1.5 text-left hover:bg-[var(--sel-soft)] data-[popup-open]:bg-[var(--sel-soft)]"
>
<WorkspaceAvatar name={active.name} size="md" active />
<span className="min-w-0 flex-1">
@@ -361,53 +364,29 @@ const WorkspaceMenu = observer(function WorkspaceMenu({
</button>
}
/>
- <DropdownMenuContent align="start" className="w-80">
+ <DropdownMenuContent
+ align="start"
+ className="w-80 rounded-[var(--radius-elevated)] bg-[var(--menu-surface)] p-1.5 shadow-[var(--menu-shadow)] ring-[0.5px] ring-[var(--hair)]"
+ >
<WorkspaceSearch value={query} onChange={setQuery} />
{store.servers.map((server) => (
- <ServerWorkspaceGroup
- key={server.id}
- server={server}
- query={query}
- official={cloudOrigin !== null && originOf(server.gatewayUrl) === cloudOrigin}
- />
+ <ServerWorkspaceGroup key={server.id} server={server} query={query} />
))}
{!anyMatch && (
<div className="px-2 py-3 text-center text-xs text-foreground-muted">
No workspace or server matches “{query.trim()}”.
</div>
)}
- <DropdownMenuSeparator />
- {/* Offered only where the gateway would take it: it refuses members,
- and a menu item that always ends in a 403 is a trap. */}
- {administersWorkspace(active) && (
- <DropdownMenuItem onClick={() => showInvitePeopleModal({ workspaceId: active.id })}>
- <UserPlus className="size-4" />
- Invite people to {active.name}…
- </DropdownMenuItem>
- )}
- {/* Above Add server because it is the commoner errand by far: you add
- a server once and make workspaces on it for as long as you use
- it. It opens on the server you are already in — the modal asks
- which only where there is more than one to ask about. */}
- <DropdownMenuItem
- onClick={() =>
- showCreateWorkspaceModal({
- serverId: activeServer.id,
- onSuccess: (workspace) => navigate('server', { serverId: workspace.serverId }),
- })
- }
- >
- <Plus className="size-4" />
- New workspace…
- </DropdownMenuItem>
- <DropdownMenuItem onClick={() => showAddServerModal({})}>
+ <DropdownMenuSeparator className="mx-1 my-1.5 h-[0.5px] bg-[var(--hair)]" />
+ {/* New workspace and Invite live with the server and the workspace
+ they act on, so only what belongs to no server is left here. */}
+ <DropdownMenuItem className={ACTION_ROW} onClick={() => showAddServerModal({})}>
<Server className="size-4" />
Add server…
</DropdownMenuItem>
- <DropdownMenuSeparator />
{/* The welcome screen is what the app opens with before any server
exists; once one does, this is how it stays reachable. */}
- <DropdownMenuItem onClick={() => navigate('home')}>
+ <DropdownMenuItem className={ACTION_ROW} onClick={() => navigate('home')}>
<SwitchConsoleMark size={16} />
About Switch
</DropdownMenuItem>
@@ -422,23 +401,6 @@ export function matchesQuery(name: string, query: string): boolean {
return q === '' || name.toLowerCase().includes(q);
}
-function originOf(url: string): string | null {
- try {
- return new URL(url).origin;
- } catch {
- return null;
- }
-}
-
-/** Where a server is, as its heading says it: the host and port it answers on. */
-function serverAddress(server: SwitchServer): string {
- try {
- return new URL(server.gatewayUrl).host;
- } catch {
- return server.gatewayUrl;
- }
-}
-
/**
* The search box at the top of the menu.
*
@@ -449,7 +411,7 @@ function serverAddress(server: SwitchServer): string {
function WorkspaceSearch({ value, onChange }: { value: string; onChange: (v: string) => void }) {
return (
<div className="relative px-1 pt-1 pb-1.5">
- <Search className="pointer-events-none absolute top-1/2 left-3.5 size-3.5 -translate-y-1/2 text-foreground-muted" />
+ <Search className="pointer-events-none absolute top-1/2 left-3.5 size-3.5 -translate-y-1/2 text-[var(--fg-dim)]" />
<input
autoFocus
type="text"
@@ -462,7 +424,7 @@ function WorkspaceSearch({ value, onChange }: { value: string; onChange: (v: str
event.stopPropagation();
}
}}
- className="h-8 w-full rounded-md border border-border bg-background-tertiary pr-2 pl-8 text-sm text-foreground outline-none placeholder:text-foreground-muted focus:border-foreground-muted"
+ className="h-[30px] w-full rounded-[7px] border-[0.5px] border-[var(--hair)] bg-[var(--menu-field)] pr-2 pl-8 text-[13px] text-[var(--fg-name)] outline-none placeholder:text-[var(--fg-dim)] focus:border-[var(--hair-strong)]"
/>
</div>
);
@@ -501,21 +463,19 @@ const LocalServerPendingButton = observer(function LocalServerPendingButton() {
const ServerWorkspaceGroup = observer(function ServerWorkspaceGroup({
server,
query,
- official,
}: {
server: SwitchServer;
query: string;
- official: boolean;
}) {
// A server you are not signed in to cannot be asked about invitations, so
// the hooks that ask only mount where it can.
return serverAvailability(server.id) === 'available' ? (
- <AvailableServerWorkspaceGroup server={server} query={query} official={official} />
+ <AvailableServerWorkspaceGroup server={server} query={query} />
) : (
<ServerWorkspaceGroupBody
server={server}
query={query}
- official={official}
+ canCreateWorkspace={false}
invitations={NO_OFFERS.invitations}
joinable={NO_OFFERS.joinable}
invitationsFailed={false}
@@ -529,22 +489,22 @@ const NO_OFFERS: { invitations: PendingInvitation[]; joinable: JoinableWorkspace
joinable: [],
};
-function AvailableServerWorkspaceGroup({
- server,
- query,
- official,
-}: {
- server: SwitchServer;
- query: string;
- official: boolean;
-}) {
+function AvailableServerWorkspaceGroup({ server, query }: { server: SwitchServer; query: string }) {
const invitations = usePendingInvitations(server.id);
const joinable = useJoinableWorkspaces(server.id);
+ // The server's own answer, so New workspace is not offered where creating
+ // one is refused: a deployment that keeps to one workspace, invite-only
+ // sign-up, or a spent allowance. Offered until it has said no.
+ const canCreate = useQuery({
+ queryKey: ['can-create-workspace', server.id],
+ queryFn: () => rpc.switchServers.canCreateWorkspace(server.id),
+ staleTime: 60_000,
+ });
return (
<ServerWorkspaceGroupBody
server={server}
query={query}
- official={official}
+ canCreateWorkspace={canCreate.data !== false}
invitations={listedInvitations(invitations.data)}
joinable={listedJoinable(joinable.data)}
invitationsFailed={invitations.isError}
@@ -556,7 +516,7 @@ function AvailableServerWorkspaceGroup({
const ServerWorkspaceGroupBody = observer(function ServerWorkspaceGroupBody({
server,
query,
- official,
+ canCreateWorkspace,
invitations,
joinable,
invitationsFailed,
@@ -564,7 +524,7 @@ const ServerWorkspaceGroupBody = observer(function ServerWorkspaceGroupBody({
}: {
server: SwitchServer;
query: string;
- official: boolean;
+ canCreateWorkspace: boolean;
invitations: PendingInvitation[];
joinable: JoinableWorkspace[];
invitationsFailed: boolean;
@@ -612,6 +572,8 @@ const ServerWorkspaceGroupBody = observer(function ServerWorkspaceGroupBody({
? joinable
: joinable.filter((j) => matchesQuery(j.workspaceName, query));
const extraRows = (signedOut && signInTarget) || noMembership;
+ // Collapsed to one row, a server not usable here is found by its own name.
+ if (searching && !whole && availability !== 'available') return null;
if (
searching &&
!(whole && extraRows) &&
@@ -620,74 +582,53 @@ const ServerWorkspaceGroupBody = observer(function ServerWorkspaceGroupBody({
return null;
}
const available = availability === 'available';
+ const createWorkspace = () =>
+ showCreateWorkspaceModal({
+ serverId: server.id,
+ onSuccess: (workspace) => navigate('server', { serverId: workspace.serverId }),
+ });
return (
<DropdownMenuGroup>
- <DropdownMenuLabel className="flex items-center gap-1.5 px-2 pt-2.5 pb-1 text-[11px] font-semibold tracking-wide text-foreground-muted uppercase">
+ <DropdownMenuLabel className="flex items-center gap-1.5 px-[9px] pt-2.5 pb-1 text-[10.5px] font-semibold tracking-[0.06em] text-[var(--fg-passive)] uppercase">
<Icon className="size-3 shrink-0" />
<span className="min-w-0 truncate">{server.name}</span>
- {/* Said only when something is wrong: a heading for every server that
- is fine would be noise on each of them. */}
- {!available && (
- <>
- <ServerStatusDot server={server} />
- <span className="shrink-0 font-normal tracking-normal normal-case">
- {serverStatusLabel(server)}
- </span>
- </>
- )}
{drift && <ServerDriftIndicator drift={drift} />}
- <span className="ml-auto shrink-0 pl-2 font-normal tracking-normal normal-case">
- {official ? (
- <span className="text-green-600 dark:text-green-500">Official</span>
- ) : (
- <span className="text-foreground-passive">{serverAddress(server)}</span>
- )}
- </span>
</DropdownMenuLabel>
- {signedOut && signInTarget && whole && (
- <DropdownMenuItem onClick={openForSignIn}>
- <LogIn className="size-4" />
- Sign in…
- </DropdownMenuItem>
- )}
- {noMembership && whole && (
- <>
- <div className="px-2 py-1.5 text-xs text-foreground-muted">
- No workspace yet — create one, or accept an invitation below.
- </div>
- <DropdownMenuItem
- onClick={() =>
- showCreateWorkspaceModal({
- serverId: server.id,
- onSuccess: (workspace) => navigate('server', { serverId: workspace.serverId }),
- })
- }
- >
- <Plus className="size-4" />
- Create a workspace…
- </DropdownMenuItem>
- </>
- )}
- {all.length === 0 ? (
- // Registering a server is what creates its first workspace, so a server
- // with none did not finish being registered. Saying so beats an empty
- // heading, which reads as a rendering fault.
- <div className="px-2 py-1.5 text-xs text-foreground-muted">
- No workspace yet — this server has not finished being set up.
- </div>
+ {/* A server this window cannot use right now collapses to one row that
+ says why and offers the one thing that changes it: its workspaces
+ cannot be opened from here until then, so listing them would only
+ offer clicks that fail. */}
+ {!available ? (
+ whole && (
+ <UnavailableServerRow server={server} onSignIn={signInTarget ? openForSignIn : null} />
+ )
) : (
- workspaces.map((workspace) => (
- <WorkspaceMenuItem
- key={workspace.id}
- workspace={workspace}
- server={server}
- onServerCount={all.length}
- />
- ))
- )}
- {available && (
<>
+ {noMembership && whole && (
+ <div className="px-2 py-1.5 text-xs text-foreground-muted">
+ {canCreateWorkspace
+ ? 'No workspace yet — create one, or accept an invitation below.'
+ : 'No workspace yet — accept an invitation below.'}
+ </div>
+ )}
+ {all.length === 0 ? (
+ // Registering a server is what creates its first workspace, so a
+ // server with none did not finish being registered. Saying so beats
+ // an empty heading, which reads as a rendering fault.
+ <div className="px-2 py-1.5 text-xs text-foreground-muted">
+ No workspace yet — this server has not finished being set up.
+ </div>
+ ) : (
+ workspaces.map((workspace) => (
+ <WorkspaceMenuItem
+ key={workspace.id}
+ workspace={workspace}
+ server={server}
+ onServerCount={all.length}
+ />
+ ))
+ )}
{invitationsFailed && (
<div className="px-2 py-1.5 text-xs text-foreground-muted">
Could not check for invitations to your address.
@@ -708,12 +649,70 @@ const ServerWorkspaceGroupBody = observer(function ServerWorkspaceGroupBody({
{shownJoinable.map((offer) => (
<JoinableWorkspaceMenuItem key={offer.tenantId} offer={offer} server={server} />
))}
+ {whole && canCreateWorkspace && (
+ <DropdownMenuItem
+ onClick={createWorkspace}
+ className={cn(ACTION_ROW, 'text-[var(--fg-dim)]')}
+ >
+ <Plus className="size-4" />
+ New workspace
+ </DropdownMenuItem>
+ )}
</>
)}
</DropdownMenuGroup>
);
});
+/**
+ * A server whose workspaces cannot be opened from here right now, as one row:
+ * its state, and the button that changes it — Start for a stack this Console
+ * runs that is stopped, Sign in for a server it is signed out of.
+ */
+const UnavailableServerRow = observer(function UnavailableServerRow({
+ server,
+ onSignIn,
+}: {
+ server: SwitchServer;
+ onSignIn: (() => void) | null;
+}) {
+ const state = serverState(server);
+ const remoteHost = server.managementKind === 'remote' ? server.sshHost : null;
+ const starting = remoteHost
+ ? remoteServerStore.isTransitioning(remoteHost)
+ : localServerStore.isTransitioning;
+ const start = () =>
+ void (remoteHost ? remoteServerStore.start(remoteHost, server.name) : localServerStore.start());
+ const action =
+ state === 'not-running'
+ ? { label: starting ? 'Starting…' : 'Start', onClick: start, disabled: starting }
+ : state === 'signed-out' && onSignIn
+ ? { label: 'Sign in', onClick: onSignIn, disabled: false }
+ : null;
+
+ return (
+ <div className="flex h-[30px] items-center rounded-[7px] bg-[var(--menu-faint)] pr-1 text-[12.5px] text-[var(--fg-dim)]">
+ <span className="mx-2 flex shrink-0 items-center">
+ <ServerStatusDot server={server} />
+ </span>
+ <span className="min-w-0 flex-1 truncate">{serverStatusLabel(server)}</span>
+ {action && (
+ <button
+ type="button"
+ className={cn(ROW_BUTTON, 'border-[0.5px] border-[var(--hair-strong)] bg-transparent')}
+ disabled={action.disabled}
+ onClick={(event) => {
+ event.stopPropagation();
+ action.onClick();
+ }}
+ >
+ {action.label}
+ </button>
+ )}
+ </div>
+ );
+});
+
const UNAVAILABLE_BADGE: Record<WorkspaceUnavailability, string> = {
withdrawn: 'No longer a member',
unmatched: 'Not matched',
@@ -746,12 +745,14 @@ const WorkspaceMenuItem = observer(function WorkspaceMenuItem({
}) {
const { navigate } = useNavigate();
const { toast } = useToast();
+ const showInvitePeopleModal = useShowModal('invitePeopleModal');
const isActive = workspacesStore.activeId === workspace.id;
// Kept in the list rather than hidden: its agents are still here and the row
// is the only thing that says where they went. Disabled, because the gateway
// refuses every call scoped to it — offering it would turn a fact the app
// already knows into an error after the click.
const unavailable = workspaceUnavailability(workspace, onServerCount);
+ const canInvite = unavailable === null && administersWorkspace(workspace);
return (
<DropdownMenuItem
@@ -759,7 +760,7 @@ const WorkspaceMenuItem = observer(function WorkspaceMenuItem({
// at a glance. `aria-current` carries the same fact for anything that
// cannot see either.
aria-current={isActive ? 'true' : undefined}
- className={cn(isActive && 'bg-[var(--sel)]')}
+ className={cn('group/ws', WORKSPACE_ROW, isActive && 'bg-[var(--sel-soft)]')}
disabled={unavailable !== null}
title={unavailable ? UNAVAILABLE_REASON[unavailable](workspace.name) : undefined}
onClick={() => {
@@ -778,8 +779,8 @@ const WorkspaceMenuItem = observer(function WorkspaceMenuItem({
});
}}
>
- <WorkspaceAvatar name={workspace.name} size="sm" active={isActive} />
- <span data-row-name className="min-w-0 flex-1 truncate text-sm text-foreground">
+ <WorkspaceAvatar name={workspace.name} size="tile" active={isActive} />
+ <span data-row-name className="min-w-0 flex-1 truncate text-[var(--fg-name)]">
{workspace.name}
</span>
{unavailable && (
@@ -787,7 +788,28 @@ const WorkspaceMenuItem = observer(function WorkspaceMenuItem({
{UNAVAILABLE_BADGE[unavailable]}
</span>
)}
- {isActive && <Check className="size-4 shrink-0 text-foreground" />}
+ {/* Shown on the open workspace and on the row under the pointer, and only where the gateway would
+ take it: it refuses members, and a button that always ends in a 403
+ is a trap. */}
+ {canInvite && (
+ <button
+ type="button"
+ className={cn(
+ ROW_BUTTON,
+ 'bg-[var(--menu-pill)]',
+ !isActive &&
+ 'opacity-0 group-hover/ws:opacity-100 group-data-[highlighted]/ws:opacity-100 focus-visible:opacity-100'
+ )}
+ onClick={(event) => {
+ event.stopPropagation();
+ showInvitePeopleModal({ workspaceId: workspace.id });
+ }}
+ >
+ <UserPlus className="size-3" />
+ Invite
+ </button>
+ )}
+ {isActive && !canInvite && <Check className="size-3.5 shrink-0 text-[var(--fg-icon)]" />}
</DropdownMenuItem>
);
});
@@ -833,6 +855,7 @@ function PendingInvitationMenuItem({
return (
<DropdownMenuItem
title={invitationSummary(invitation)}
+ className={WORKSPACE_ROW}
data-testid="pending-invitation-item"
onClick={() => {
void workspacesStore
@@ -851,8 +874,8 @@ function PendingInvitationMenuItem({
);
}}
>
- <WorkspaceAvatar name={invitation.workspaceName} size="sm" />
- <span data-row-name className="min-w-0 flex-1 truncate text-sm text-foreground">
+ <WorkspaceAvatar name={invitation.workspaceName} size="tile" />
+ <span data-row-name className="min-w-0 flex-1 truncate text-[var(--fg-name)]">
{invitation.workspaceName}
</span>
<InvitedBadge />
@@ -874,6 +897,7 @@ function JoinableWorkspaceMenuItem({
return (
<DropdownMenuItem
title={joinableSummary(offer)}
+ className={WORKSPACE_ROW}
data-testid="joinable-workspace-item"
onClick={() => {
void workspacesStore
@@ -892,8 +916,8 @@ function JoinableWorkspaceMenuItem({
);
}}
>
- <WorkspaceAvatar name={offer.workspaceName} size="sm" />
- <span data-row-name className="min-w-0 flex-1 truncate text-sm text-foreground">
+ <WorkspaceAvatar name={offer.workspaceName} size="tile" />
+ <span data-row-name className="min-w-0 flex-1 truncate text-[var(--fg-name)]">
{offer.workspaceName}
</span>
<span className="shrink-0 text-xs font-medium text-foreground-muted">Join</span>
diff --git a/console/apps/switch-console-desktop/src/renderer/features/workspaces/create-workspace-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/workspaces/create-workspace-modal.tsx
index 7a2ae23aa..f87a30165 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/workspaces/create-workspace-modal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/workspaces/create-workspace-modal.tsx
@@ -14,18 +14,11 @@ import {
} from '@renderer/lib/ui/dialog';
import { Field, FieldGroup, FieldLabel } from '@renderer/lib/ui/field';
import { Input } from '@renderer/lib/ui/input';
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from '@renderer/lib/ui/select';
import type { Workspace } from '@shared/core/workspaces/workspaces';
import { createWorkspaceFailureText } from './describe-create-failure';
type CreateWorkspaceModalArgs = {
- /** The server to create it on — the one the window is currently scoped to. */
+ /** The server to create it on: the one whose "New workspace" was chosen. */
serverId: string;
};
@@ -58,10 +51,9 @@ function whyNotReady(serverId: string): string | null {
/**
* Make a workspace from the switcher.
*
- * A workspace belongs to a server, so the first thing this has to be sure of is
- * which one. It opens on the server the window is already in and offers the
- * others only where there is a choice to make — on the ordinary single-server
- * install the question never appears.
+ * A workspace belongs to a server, and the switcher has already said which:
+ * each server's group ends with its own New workspace, so the server is the
+ * one whose row was chosen and this asks only for the name.
*
* Only a server you are signed in to can be asked. Offering the rest and
* letting Create come back with an authentication failure would blame the name
@@ -79,7 +71,6 @@ export const CreateWorkspaceModal = observer(function CreateWorkspaceModal({
onClose,
}: Props) {
const { transitionModal, setCloseGuard } = useModalContext();
- const [chosen, setChosen] = useState<string | null>(null);
const [name, setName] = useState('');
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -93,17 +84,7 @@ export const CreateWorkspaceModal = observer(function CreateWorkspaceModal({
*/
const [created, setCreated] = useState<Workspace | null>(null);
- const candidates = switchServersStore.servers.filter((server) =>
- switchServersStore.isConnected(server.id)
- );
- // The server the window is in, when it can be asked; otherwise the only one
- // that can. A default that is not a candidate would hide the picker on a
- // question the user still has to answer, and leave Create disabled with the
- // usable server offered nowhere.
- const fallback = candidates.some((server) => server.id === serverId)
- ? serverId
- : (candidates[0]?.id ?? serverId);
- const where = chosen ?? fallback;
+ const where = serverId;
const target = switchServersStore.serverById(where);
const notReady = whyNotReady(where);
const trimmed = name.trim();
@@ -150,7 +131,9 @@ export const CreateWorkspaceModal = observer(function CreateWorkspaceModal({
return (
<>
<DialogHeader showCloseButton={false}>
- <DialogTitle>Create a workspace</DialogTitle>
+ <DialogTitle>
+ {target ? `Create a workspace on ${target.name}` : 'Create a workspace'}
+ </DialogTitle>
</DialogHeader>
<DialogContentArea className="pt-0">
<FieldGroup>
@@ -171,28 +154,6 @@ export const CreateWorkspaceModal = observer(function CreateWorkspaceModal({
/>
</Field>
- {candidates.length > 1 && (
- <Field>
- <FieldLabel>Server</FieldLabel>
- <Select
- value={where}
- onValueChange={(value) => value && setChosen(value)}
- disabled={submitting || created !== null}
- >
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {candidates.map((server) => (
- <SelectItem key={server.id} value={server.id}>
- {server.name}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </Field>
- )}
-
{created !== null ? (
<p className="text-xs text-foreground-muted">
{created.name} was created on {target?.name ?? 'the server'}, but this window could
@@ -200,7 +161,7 @@ export const CreateWorkspaceModal = observer(function CreateWorkspaceModal({
</p>
) : notReady !== null ? (
<p className="text-xs text-destructive">{notReady}</p>
- ) : target !== null && candidates.length <= 1 ? (
+ ) : target !== null ? (
<p className="text-xs text-foreground-muted">
It will live on {target.name}, along with its rooms and agents.
</p>
diff --git a/console/apps/switch-console-desktop/src/renderer/features/workspaces/describe-create-failure.test.ts b/console/apps/switch-console-desktop/src/renderer/features/workspaces/describe-create-failure.test.ts
index d7de0cc47..af220c1d5 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/workspaces/describe-create-failure.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/workspaces/describe-create-failure.test.ts
@@ -14,29 +14,27 @@ function gatewayError(status: number, detail: string): RpcError {
const FALLBACK = 'Local dev could not create it.';
describe('creating a workspace, when it fails', () => {
- /**
- * The gateway's own words are `Slug already taken: acme-robotics` — no
- * terminal punctuation, so the shared description does not read it as a
- * sentence and shows it as diagnostics instead. What reached the user was a
- * status code and a slug they never typed, for the one refusal that is
- * entirely about what they did type.
- */
- it('blames the name for a name conflict, and says nothing about slugs', () => {
+ // A conflict is a deployment that keeps to one workspace, or a create racing
+ // another — never the name, which may repeat. Telling the user to rename sent
+ // them round in circles on a server that would refuse every name.
+ it('says what the server said for a conflict, not that the name is taken', () => {
const text = createWorkspaceFailureText(
- gatewayError(409, 'Slug already taken: acme-robotics'),
+ gatewayError(
+ 409,
+ 'This server is not isolating tenants: it runs only because DB_REQUIRE_RESTRICTED_ROLE is false, which allows a single workspace.'
+ ),
'Local dev',
FALLBACK
);
- expect(text).toContain('already goes by that name');
- expect(text).toContain('Local dev');
- expect(text).not.toContain('acme-robotics');
+ expect(text).toContain('Local dev could not create it');
+ expect(text).toContain('allows a single workspace');
+ expect(text).not.toContain('already goes by that name');
expect(text).not.toContain('409');
});
- // The whole point of the rewrite is that the name is at fault. Saying so over
- // an expired session sends the user to rename a workspace when what they have
- // to do is sign in.
+ // Only the conflict is the server's own sentence; an expired session still
+ // says to sign in again.
it('leaves every other gateway refusal to the shared description', () => {
const expired = new RpcError({
__switchConsoleRpcError: true,
diff --git a/console/apps/switch-console-desktop/src/renderer/features/workspaces/describe-create-failure.ts b/console/apps/switch-console-desktop/src/renderer/features/workspaces/describe-create-failure.ts
index 37d626664..9d419616f 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/workspaces/describe-create-failure.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/workspaces/describe-create-failure.ts
@@ -4,28 +4,26 @@ import { RpcError } from '@shared/lib/ipc/rpc-error';
/**
* What to put under the name field when creating a workspace fails.
*
- * The name being taken is by far the likeliest way this form fails, and it is
- * the only failure the person at the keyboard can fix. The gateway derives a
- * slug from the name and refuses a duplicate with `Slug already taken:
- * acme-robotics` — no terminal punctuation, so the generic description does not
- * read it as a sentence and shows it as diagnostic text instead: a status code
- * and a slug the user never typed, for the one refusal that is about what they
- * did type.
+ * A conflict from the gateway is never about the name: a slug already taken is
+ * retried with a suffix, so the name is free to repeat. What it refuses with
+ * 409 is a deployment that keeps to one workspace (it is not isolating tenants)
+ * or a second create racing the first, and only the server can say which, in a
+ * sentence of its own. So its words are shown as they are, said to come from
+ * the server, rather than turned into advice to rename.
*
- * Only that route's conflict is rewritten. Everything else keeps the shared
- * description, because a name-specific sentence over an expired session or an
- * unreachable server would blame the name for something it had nothing to do
- * with.
+ * Everything else keeps the shared description.
*/
export function createWorkspaceFailureText(
error: unknown,
serverName: string,
fallback: string
): string {
- const conflict =
+ const detail =
error instanceof RpcError &&
error.code === 'GatewayError' &&
- error.numberField('status') === 409;
- if (!conflict) return failureText(error, fallback);
- return `A workspace on ${serverName} already goes by that name. Capitalisation and punctuation do not make it a different one, so pick a name that stands apart.`;
+ error.numberField('status') === 409
+ ? error.stringField('detail')?.trim()
+ : undefined;
+ if (!detail) return failureText(error, fallback);
+ return `${serverName} could not create it: ${detail}`;
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspace-avatar.tsx b/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspace-avatar.tsx
index 10c26c24a..e5a4753f1 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspace-avatar.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/workspaces/workspace-avatar.tsx
@@ -2,6 +2,7 @@ import { cn } from '@renderer/utils/utils';
const SIZE = {
sm: 'size-5 rounded-md text-[10px]',
+ tile: 'size-[22px] rounded-[7px] text-[10.5px]',
md: 'size-[26px] rounded-md text-xs',
lg: 'size-9 rounded-lg text-lg',
} as const;
@@ -25,9 +26,13 @@ export function WorkspaceAvatar({
className={cn(
'flex shrink-0 items-center justify-center font-semibold before:content-[attr(data-initial)]',
SIZE[size],
- active
- ? 'bg-[var(--accent-solid)] text-white'
- : 'bg-background-tertiary text-foreground-muted'
+ size === 'tile'
+ ? active
+ ? 'bg-[var(--accent-solid)] text-[var(--menu-tile-active-fg)]'
+ : 'bg-[var(--menu-tile)] text-[var(--menu-tile-fg)]'
+ : active
+ ? 'bg-[var(--accent-solid)] text-white'
+ : 'bg-background-tertiary text-foreground-muted'
)}
/>
);
diff --git a/console/apps/switch-console-desktop/src/renderer/index.css b/console/apps/switch-console-desktop/src/renderer/index.css
index 95437fa39..79509f69c 100644
--- a/console/apps/switch-console-desktop/src/renderer/index.css
+++ b/console/apps/switch-console-desktop/src/renderer/index.css
@@ -423,6 +423,23 @@
is the design's passive step, one stop darker. */
--fg-passive: #8d8d8d;
+ /* An elevated menu over the sidebar (the workspace switcher): a surface a
+ step off the material, with a soft shadow, so it lifts rather than
+ reading as more sidebar. Text steps down from the names it lists, so
+ those are what the eye lands on. */
+ --menu-surface: #ffffff;
+ --menu-field: #f6f6f5;
+ --menu-shadow: 0 20px 44px rgb(0 0 0 / 0.12);
+ --menu-faint: rgb(0 0 0 / 0.03);
+ --menu-pill: rgb(0 0 0 / 0.06);
+ --menu-tile: #ebebea;
+ --menu-tile-fg: #6f6f6f;
+ --menu-tile-active-fg: #f5fbf7;
+ --fg-name: #1f1f1f;
+ --fg-action: #3a3a3a;
+ --fg-icon: #8d8d8d;
+ --fg-dim: #8a8a8a;
+
/* The segmented control's track. Its own token rather than `--hair-soft`,
which in dark lands within a couple of levels of the raised segment and
leaves the active option indistinguishable from the inactive one. */
@@ -720,6 +737,19 @@
--fg-passive: #8d8d8d;
+ --menu-surface: #262626;
+ --menu-field: #1e1e1e;
+ --menu-shadow: 0 20px 44px rgb(0 0 0 / 0.28);
+ --menu-faint: rgb(255 255 255 / 0.03);
+ --menu-pill: rgb(255 255 255 / 0.1);
+ --menu-tile: #333333;
+ --menu-tile-fg: #bbbbbb;
+ --menu-tile-active-fg: #f5fbf7;
+ --fg-name: #ededed;
+ --fg-action: #d8d8d8;
+ --fg-icon: #9a9a9a;
+ --fg-dim: #9a9a9a;
+
/* Darker than the material rather than lighter, so the raised segment
reads as sitting on top of the track instead of merging into it. */
--segment-track: rgb(0 0 0 / 0.32);
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/hooks/useFeatureFlags.ts b/console/apps/switch-console-desktop/src/renderer/lib/hooks/useFeatureFlags.ts
new file mode 100644
index 000000000..49bcce0a2
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/lib/hooks/useFeatureFlags.ts
@@ -0,0 +1,61 @@
+import { useEffect, useState } from 'react';
+import { events, rpc } from '@renderer/lib/ipc';
+import {
+ allFeatureFlagsOff,
+ type FeatureFlagKey,
+ type FeatureFlags,
+} from '@shared/core/feature-flags/feature-flags';
+import { featureFlagsChangedChannel } from '@shared/events/featureFlagEvents';
+
+/**
+ * A Switch server's feature flags, kept current: the hook re-renders when the
+ * main process sees the server's flags change, so a redeploy that turns one on
+ * or off applies without restarting Console. Every flag is off until the flags
+ * have been read, and stays off for a server whose flags never could be.
+ */
+export function useFeatureFlags(serverId: string | null | undefined): FeatureFlags {
+ const [flags, setFlags] = useState<FeatureFlags>(allFeatureFlagsOff);
+
+ useEffect(() => {
+ setFlags(allFeatureFlagsOff());
+ if (!serverId) return;
+ let current = true;
+ const off = events.on(featureFlagsChangedChannel, (state) => {
+ if (state.serverId === serverId) setFlags(state.flags);
+ });
+ void rpc.featureFlags.get(serverId).then((res) => {
+ if (current && res?.success) setFlags(res.data.flags);
+ });
+ return () => {
+ current = false;
+ off();
+ };
+ }, [serverId]);
+
+ return flags;
+}
+
+/**
+ * Whether any connected server turns `key` on, kept current. For what Console
+ * shows outside any one server — a settings page about every server's agents —
+ * and off until a server has been read that turns it on.
+ */
+export function useAnyServerFeatureFlag(key: FeatureFlagKey): boolean {
+ const [enabled, setEnabled] = useState(false);
+
+ useEffect(() => {
+ let current = true;
+ const read = () =>
+ void rpc.featureFlags.anyEnabled(key).then((res) => {
+ if (current && res?.success) setEnabled(res.data);
+ });
+ const off = events.on(featureFlagsChangedChannel, read);
+ read();
+ return () => {
+ current = false;
+ off();
+ };
+ }, [key]);
+
+ return enabled;
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/ui/segmented-control.tsx b/console/apps/switch-console-desktop/src/renderer/lib/ui/segmented-control.tsx
index 5c2946f79..d3bf5a31c 100644
--- a/console/apps/switch-console-desktop/src/renderer/lib/ui/segmented-control.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/lib/ui/segmented-control.tsx
@@ -19,12 +19,19 @@ export function SegmentedControl<T extends string>({
options,
ariaLabel,
className,
+ quiet = false,
}: {
value: T;
onChange: (value: T) => void;
options: readonly { value: T; label: string; icon?: LucideIcon }[];
ariaLabel: string;
className?: string;
+ /**
+ * A lighter control for the sidebar: a faint track and a faint fill on the
+ * chosen option, no raised button and no shadow, so it sits as quietly as the
+ * headings around it.
+ */
+ quiet?: boolean;
}) {
return (
<ToggleGroup
@@ -39,6 +46,7 @@ export function SegmentedControl<T extends string>({
aria-label={ariaLabel}
className={cn(
'h-auto gap-0 rounded-[9px] border-transparent bg-[var(--segment-track)] p-[2px]',
+ quiet && 'rounded-[8px] bg-[var(--hair-soft)]',
className
)}
>
@@ -50,7 +58,11 @@ export function SegmentedControl<T extends string>({
// The hover fill is an overlay, and only on the option that is not
// already chosen: the default `background-1` is the dialog and panel
// surface itself in dark mode, so it draws nothing.
- className="h-auto cursor-pointer rounded-[7px] px-[9px] py-[2px] text-[11.5px] font-medium text-foreground-muted transition-colors hover:bg-transparent hover:text-foreground aria-pressed:bg-[var(--btn-1)] aria-pressed:text-foreground aria-pressed:shadow-[0_1px_2px_rgb(0_0_0_/_0.12)] aria-[pressed=false]:hover:bg-[var(--sel-soft)] data-pressed:bg-[var(--btn-1)] data-[state=on]:bg-[var(--btn-1)] data-[state=on]:text-foreground data-[state=on]:shadow-[0_1px_2px_rgb(0_0_0_/_0.12)]"
+ className={cn(
+ 'h-auto cursor-pointer rounded-[7px] px-[9px] py-[2px] text-[11.5px] font-medium text-foreground-muted transition-colors hover:bg-transparent hover:text-foreground aria-pressed:bg-[var(--btn-1)] aria-pressed:text-foreground aria-pressed:shadow-[0_1px_2px_rgb(0_0_0_/_0.12)] aria-[pressed=false]:hover:bg-[var(--sel-soft)] data-pressed:bg-[var(--btn-1)] data-[state=on]:bg-[var(--btn-1)] data-[state=on]:text-foreground data-[state=on]:shadow-[0_1px_2px_rgb(0_0_0_/_0.12)]',
+ quiet &&
+ 'rounded-[6px] px-2.5 text-[var(--fg-dim)] aria-pressed:bg-[var(--menu-pill)] aria-pressed:text-[var(--fg-name)] aria-pressed:shadow-none data-pressed:bg-[var(--menu-pill)] data-[state=on]:bg-[var(--menu-pill)] data-[state=on]:shadow-none'
+ )}
>
{option.icon && <option.icon className="size-3.5" />}
{option.label}
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/add-server-choose-step.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/add-server-choose-step.test.tsx
new file mode 100644
index 000000000..be6f40116
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/add-server-choose-step.test.tsx
@@ -0,0 +1,94 @@
+/**
+ * The add-server chooser's Switch Cloud choice: offered while the Cloud is not
+ * one of the servers yet, and not once it is.
+ */
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';
+
+const state = vi.hoisted(() => ({ servers: [] as SwitchServer[] }));
+
+vi.hoisted(() => {
+ window.electronAPI ??= {
+ invoke: () => Promise.resolve(undefined),
+ eventOn: () => () => {},
+ eventSend: () => {},
+ } as unknown as typeof window.electronAPI;
+});
+
+vi.mock('@renderer/features/switch-servers/use-switch-cloud', () => ({
+ useSwitchCloud: () => ({ kind: 'open', url: 'https://cloud.example.invalid' }),
+}));
+
+vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({
+ switchServersStore: {
+ get servers() {
+ return state.servers;
+ },
+ connectToSwitchCloud: vi.fn(),
+ },
+}));
+
+import { ChooseStep } from '@renderer/features/switch-servers/AddServerModal';
+import { WizardChromeProvider } from '@renderer/lib/ui/wizard-frame';
+
+let container: HTMLDivElement | null = null;
+let root: Root | null = null;
+
+afterEach(async () => {
+ await act(async () => root?.unmount());
+ container?.remove();
+ container = null;
+ root = null;
+});
+
+function server(url: string): SwitchServer {
+ return {
+ id: url,
+ name: url,
+ gatewayUrl: url,
+ apiUrl: url,
+ managed: false,
+ managementKind: null,
+ sshHost: null,
+ createdAt: '',
+ updatedAt: '',
+ };
+}
+
+async function render(): Promise<string> {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const noop = () => {};
+ await act(async () =>
+ root!.render(
+ // Drawn as a page, the way first run draws it, so it needs no dialog.
+ <WizardChromeProvider chrome="page" exit={null}>
+ <ChooseStep
+ onLocal={noop}
+ onRemoteHost={noop}
+ onExternal={noop}
+ onCloud={noop}
+ onClose={noop}
+ />
+ </WizardChromeProvider>
+ )
+ );
+ return document.body.textContent ?? '';
+}
+
+describe('the Switch Cloud choice', () => {
+ it('is offered while Switch Cloud is not one of your servers', async () => {
+ state.servers = [server('https://other.example.invalid')];
+ expect(await render()).toContain('Connect to Switch Cloud');
+ });
+
+ it('is not offered once Switch Cloud is already added', async () => {
+ state.servers = [server('https://cloud.example.invalid')];
+ const text = await render();
+ expect(text).not.toContain('Connect to Switch Cloud');
+ expect(text).toContain('Connect to an existing server');
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/create-workspace-modal.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/create-workspace-modal.test.tsx
index ba243866c..99e4a414c 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/create-workspace-modal.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/create-workspace-modal.test.tsx
@@ -184,13 +184,14 @@ describe('the create-workspace modal', () => {
expect(el.textContent).toContain('Acme prod');
});
- it('asks which server once there are two you are signed in to', async () => {
+ it('never asks which server: it is the one whose New workspace was chosen', async () => {
addServer('srv-1', 'Acme prod', 'signedIn');
addServer('srv-2', 'Acme staging', 'signedIn');
- const el = await render('srv-1');
+ const el = await render('srv-2');
- expect(hasLabel(el, 'Server')).toBe(true);
+ expect(hasLabel(el, 'Server')).toBe(false);
+ expect(el.textContent).toContain('Create a workspace on Acme staging');
});
// The failure would otherwise arrive as an authentication error on Create,
@@ -228,21 +229,17 @@ describe('the create-workspace modal', () => {
expect(button(el, 'Create workspace').disabled).toBe(false);
});
- /**
- * The refusal the gateway actually sends, rather than a plain Error. Its
- * words are `Slug already taken: weekend-robotics` — no terminal punctuation,
- * so the shared description does not read it as a sentence and demotes it to
- * diagnostics. What reached the user was a status code and a slug they never
- * typed, for the likeliest failure of this form and the only one they can fix.
- */
- it('blames the name for a name conflict, not the status code and the slug', async () => {
+ // A conflict is the server refusing a second workspace (it is not isolating
+ // tenants) or a create racing another; its own sentence says which.
+ it('shows the server’s reason for a conflict instead of blaming the name', async () => {
addServer('srv-1', 'Acme prod', 'signedIn');
+ const detail = 'This server is not isolating tenants, which allows a single workspace.';
create.mockRejectedValue(
new RpcError({
__switchConsoleRpcError: true,
code: 'GatewayError',
- message: 'Gateway returned 409: Slug already taken: weekend-robotics',
- data: { kind: 'http', status: 409, detail: 'Slug already taken: weekend-robotics' },
+ message: `Gateway returned 409: ${detail}`,
+ data: { kind: 'http', status: 409, detail },
} as unknown as ConstructorParameters<typeof RpcError>[0])
);
@@ -251,11 +248,9 @@ describe('the create-workspace modal', () => {
await act(async () => button(el, 'Create workspace').click());
await settle();
- expect(el.textContent).toContain('already goes by that name');
- expect(el.textContent).not.toContain('weekend-robotics');
- expect(el.textContent).not.toContain('409');
- // Still typeable: a different name is the whole of the remedy.
- expect(el.querySelector('input')!.disabled).toBe(false);
+ expect(el.textContent).toContain('Acme prod could not create it');
+ expect(el.textContent).toContain('allows a single workspace');
+ expect(el.textContent).not.toContain('already goes by that name');
});
/**
@@ -285,25 +280,6 @@ describe('the create-workspace modal', () => {
expect(refreshStatus).toHaveBeenCalledWith('srv-1');
});
- /**
- * The hidden default was the window's own server, which may be the one that
- * cannot be asked — leaving Create permanently off with the usable server
- * offered nowhere.
- */
- it('opens on a server it can ask when the window’s own cannot be', async () => {
- addServer('srv-1', 'Acme prod', 'signedOut');
- addServer('srv-2', 'Acme staging', 'signedIn');
- create.mockResolvedValue(workspace('ws-9', 'srv-2'));
-
- const el = await render('srv-1');
- await typeName(el, 'Weekend Robotics');
- await act(async () => button(el, 'Create workspace').click());
- await settle();
-
- expect(el.textContent).toContain('Acme staging');
- expect(create).toHaveBeenCalledWith('srv-2', 'Weekend Robotics');
- });
-
/**
* `dismissOnOutsideClick: false` stops the backdrop but not Escape, so
* without the guard a keypress mid-create leaves the window re-scoped and
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/server-sign-up.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/server-sign-up.test.tsx
index a39307ce1..1261adb63 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/server-sign-up.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/server-sign-up.test.tsx
@@ -19,6 +19,7 @@ const switchServers = vi.hoisted(() => ({
ensureCloudMachine: vi.fn(),
switchCloud: vi.fn(),
}));
+const featureFlags = vi.hoisted(() => ({ current: vi.fn() }));
const workspaces = vi.hoisted(() => ({
list: vi.fn(async () => []),
getActiveId: vi.fn(async () => null),
@@ -27,7 +28,7 @@ const workspaces = vi.hoisted(() => ({
vi.mock('@renderer/lib/ipc', () => ({
events: { on: () => () => {} },
- rpc: { switchServers, workspaces },
+ rpc: { switchServers, workspaces, featureFlags },
}));
import {
@@ -67,8 +68,13 @@ beforeEach(() => {
user: null,
});
switchServers.ensureCloudMachine.mockResolvedValue({});
+ featureFlags.current.mockResolvedValue(hostedAgents(true));
});
+function hostedAgents(enabled: boolean) {
+ return { success: true, data: { flags: { hosted_agents: enabled } } };
+}
+
afterEach(async () => {
if (root) await act(async () => root!.unmount());
container?.remove();
@@ -239,5 +245,20 @@ it('warms the cloud machine after signing in to Switch Cloud', async () => {
await submit(el);
await vi.waitFor(() => expect(onSignedIn).toHaveBeenCalledWith({ machine: null }));
- expect(switchServers.ensureCloudMachine).toHaveBeenCalledWith('server');
+ await vi.waitFor(() => expect(switchServers.ensureCloudMachine).toHaveBeenCalledWith('server'));
+});
+
+it('leaves the cloud machine alone when Switch Cloud turns cloud machines off', async () => {
+ featureFlags.current.mockResolvedValue(hostedAgents(false));
+ switchServers.passwordLogin.mockResolvedValue({ success: true, data: {} });
+ const onSignedIn = vi.fn();
+ const el = await render(onSignedIn);
+ await type(el, 'test-email', '[email protected]');
+ await type(el, 'test-password', 'correct-horse');
+
+ await submit(el);
+
+ await vi.waitFor(() => expect(onSignedIn).toHaveBeenCalledWith({ machine: null }));
+ await vi.waitFor(() => expect(featureFlags.current).toHaveBeenCalledWith('server'));
+ expect(switchServers.ensureCloudMachine).not.toHaveBeenCalled();
});
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/workspace-switcher.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/workspace-switcher.test.tsx
index 9e7d607a1..2a3aff312 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/workspace-switcher.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/workspace-switcher.test.tsx
@@ -28,6 +28,7 @@ const state = vi.hoisted(() => ({
toast: vi.fn(),
unavailable: new Set<string>(),
noMembership: new Set<string>(),
+ noCreate: new Set<string>(),
listPendingInvitations: vi.fn(),
acceptPendingInvitation: vi.fn(),
listJoinableWorkspaces: vi.fn(),
@@ -40,6 +41,7 @@ vi.mock('@renderer/lib/ipc', () => ({
switchServers: {
listPendingInvitations: state.listPendingInvitations,
listJoinableWorkspaces: state.listJoinableWorkspaces,
+ canCreateWorkspace: (serverId: string) => Promise.resolve(!state.noCreate.has(serverId)),
},
},
events: { on: () => () => {}, emit: () => {} },
@@ -87,11 +89,20 @@ vi.mock('@renderer/features/workspaces/workspaces-store', () => ({
}));
vi.mock('@renderer/features/switch-servers/local-server-store', () => ({
- localServerStore: { init: () => Promise.resolve(), dispose: () => {}, phase: 'stopped' },
+ localServerStore: {
+ init: () => Promise.resolve(),
+ dispose: () => {},
+ phase: 'stopped',
+ isTransitioning: false,
+ },
}));
vi.mock('@renderer/features/switch-servers/remote-server-store', () => ({
- remoteServerStore: { init: () => Promise.resolve(), dispose: () => {} },
+ remoteServerStore: {
+ init: () => Promise.resolve(),
+ dispose: () => {},
+ isTransitioning: () => false,
+ },
}));
// Presentation of a server — its avatar, icon, status words and drift — is the
@@ -103,6 +114,8 @@ vi.mock('@renderer/features/switch-servers/server-presentation', () => ({
ServerStatusDot: () => null,
serverDrift: () => null,
serverPlacementLabel: () => null,
+ serverState: (server: SwitchServer) =>
+ state.unavailable.has(server.id) ? 'signed-out' : 'connected',
serverStatusLabel: (server: SwitchServer) => `${server.name} status`,
serverSubtitleLabel: (server: SwitchServer) => `${server.name} status`,
}));
@@ -213,6 +226,7 @@ beforeEach(() => {
state.toast.mockReset();
state.unavailable.clear();
state.noMembership.clear();
+ state.noCreate.clear();
state.listPendingInvitations.mockReset().mockResolvedValue({ kind: 'listed', invitations: [] });
state.acceptPendingInvitation.mockReset();
state.listJoinableWorkspaces.mockReset().mockResolvedValue({ kind: 'listed', workspaces: [] });
@@ -241,8 +255,8 @@ describe('the workspaces the switcher offers', () => {
group.querySelector('[data-slot="dropdown-menu-label"]')?.textContent,
// The first span on a row is its name; a second one, where there is one,
// is the role or the reason it cannot be opened.
- [...group.querySelectorAll('[role="menuitem"]')].map(
- (item) => item.querySelector('[data-row-name]')?.textContent
+ [...group.querySelectorAll('[role="menuitem"] [data-row-name]')].map(
+ (name) => name.textContent
),
]);
@@ -356,26 +370,70 @@ describe('a workspace that cannot be opened', () => {
});
describe('inviting people from the switcher', () => {
- function inviteItem(): HTMLElement | undefined {
- return [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find((item) =>
- item.textContent?.startsWith('Invite people')
+ function inviteButton(workspaceName: string): HTMLButtonElement | undefined {
+ const row = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find(
+ (item) => item.querySelector('[data-row-name]')?.textContent === workspaceName
+ );
+ return [...(row?.querySelectorAll('button') ?? [])].find(
+ (button) => button.textContent === 'Invite'
);
}
- it('is offered in a workspace the account administers', async () => {
+ it('is a button on each workspace row the account administers, not only the open one', async () => {
await openSwitcher(
[server('srv-1', 'Acme')],
- [workspace('ws-a', 'srv-1', { role: 'admin' })],
+ [
+ workspace('ws-a', 'srv-1', { role: 'admin' }),
+ workspace('ws-b', 'srv-1', { role: 'owner' }),
+ ],
'ws-a'
);
- expect(inviteItem()?.textContent).toBe('Invite people to ws-a…');
+ expect(inviteButton('ws-a')).toBeDefined();
+ expect(inviteButton('ws-b')).toBeDefined();
+ expect(document.body.textContent).not.toContain('Invite people to');
});
it('is not offered to a member, whom the server would refuse', async () => {
await openSwitcher([server('srv-1', 'Acme')], [workspace('ws-a', 'srv-1')], 'ws-a');
- expect(inviteItem()).toBeUndefined();
+ expect(inviteButton('ws-a')).toBeUndefined();
+ });
+});
+
+describe('new workspaces from the switcher', () => {
+ it('is not offered on a server that says you cannot create one there', async () => {
+ state.noCreate.add('srv-2');
+ await openSwitcher(
+ [server('srv-1', 'Acme'), server('srv-2', 'Local dev')],
+ [workspace('ws-a', 'srv-1'), workspace('ws-b', 'srv-2')],
+ 'ws-a'
+ );
+ await settle();
+
+ const groups = [...document.querySelectorAll<HTMLElement>('[data-slot="dropdown-menu-group"]')];
+ const rows = (group: HTMLElement) =>
+ [...group.querySelectorAll('[role="menuitem"]')].map((item) => item.textContent);
+ expect(rows(groups[0]!)).toContain('New workspace');
+ expect(rows(groups[1]!)).not.toContain('New workspace');
+ });
+
+ it('ends each server you can use with its own New workspace', async () => {
+ state.unavailable.add('srv-3');
+ await openSwitcher(
+ [server('srv-1', 'Acme'), server('srv-2', 'Local dev'), server('srv-3', 'Pi')],
+ [workspace('ws-a', 'srv-1'), workspace('ws-b', 'srv-2'), workspace('ws-c', 'srv-3')],
+ 'ws-a'
+ );
+
+ const groups = [...document.querySelectorAll<HTMLElement>('[data-slot="dropdown-menu-group"]')];
+ const lastRow = (group: HTMLElement) =>
+ [...group.querySelectorAll('[role="menuitem"]')].at(-1)?.textContent;
+ expect(groups.map((group) => lastRow(group))).toEqual([
+ 'New workspace',
+ 'New workspace',
+ undefined,
+ ]);
});
});
@@ -685,7 +743,7 @@ describe('finding a workspace in the menu', () => {
});
describe('the server headings', () => {
- it('marks the Switch Cloud server as official and names where the others are', async () => {
+ it('names each server and nothing else: no address, no "Official"', async () => {
await openSwitcher(
[server('cloud', 'Switch Cloud'), server('srv-2', 'Local dev')],
[workspace('ws-a', 'cloud'), workspace('ws-b', 'srv-2')],
@@ -695,9 +753,8 @@ describe('the server headings', () => {
const labels = [...document.querySelectorAll('[data-slot="dropdown-menu-label"]')].map(
(el) => el.textContent
);
- expect(labels[0]).toContain('Official');
- expect(labels[1]).toContain('srv-2.example.invalid');
- expect(labels[1]).not.toContain('Official');
+ expect(labels[0]).toBe('Switch Cloud');
+ expect(labels[1]).toBe('Local dev');
});
});
@@ -706,7 +763,7 @@ describe('a server with no workspace to show yet', () => {
return [...document.querySelectorAll('[role="menuitem"]')].map((el) => el.textContent ?? '');
}
- it('offers Sign in… instead of a workspace named after a server you are signed out of', async () => {
+ it('collapses a server you are signed out of to one row with Sign in', async () => {
state.unavailable.add('cloud');
await openSwitcher(
[server('srv-1', 'Acme'), server('cloud', 'Switch Cloud')],
@@ -714,11 +771,11 @@ describe('a server with no workspace to show yet', () => {
'ws-a'
);
- expect(menuText()).toContain('Sign in…');
+ expect(document.body.textContent).toContain('Switch Cloud status');
expect(names()).not.toContain('Switch Cloud');
- const signIn = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find(
- (el) => el.textContent === 'Sign in…'
+ const signIn = [...document.querySelectorAll<HTMLElement>('button')].find(
+ (el) => el.textContent === 'Sign in'
);
await act(async () => signIn!.click());
expect(state.setActive).toHaveBeenCalledWith('Switch Cloud');
@@ -734,7 +791,7 @@ describe('a server with no workspace to show yet', () => {
);
expect(document.body.textContent).toContain('No workspace yet');
- expect(menuText()).toContain('Create a workspace…');
+ expect(menuText()).toContain('New workspace');
expect(names()).not.toContain('Switch Cloud');
});
diff --git a/console/apps/switch-console-desktop/src/shared/app-identity.ts b/console/apps/switch-console-desktop/src/shared/app-identity.ts
index 84cc7e710..642062734 100644
--- a/console/apps/switch-console-desktop/src/shared/app-identity.ts
+++ b/console/apps/switch-console-desktop/src/shared/app-identity.ts
@@ -44,6 +44,7 @@ export const USER_DATA_DIR_NAME = isDev ? 'switchdash-dev' : 'switchdash';
export const UPDATE_CHANNEL = isCanary ? 'v1-canary' : 'v1-stable';
export const ARTIFACT_PREFIX = isCanary ? 'switch-console-canary' : 'switch-console';
export const IS_CANARY = isCanary;
+export const IS_DEV = isDev;
export const IS_RELEASE_BUILD = isRelease;
// GitHub repo the desktop app publishes releases to / reads auto-updates from.
diff --git a/console/apps/switch-console-desktop/src/shared/core/feature-flags/feature-flags.ts b/console/apps/switch-console-desktop/src/shared/core/feature-flags/feature-flags.ts
new file mode 100644
index 000000000..6e6795a48
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/shared/core/feature-flags/feature-flags.ts
@@ -0,0 +1,73 @@
+import { IS_CANARY, IS_DEV } from '@shared/app-identity';
+
+/**
+ * Feature flags Console knows about. Each Switch server sets its own at deploy
+ * time and serves them at `GET /gateway/feature-flags`; Console reads every
+ * server it is connected to on a schedule, so a redeploy that turns a flag on
+ * or off reaches a running Console without a restart.
+ *
+ * A key the server sends that is not listed here is ignored, and a key listed
+ * here that the server does not send (an older server) is off.
+ */
+export const CONSOLE_FEATURE_FLAGS = [
+ 'ecosystem.show_owners',
+ 'switch_cloud',
+ 'hosted_agents',
+ 'agent_management',
+] as const;
+
+export type FeatureFlagKey = (typeof CONSOLE_FEATURE_FLAGS)[number];
+
+export type FeatureFlags = Record<FeatureFlagKey, boolean>;
+
+/** One flag as the gateway serves it. */
+export type RemoteFeatureFlag = { key: string; enabled: boolean };
+
+/** What Console last learned about one server's flags. */
+export type ServerFeatureFlags = {
+ serverId: string;
+ flags: FeatureFlags;
+ /** When the flags were last read successfully; null if they never were. */
+ fetchedAt: number | null;
+ /** Why the last read failed; null when it succeeded. `flags` then still
+ * holds the last values read, or every flag off if none ever were. */
+ error: string | null;
+};
+
+export function allFeatureFlagsOff(): FeatureFlags {
+ return Object.fromEntries(CONSOLE_FEATURE_FLAGS.map((key) => [key, false])) as FeatureFlags;
+}
+
+export function resolveFeatureFlags(remote: readonly RemoteFeatureFlag[]): FeatureFlags {
+ const flags = allFeatureFlagsOff();
+ for (const { key, enabled } of remote) {
+ if ((CONSOLE_FEATURE_FLAGS as readonly string[]).includes(key)) {
+ flags[key as FeatureFlagKey] = enabled === true;
+ }
+ }
+ return flags;
+}
+
+export function sameFeatureFlags(a: FeatureFlags, b: FeatureFlags): boolean {
+ return CONSOLE_FEATURE_FLAGS.every((key) => a[key] === b[key]);
+}
+
+/**
+ * What this build turns on before it has a server to ask.
+ *
+ * The first-run pages and the Switch Cloud choice are drawn before Console is
+ * connected to anything, so no server's flags can decide them. A run from a
+ * checkout and a canary have them on; a stable release has them off. Once
+ * Console is connected, the server's own flags decide everything else.
+ */
+export type BuildFeatureFlags = {
+ /** The first-run pages. Without them a fresh install opens the app itself. */
+ onboarding: boolean;
+ /** Switch Cloud as a place to connect to. It also needs the build's Cloud URL. */
+ switch_cloud: boolean;
+};
+
+export const BUILD_FEATURE_FLAGS: BuildFeatureFlags = {
+ onboarding: IS_DEV || IS_CANARY,
+ switch_cloud: IS_DEV || IS_CANARY,
+};
diff --git a/console/apps/switch-console-desktop/src/shared/events/featureFlagEvents.ts b/console/apps/switch-console-desktop/src/shared/events/featureFlagEvents.ts
new file mode 100644
index 000000000..79fc61239
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/shared/events/featureFlagEvents.ts
@@ -0,0 +1,5 @@
+import type { ServerFeatureFlags } from '@shared/core/feature-flags/feature-flags';
+import { defineEvent } from '@shared/lib/ipc/events';
+
+/** A server's feature flags changed, or reading them started or stopped failing. */
+export const featureFlagsChangedChannel = defineEvent<ServerFeatureFlags>('feature-flags:changed');
diff --git a/console/apps/switch-console-desktop/tooling/fixtures/baseline.db b/console/apps/switch-console-desktop/tooling/fixtures/baseline.db
index c1759e17b..30615464e 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
deleted file mode 100644
index fe9ac2845..000000000
Binary files a/console/apps/switch-console-desktop/tooling/fixtures/baseline.db-shm and /dev/null 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
deleted file mode 100644
index e69de29bb..000000000
diff --git a/console/apps/switch-console-desktop/tooling/fixtures/empty.db b/console/apps/switch-console-desktop/tooling/fixtures/empty.db
index ef513691c..6ce3d7ee2 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
deleted file mode 100644
index fe9ac2845..000000000
Binary files a/console/apps/switch-console-desktop/tooling/fixtures/empty.db-shm and /dev/null 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
deleted file mode 100644
index e69de29bb..000000000
diff --git a/console/packages/agent-controller/README.md b/console/packages/agent-controller/README.md
index 5fd7e6514..6091f002b 100644
--- a/console/packages/agent-controller/README.md
+++ b/console/packages/agent-controller/README.md
@@ -37,7 +37,8 @@ relay accepts.
- Each provider CLI the agents use, installed on `PATH` and signed in as the user
the controller runs as (`claude`, `codex`, `opencode`, `agent`/`cursor-agent`,
`antigravity-acp`), or its API key in the `--env-file` the controller runs with.
-- A Switch server with `AGENT_MANAGEMENT_ENABLED=true`. Behind a proxy or ingress,
+- A Switch server with the `agent_management` feature flag on
+ (`FEATURE_FLAGS_ENABLED=agent_management`). Behind a proxy or ingress,
`/v1` must reach switch-core (the Helm chart routes it).
## Install
diff --git a/core/switch_core/bridges/agent/api/handlers.py b/core/switch_core/bridges/agent/api/handlers.py
index 9ae01e01c..a99236e6c 100644
--- a/core/switch_core/bridges/agent/api/handlers.py
+++ b/core/switch_core/bridges/agent/api/handlers.py
@@ -66,7 +66,6 @@ from switch_core.bridges.agent.api.schemas import (
RoomListResponse,
RuntimeStateRequest,
SendMessageRequest,
- SetFeatureFlagRequest,
StatusRequest,
TaskAgentsResponse,
TaskInfo,
@@ -122,8 +121,6 @@ from switch_core.budgets import BudgetExceeded
from switch_core.config import SwitchConfig
from switch_core.db.models import Agent, Task
from switch_core.db.stores.api_key_store import ApiKeyStore
-from switch_core.db.stores.feature_flag_store import FeatureFlagStore
-from switch_core.feature_flags import is_known_flag
from switch_core.gateway.known_agents import KNOWN_AGENTS
from switch_core.observability.catalogue import AGENT_CONNECTIONS_REFUSED
from switch_core.observability.metrics import metrics
@@ -2053,34 +2050,15 @@ async def list_bridges(
@router.get("/feature-flags")
async def list_feature_flags(
_agent: Annotated[Agent, Depends(get_agent_from_scope)],
- session: Annotated[AsyncSession, Depends(get_session)],
+ config: Annotated[SwitchConfig, Depends(get_config)],
) -> FeatureFlagListResponse:
- """List every server-global feature flag and its current state.
+ """List every feature flag and whether this deployment turned it on.
- Any authenticated agent may read the flags.
+ Any authenticated agent may read them. Flags are set at deploy time
+ (`FEATURE_FLAGS_ENABLED`); nothing can change them through the API.
"""
- flags = await FeatureFlagStore().get_all(session)
return FeatureFlagListResponse(
- flags=[FeatureFlagInfo(key=k, enabled=v) for k, v in sorted(flags.items())]
+ flags=[
+ FeatureFlagInfo(key=k, enabled=v) for k, v in config.feature_flags.items()
+ ]
)
-
-
[email protected]("/feature-flags/{key}")
-async def set_feature_flag(
- key: str,
- req: SetFeatureFlagRequest,
- _agent: Annotated[Agent, Depends(get_agent_from_scope)],
- session: Annotated[AsyncSession, Depends(get_session)],
-) -> FeatureFlagInfo:
- """Flip a server-global feature flag on or off.
-
- Gated by any valid agent API token. Only keys in the known-flag registry
- are accepted so the endpoint cannot write arbitrary rows.
- """
- if not is_known_flag(key):
- raise HTTPException(status_code=400, detail=f"Unknown feature flag: {key}")
-
- store = FeatureFlagStore()
- await store.set(session, key, req.enabled)
- await session.commit()
- return FeatureFlagInfo(key=key, enabled=req.enabled)
diff --git a/core/switch_core/bridges/agent/api/schemas.py b/core/switch_core/bridges/agent/api/schemas.py
index 3040f1815..80b0d4229 100644
--- a/core/switch_core/bridges/agent/api/schemas.py
+++ b/core/switch_core/bridges/agent/api/schemas.py
@@ -465,10 +465,6 @@ class AgentListResponse(BaseModel):
agents: list[AgentInfo]
-class SetFeatureFlagRequest(BaseModel):
- enabled: bool
-
-
class FeatureFlagInfo(BaseModel):
key: str
enabled: bool
diff --git a/core/switch_core/bridges/agent/operations/agent_management.py b/core/switch_core/bridges/agent/operations/agent_management.py
index 5b10a1a68..cc66b0243 100644
--- a/core/switch_core/bridges/agent/operations/agent_management.py
+++ b/core/switch_core/bridges/agent/operations/agent_management.py
@@ -1,7 +1,7 @@
"""Agent operations on the owner's agent management: machines and managed agents.
These exist only on a server running agent management
-(`AGENT_MANAGEMENT_ENABLED`): they are declared in their own operation group,
+(the `agent_management` feature flag): they are declared in their own operation group,
and the group is enabled when the process wiring hands over management's
implementation of `AgentManagementPort` (`enable_agent_management`). Until
then they are on neither front door.
diff --git a/core/switch_core/clients/client_lifecycle_service.py b/core/switch_core/clients/client_lifecycle_service.py
index feae02da4..d9c23ab24 100644
--- a/core/switch_core/clients/client_lifecycle_service.py
+++ b/core/switch_core/clients/client_lifecycle_service.py
@@ -91,6 +91,11 @@ class ClientLifecycleService:
self._client_tenants: dict[str, str] = {}
self._tasks: dict[str, asyncio.Task[None]] = {}
+ @property
+ def tenants_isolated(self) -> bool:
+ """Whether a tenant beyond the first can be created on this deployment."""
+ return self._tenants_isolated
+
def _make_user_id(self, localpart: str) -> str:
return f"@{localpart}:{self._config.id_server_name}"
diff --git a/core/switch_core/config.py b/core/switch_core/config.py
index 978d3a2c6..f31b03cac 100644
--- a/core/switch_core/config.py
+++ b/core/switch_core/config.py
@@ -13,6 +13,11 @@ from cryptography.hazmat.primitives.asymmetric import rsa
from pydantic import AliasChoices, Field, model_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
+from switch_core.feature_flags import (
+ AGENT_MANAGEMENT,
+ HOSTED_AGENTS,
+ KNOWN_FEATURE_FLAGS,
+)
from switch_core.keys import Keyring
from switch_core.outbound import OutboundPolicy
@@ -158,6 +163,12 @@ class SwitchConfig(BaseSettings):
# See `outbound.py`.
outbound_allowed_private_hosts: str = ""
+ # Feature flags that are on for this deployment: comma-separated keys from
+ # `feature_flags.KNOWN_FEATURE_FLAGS`. Every other flag is off. Fixed for
+ # the life of the process; an unknown key is a startup error rather than a
+ # silently ignored typo.
+ feature_flags_enabled: str = ""
+
# Gateway admin seed
gateway_admin_email: str
gateway_admin_password: str
@@ -221,8 +232,10 @@ class SwitchConfig(BaseSettings):
# OIDC first sign-in alike), read from the users table so it holds across
# replicas. Sign-up is refused once the count reaches this.
gateway_signup_max_per_hour: int = Field(default=20, ge=1)
- # How many cloud machines the bound tenant may have at once. Cloud machines
- # run the agents controller, so they need AGENT_MANAGEMENT_ENABLED.
+ # How many cloud machines the bound tenant may have at once; 0 means this
+ # server cannot run them. The `hosted_agents` flag is what offers them.
+ # Cloud machines run the agents controller, so above 0 this needs the
+ # `agent_management` flag.
hosted_launch_capacity: int = Field(default=0, ge=0, le=100)
hosted_idle_stop_minutes: int = Field(default=30, ge=0, le=1440)
hosted_disk_retention_days: int = Field(default=7, ge=1, le=90)
@@ -614,11 +627,12 @@ class SwitchConfig(BaseSettings):
# evicted past this, so a flood of tokens cannot grow the process.
agent_auth_cache_max_entries: int = 4096
- # Agent management: managed agent definitions, the agent controllers that
- # run them, and the controller-facing routes under /v1/management and
- # /v1/controllers. Off by default; with it off none of those routes are
- # mounted and the bearer middleware never treats a token as a controller's.
- agent_management_enabled: bool = False
+ # AGENT_MANAGEMENT_ENABLED, replaced by the `agent_management` feature flag.
+ # Read only to refuse a deployment that still turns it on, which would
+ # otherwise lose agent management without a word.
+ legacy_agent_management_enabled: bool | None = Field(
+ default=None, validation_alias="agent_management_enabled"
+ )
# Signs controller access tokens. Required (at least 32 characters) when
# agent management is on, and deliberately separate from SECRET_KEYS so
# rotating one never invalidates the other.
@@ -718,17 +732,24 @@ class SwitchConfig(BaseSettings):
"CONTROLLER_STATUS_INTERVAL_SECONDS must be at least 1, got "
f"{self.controller_status_interval_seconds!r}."
)
+ if self.legacy_agent_management_enabled:
+ raise ValueError(
+ "AGENT_MANAGEMENT_ENABLED has been replaced by a feature flag: "
+ f"remove it and add {AGENT_MANAGEMENT!r} to FEATURE_FLAGS_ENABLED."
+ )
if not self.agent_management_enabled:
if self.hosted_launch_capacity > 0:
raise ValueError(
- "HOSTED_LAUNCH_CAPACITY needs AGENT_MANAGEMENT_ENABLED: cloud "
- "machines run the agents controller."
+ "HOSTED_LAUNCH_CAPACITY needs the "
+ f"{AGENT_MANAGEMENT!r} feature flag: cloud machines run the "
+ "agents controller."
)
return self
if not self.controller_token_secret:
raise ValueError(
- "CONTROLLER_TOKEN_SECRET is required when AGENT_MANAGEMENT_ENABLED "
- "is true: it signs the access tokens agent controllers use."
+ "CONTROLLER_TOKEN_SECRET is required when the "
+ f"{AGENT_MANAGEMENT!r} feature flag is on: it signs the access "
+ "tokens agent controllers use."
)
if len(self.controller_token_secret) < 32:
raise ValueError(
@@ -993,6 +1014,35 @@ class SwitchConfig(BaseSettings):
)
return self
+ @model_validator(mode="after")
+ def _validate_feature_flags_enabled(self) -> "SwitchConfig":
+ unknown = sorted(self._enabled_feature_flags() - KNOWN_FEATURE_FLAGS)
+ if unknown:
+ raise ValueError(
+ f"FEATURE_FLAGS_ENABLED names unknown feature flag(s): {unknown}. "
+ f"Known flags: {sorted(KNOWN_FEATURE_FLAGS)}."
+ )
+ return self
+
+ def _enabled_feature_flags(self) -> set[str]:
+ return {
+ key.strip() for key in self.feature_flags_enabled.split(",") if key.strip()
+ }
+
+ @property
+ def feature_flags(self) -> dict[str, bool]:
+ """Every known flag and whether this deployment turned it on."""
+ enabled = self._enabled_feature_flags()
+ return {key: key in enabled for key in sorted(KNOWN_FEATURE_FLAGS)}
+
+ @property
+ def agent_management_enabled(self) -> bool:
+ return self.feature_flags[AGENT_MANAGEMENT]
+
+ @property
+ def hosted_agents_enabled(self) -> bool:
+ return self.feature_flags[HOSTED_AGENTS]
+
@model_validator(mode="after")
def _validate_outbound_allowed_private_hosts(self) -> "SwitchConfig":
OutboundPolicy.parse(self.outbound_allowed_private_hosts)
diff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.py
index 855de57bf..997dabef6 100644
--- a/core/switch_core/db/models.py
+++ b/core/switch_core/db/models.py
@@ -2141,29 +2141,6 @@ class SwitchCoreProcess(Base):
)
-# ── Feature flags ────────────────────────────────────────────────────────────
-
-
-class FeatureFlag(Base):
- """Server-global on/off switch keyed by a well-known flag name.
-
- A row exists only once a flag has been written; an absent row means the
- flag is OFF (its default). Which keys are writable is enforced in the
- application layer (see ``switch_core.feature_flags``), not by the table.
- """
-
- __tablename__ = "feature_flags"
-
- key: Mapped[str] = mapped_column(Text, primary_key=True)
- enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
- updated_at: Mapped[str] = mapped_column(
- DateTime(timezone=True),
- server_default=func.now(),
- onupdate=func.now(),
- nullable=False,
- )
-
-
# ── Messages ─────────────────────────────────────────────────────────────────
diff --git a/core/switch_core/db/rls_ddl.py b/core/switch_core/db/rls_ddl.py
index cb2893d61..a234dffe9 100644
--- a/core/switch_core/db/rls_ddl.py
+++ b/core/switch_core/db/rls_ddl.py
@@ -114,9 +114,7 @@ POLICY_NAME = "tenant_isolation"
# so widening it fails the suite until someone changes the test too.
#
# A person is not a tenant member (`users`), nor is the record of how they
-# prove who they are (`oidc_identities`); `feature_flags` is a deployment
-# switch, and a flag that needs to vary per customer is a new scoped table
-# rather than a nullable column here. Alembic's `alembic_version` needs no
+# prove who they are (`oidc_identities`). Alembic's `alembic_version` needs no
# entry: Alembic owns that table and never registers it on this metadata.
#
# The three telemetry tables are global because each records a fact about the
@@ -144,7 +142,6 @@ GLOBAL_TABLES = frozenset(
"cloud_machines",
"users",
"oidc_identities",
- "feature_flags",
"deployment_identity",
"telemetry_milestones",
"telemetry_snapshot_watermark",
diff --git a/core/switch_core/db/stores/feature_flag_store.py b/core/switch_core/db/stores/feature_flag_store.py
deleted file mode 100644
index a6d6ebd58..000000000
--- a/core/switch_core/db/stores/feature_flag_store.py
+++ /dev/null
@@ -1,47 +0,0 @@
-from __future__ import annotations
-
-from sqlalchemy import func, select
-from sqlalchemy.dialects.postgresql import insert
-from sqlalchemy.ext.asyncio import AsyncSession
-
-from switch_core.db.models import FeatureFlag
-from switch_core.feature_flags import KNOWN_FEATURE_FLAGS
-
-
-class FeatureFlagStore:
- """Storage for server-global feature flags (``feature_flags``).
-
- Only the value is persisted; an absent row means the flag is OFF. Callers
- are responsible for validating the key against the known-flag registry
- before writing (see ``switch_core.feature_flags``).
- """
-
- async def get(self, session: AsyncSession, key: str) -> bool:
- result = await session.execute(
- select(FeatureFlag.enabled).where(FeatureFlag.key == key)
- )
- enabled = result.scalar_one_or_none()
- if enabled is None:
- return KNOWN_FEATURE_FLAGS.get(key, False)
- return enabled
-
- async def get_all(self, session: AsyncSession) -> dict[str, bool]:
- """Return the effective state of every known flag (defaults + overrides)."""
- flags = dict(KNOWN_FEATURE_FLAGS)
- result = await session.execute(select(FeatureFlag.key, FeatureFlag.enabled))
- for key, enabled in result.all():
- if key in flags:
- flags[key] = enabled
- return flags
-
- async def set(self, session: AsyncSession, key: str, enabled: bool) -> None:
- stmt = (
- insert(FeatureFlag)
- .values(key=key, enabled=enabled)
- .on_conflict_do_update(
- index_elements=[FeatureFlag.key],
- set_={"enabled": enabled, "updated_at": func.now()},
- )
- )
- await session.execute(stmt)
- await session.flush()
diff --git a/core/switch_core/db/tenant_session.py b/core/switch_core/db/tenant_session.py
index 0d500092f..cb41dad8e 100644
--- a/core/switch_core/db/tenant_session.py
+++ b/core/switch_core/db/tenant_session.py
@@ -272,7 +272,7 @@ def _refuse_a_row_from_another_tenant(instance: object) -> None:
"""
tenant_id = _tenant_of(instance)
if tenant_id is None:
- # A global table (`users`, `oidc_identities`, `feature_flags`) carries
+ # A global table (`users`, `oidc_identities`) carries
# no tenant, so there is nothing to compare and nothing to refuse.
return
bound = current_tenant_id()
diff --git a/core/switch_core/feature_flags.py b/core/switch_core/feature_flags.py
index 10b773e50..8d2a4523a 100644
--- a/core/switch_core/feature_flags.py
+++ b/core/switch_core/feature_flags.py
@@ -1,10 +1,16 @@
-"""Registry of server-global feature flags.
+"""Registry of feature flags.
-A feature flag is a named on/off switch stored in the ``feature_flags`` table
-and flipped through the agent bridge (``PUT /agents/feature-flags/{key}``).
-Only keys listed here may be written or read — an unknown key is rejected so
-the endpoint cannot be used to write arbitrary rows. An absent row means the
-flag is OFF, so ``DEFAULTS`` is purely documentation of that baseline.
+A feature flag is a named on/off switch for the whole deployment. It is set
+when the server is deployed (``FEATURE_FLAGS_ENABLED``, a comma-separated list
+of the flags that are on) and nobody can change it while the server runs.
+Every flag not listed is off. Naming a key that is not registered here is a
+startup error, so a typo cannot silently leave a flag off.
+
+Core reads them from config. Agents read them at ``GET /agents/feature-flags``,
+and Switch Console and the dashboard at ``GET /gateway/feature-flags``. Console
+re-reads every server it is connected to on a schedule, keeps its own list of
+the keys it acts on, and treats a key it does not know, or one the server did
+not send, as off.
"""
from __future__ import annotations
@@ -13,11 +19,21 @@ from __future__ import annotations
# exposes owner data, so the frontend toggle has nothing to reveal.
ECOSYSTEM_SHOW_OWNERS = "ecosystem.show_owners"
-# All flags the server recognises, mapped to their default (off) state.
-KNOWN_FEATURE_FLAGS: dict[str, bool] = {
- ECOSYSTEM_SHOW_OWNERS: False,
-}
+# Switch Cloud. Core has nothing of its own behind it; clients read it.
+SWITCH_CLOUD = "switch_cloud"
+
+# Cloud machines: one machine per user, run by Switch, that agents can be
+# placed on. The flag offers them; whether this server can run them is its
+# hosted settings (HOSTED_LAUNCH_CAPACITY and the controller config), and a
+# server that cannot says so when one is claimed.
+HOSTED_AGENTS = "hosted_agents"
+# Agent management: managed agents, the machines and agent controllers that
+# run them, and the controller-facing routes under /v1/management and
+# /v1/controllers. With it off none of those routes are mounted.
+AGENT_MANAGEMENT = "agent_management"
-def is_known_flag(key: str) -> bool:
- return key in KNOWN_FEATURE_FLAGS
+# Every flag the server recognises.
+KNOWN_FEATURE_FLAGS: frozenset[str] = frozenset(
+ {ECOSYSTEM_SHOW_OWNERS, SWITCH_CLOUD, HOSTED_AGENTS, AGENT_MANAGEMENT}
+)
diff --git a/core/switch_core/gateway/app.py b/core/switch_core/gateway/app.py
index 6b81fdc85..b81eb550b 100644
--- a/core/switch_core/gateway/app.py
+++ b/core/switch_core/gateway/app.py
@@ -42,6 +42,7 @@ from switch_core.gateway.connectors import router as connectors_router
from switch_core.gateway.dependencies import init_dependencies
from switch_core.gateway.documents import router as documents_router
from switch_core.gateway.ecosystem import router as ecosystem_router
+from switch_core.gateway.feature_flags import router as feature_flags_router
from switch_core.gateway.github_connections import router as github_connections_router
from switch_core.gateway.hosted_controller import router as hosted_controller_router
from switch_core.gateway.hosted_machines import router as hosted_machines_router
@@ -188,6 +189,7 @@ def create_gateway_app(
app.include_router(templates_router, tags=["templates"])
app.include_router(template_runs_router, tags=["templates"])
app.include_router(ecosystem_router, prefix="/ecosystem", tags=["ecosystem"])
+ app.include_router(feature_flags_router, tags=["feature-flags"])
app.include_router(
messaging_installs_router,
prefix="/messaging-apps",
diff --git a/core/switch_core/gateway/auth.py b/core/switch_core/gateway/auth.py
index 08532287e..812d14987 100644
--- a/core/switch_core/gateway/auth.py
+++ b/core/switch_core/gateway/auth.py
@@ -486,6 +486,7 @@ def describe_session_state(
user: User,
tenant_claim: str | None,
tenants: list[TenantMembershipResponse],
+ tenants_isolated: bool,
) -> SessionStateResponse:
"""What `_resolve_tenant_id` would make of this session, as data.
@@ -516,7 +517,10 @@ def describe_session_state(
tenant=tenant,
tenants=tenants,
state=state,
- can_create_workspace=workspace_creation_refusal(
+ # A deployment that is not isolating tenants keeps to the one it has,
+ # for operators too: `POST /tenants` would refuse any name.
+ can_create_workspace=tenants_isolated
+ and workspace_creation_refusal(
config,
is_operator=is_operator,
workspaces_created=user.workspaces_created,
diff --git a/core/switch_core/gateway/auth_routes.py b/core/switch_core/gateway/auth_routes.py
index 1566cd0fc..71fca8d78 100644
--- a/core/switch_core/gateway/auth_routes.py
+++ b/core/switch_core/gateway/auth_routes.py
@@ -9,6 +9,7 @@ from sqlalchemy import text
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+from switch_core.clients.client_lifecycle_service import ClientLifecycleService
from switch_core.config import SwitchConfig
from switch_core.db.models import TENANT_ZERO_ID, User
from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore
@@ -33,6 +34,7 @@ from switch_core.gateway.auth import (
)
from switch_core.gateway.dependencies import (
get_bridge_store,
+ get_client_lifecycle,
get_config,
get_external_user_store,
get_session,
@@ -316,6 +318,7 @@ async def session_state(
],
user_store: Annotated[UserStore, Depends(get_user_store)],
config: Annotated[SwitchConfig, Depends(get_config)],
+ client_lifecycle: Annotated[ClientLifecycleService, Depends(get_client_lifecycle)],
) -> SessionStateResponse:
"""Who is signed in, which workspace this session is in, and — when it
is in none — what would get it into one.
@@ -332,7 +335,9 @@ async def session_state(
# One connection at a time: release this one before the lookup opens its own.
await session.commit()
tenants = await list_tenant_memberships(session_factory, user_store, user.id)
- return describe_session_state(config, user, auth.tenant_claim, tenants)
+ return describe_session_state(
+ config, user, auth.tenant_claim, tenants, client_lifecycle.tenants_isolated
+ )
@router.get("/auth/me")
diff --git a/core/switch_core/gateway/cloud_controllers.py b/core/switch_core/gateway/cloud_controllers.py
index ad539c51c..9e559bd80 100644
--- a/core/switch_core/gateway/cloud_controllers.py
+++ b/core/switch_core/gateway/cloud_controllers.py
@@ -66,7 +66,7 @@ class CloudEnrollmentUnavailable(Exception):
def cloud_enrollment() -> CloudEnrollment:
if _enrollment is None:
raise CloudEnrollmentUnavailable(
- "Cloud machines need agent management: set AGENT_MANAGEMENT_ENABLED."
+ "Cloud machines need agent management: turn on the agent_management feature flag."
)
return _enrollment
diff --git a/core/switch_core/gateway/ecosystem.py b/core/switch_core/gateway/ecosystem.py
index 6761bbe62..0b9299e64 100644
--- a/core/switch_core/gateway/ecosystem.py
+++ b/core/switch_core/gateway/ecosystem.py
@@ -5,16 +5,17 @@ from typing import Annotated
from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
+from switch_core.config import SwitchConfig
from switch_core.db.models import User
from switch_core.db.stores.agent_store import AgentStore
from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore
-from switch_core.db.stores.feature_flag_store import FeatureFlagStore
from switch_core.db.stores.user_store import UserStore
from switch_core.feature_flags import ECOSYSTEM_SHOW_OWNERS
from switch_core.gateway.auth import get_current_user
from switch_core.gateway.dependencies import (
get_agent_store,
get_bridge_store,
+ get_config,
get_session,
get_user_store,
)
@@ -36,6 +37,7 @@ async def get_ecosystem_graph(
bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],
user_store: Annotated[UserStore, Depends(get_user_store)],
_user: Annotated[User, Depends(get_current_user)],
+ config: Annotated[SwitchConfig, Depends(get_config)],
) -> EcosystemGraphResponse:
"""Switch-centric ecosystem graph: the Switch at the centre, with agent
types branching out (and individual agents under each type) and one branch
@@ -48,9 +50,9 @@ async def get_ecosystem_graph(
]
edges: list[EcosystemEdge] = []
- # "Show owners" is gated by a server-global feature flag. When OFF the
+ # "Show owners" is gated by a deployment feature flag. When OFF the
# graph withholds owner data entirely, so the frontend toggle is inert.
- show_owners = await FeatureFlagStore().get(session, ECOSYSTEM_SHOW_OWNERS)
+ show_owners = config.feature_flags[ECOSYSTEM_SHOW_OWNERS]
# Agents grouped by connector_type -> one agent-type node per type, with
# each agent hanging off its type.
diff --git a/core/switch_core/gateway/feature_flags.py b/core/switch_core/gateway/feature_flags.py
new file mode 100644
index 000000000..97ded6045
--- /dev/null
+++ b/core/switch_core/gateway/feature_flags.py
@@ -0,0 +1,31 @@
+from __future__ import annotations
+
+from typing import Annotated
+
+from fastapi import APIRouter, Depends
+
+from switch_core.config import SwitchConfig
+from switch_core.gateway.auth import get_authenticated_user_id
+from switch_core.gateway.dependencies import get_config
+from switch_core.gateway.schemas import FeatureFlagsResponse, FeatureFlagState
+
+router = APIRouter()
+
+
[email protected]("/feature-flags")
+async def list_feature_flags(
+ _user_id: Annotated[str, Depends(get_authenticated_user_id)],
+ config: Annotated[SwitchConfig, Depends(get_config)],
+) -> FeatureFlagsResponse:
+ """Every known flag and whether this deployment turned it on.
+
+ Flags belong to the deployment, not a workspace, so any signed-in caller may
+ read them before choosing a workspace. They are set at deploy time and
+ cannot be changed here.
+ """
+ return FeatureFlagsResponse(
+ flags=[
+ FeatureFlagState(key=key, enabled=enabled)
+ for key, enabled in config.feature_flags.items()
+ ]
+ )
diff --git a/core/switch_core/gateway/hosted_machines.py b/core/switch_core/gateway/hosted_machines.py
index c1ab9904b..bd72abaf5 100644
--- a/core/switch_core/gateway/hosted_machines.py
+++ b/core/switch_core/gateway/hosted_machines.py
@@ -36,7 +36,7 @@ router = APIRouter(prefix="/hosted-machines")
RETIRED_STATES = frozenset({"retained", "deleting", "deleted"})
-MACHINES_DISABLED = "Switch cloud machines are not enabled on this server."
+MACHINES_DISABLED = "This server does not support cloud agents."
def hosted_settings(request: Request) -> HostedControllerSettings | None:
@@ -54,9 +54,13 @@ def controller_settings(request: Request) -> HostedControllerSettings:
def machines_enabled(config: SwitchConfig, settings: HostedControllerSettings) -> bool:
"""Whether the bound tenant may use cloud machines on this server."""
- return config.hosted_launch_capacity > 0 and (
- settings.allowed_tenant_ids is None
- or require_tenant_id() in settings.allowed_tenant_ids
+ return (
+ config.hosted_agents_enabled
+ and config.hosted_launch_capacity > 0
+ and (
+ settings.allowed_tenant_ids is None
+ or require_tenant_id() in settings.allowed_tenant_ids
+ )
)
@@ -191,14 +195,22 @@ async def _owned(
async def owned_machines(
user: Annotated[User, Depends(get_current_user)],
session: Annotated[AsyncSession, Depends(get_session)],
+ config: Annotated[SwitchConfig, Depends(get_config)],
+ settings: Annotated[HostedControllerSettings | None, Depends(hosted_settings)],
) -> dict:
"""The owner's machine, when it serves the bound workspace: in another
- workspace it is the same machine, joined from there."""
+ workspace it is the same machine, joined from there. `available` says
+ whether the bound workspace may claim one here at all, so a client can
+ offer cloud agents only where claiming one can work."""
+ available = settings is not None and machines_enabled(config, settings)
machine = await CloudMachineStore().live_for_owner(session, user.id)
workspace = None if machine is None else await workspace_on(session, machine.id)
if machine is None or workspace is None:
- return {"machines": []}
- return {"machines": [await machine_summary(session, machine, workspace)]}
+ return {"available": available, "machines": []}
+ return {
+ "available": available,
+ "machines": [await machine_summary(session, machine, workspace)],
+ }
@router.post("/ensure")
diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.py
index fc61335ea..550289666 100644
--- a/core/switch_core/gateway/schemas.py
+++ b/core/switch_core/gateway/schemas.py
@@ -1476,3 +1476,12 @@ class BudgetResponse(BaseModel):
spent: int
resets_at: datetime
exhausted: bool
+
+
+class FeatureFlagState(BaseModel):
+ key: str
+ enabled: bool
+
+
+class FeatureFlagsResponse(BaseModel):
+ flags: list[FeatureFlagState]
diff --git a/core/switch_core/main.py b/core/switch_core/main.py
index 590733cbe..32b3ae3e7 100644
--- a/core/switch_core/main.py
+++ b/core/switch_core/main.py
@@ -720,7 +720,7 @@ async def run(config: SwitchConfig) -> None:
frontend_base_url=config.frontend_base_url,
)
- # ── Agent management (off unless AGENT_MANAGEMENT_ENABLED) ───────────────
+ # ── Agent management (off unless the agent_management flag is on) ─────────
# Built before the agent bridge app because its authenticator is the bearer
# middleware's controller branch; its routes are installed once both apps
# exist, below.
diff --git a/core/switch_core/management/__init__.py b/core/switch_core/management/__init__.py
index 9077c852f..b2b9da24d 100644
--- a/core/switch_core/management/__init__.py
+++ b/core/switch_core/management/__init__.py
@@ -1,6 +1,6 @@
"""Agent management: managed agent definitions and the controllers that run them.
-Off unless `AGENT_MANAGEMENT_ENABLED` is set. Management is the source of
+Off unless the `agent_management` feature flag is on. Management is the source of
truth for which agents are managed, how each is defined, which controller
runs it, controller enrollment and credentials, controller status, and
operations. It tells Core which controller runs each agent through Core's
diff --git a/core/switch_core/management/wiring.py b/core/switch_core/management/wiring.py
index 7e2e61fda..47243e733 100644
--- a/core/switch_core/management/wiring.py
+++ b/core/switch_core/management/wiring.py
@@ -1,6 +1,6 @@
"""Building the management module and attaching it to the two apps.
-`create_management` returns None when `AGENT_MANAGEMENT_ENABLED` is off, and
+`create_management` returns None when the `agent_management` feature flag is off, and
with None nothing is mounted and the bearer middleware has no controller
branch. When it is on, the authenticator goes to the middleware as the agent
bridge app is built, `install` adds the routes once both apps exist, and
@@ -194,7 +194,7 @@ def create_management(
return None
if config.controller_token_secret is None:
raise RuntimeError(
- "AGENT_MANAGEMENT_ENABLED is set without CONTROLLER_TOKEN_SECRET; the "
+ "The agent_management feature flag is on without CONTROLLER_TOKEN_SECRET; the "
"config validator should have refused this"
)
return build_management(
diff --git a/core/switch_core/migrations/versions/9c4e7a1f2b38_drop_feature_flags_table.py b/core/switch_core/migrations/versions/9c4e7a1f2b38_drop_feature_flags_table.py
new file mode 100644
index 000000000..e5dbfa8b2
--- /dev/null
+++ b/core/switch_core/migrations/versions/9c4e7a1f2b38_drop_feature_flags_table.py
@@ -0,0 +1,56 @@
+"""Drop the feature_flags table: flags are set when the server is deployed.
+
+Revision ID: 9c4e7a1f2b38
+Revises: fabf9b9bff78
+Create Date: 2026-10-07 00:00:00.000000
+
+Flags used to be rows anyone holding an agent token could flip. They now come
+from `FEATURE_FLAGS_ENABLED` alone, so the table goes. A flag that was on is
+logged, so an operator knows what to put in that setting to keep it on.
+Downgrade recreates the table empty: every flag reads as off until set again.
+"""
+
+import logging
+
+import sqlalchemy as sa
+from alembic import op
+
+logger = logging.getLogger("alembic.runtime.migration")
+
+revision = "9c4e7a1f2b38"
+down_revision = "fabf9b9bff78"
+branch_labels = None
+depends_on = None
+
+
+def upgrade() -> None:
+ enabled = [
+ row.key
+ for row in op.get_bind().execute(
+ sa.text("SELECT key FROM feature_flags WHERE enabled ORDER BY key")
+ )
+ ]
+ if enabled:
+ logger.warning(
+ "Feature flags are now set at deploy time. These were on and are "
+ "off from now on unless listed in FEATURE_FLAGS_ENABLED: %s",
+ ", ".join(enabled),
+ )
+ op.drop_table("feature_flags")
+
+
+def downgrade() -> None:
+ op.create_table(
+ "feature_flags",
+ sa.Column("key", sa.Text(), nullable=False),
+ sa.Column(
+ "enabled", sa.Boolean(), nullable=False, server_default=sa.text("false")
+ ),
+ sa.Column(
+ "updated_at",
+ sa.DateTime(timezone=True),
+ server_default=sa.func.now(),
+ nullable=False,
+ ),
+ sa.PrimaryKeyConstraint("key"),
+ )
diff --git a/core/switch_core/migrations/versions/cba933f98e1c_merge_feature_flags_and_main_heads.py b/core/switch_core/migrations/versions/cba933f98e1c_merge_feature_flags_and_main_heads.py
new file mode 100644
index 000000000..050fb0bb6
--- /dev/null
+++ b/core/switch_core/migrations/versions/cba933f98e1c_merge_feature_flags_and_main_heads.py
@@ -0,0 +1,14 @@
+"""Merge the feature-flags migration head with main's head."""
+
+revision = "cba933f98e1c"
+down_revision = ("9c4e7a1f2b38", "b6e1c9d4a7f2")
+branch_labels = None
+depends_on = None
+
+
+def upgrade() -> None:
+ pass
+
+
+def downgrade() -> None:
+ pass
diff --git a/core/tests/switch_core/db/stores/test_feature_flag_store.py b/core/tests/switch_core/db/stores/test_feature_flag_store.py
deleted file mode 100644
index 3402c4b88..000000000
--- a/core/tests/switch_core/db/stores/test_feature_flag_store.py
+++ /dev/null
@@ -1,50 +0,0 @@
-from __future__ import annotations
-
-from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
-
-from switch_core.db.stores.feature_flag_store import FeatureFlagStore
-from switch_core.feature_flags import ECOSYSTEM_SHOW_OWNERS
-
-
-class TestFeatureFlagStore:
- async def test_absent_flag_defaults_off(
- self, session_factory: async_sessionmaker[AsyncSession]
- ) -> None:
- store = FeatureFlagStore()
- async with session_factory() as session:
- assert await store.get(session, ECOSYSTEM_SHOW_OWNERS) is False
-
- async def test_set_then_get(
- self, session_factory: async_sessionmaker[AsyncSession]
- ) -> None:
- store = FeatureFlagStore()
- async with session_factory() as session:
- await store.set(session, ECOSYSTEM_SHOW_OWNERS, True)
- await session.commit()
-
- assert await store.get(session, ECOSYSTEM_SHOW_OWNERS) is True
-
- async def test_set_is_idempotent_upsert(
- self, session_factory: async_sessionmaker[AsyncSession]
- ) -> None:
- store = FeatureFlagStore()
- async with session_factory() as session:
- await store.set(session, ECOSYSTEM_SHOW_OWNERS, True)
- await store.set(session, ECOSYSTEM_SHOW_OWNERS, False)
- await session.commit()
-
- assert await store.get(session, ECOSYSTEM_SHOW_OWNERS) is False
-
- async def test_get_all_includes_known_defaults(
- self, session_factory: async_sessionmaker[AsyncSession]
- ) -> None:
- store = FeatureFlagStore()
- async with session_factory() as session:
- flags = await store.get_all(session)
- assert flags[ECOSYSTEM_SHOW_OWNERS] is False
-
- await store.set(session, ECOSYSTEM_SHOW_OWNERS, True)
- await session.commit()
-
- flags = await store.get_all(session)
- assert flags[ECOSYSTEM_SHOW_OWNERS] is True
diff --git a/core/tests/switch_core/db/test_tenant_exemption_allowlist.py b/core/tests/switch_core/db/test_tenant_exemption_allowlist.py
index 5020bd8d1..021e5fc3c 100644
--- a/core/tests/switch_core/db/test_tenant_exemption_allowlist.py
+++ b/core/tests/switch_core/db/test_tenant_exemption_allowlist.py
@@ -28,8 +28,8 @@ module, never directly through a store any endpoint could declare for itself.
**A raw `session_factory()` call** is the other surface. It inherits whatever
is ambient, which in background code is nothing at all, since the long-lived
tasks deliberately unbind (see `tenant_context.no_tenant`). Such a session can
-now only read the tables that carry no policy — `users`, `oidc_identities`,
-`feature_flags` — so it is no longer a way to cross a tenant boundary, but it
+now only read the tables that carry no policy — `users`, `oidc_identities`
+and the installation's telemetry records — so it is no longer a way to cross a tenant boundary, but it
is still a session whose call site did not say what it was for.
A module failing either check is not a bug in the test. It means someone
diff --git a/core/tests/switch_core/db/test_tenant_schema_catalogue.py b/core/tests/switch_core/db/test_tenant_schema_catalogue.py
index a74bf5557..ef5b68dc0 100644
--- a/core/tests/switch_core/db/test_tenant_schema_catalogue.py
+++ b/core/tests/switch_core/db/test_tenant_schema_catalogue.py
@@ -91,9 +91,7 @@ class TestEveryTableIsScopedUnlessItIsNamedGlobal:
"""Hardcoded on purpose, and hardcoded twice on purpose.
`users` is a person rather than a tenant member, `oidc_identities`
- records how that person proves who they are, and `feature_flags` is a
- deployment switch — a flag that has to vary per customer is a new
- scoped table, not a nullable column there. `cloud_machines` is a
+ records how that person proves who they are. `cloud_machines` is a
person's VM, one per person whatever workspaces it serves; what it
runs in each is the scoped `machine_workspaces`. `alembic_version` is
global too but is not in this metadata: Alembic owns it.
@@ -102,7 +100,6 @@ class TestEveryTableIsScopedUnlessItIsNamedGlobal:
"cloud_machines",
"users",
"oidc_identities",
- "feature_flags",
# Facts about the installation, not about anything in it: which
# deployment this is to the analytics relay and when it was
# installed, which once-ever milestones it has reported, and when
diff --git a/core/tests/switch_core/gateway/test_cloud_controller_machines.py b/core/tests/switch_core/gateway/test_cloud_controller_machines.py
index 5030c1172..dd2d584e1 100644
--- a/core/tests/switch_core/gateway/test_cloud_controller_machines.py
+++ b/core/tests/switch_core/gateway/test_cloud_controller_machines.py
@@ -103,6 +103,7 @@ def _hosted_app(
hosted_idle_stop_minutes=30,
hosted_disk_retention_days=7,
hosted_launch_capacity=1,
+ hosted_agents_enabled=True,
)
async def session():
@@ -636,7 +637,7 @@ async def test_a_controller_machine_needs_agent_management(
f"/hosted-controller/machines/{machine.id}/prepare", headers=HEADERS
)
assert response.status_code == 409, response.text
- assert "AGENT_MANAGEMENT_ENABLED" in response.json()["detail"]
+ assert "agent_management feature flag" in response.json()["detail"]
def test_a_waking_machine_is_judged_by_its_last_report() -> None:
diff --git a/core/tests/switch_core/gateway/test_feature_flags_route.py b/core/tests/switch_core/gateway/test_feature_flags_route.py
new file mode 100644
index 000000000..0b1c7e754
--- /dev/null
+++ b/core/tests/switch_core/gateway/test_feature_flags_route.py
@@ -0,0 +1,43 @@
+"""`GET /gateway/feature-flags`: the deployment's flags, read-only."""
+
+from __future__ import annotations
+
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from switch_core.feature_flags import ECOSYSTEM_SHOW_OWNERS
+from switch_core.gateway.auth import get_authenticated_user_id
+from switch_core.gateway.dependencies import get_config
+from switch_core.gateway.feature_flags import router
+
+
+class _Config:
+ def __init__(self, flags: dict[str, bool]) -> None:
+ self.feature_flags = flags
+
+
+def _client(flags: dict[str, bool]) -> TestClient:
+ app = FastAPI()
+ app.include_router(router)
+ app.dependency_overrides[get_authenticated_user_id] = lambda: "user-1"
+ app.dependency_overrides[get_config] = lambda: _Config(flags)
+ return TestClient(app)
+
+
+def test_lists_every_flag_with_its_deployment_state() -> None:
+ response = _client({ECOSYSTEM_SHOW_OWNERS: True}).get("/feature-flags")
+ assert response.status_code == 200
+ assert response.json() == {
+ "flags": [{"key": ECOSYSTEM_SHOW_OWNERS, "enabled": True}]
+ }
+
+
+def test_there_is_no_way_to_change_a_flag() -> None:
+ client = _client({ECOSYSTEM_SHOW_OWNERS: False})
+ assert client.put(
+ f"/feature-flags/{ECOSYSTEM_SHOW_OWNERS}", json={"enabled": True}
+ ).status_code in (404, 405)
+ assert client.delete(f"/feature-flags/{ECOSYSTEM_SHOW_OWNERS}").status_code in (
+ 404,
+ 405,
+ )
diff --git a/core/tests/switch_core/gateway/test_hosted_controller.py b/core/tests/switch_core/gateway/test_hosted_controller.py
index e3fc56426..10b11f4db 100644
--- a/core/tests/switch_core/gateway/test_hosted_controller.py
+++ b/core/tests/switch_core/gateway/test_hosted_controller.py
@@ -137,6 +137,7 @@ async def controller_app(session_factory):
hosted_idle_stop_minutes=0,
hosted_disk_retention_days=7,
hosted_launch_capacity=2,
+ hosted_agents_enabled=True,
)
app = FastAPI()
app.state.hosted_controller_settings = settings
@@ -340,9 +341,7 @@ async def test_routes_are_unavailable_without_controller_settings(controller_app
app.client._transport.app.state.hosted_controller_settings = None
response = await app.client.get("/hosted-controller/machines", headers=HEADERS)
assert response.status_code == 503
- assert response.json() == {
- "detail": "Switch cloud machines are not enabled on this server."
- }
+ assert response.json() == {"detail": "This server does not support cloud agents."}
async def test_machines_lists_every_live_machine_with_the_contract_keys(
diff --git a/core/tests/switch_core/gateway/test_hosted_machines.py b/core/tests/switch_core/gateway/test_hosted_machines.py
index 01d1ca912..c92710316 100644
--- a/core/tests/switch_core/gateway/test_hosted_machines.py
+++ b/core/tests/switch_core/gateway/test_hosted_machines.py
@@ -122,7 +122,10 @@ async def test_other_owners_machines_read_as_missing(controller_app): # noqa: F
fastapi_app.dependency_overrides[get_current_user] = lambda: SimpleNamespace(
id="someone-else"
)
- assert (await app.client.get("/hosted-machines")).json() == {"machines": []}
+ assert (await app.client.get("/hosted-machines")).json() == {
+ "available": True,
+ "machines": [],
+ }
assert (
await app.client.get(f"/hosted-machines/{app.machine_id}")
).status_code == 404
@@ -348,14 +351,18 @@ async def test_ensure_refuses_when_every_machine_is_in_use(controller_app): # n
assert refused.json() == {"detail": MACHINES_FULL}
[email protected]("disabled", ["capacity", "settings", "tenant", "no-tenant"])
+ "disabled", ["flag", "capacity", "settings", "tenant", "no-tenant"]
+)
async def test_ensure_is_unavailable_when_machines_are_not_enabled(
controller_app, # noqa: F811
disabled,
):
app = controller_app
fastapi_app = app.client._transport.app
- if disabled == "capacity":
+ if disabled == "flag":
+ app.config.hosted_agents_enabled = False
+ elif disabled == "capacity":
app.config.hosted_launch_capacity = 0
elif disabled == "settings":
fastapi_app.state.hosted_controller_settings = None
@@ -369,9 +376,8 @@ async def test_ensure_is_unavailable_when_machines_are_not_enabled(
)
response = await _ensure(app)
assert response.status_code == 503
- assert response.json() == {
- "detail": "Switch cloud machines are not enabled on this server."
- }
+ assert response.json() == {"detail": "This server does not support cloud agents."}
+ assert (await app.client.get("/hosted-machines")).json()["available"] is False
async def test_every_workspace_may_use_machines_when_none_is_listed(
@@ -405,9 +411,7 @@ async def test_a_workspace_off_the_list_is_refused_and_not_joined(
with tenant_scope("tenant-b"):
refused = await _ensure(app)
assert refused.status_code == 503
- assert refused.json() == {
- "detail": "Switch cloud machines are not enabled on this server."
- }
+ assert refused.json() == {"detail": "This server does not support cloud agents."}
assert await tenants_of_cloud_machine(app.factory, app.machine_id) == [
TENANT_ZERO_ID
]
@@ -500,7 +504,10 @@ async def test_a_workspace_the_machine_does_not_serve_lists_no_machine(
await add_tenant(session, "tenant-b")
await session.commit()
with tenant_scope("tenant-b"):
- assert (await app.client.get("/hosted-machines")).json() == {"machines": []}
+ assert (await app.client.get("/hosted-machines")).json() == {
+ "available": False,
+ "machines": [],
+ }
assert (
await app.client.get(f"/hosted-machines/{app.machine_id}")
).status_code == 404
diff --git a/core/tests/switch_core/gateway/test_session_requires_authentication.py b/core/tests/switch_core/gateway/test_session_requires_authentication.py
index 0bef2df02..df465a1dd 100644
--- a/core/tests/switch_core/gateway/test_session_requires_authentication.py
+++ b/core/tests/switch_core/gateway/test_session_requires_authentication.py
@@ -118,6 +118,9 @@ _ROUTES_THAT_NEVER_BIND_A_TENANT = {
# `list_joinable_tenants` and `join_tenant_by_domain`.
("GET", "/joinable-tenants"),
("POST", "/joinable-tenants/{tenant_id}/join"),
+ # Feature flags belong to the deployment and come from its config, so
+ # there is no workspace to scope them to and no session is opened.
+ ("GET", "/feature-flags"),
}
diff --git a/core/tests/switch_core/gateway/test_signup.py b/core/tests/switch_core/gateway/test_signup.py
index 847ba7c8b..38a78b273 100644
--- a/core/tests/switch_core/gateway/test_signup.py
+++ b/core/tests/switch_core/gateway/test_signup.py
@@ -59,6 +59,7 @@ async def signup_app(session_factory):
gateway_oidc_enabled=False,
gateway_oidc_provider_label=None,
hosted_launch_capacity=2,
+ hosted_agents_enabled=True,
keyring=TEST_KEYRING,
gateway_cookie_secure=False,
)
@@ -254,9 +255,9 @@ async def test_weak_password_or_bad_email_is_rejected(signup_app, payload):
assert await session.scalar(select(func.count()).select_from(User)) == 0
-async def test_signup_succeeds_without_cloud_capacity(signup_app, caplog):
+async def test_signup_succeeds_without_cloud_machines(signup_app, caplog):
app = signup_app
- app.config.hosted_launch_capacity = 0
+ app.config.hosted_agents_enabled = False
response = await _signup(app)
assert response.status_code == 201, response.text
assert response.json()["machine"] == {
@@ -297,9 +298,9 @@ async def test_signup_succeeds_when_every_machine_is_in_use(signup_app):
async def test_ensure_is_idempotent(signup_app):
app = signup_app
- app.config.hosted_launch_capacity = 0
+ app.config.hosted_agents_enabled = False
await _signup(app)
- app.config.hosted_launch_capacity = 2
+ app.config.hosted_agents_enabled = True
first = await _ensure(app, "[email protected]")
assert first.status_code == 200, first.text
second = await _ensure(app, "[email protected]")
@@ -453,7 +454,7 @@ async def test_ensure_wakes_an_idle_sleeping_machine(signup_app):
async def test_ensure_refuses_when_cloud_machines_are_off(signup_app):
app = signup_app
await _signup(app)
- app.config.hosted_launch_capacity = 0
+ app.config.hosted_agents_enabled = False
response = await _ensure(app, "[email protected]")
assert response.status_code == 503
assert response.json()["detail"] == MACHINES_DISABLED
diff --git a/core/tests/switch_core/gateway/test_tenant_resolution.py b/core/tests/switch_core/gateway/test_tenant_resolution.py
index 89f980b91..a819179c7 100644
--- a/core/tests/switch_core/gateway/test_tenant_resolution.py
+++ b/core/tests/switch_core/gateway/test_tenant_resolution.py
@@ -140,6 +140,7 @@ def _session_app(
*,
signup_mode: str,
invite_email_enabled: bool = False,
+ tenants_isolated: bool = True,
) -> FastAPI:
"""A route-scoped app for `GET /auth/session`, stubbed as `_app` is."""
@@ -158,6 +159,9 @@ def _session_app(
gateway_max_workspaces_per_user=3,
invite_email_enabled=invite_email_enabled,
)
+ app.dependency_overrides[gw_deps.get_client_lifecycle] = lambda: SimpleNamespace(
+ tenants_isolated=tenants_isolated
+ )
return app
@@ -375,12 +379,14 @@ class TestSessionStateEndpoint:
*,
signup_mode: str,
invite_email_enabled: bool = False,
+ tenants_isolated: bool = True,
) -> httpx.Response:
async with _client(
_session_app(
session_factory,
signup_mode=signup_mode,
invite_email_enabled=invite_email_enabled,
+ tenants_isolated=tenants_isolated,
),
token,
) as client:
@@ -485,6 +491,22 @@ class TestSessionStateEndpoint:
assert body["state"] == "needs_workspace"
assert body["can_create_workspace"] is False
+ async def test_a_server_not_isolating_tenants_offers_no_workspace_creation(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ user_id = await _make_user_with_memberships(
+ session_factory, name="single", tenant_ids=[TENANT_ZERO_ID]
+ )
+ token = create_jwt(user_id, "[email protected]", "admin", _KEYRING, None)
+
+ body = (
+ await self._get(
+ session_factory, token, signup_mode="open", tenants_isolated=False
+ )
+ ).json()
+
+ assert body["can_create_workspace"] is False
+
async def test_it_says_whether_invitations_are_e_mailed(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
diff --git a/core/tests/switch_core/management/test_config.py b/core/tests/switch_core/management/test_config.py
index d18fa850b..919fa00d4 100644
--- a/core/tests/switch_core/management/test_config.py
+++ b/core/tests/switch_core/management/test_config.py
@@ -1,4 +1,4 @@
-"""Agent management config: the flag needs its own token secret."""
+"""Agent management and cloud machine config: the flags and what they need."""
from __future__ import annotations
@@ -40,21 +40,67 @@ def test_off_by_default_and_needs_no_secret() -> None:
def test_on_with_a_secret_is_accepted() -> None:
config = _config(
- agent_management_enabled=True, controller_token_secret=_LONG_ENOUGH
+ feature_flags_enabled="agent_management", controller_token_secret=_LONG_ENOUGH
)
+ assert config.agent_management_enabled is True
assert config.controller_token_secret == _LONG_ENOUGH
def test_on_without_a_secret_raises() -> None:
with pytest.raises(ValueError, match="CONTROLLER_TOKEN_SECRET is required"):
- _config(agent_management_enabled=True)
+ _config(feature_flags_enabled="agent_management")
def test_on_with_a_short_secret_raises() -> None:
with pytest.raises(ValueError, match="at least 32 characters"):
- _config(agent_management_enabled=True, controller_token_secret="x" * 31)
+ _config(
+ feature_flags_enabled="agent_management", controller_token_secret="x" * 31
+ )
def test_the_status_interval_must_be_positive() -> None:
with pytest.raises(ValueError, match="CONTROLLER_STATUS_INTERVAL_SECONDS"):
_config(controller_status_interval_seconds=0)
+
+
+def test_the_old_setting_turned_on_is_refused() -> None:
+ with pytest.raises(ValueError, match="AGENT_MANAGEMENT_ENABLED has been replaced"):
+ _config(agent_management_enabled=True, controller_token_secret=_LONG_ENOUGH)
+
+
+def test_the_old_setting_left_off_is_accepted() -> None:
+ assert _config(agent_management_enabled=False).agent_management_enabled is False
+
+
+def test_the_old_setting_is_refused_from_the_environment(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setenv("AGENT_MANAGEMENT_ENABLED", "true")
+ with pytest.raises(ValueError, match="AGENT_MANAGEMENT_ENABLED has been replaced"):
+ _config()
+
+
+def test_cloud_machines_are_off_by_default() -> None:
+ config = _config()
+ assert config.hosted_agents_enabled is False
+ assert config.hosted_launch_capacity == 0
+
+
+def test_the_flag_offers_cloud_machines_on_a_server_that_cannot_run_them() -> None:
+ config = _config(feature_flags_enabled="hosted_agents")
+ assert config.hosted_agents_enabled is True
+ assert config.hosted_launch_capacity == 0
+
+
+def test_capacity_needs_agent_management() -> None:
+ with pytest.raises(ValueError, match="HOSTED_LAUNCH_CAPACITY needs"):
+ _config(hosted_launch_capacity=1)
+
+
+def test_capacity_with_agent_management_is_accepted() -> None:
+ config = _config(
+ feature_flags_enabled="agent_management",
+ controller_token_secret=_LONG_ENOUGH,
+ hosted_launch_capacity=2,
+ )
+ assert config.hosted_launch_capacity == 2
diff --git a/core/tests/switch_core/management/test_import_boundary.py b/core/tests/switch_core/management/test_import_boundary.py
index de42cc225..d4d4775d6 100644
--- a/core/tests/switch_core/management/test_import_boundary.py
+++ b/core/tests/switch_core/management/test_import_boundary.py
@@ -19,7 +19,7 @@ _MANAGEMENT = "switch_core.management"
# The only Core modules allowed to import the management package.
_ALLOWED_IMPORTERS = {
- # Builds the module when AGENT_MANAGEMENT_ENABLED is set, hands its
+ # Builds the module when the agent_management feature flag is on, hands its
# authenticator to the bearer middleware, and installs its routes.
"switch_core.main",
}
diff --git a/core/tests/switch_core/test_config_feature_flags.py b/core/tests/switch_core/test_config_feature_flags.py
new file mode 100644
index 000000000..2082572ff
--- /dev/null
+++ b/core/tests/switch_core/test_config_feature_flags.py
@@ -0,0 +1,45 @@
+"""FEATURE_FLAGS_ENABLED: which flags this deployment turns on."""
+
+from __future__ import annotations
+
+import pytest
+from pydantic import ValidationError
+
+from switch_core.config import SwitchConfig
+from switch_core.feature_flags import ECOSYSTEM_SHOW_OWNERS, KNOWN_FEATURE_FLAGS
+
+_BASE_KWARGS = dict(
+ db_host="db",
+ db_port="5432",
+ db_user="postgres",
+ db_password="pw",
+ db_name="switch",
+ matrix_server_name="switch.local",
+ agent_registration_token="token",
+ jwt_secret_key="jwt",
+ gateway_admin_email="[email protected]",
+ gateway_admin_password="pw",
+ secret_keys="test:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
+)
+
+
+def test_unset_leaves_every_flag_off(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.delenv("FEATURE_FLAGS_ENABLED", raising=False)
+ assert SwitchConfig(**_BASE_KWARGS).feature_flags == { # type: ignore[arg-type]
+ key: False for key in KNOWN_FEATURE_FLAGS
+ }
+
+
+def test_listed_flags_are_on(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("FEATURE_FLAGS_ENABLED", f" {ECOSYSTEM_SHOW_OWNERS} ,")
+ assert SwitchConfig(**_BASE_KWARGS).feature_flags == { # type: ignore[arg-type]
+ key: key == ECOSYSTEM_SHOW_OWNERS for key in KNOWN_FEATURE_FLAGS
+ }
+
+
+def test_an_unknown_flag_is_a_startup_error(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("FEATURE_FLAGS_ENABLED", "ecosystem.show_ownres")
+ with pytest.raises(ValidationError, match="ecosystem.show_ownres"):
+ SwitchConfig(**_BASE_KWARGS) # type: ignore[arg-type]
diff --git a/core/tests/switch_core/test_migration_drop_feature_flags_table.py b/core/tests/switch_core/test_migration_drop_feature_flags_table.py
new file mode 100644
index 000000000..c2ab02302
--- /dev/null
+++ b/core/tests/switch_core/test_migration_drop_feature_flags_table.py
@@ -0,0 +1,92 @@
+"""Dropping the feature_flags table names the flags that were on.
+
+Flags are set at deploy time after `9c4e7a1f2b38`, so a flag a deployment had
+switched on through the old table is off after upgrading unless the operator
+lists it in FEATURE_FLAGS_ENABLED. The migration says which ones those are.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+
+import pytest
+from alembic.config import Config
+from alembic.runtime.environment import EnvironmentContext
+from alembic.script import ScriptDirectory
+from sqlalchemy import Connection, text
+from sqlalchemy.ext.asyncio import create_async_engine
+
+_CORE = Path(__file__).resolve().parents[2]
+_MIGRATION_DB = "migration_drop_feature_flags_table"
+
+_PRE_MIGRATION_REVISION = "fabf9b9bff78"
+_MIGRATION_UNDER_TEST = "9c4e7a1f2b38"
+
+
+def _script_directory(config: Config) -> ScriptDirectory:
+ config.set_main_option("script_location", str(_CORE / "switch_core" / "migrations"))
+ return ScriptDirectory.from_config(config)
+
+
+def _migrate(revision: str, *, down: bool) -> Any:
+ def migrate(connection: Connection) -> None:
+ config = Config(str(_CORE / "alembic.ini"))
+ script = _script_directory(config)
+
+ def do_migrate(current_revision: str, context: Any) -> Any:
+ if down:
+ return script._downgrade_revs(revision, current_revision)
+ return script._upgrade_revs(revision, current_revision)
+
+ with EnvironmentContext(config, script, fn=do_migrate) as environment:
+ environment.configure(connection=connection)
+ with environment.begin_transaction():
+ environment.run_migrations()
+
+ return migrate
+
+
+async def test_the_flags_that_were_on_are_logged_and_the_table_goes(
+ postgres_url: str, caplog: pytest.LogCaptureFixture
+) -> None:
+ admin = create_async_engine(postgres_url, isolation_level="AUTOCOMMIT")
+ async with admin.connect() as connection:
+ await connection.execute(text(f'DROP DATABASE IF EXISTS "{_MIGRATION_DB}"'))
+ await connection.execute(text(f'CREATE DATABASE "{_MIGRATION_DB}"'))
+ base, _, _ = postgres_url.rpartition("/")
+ engine = create_async_engine(f"{base}/{_MIGRATION_DB}")
+ try:
+ async with engine.begin() as connection:
+ await connection.run_sync(_migrate(_PRE_MIGRATION_REVISION, down=False))
+ async with engine.begin() as connection:
+ await connection.execute(
+ text(
+ "INSERT INTO feature_flags (key, enabled) VALUES "
+ "('ecosystem.show_owners', true), ('retired.flag', false)"
+ )
+ )
+
+ with caplog.at_level("WARNING", logger="alembic.runtime.migration"):
+ async with engine.begin() as connection:
+ await connection.run_sync(_migrate(_MIGRATION_UNDER_TEST, down=False))
+ assert "FEATURE_FLAGS_ENABLED: ecosystem.show_owners" in caplog.text
+ assert "retired.flag" not in caplog.text
+
+ async with engine.begin() as connection:
+ assert (
+ await connection.scalar(text("SELECT to_regclass('feature_flags')"))
+ is None
+ )
+
+ async with engine.begin() as connection:
+ await connection.run_sync(_migrate(_PRE_MIGRATION_REVISION, down=True))
+ async with engine.begin() as connection:
+ assert (
+ await connection.scalar(text("SELECT count(*) FROM feature_flags")) == 0
+ )
+ finally:
+ await engine.dispose()
+ async with admin.connect() as connection:
+ await connection.execute(text(f'DROP DATABASE IF EXISTS "{_MIGRATION_DB}"'))
+ await admin.dispose()
diff --git a/deploy/hosted/README.md b/deploy/hosted/README.md
index a74568212..13016106a 100644
--- a/deploy/hosted/README.md
+++ b/deploy/hosted/README.md
@@ -51,9 +51,13 @@ to its controller's own key: Core relays only ciphertext.
## Enable cloud machines
-Core needs agent management (`AGENT_MANAGEMENT_ENABLED`, with
-`CONTROLLER_TOKEN_SECRET`): it refuses to start with `HOSTED_LAUNCH_CAPACITY`
-above 0 without it.
+Switch Console offers cloud machines on a server whose `hosted_agents` feature
+flag is on. The server runs them only once it is set up as below, which needs
+agent management too: `FEATURE_FLAGS_ENABLED=hosted_agents,agent_management`,
+with `CONTROLLER_TOKEN_SECRET` set. Core refuses to start with
+`HOSTED_LAUNCH_CAPACITY` above 0 without agent management. A server with the
+flag on and nothing set up answers a claim with "This server does not support
+cloud agents."
Mount a private JSON file through `HOSTED_CONTROLLER_CONFIG_PATH` with
`allowed_tenant_ids`, a dedicated `token` of at least 32 characters and the
@@ -62,7 +66,7 @@ lists the workspaces whose members may use cloud machines, or is `null` for
every workspace. Core refuses unknown keys, the old `tenant_id` among them.
`HOSTED_LAUNCH_CAPACITY` is how many machines may exist at once across the
server, one per user, 0–100; 0
-disables cloud machines. Keep it no higher than the hosted controller's
+means the server cannot run them. Keep it no higher than the hosted controller's
`max_machines`. The backend chart exposes
`switchCore.hostedControllerSecret` (file `controller.json`),
`switchCore.hostedLaunchCapacity`, `switchCore.hostedIdleStopMinutes` and
diff --git a/deploy/hosted/machine/README.md b/deploy/hosted/machine/README.md
index a1ae0321f..80107eeeb 100644
--- a/deploy/hosted/machine/README.md
+++ b/deploy/hosted/machine/README.md
@@ -149,7 +149,8 @@ can run at once.
## Running it
-- Core needs `AGENT_MANAGEMENT_ENABLED` as well as the hosted settings; see
+- Core needs the `hosted_agents` and `agent_management` feature flags as
+ well as the hosted settings; see
[../README.md](../README.md).
- The hosted controller's `image_id` must be an image baked here.
- A machine is stopped once its status reports say no session has
diff --git a/deploy/hosted/machine/switch_machine_boot.py b/deploy/hosted/machine/switch_machine_boot.py
index 40ce1b15c..914772eab 100644
--- a/deploy/hosted/machine/switch_machine_boot.py
+++ b/deploy/hosted/machine/switch_machine_boot.py
@@ -265,7 +265,9 @@ def parse_bundle(raw: str) -> Bundle:
raise BootError("The machine bundle's server is not an HTTPS URL.")
entries = value["controllers"]
if not isinstance(entries, list) or not 1 <= len(entries) <= MAX_CONTROLLERS:
- raise BootError(f"The machine bundle must list 1 to {MAX_CONTROLLERS} controllers.")
+ raise BootError(
+ f"The machine bundle must list 1 to {MAX_CONTROLLERS} controllers."
+ )
controllers = tuple(_bundle_controller(entry) for entry in entries)
if len({controller.key for controller in controllers}) != len(controllers):
raise BootError("The machine bundle lists a controller key twice.")
@@ -282,7 +284,9 @@ def parse_bundle(raw: str) -> Bundle:
def _bundle_controller(entry: Any) -> BundleController:
- controller = _strict(entry, {"key", "id", "enrollmentCode"}, "machine bundle's controller")
+ controller = _strict(
+ entry, {"key", "id", "enrollmentCode"}, "machine bundle's controller"
+ )
key = controller["key"]
if not isinstance(key, str) or not UUID_RE.fullmatch(key):
raise BootError("The machine bundle's controller key is invalid.")
@@ -295,7 +299,9 @@ def _bundle_controller(entry: Any) -> BundleController:
):
raise BootError("The machine bundle's controller is invalid.")
elif not isinstance(code, str) or not ENROLLMENT_CODE_RE.fullmatch(code):
- raise BootError("The machine bundle holds neither a controller nor an enrollment code.")
+ raise BootError(
+ "The machine bundle holds neither a controller nor an enrollment code."
+ )
return BundleController(key=key, controller_id=controller_id, enrollment_code=code)
@@ -307,7 +313,9 @@ def _user_data(opener: OpenerDirector) -> str:
)
with opener.open(token_request, timeout=5) as response:
token = response.read().decode()
- request = Request(f"{METADATA_URL}/user-data", headers={"X-aws-ec2-metadata-token": token})
+ request = Request(
+ f"{METADATA_URL}/user-data", headers={"X-aws-ec2-metadata-token": token}
+ )
try:
with opener.open(request, timeout=5) as response:
raw = response.read(MAX_JSON_BYTES + 1)
@@ -341,7 +349,9 @@ def read_bundle(
raise
except Exception as error:
if time.monotonic() > deadline:
- raise BootError(f"The instance's user data cannot be read: {error}") from None
+ raise BootError(
+ f"The instance's user data cannot be read: {error}"
+ ) from None
logger.warning("Waiting for instance metadata: %s", error)
sleep(5)
return parse_bundle(raw)
@@ -428,13 +438,17 @@ def prepare_storage(
if signatures or device.get("uuid"):
raise BootError("The data volume is not blank, but holds no filesystem.")
logger.info("Formatting the blank data volume %s", volume_id)
- commands.run(["/usr/sbin/mkfs.ext4", "-q", "-m", "0", "-L", "switch-data", path])
+ commands.run(
+ ["/usr/sbin/mkfs.ext4", "-q", "-m", "0", "-L", "switch-data", path]
+ )
commands.run(["/usr/bin/udevadm", "settle", "--timeout=30"])
device = _data_device(commands, volume_id)
if device is None:
raise BootError("The data volume went away while it was formatted.")
if device.get("fstype") != "ext4":
- raise BootError("The data volume's filesystem is not ext4; refusing to mount it.")
+ raise BootError(
+ "The data volume's filesystem is not ext4; refusing to mount it."
+ )
DATA_MOUNT.mkdir(mode=0o755, exist_ok=True)
mounted = commands.result(
[
@@ -450,7 +464,9 @@ def prepare_storage(
if os.path.realpath(mounted.stdout.strip()) != os.path.realpath(path):
raise BootError("/data is another device's mountpoint.")
return
- commands.run([SYSTEMD_MOUNT, "--type=ext4", "--options=nodev,nosuid", path, str(DATA_MOUNT)])
+ commands.run(
+ [SYSTEMD_MOUNT, "--type=ext4", "--options=nodev,nosuid", path, str(DATA_MOUNT)]
+ )
def reconcile_marker(data: Path, bundle: Bundle) -> None:
@@ -467,7 +483,9 @@ def reconcile_marker(data: Path, bundle: Bundle) -> None:
if marker.is_symlink():
raise BootError("The data volume's marker is a link.")
if json.loads(marker.read_text()) != wanted:
- raise BootError("The data volume belongs to another machine; refusing to use it.")
+ raise BootError(
+ "The data volume belongs to another machine; refusing to use it."
+ )
return
_write_atomically(marker, json.dumps(wanted), 0o600)
@@ -476,7 +494,9 @@ def _write_atomically(path: Path, text: str, mode: int) -> None:
"""Writes `path` through a fresh file renamed over it, never through a link."""
temporary = path.with_name(f"{path.name}.new")
temporary.unlink(missing_ok=True)
- descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, mode)
+ descriptor = os.open(
+ temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, mode
+ )
with os.fdopen(descriptor, "w") as file:
os.fchmod(file.fileno(), mode)
file.write(text)
@@ -501,12 +521,16 @@ def load_indexes(data: Path) -> dict[str, int] | None:
or not isinstance(indexes, dict)
or not all(isinstance(key, str) and UUID_RE.fullmatch(key) for key in indexes)
or not all(
- isinstance(index, int) and not isinstance(index, bool) and 0 <= index < MAX_CONTROLLERS
+ isinstance(index, int)
+ and not isinstance(index, bool)
+ and 0 <= index < MAX_CONTROLLERS
for index in indexes.values()
)
or len(set(indexes.values())) != len(indexes)
):
- raise BootError(f"The controllers' indexes at {path} are not ones this image reads.")
+ raise BootError(
+ f"The controllers' indexes at {path} are not ones this image reads."
+ )
return dict(indexes)
@@ -587,7 +611,14 @@ def ensure_identities(commands: Commands, config: MachineConfig, seat: Seat) ->
seat's fixed ids, as install.sh does for index 0, so that install-service
finds them all and creates none with ids of its own choosing."""
_ensure_group(commands, seat.user, seat.gid)
- _ensure_user(commands, seat.user, seat.uid, str(seat.gid), seat.gid, "Switch agents controller")
+ _ensure_user(
+ commands,
+ seat.user,
+ seat.uid,
+ str(seat.gid),
+ seat.gid,
+ "Switch agents controller",
+ )
_ensure_group(commands, seat.agents_group, seat.agents_gid)
for slot in range(1, config.agent_users + 1):
_ensure_user(
@@ -615,7 +646,9 @@ def stop_controller(commands: Commands, seat: Seat) -> None:
its agents still running. Its data stays on the volume."""
stopped = commands.result(["/usr/bin/systemctl", "disable", "--now", seat.unit])
output = f"{stopped.stdout}\n{stopped.stderr}"
- if stopped.returncode != 0 and not ("not loaded" in output or "does not exist" in output):
+ if stopped.returncode != 0 and not (
+ "not loaded" in output or "does not exist" in output
+ ):
raise BootError(f"{seat.unit} cannot be stopped: {output.strip()}")
commands.run(["/usr/bin/systemctl", "stop", f"switch-agent-{seat.uid}@*.service"])
@@ -635,7 +668,9 @@ def _ensure_root_directories(path: Path) -> None:
def enrolled(commands: Commands, config: MachineConfig, seat: Seat) -> bool:
"""Whether the seat's data directory holds an enrollment that was not revoked."""
status = commands.result(
- _as_controller(seat, [*_cli(config), "status", "--data-dir", str(seat.data_dir)]),
+ _as_controller(
+ seat, [*_cli(config), "status", "--data-dir", str(seat.data_dir)]
+ ),
env=_environment(config),
)
if status.returncode != 0:
@@ -793,7 +828,9 @@ def boot_controllers(
if seat.index:
write_drop_in(seat)
commands.run(["/usr/bin/systemctl", "daemon-reload"])
- failures.update(start_controllers(commands, config, bundle, indexes, set(keys), now))
+ failures.update(
+ start_controllers(commands, config, bundle, indexes, set(keys), now)
+ )
return failures
@@ -821,7 +858,9 @@ def start_controllers(
try:
if seat.index:
ensure_identities(commands, config, seat)
- start_controller(commands, config, bundle.api_endpoint, seat, controller, now)
+ start_controller(
+ commands, config, bundle.api_endpoint, seat, controller, now
+ )
except (BootError, OSError) as error:
failures[controller.key] = (
f"The controller {seat.user} (seat {controller.key}): {error}"
@@ -862,7 +901,9 @@ def main(argv: list[str] | None = None) -> int:
for failure in failures.values():
logger.warning("%s; trying again", failure)
time.sleep(CONTROLLER_RETRY_SECONDS)
- failures = start_controllers(commands, config, bundle, indexes, set(failures))
+ failures = start_controllers(
+ commands, config, bundle, indexes, set(failures)
+ )
except NoBundle as error:
logger.error("%s", error)
return NO_BUNDLE_EXIT
diff --git a/deploy/hosted/machine/tests/test_boot.py b/deploy/hosted/machine/tests/test_boot.py
index 4b0922e55..16d322973 100644
--- a/deploy/hosted/machine/tests/test_boot.py
+++ b/deploy/hosted/machine/tests/test_boot.py
@@ -130,7 +130,9 @@ def test_the_bundle_is_read_strictly():
api_endpoint="https://switch.example.test/agent-api",
controllers=(
boot.BundleController(key=KEY_A, controller_id=None, enrollment_code=CODE),
- boot.BundleController(key=KEY_B, controller_id=CONTROLLER_ID, enrollment_code=None),
+ boot.BundleController(
+ key=KEY_B, controller_id=CONTROLLER_ID, enrollment_code=None
+ ),
),
)
@@ -271,7 +273,9 @@ def test_a_blank_volume_is_formatted_and_mounted(monkeypatch, tmp_path):
]
-def test_a_volume_attached_late_is_waited_for_and_a_formatted_one_kept(monkeypatch, tmp_path):
+def test_a_volume_attached_late_is_waited_for_and_a_formatted_one_kept(
+ monkeypatch, tmp_path
+):
monkeypatch.setattr(boot, "DATA_MOUNT", tmp_path / "data")
commands = FakeCommands(
{
@@ -349,12 +353,17 @@ def test_the_first_boot_numbers_the_seats_in_bundle_order(machine):
raw = bundle(enrolled_entry(KEY_B), enrolled_entry(KEY_A, OTHER_CONTROLLER_ID))
assert boot.boot_controllers(commands, CONFIG, boot.parse_bundle(raw)) == {}
path = machine / ".switch-controllers.json"
- assert json.loads(path.read_text()) == {"version": 1, "controllers": {KEY_B: 0, KEY_A: 1}}
+ assert json.loads(path.read_text()) == {
+ "version": 1,
+ "controllers": {KEY_B: 0, KEY_A: 1},
+ }
assert stat.S_IMODE(path.lstat().st_mode) == 0o600
assert setups(commands) == ["switch-controller", "switch-controller-1"]
-def test_a_seat_that_left_keeps_its_index_and_its_data_and_its_controller_is_stopped(machine):
+def test_a_seat_that_left_keeps_its_index_and_its_data_and_its_controller_is_stopped(
+ machine,
+):
boot.save_indexes(machine, {KEY_A: 0, KEY_B: 1})
left = boot.seat_for(1, CONFIG)
left.data_dir.mkdir(parents=True)
@@ -362,10 +371,17 @@ def test_a_seat_that_left_keeps_its_index_and_its_data_and_its_controller_is_sto
commands = FakeCommands()
raw = bundle(enrolled_entry(KEY_A))
assert boot.boot_controllers(commands, CONFIG, boot.parse_bundle(raw)) == {}
- assert ["/usr/bin/systemctl", "disable", "--now", "switch-agent-controller-2200.service"] in (
- commands.calls
- )
- assert ["/usr/bin/systemctl", "stop", "switch-agent-2200@*.service"] in commands.calls
+ assert [
+ "/usr/bin/systemctl",
+ "disable",
+ "--now",
+ "switch-agent-controller-2200.service",
+ ] in (commands.calls)
+ assert [
+ "/usr/bin/systemctl",
+ "stop",
+ "switch-agent-2200@*.service",
+ ] in commands.calls
assert (left.data_dir / "controller.db").read_text() == "kept"
assert setups(commands) == ["switch-controller"]
assert boot.load_indexes(machine) == {KEY_A: 0, KEY_B: 1}
@@ -377,14 +393,16 @@ def test_a_seat_that_left_keeps_its_index_and_its_data_and_its_controller_is_sto
assert setups(again) == ["switch-controller", "switch-controller-2"]
-def test_a_controller_that_left_is_stopped_even_when_its_unit_is_not_on_this_root_volume(machine):
+def test_a_controller_that_left_is_stopped_even_when_its_unit_is_not_on_this_root_volume(
+ machine,
+):
boot.save_indexes(machine, {KEY_A: 0, KEY_B: 1})
- missing = (
- "Failed to disable unit: Unit file switch-agent-controller-2200.service does not exist."
- )
+ missing = "Failed to disable unit: Unit file switch-agent-controller-2200.service does not exist."
commands = FakeCommands({"disable --now": [(1, missing)]})
assert (
- boot.boot_controllers(commands, CONFIG, boot.parse_bundle(bundle(enrolled_entry(KEY_A))))
+ boot.boot_controllers(
+ commands, CONFIG, boot.parse_bundle(bundle(enrolled_entry(KEY_A)))
+ )
== {}
)
failing = FakeCommands({"disable --now": [(1, "Access denied")]})
@@ -399,7 +417,9 @@ def test_a_seat_without_a_free_index_fails_alone(machine):
boot.save_indexes(machine, {uuid_key(n): n for n in range(1, 8)} | {KEY_A: 0})
commands = FakeCommands()
raw = bundle(enrolled_entry(KEY_A), enrolled_entry(KEY_B, OTHER_CONTROLLER_ID))
- [(key, failure)] = boot.boot_controllers(commands, CONFIG, boot.parse_bundle(raw)).items()
+ [(key, failure)] = boot.boot_controllers(
+ commands, CONFIG, boot.parse_bundle(raw)
+ ).items()
assert key == KEY_B and "no free controller index" in failure
assert setups(commands) == ["switch-controller"]
@@ -517,8 +537,16 @@ def test_users_that_exist_with_their_fixed_ids_are_kept():
@pytest.mark.parametrize(
"answers",
[
- {"getent passwd switch-controller-1": [(0, "switch-controller-1:x:4242:2200::/:/bin/sh")]},
- {"getent passwd switch-controller-1": [(0, "switch-controller-1:x:2200:100::/:/bin/sh")]},
+ {
+ "getent passwd switch-controller-1": [
+ (0, "switch-controller-1:x:4242:2200::/:/bin/sh")
+ ]
+ },
+ {
+ "getent passwd switch-controller-1": [
+ (0, "switch-controller-1:x:2200:100::/:/bin/sh")
+ ]
+ },
{"getent group switch-controller-1": [(0, "switch-controller-1:x:4242:")]},
{"getent group switch-agents-2200": [(0, "switch-agents-2200:x:4242:")]},
{"getent passwd sa2200-01": [(0, "sa2200-01:x:4242:2201::/:/bin/sh")]},
@@ -528,7 +556,9 @@ def test_a_user_or_group_with_another_id_is_refused(answers):
commands = FakeCommands({**answers, "getent": [(2, "")]})
seat = boot.seat_for(1, CONFIG)
with pytest.raises(boot.BootError, match="another"):
- boot.ensure_identities(commands, dataclasses.replace(CONFIG, agent_users=1), seat)
+ boot.ensure_identities(
+ commands, dataclasses.replace(CONFIG, agent_users=1), seat
+ )
refused = next(name for name in answers)
assert commands.calls[-1] == ["/usr/bin/getent", *refused.split()[1:]]
@@ -539,7 +569,10 @@ def test_another_indexs_unit_is_ordered_after_the_boot(machine):
assert boot.boot_controllers(commands, CONFIG, boot.parse_bundle(raw)) == {}
systemd = boot.SYSTEMD_SYSTEM_DIR
drop_in = systemd / "switch-agent-controller-2200.service.d" / "after-boot.conf"
- assert drop_in.read_text() == (SCRIPT.parent / "controller-after-boot.conf").read_text()
+ assert (
+ drop_in.read_text()
+ == (SCRIPT.parent / "controller-after-boot.conf").read_text()
+ )
assert stat.S_IMODE(drop_in.stat().st_mode) == 0o644
assert not (systemd / "switch-agent-controller-2000.service.d").exists()
reloads = [i for i, call in enumerate(commands.calls) if "daemon-reload" in call]
@@ -558,7 +591,11 @@ def test_another_index_enrolls_and_runs_on_its_own_paths_as_its_own_user(machine
[enroll] = commands.ran("enroll")
assert enroll[:4] == ["/usr/sbin/runuser", "-u", "switch-controller-2", "--"]
assert enroll[enroll.index("--data-dir") + 1] == str(seat.data_dir)
- assert ["/usr/bin/chown", "switch-controller-2:", str(seat.data_dir)] in commands.calls
+ assert [
+ "/usr/bin/chown",
+ "switch-controller-2:",
+ str(seat.data_dir),
+ ] in commands.calls
assert stat.S_IMODE(seat.data_dir.stat().st_mode) == 0o700
for directory in (machine / "controllers", machine / "controllers" / "2"):
assert stat.S_IMODE(directory.stat().st_mode) == 0o755
@@ -610,10 +647,14 @@ def test_an_enrolled_machine_only_starts_its_controller(machine):
def test_a_new_code_sets_a_revoked_enrollment_aside(machine):
(machine / ".switch-controller").mkdir()
(machine / ".switch-controller" / "controller.db").write_text("old")
- (machine / ".switch-controller-code").write_text(hashlib.sha256(b"swce_old").hexdigest())
+ (machine / ".switch-controller-code").write_text(
+ hashlib.sha256(b"swce_old").hexdigest()
+ )
commands = FakeCommands({" status ": [(0, "Controller: old")]})
start(commands)
- assert (machine / ".switch-controller.replaced-7" / "controller.db").read_text() == "old"
+ assert (
+ machine / ".switch-controller.replaced-7" / "controller.db"
+ ).read_text() == "old"
assert not (machine / ".switch-controller" / "controller.db").exists()
assert len(commands.ran("enroll")) == 1
assert (machine / ".switch-controller-code").read_text() != hashlib.sha256(
@@ -681,14 +722,20 @@ def test_one_failing_controller_does_not_keep_the_others_from_starting(
assert len(commands.ran("enroll")) == 1 + boot.CONTROLLER_RETRIES
assert setups(commands) == ["switch-controller-1"]
[failure] = [
- record.getMessage() for record in caplog.records if record.levelno == logging.ERROR
+ record.getMessage()
+ for record in caplog.records
+ if record.levelno == logging.ERROR
]
assert "switch-controller" in failure and KEY_A in failure
def test_a_controller_that_fails_once_is_started_on_the_next_try(machine, monkeypatch):
commands = FakeCommands(
- {" status ": [(1, "Not enrolled.")], " enroll ": [(1, ""), (0, "")], "getent": [(2, "")]}
+ {
+ " status ": [(1, "Not enrolled.")],
+ " enroll ": [(1, ""), (0, "")],
+ "getent": [(2, "")],
+ }
)
parsed = boot.parse_bundle(bundle(entry(KEY_A)))
monkeypatch.setattr(boot.os, "geteuid", lambda: 0)
@@ -717,7 +764,10 @@ def test_a_machine_whose_controllers_all_start_boots(machine, monkeypatch):
monkeypatch.setattr(boot, "Commands", lambda: commands)
monkeypatch.setattr(boot, "prepare_storage", lambda *_: None)
assert boot.main([]) == 0
- assert json.loads((machine / ".switch-machine.json").read_text())["machineId"] == MACHINE_ID
+ assert (
+ json.loads((machine / ".switch-machine.json").read_text())["machineId"]
+ == MACHINE_ID
+ )
assert setups(commands) == ["switch-controller", "switch-controller-1"]
diff --git a/deploy/local/standalone-docker-compose.yml b/deploy/local/standalone-docker-compose.yml
index 1bb382553..aa6dd41de 100644
--- a/deploy/local/standalone-docker-compose.yml
+++ b/deploy/local/standalone-docker-compose.yml
@@ -228,8 +228,11 @@ services:
# The bundled Mattermost is on the compose network, a private address,
# so it is always allowed; .env adds to it rather than replacing it.
OUTBOUND_ALLOWED_PRIVATE_HOSTS: mattermost,${OUTBOUND_ALLOWED_PRIVATE_HOSTS:-}
+ # Replaced by the agent_management feature flag. Still passed through so
+ # switch-core refuses a .env that turns it on, rather than ignoring it.
AGENT_MANAGEMENT_ENABLED: ${AGENT_MANAGEMENT_ENABLED:-false}
CONTROLLER_TOKEN_SECRET: ${CONTROLLER_TOKEN_SECRET:-}
+ FEATURE_FLAGS_ENABLED: ${FEATURE_FLAGS_ENABLED:-}
GATEWAY_ADMIN_EMAIL: ${GATEWAY_ADMIN_EMAIL}
GATEWAY_ADMIN_PASSWORD: ${GATEWAY_ADMIN_PASSWORD}
FRONTEND_BASE_URL: ${FRONTEND_BASE_URL}
diff --git a/deploy/remote/helm/switch/README.md b/deploy/remote/helm/switch/README.md
index 6e484a0a3..be0dae3d0 100644
--- a/deploy/remote/helm/switch/README.md
+++ b/deploy/remote/helm/switch/README.md
@@ -188,22 +188,26 @@ stored in the database.
## Agent management
Managed agents, and the agent controllers that run them on users' machines, are
-off by default. To turn them on:
+off by default. The `agent_management` feature flag turns them on:
```yaml
switchCore:
- agentManagement:
- enabled: true
+ featureFlags:
+ enabled: ["agent_management"]
secrets:
controllerTokenSecret: "<openssl rand -hex 32>"
```
With `secrets.existingSecret`, put the token secret in that Secret as
-`CONTROLLER_TOKEN_SECRET` instead. The chart sets `AGENT_MANAGEMENT_ENABLED`,
+`CONTROLLER_TOKEN_SECRET` instead. The chart sets `FEATURE_FLAGS_ENABLED`,
`CONTROLLER_TOKEN_SECRET` and `CONTROLLER_STATUS_INTERVAL_SECONDS` on switch-core
and its migration Job, so enabling it is one rollout. Controllers enroll and
connect under `/v1`, which `ingress.agentApiPaths` routes to switch-core by default.
+`switchCore.agentManagement.enabled` is gone: the chart refuses to render with it
+set to true, and switch-core refuses to start with `AGENT_MANAGEMENT_ENABLED=true`.
+Move it to the flag list instead.
+
A deployment that set these variables with `kubectl set env` should remove them
before the first upgrade that renders them (`kubectl set env deployment/<release>-switch-core
AGENT_MANAGEMENT_ENABLED- CONTROLLER_TOKEN_SECRET-`). Otherwise Helm merges its
diff --git a/deploy/remote/helm/switch/templates/_helpers.tpl b/deploy/remote/helm/switch/templates/_helpers.tpl
index 496ccdd50..47e2d22f9 100644
--- a/deploy/remote/helm/switch/templates/_helpers.tpl
+++ b/deploy/remote/helm/switch/templates/_helpers.tpl
@@ -60,7 +60,10 @@ SECRET_KEYS: {{ required "secrets.secretKeys is required (\"<id>:<secret>\", see
JWT_SECRET_KEY: {{ . | b64enc | quote }}
{{- end }}
{{- if .Values.switchCore.agentManagement.enabled }}
-{{- $controllerSecret := required "secrets.controllerTokenSecret is required when switchCore.agentManagement.enabled" .Values.secrets.controllerTokenSecret }}
+{{- fail "switchCore.agentManagement.enabled has been replaced by a feature flag: remove it and add \"agent_management\" to switchCore.featureFlags.enabled." }}
+{{- end }}
+{{- if has "agent_management" .Values.switchCore.featureFlags.enabled }}
+{{- $controllerSecret := required "secrets.controllerTokenSecret is required with the agent_management feature flag on" .Values.secrets.controllerTokenSecret }}
{{- if lt (len $controllerSecret) 32 }}
{{- fail "secrets.controllerTokenSecret must be at least 32 characters; switch-core refuses to start with a shorter one." }}
{{- end }}
@@ -661,18 +664,14 @@ this one. Drop it once the oldest supported image reads ID_SERVER_NAME. */}}
name: {{ include "switch.secretName" . }}
key: JWT_SECRET_KEY
optional: true
-{{- with .Values.switchCore.agentManagement }}
-{{- if .enabled }}
-- name: AGENT_MANAGEMENT_ENABLED
- value: "true"
+{{- if has "agent_management" .Values.switchCore.featureFlags.enabled }}
- name: CONTROLLER_TOKEN_SECRET
valueFrom:
secretKeyRef:
- name: {{ include "switch.secretName" $ }}
+ name: {{ include "switch.secretName" . }}
key: CONTROLLER_TOKEN_SECRET
- name: CONTROLLER_STATUS_INTERVAL_SECONDS
- value: {{ .statusIntervalSeconds | quote }}
-{{- end }}
+ value: {{ .Values.switchCore.agentManagement.statusIntervalSeconds | quote }}
{{- end }}
- name: GATEWAY_ADMIN_EMAIL
valueFrom:
@@ -737,6 +736,10 @@ this one. Drop it once the oldest supported image reads ID_SERVER_NAME. */}}
- name: OUTBOUND_ALLOWED_PRIVATE_HOSTS
value: {{ join "," $outboundHosts | quote }}
{{- end }}
+{{- with .Values.switchCore.featureFlags.enabled }}
+- name: FEATURE_FLAGS_ENABLED
+ value: {{ join "," . | quote }}
+{{- end }}
{{- with .Values.switchCore.smtp }}
{{- if .enabled }}
{{- if not $.Values.switchCore.frontendBaseUrl }}
diff --git a/deploy/remote/helm/switch/values.yaml b/deploy/remote/helm/switch/values.yaml
index 0ecdec4b8..e78e2a90f 100644
--- a/deploy/remote/helm/switch/values.yaml
+++ b/deploy/remote/helm/switch/values.yaml
@@ -174,8 +174,10 @@ switchCore:
# Existing Secret with github.json (client_id, client_secret, slug, origin).
githubConnectionsSecret: ""
hostedControllerSecret: ""
- # How many cloud machines may run at once. Cloud machines run the agents
- # controller and their owner's managed agents, so they need agentManagement.
+ # How many cloud machines may run at once; 0 means this server cannot run
+ # them. Cloud machines run the agents controller, so above 0 this needs the
+ # "agent_management" feature flag. The "hosted_agents" flag is what offers
+ # them in Switch Console.
hostedLaunchCapacity: 0
hostedDiskRetentionDays: 7
hostedIdleStopMinutes: 30
@@ -315,11 +317,11 @@ switchCore:
# once every API client authenticating against this deployment handles it.
tenantChoiceEnabled: false
# Agent management: managed agents, and the agent controllers (Switch Console,
- # or switch-agent-controller on a user's own machine) that run them. Needs
+ # or switch-agent-controller on a user's own machine) that run them. Turned on
+ # by the "agent_management" feature flag (featureFlags.enabled below). Needs
# secrets.controllerTokenSecret, and `/v1` routed to switch-core
# (ingress.agentApiPaths does by default).
agentManagement:
- enabled: false
# How often a controller must report; one silent for three of these is
# shown as unknown and gets no new placements.
statusIntervalSeconds: 60
@@ -330,6 +332,13 @@ switchCore:
# Mattermost (mattermost.enabled) is added automatically.
outbound:
allowedPrivateHosts: []
+ # Feature flags turned on for this deployment (FEATURE_FLAGS_ENABLED), e.g.
+ # ["ecosystem.show_owners"]. Every other flag is off, and no one can change
+ # them while the server runs. An unknown flag stops switch-core at startup.
+ # Known flags: ecosystem.show_owners, agent_management, switch_cloud,
+ # hosted_agents.
+ featureFlags:
+ enabled: []
# Invitation e-mails. When enabled, an invitation addressed to an e-mail is
# sent there through this SMTP relay (SES SMTP, Postmark, a company relay —
# anything that speaks SMTP). Off, the invitation is still created and the
diff --git a/docs/design/agent-controllers-v1.md b/docs/design/agent-controllers-v1.md
index 1fba52eb9..73e12f5f2 100644
--- a/docs/design/agent-controllers-v1.md
+++ b/docs/design/agent-controllers-v1.md
@@ -8,8 +8,8 @@ where it deliberately stops short.
## Shape
-- **Management** (Core package `switch_core/management/`, off unless
- `AGENT_MANAGEMENT_ENABLED=true`): the source of truth for managed agents. It holds agent
+- **Management** (Core package `switch_core/management/`, off unless the
+ `agent_management` feature flag is on): the source of truth for managed agents. It holds agent
definitions, which controller each one runs on, controller enrollment and credentials,
controller status, and operations.
- **Agents controller** (`console/packages/agent-controller`, a Node CLI): one per
@@ -33,7 +33,9 @@ where it deliberately stops short.
## Core
### Config (`config.py`)
-- `agent_management_enabled: bool = False` (`AGENT_MANAGEMENT_ENABLED`).
+- `agent_management_enabled`: whether the `agent_management` feature flag is on
+ (`FEATURE_FLAGS_ENABLED`). `AGENT_MANAGEMENT_ENABLED=true`, the setting it replaced,
+ stops startup.
- `controller_token_secret: str | None = None` (`CONTROLLER_TOKEN_SECRET`). **Required
when the flag is on**: a model validator raises if it is missing or shorter than 32 chars. It is
separate from `jwt_secret_key` on purpose.
diff --git a/docs/old/multi-tenancy-phase1-db.md b/docs/old/multi-tenancy-phase1-db.md
index 6b36cde16..8c5ea27ea 100644
--- a/docs/old/multi-tenancy-phase1-db.md
+++ b/docs/old/multi-tenancy-phase1-db.md
@@ -136,8 +136,9 @@ Three entries are worth justifying:
A user is a person, not a tenant member; the membership row is the per-tenant
object. `oidc_identities` records how that person proves who they are, equally
-tenant-independent. `feature_flags` is a deployment switch; a flag that needs
-to vary per tenant is a new table, not a nullable column.
+tenant-independent. `feature_flags` was a deployment switch in Phase 1; the
+table has since been dropped (migration `9c4e7a1f2b38`), and flags are now set
+at deploy time through `FEATURE_FLAGS_ENABLED`.
**This is the list that is written down, and the scoped list is the one that
is derived** — that way round, deliberately. The three in the model metadata
diff --git a/gateway/src/data/management.ts b/gateway/src/data/management.ts
index 5cfc46181..68a1015df 100644
--- a/gateway/src/data/management.ts
+++ b/gateway/src/data/management.ts
@@ -1,6 +1,6 @@
// Agent management: the machines (agent controllers) that run managed agents,
// the agents placed on them, and the operations sent to them. Served under
-// /gateway/management only when the server runs with AGENT_MANAGEMENT_ENABLED;
+// /gateway/management only when the server turns on its agent_management flag;
// every failure comes back as {"error": {"code", "message", "retryable"}}.
const BASE = "/gateway/management";
diff --git a/gateway/src/pages/machines/MachinesPage.tsx b/gateway/src/pages/machines/MachinesPage.tsx
index c53ecb887..8d201060a 100644
--- a/gateway/src/pages/machines/MachinesPage.tsx
+++ b/gateway/src/pages/machines/MachinesPage.tsx
@@ -174,7 +174,7 @@ export default function MachinesPage() {
} catch (err) {
setLoadError(
err instanceof ManagementApiError && err.status === 404 && err.code === "http_error"
- ? "Agent management is not enabled on this server. An operator turns it on with AGENT_MANAGEMENT_ENABLED."
+ ? "Agent management is not enabled on this server. An operator turns it on by adding agent_management to FEATURE_FLAGS_ENABLED."
: `Could not load machines and managed agents: ${errorMessage(err)}`,
);
}