Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
Serve the web gateway from a Docker-free local server
Simon Flack77d8a4534fe1
diff --git a/console/apps/switch-console-desktop/scripts/build-local-server-bundle.mjs b/console/apps/switch-console-desktop/scripts/build-local-server-bundle.mjsindex 672756e06..4c72eedea 100644--- a/console/apps/switch-console-desktop/scripts/build-local-server-bundle.mjs+++ b/console/apps/switch-console-desktop/scripts/build-local-server-bundle.mjs@@ -7,6 +7,9 @@* uv/ the pinned uv* python/ a relocatable CPython 3.12, fetched by that uv* switch/src the pinned switch-core release's `core/` and its setup script+ * switch/gateway-ui+ * the same release's gateway pages (the admin dashboard), built,+ * for switch-core to serve on its own address* switch/wheels, switch/requirements.txt* every package switch-core needs, as wheels, with the hashes of* the release's own lockfile — installed offline at first start@@ -87,6 +90,9 @@ const wanted = {postgresVersion: pins.postgresArchive(platform) ? pins.POSTGRES_VERSION : null,opensslVersion: buildsOpenssl ? pins.OPENSSL_VERSION : null,python: pins.SWITCH_CORE_PYTHON,+ // Bumped when what the bundle holds of the gateway changes, so a bundle+ // already on disk from before is rebuilt (1: its built pages).+ gatewayUi: 1,};try {@@ -260,6 +266,29 @@ await cp(path.join(source, 'deploy', 'shared_resources', 'setup.py'),path.join(switchDir, 'src', 'deploy', 'shared_resources', 'setup.py'));++// The release's gateway pages, built from the same source, as the published+// image builds them: switch-core serves them when GATEWAY_UI_DIR names them.+console.log(`local-server bundle: gateway pages for switch-core ${switchVersion}`);+const gatewaySource = path.join(source, 'gateway');+// The build tools are dev dependencies, which npm drops under+// NODE_ENV=production; Windows' npm is a .cmd script, run through a shell.+const npmEnv = { ...process.env };+delete npmEnv.NODE_ENV;+const npm = (args) =>+ execFileSync('npm', args, {+ cwd: gatewaySource,+ stdio: 'inherit',+ env: npmEnv,+ shell: process.platform === 'win32',+ });+npm(['ci', '--no-audit', '--no-fund']);+npm(['run', 'build']);+const gatewayUi = path.join(switchDir, 'gateway-ui');+await cp(path.join(gatewaySource, 'dist'), gatewayUi, { recursive: true });+if (!existsSync(path.join(gatewayUi, 'index.html'))) {+ throw new Error(`The gateway build in ${gatewaySource} produced no index.html`);+}const requirements = execFileSync(uv,['export', '--frozen', '--no-dev', '--no-emit-project', '--format', 'requirements-txt', '-q'],diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/local-server-service.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/local-server-service.test.tsindex bf962103d..73fb50698 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/local-server-service.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/local-server-service.test.ts@@ -119,6 +119,7 @@ vi.mock('./native/native-stack', () => ({nativeStartedAt: vi.fn(),readNativeDeployedVersion: native.deployed,readNativeTelemetry: vi.fn(async () => ({ known: true, enabled: false })),+ readNativeAdminPages: vi.fn(async () => 'served'),nativeMattermostLauncher: native.launcher,discardNativeData: native.discard,nativeCoreFailureLine: native.failureLine,@@ -496,6 +497,8 @@ it('reads a native server as running from its processes, not from Docker', asyncphase: 'running',runtime: 'native',deployedVersion: '0.11.0',+ // Read off the running server, so its page knows whether to link to them.+ adminPages: 'served',});});diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/local-server-service.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/local-server-service.tsindex 941096155..6ebe40d94 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/local-server-service.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/local-server-service.ts@@ -14,6 +14,7 @@ import {type DockerAvailability,type LocalActivityEntry,type LocalServerRuntime,+ type LocalServerAdminPages,type LocalServerStatus,type StartLocalServerResult,managedServerUpgradeBlockedReason,@@ -66,6 +67,7 @@ import {nativeStackRunning,nativeStartedAt,readNativeDeployedVersion,+ readNativeAdminPages,readNativeTelemetry,resetNativeStack,startNativeStack,@@ -117,6 +119,7 @@ function initialStatus(): LocalServerStatus {drift: null,checkoutBuild: null,deployedTelemetry: null,+ adminPages: null,message: null,error: null,failedTo: null,@@ -267,6 +270,16 @@ export class LocalServerService {return { root, enabled: await isCheckoutBuildEnabled(host), forcedBy: null };}+ /** A running native server's admin pages, read off the server; null for a+ * Docker one, which always serves them. */+ private async adminPages(+ native: boolean,+ layout: NativeLayout+ ): Promise<LocalServerAdminPages | null> {+ if (!native) return null;+ return readNativeAdminPages(layout, this.checkoutRootForStart(), localServerBundleRoot());+ }+/** The checkout the next start should build from, or null to run the* released switch-core. */private checkoutRootForStart(): string | null {@@ -345,6 +358,7 @@ export class LocalServerService {deployedTelemetry: native? await readNativeTelemetry(layout): await readDeployedTelemetry(host),+ adminPages: await this.adminPages(native, layout),});}const version = native@@ -455,6 +469,7 @@ export class LocalServerService {deployedTelemetry: native? await readNativeTelemetry(layout): await readDeployedTelemetry(host),+ adminPages: await this.adminPages(native, layout),});}return;@@ -504,6 +519,7 @@ export class LocalServerService {notice: null,mattermostState: null,deployedTelemetry: null,+ adminPages: null,});await recordLocalActivity('crashed', error);}@@ -687,6 +703,7 @@ export class LocalServerService {deployedTelemetry: ranNative? await readNativeTelemetry(layout): await readDeployedTelemetry(host),+ adminPages: await this.adminPages(ranNative, layout),notice:moveFailure !== null? `Could not move this server off Docker, so it is still running on Docker: ` +@@ -810,6 +827,7 @@ export class LocalServerService {message: null,error: null,deployedTelemetry: null,+ adminPages: null,notice: null,mattermostState: null,upgrade: upgrade && upgradeState(upgrade, false),@@ -842,6 +860,7 @@ export class LocalServerService {message: null,error: null,deployedTelemetry: null,+ adminPages: null,notice: null,mattermostState: null,upgrade: upgrade && upgradeState(upgrade, false),@@ -888,6 +907,7 @@ export class LocalServerService {message: null,error: null,deployedTelemetry: null,+ adminPages: null,notice: null,mattermostState: null,deployedVersion: null,diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/native/bundle.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/native/bundle.tsindex d57cf5455..7789603c8 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/native/bundle.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/native/bundle.ts@@ -2,6 +2,7 @@ import { createHash } from 'node:crypto';import { access, cp, readdir, readFile, rename, rm } from 'node:fs/promises';import path from 'node:path';import { log } from '@main/lib/logger';+import { GATEWAY_UI_DIR_NAME, gatewayUiOrNull } from './gateway-ui';import { exe } from './native-paths';import { BUNDLE_FORMAT, SWITCH_CORE_PYTHON } from './toolchain-pins';@@ -29,6 +30,9 @@ export type LocalServerBundle = {sitePackages: string;/** Pure-Python wheels the editable install of switch-core builds with. */buildWheels: string;+ /** The gateway's built pages for that switch-core, or null in a bundle+ * built before they were shipped. */+ gatewayUi: string | null;};type Manifest = {@@ -89,6 +93,7 @@ export async function readLocalServerBundle(switchSource: path.join(root, 'switch', 'src'),sitePackages: path.join(root, 'switch', 'site-packages'),buildWheels: path.join(root, 'switch', 'build-wheels'),+ gatewayUi: await gatewayUiOrNull(path.join(root, 'switch', GATEWAY_UI_DIR_NAME)),};}diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/native/core-process.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/native/core-process.test.tsindex 7cbf14984..77a3e3a84 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/native/core-process.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/native/core-process.test.ts@@ -72,7 +72,7 @@ it.skipIf(process.platform === 'win32')();await startCore(layout,- { version: '0.30.0', sourceRoot: root, projectDir: root, python },+ { version: '0.30.0', sourceRoot: root, projectDir: root, python, gatewayUiDir: null },{});const healthy = await waitForCoreHealth(diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/native/core-settings.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/native/core-settings.tsindex e995fcd2f..d8e052fd5 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/native/core-settings.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/native/core-settings.ts@@ -6,11 +6,13 @@ import {TELEMETRY_ENDPOINT_KEY,} from '../env-file';import type { LocalServerSecrets } from '../secret-values';+import { GATEWAY_UI_ENV } from './gateway-ui';import { DATABASE, OWNER_ROLE, RUNTIME_ROLE } from './postgres-cluster';export type NativeCoreSettingsParams = {- /** switch-core's port on loopback, which serves both the agent API and the- * gateway API — there is no separate dashboard process in native mode. */+ /** switch-core's port on loopback, which serves the agent API, the gateway+ * API and the gateway's pages — there is no separate dashboard process in+ * native mode. */apiPort: number;postgresPort: number;/** Where switch-core takes Mattermost's button presses, when it runs one. */@@ -21,6 +23,9 @@ export type NativeCoreSettingsParams = {telemetryInternal: boolean;/** The relay the server sends its usage to: the one the app reports to. */telemetryEndpoint: string;+ /** The gateway's built pages, for switch-core to serve on its own address;+ * null to run without them. */+ gatewayUiDir: string | null;};export function nativeApiUrl(apiPort: number): string {@@ -71,5 +76,8 @@ export function buildNativeCoreSettings(params: NativeCoreSettingsParams): Recor// Tells the server's agents that Switch Console runs it, as the Docker// stack's `.env` does.MANAGED_BY_CONSOLE: 'true',+ // Only ever a directory with a build in it: switch-core refuses to start+ // on one without.+ ...(params.gatewayUiDir === null ? {} : { [GATEWAY_UI_ENV]: params.gatewayUiDir }),};}diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/native/gateway-ui.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/native/gateway-ui.test.tsnew file mode 100644index 000000000..39a917444--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/native/gateway-ui.test.ts@@ -0,0 +1,249 @@+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { generateSecrets } from '../secret-values';+import { readLocalServerBundle } from './bundle';+import { CORE_ENV_FILE, renderEnv } from './core-process';+import { buildNativeCoreSettings } from './core-settings';+import {+ buildGatewayUi,+ checkoutGatewayUi,+ GATEWAY_UI_ENV,+ hasGatewayUiBuild,+ nativeAdminPages,+ runningServesAdminPages,+} from './gateway-ui';+import { nativeLayout } from './native-paths';+import { installSwitchCore } from './switch-core-install';+import { BUNDLE_FORMAT } from './toolchain-pins';++vi.mock('@main/lib/logger', () => ({+ log: { warn: vi.fn(), error: vi.fn(), info: vi.fn(), debug: vi.fn() },+}));++const unix = it.skipIf(process.platform === 'win32');++let root: string;+beforeEach(async () => {+ root = await mkdtemp(path.join(os.tmpdir(), 'switch-gateway-ui-'));+});+afterEach(async () => {+ await rm(root, { recursive: true, force: true });+});++async function writeBuild(dir: string): Promise<void> {+ await mkdir(path.join(dir, 'assets'), { recursive: true });+ await writeFile(path.join(dir, 'index.html'), '<!doctype html>');+ await writeFile(path.join(dir, 'assets', 'app.js'), '');+}++async function writeExecutable(file: string, lines: string[]): Promise<void> {+ await mkdir(path.dirname(file), { recursive: true });+ await writeFile(file, ['#!/bin/sh', ...lines, ''].join('\n'), { mode: 0o755 });+}++function settingsWith(gatewayUiDir: string | null): Record<string, string> {+ return buildNativeCoreSettings({+ apiPort: 51001,+ postgresPort: 51002,+ callbackPort: 51003,+ secrets: generateSecrets(),+ telemetryEnabled: false,+ telemetryEnvironment: 'local',+ telemetryInternal: false,+ telemetryEndpoint: 'https://relay.example.test',+ gatewayUiDir,+ });+}++describe('core settings', () => {+ it('hands switch-core the pages when there are some', () => {+ expect(settingsWith('/srv/pages')[GATEWAY_UI_ENV]).toBe('/srv/pages');+ });++ it('leaves the setting out when there are none, which switch-core reads as off', () => {+ expect(settingsWith(null)).not.toHaveProperty(GATEWAY_UI_ENV);+ });+});++describe('finding a build', () => {+ it('needs an index.html, as switch-core does', async () => {+ const dir = path.join(root, 'dist');+ await mkdir(dir);+ expect(await hasGatewayUiBuild(dir)).toBe(false);+ await writeBuild(dir);+ expect(await hasGatewayUiBuild(dir)).toBe(true);+ });++ it("uses a checkout's own build, and nothing when it has none", async () => {+ expect(await checkoutGatewayUi(root)).toBeNull();+ await writeBuild(path.join(root, 'gateway', 'dist'));+ expect(await checkoutGatewayUi(root)).toBe(path.join(root, 'gateway', 'dist'));+ });+});++describe('what a running server serves', () => {+ const layout = () => nativeLayout(root);++ async function startedWith(settings: Record<string, string>): Promise<void> {+ await mkdir(layout().run, { recursive: true });+ await writeFile(path.join(layout().run, CORE_ENV_FILE), renderEnv(settings));+ }++ it('reads it off the environment the server was started with', async () => {+ expect(await runningServesAdminPages(layout())).toBe(false);+ await startedWith(settingsWith(null));+ expect(await runningServesAdminPages(layout())).toBe(false);+ await startedWith(settingsWith('/srv/pages'));+ expect(await runningServesAdminPages(layout())).toBe(true);+ });++ it('offers a restart only where one would bring the pages', async () => {+ await startedWith(settingsWith(null));+ expect(await nativeAdminPages(layout(), async () => true)).toBe('restart');+ expect(await nativeAdminPages(layout(), async () => false)).toBe('unavailable');+ await startedWith(settingsWith('/srv/pages'));+ expect(await nativeAdminPages(layout(), async () => false)).toBe('served');+ });+});++describe('the bundle', () => {+ async function writeBundle(dir: string, withPages: boolean): Promise<void> {+ await mkdir(dir, { recursive: true });+ await writeFile(+ path.join(dir, 'manifest.json'),+ JSON.stringify({ bundle: BUNDLE_FORMAT, switchVersion: '0.31.0', builtAt: 'now' })+ );+ await mkdir(path.join(dir, 'switch', 'src', 'core'), { recursive: true });+ if (withPages) await writeBuild(path.join(dir, 'switch', 'gateway-ui'));+ }++ it('names its pages, or none for a bundle built before it shipped them', async () => {+ await writeBundle(path.join(root, 'old'), false);+ await writeBundle(path.join(root, 'new'), true);+ expect((await readLocalServerBundle(path.join(root, 'old'), '0.31.0'))?.gatewayUi).toBeNull();+ expect((await readLocalServerBundle(path.join(root, 'new'), '0.31.0'))?.gatewayUi).toBe(+ path.join(root, 'new', 'switch', 'gateway-ui')+ );+ });++ unix(+ "installs the pages beside the server's own source, never serving them from the bundle",+ async () => {+ const bundleRoot = path.join(root, 'bundle');+ await writeBundle(bundleRoot, true);+ const bundle = await readLocalServerBundle(bundleRoot, '0.31.0');+ if (bundle === null) throw new Error('fixture bundle unreadable');+ // Stands in for uv: `venv <python> <dir>` makes the directory the+ // install writes its .pth file into; anything else succeeds silently.+ const uv = path.join(root, 'uv');+ await writeExecutable(uv, [+ 'if [ "$1" = venv ]; then mkdir -p "$4/lib/python3.12/site-packages"; fi',+ 'exit 0',+ ]);+ const layout = nativeLayout(path.join(root, 'server'));+ const install = await installSwitchCore({+ layout,+ uv: { path: uv, version: '0.0.0', source: 'installed' },+ bundle,+ version: '0.31.0',+ owner: 'example',+ repo: 'switch',+ checkoutRoot: null,+ buildGatewayUiFromSource: false,+ onMessage: () => {},+ });+ expect(install.gatewayUiDir).toBe(path.join(layout.switchCore, '0.31.0', 'gateway-ui'));+ expect(install.gatewayUiDir?.startsWith(bundleRoot)).toBe(false);+ expect(await hasGatewayUiBuild(install.gatewayUiDir ?? '')).toBe(true);+ // Gone from the app (an update replaced it): the server's copy stays.+ await rm(bundleRoot, { recursive: true, force: true });+ expect(await hasGatewayUiBuild(install.gatewayUiDir ?? '')).toBe(true);+ }+ );+});++describe('building the pages from source', () => {+ const originalPath = process.env.PATH;+ afterEach(() => {+ process.env.PATH = originalPath;+ });++ /** Puts an `npm` on PATH that records its arguments and, on `run build`,+ * writes a build (or fails, with `fail`). */+ async function fakeNpm(fail = false): Promise<string> {+ const bin = path.join(root, 'bin');+ const calls = path.join(root, 'npm-calls');+ await writeExecutable(path.join(bin, 'npm'), [+ `echo "$@ NODE_ENV=$NODE_ENV" >> "${calls}"`,+ 'if [ "$1" = ci ]; then mkdir -p node_modules; fi',+ fail+ ? 'if [ "$1" = run ]; then echo "vite: build failed" >&2; exit 1; fi'+ : 'if [ "$1" = run ]; then mkdir -p dist && echo ok > dist/index.html; fi',+ 'exit 0',+ ]);+ process.env.PATH = `${bin}${path.delimiter}${originalPath ?? ''}`;+ return calls;+ }++ async function source(): Promise<string> {+ const src = path.join(root, 'src');+ await mkdir(path.join(src, 'gateway'), { recursive: true });+ await writeFile(path.join(src, 'gateway', 'package.json'), '{}');+ return src;+ }++ unix('installs, builds, keeps the build and drops the packages', async () => {+ const calls = await fakeNpm();+ const src = await source();+ const destination = path.join(root, 'gateway-ui');+ process.env.NODE_ENV = 'production';+ try {+ const built = await buildGatewayUi({+ layout: nativeLayout(root),+ sourceRoot: src,+ destination,+ onMessage: () => {},+ });+ expect(built).toBe(destination);+ } finally {+ delete process.env.NODE_ENV;+ }+ expect(await hasGatewayUiBuild(destination)).toBe(true);+ const lines = (await readFile(calls, 'utf8')).trim().split('\n');+ // Dev dependencies hold the build tools: npm must not drop them.+ expect(lines).toEqual(['ci --no-audit --no-fund NODE_ENV=', 'run build NODE_ENV=']);+ expect(await hasGatewayUiBuild(path.join(src, 'gateway', 'node_modules'))).toBe(false);+ });++ unix('reports a failed build and carries on without the pages', async () => {+ await fakeNpm(true);+ const src = await source();+ const messages: string[] = [];+ const built = await buildGatewayUi({+ layout: nativeLayout(root),+ sourceRoot: src,+ destination: path.join(root, 'gateway-ui'),+ onMessage: (message) => messages.push(message),+ });+ expect(built).toBeNull();+ expect(messages.at(-1)).toMatch(/starts without them/);+ const buildLog = await readFile(+ path.join(nativeLayout(root).logs, 'gateway-build.log'),+ 'utf8'+ );+ expect(buildLog).toContain('vite: build failed');+ });++ it('has nothing to build from a source without the gateway', async () => {+ expect(+ await buildGatewayUi({+ layout: nativeLayout(root),+ sourceRoot: root,+ destination: path.join(root, 'gateway-ui'),+ onMessage: () => {},+ })+ ).toBeNull();+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/native/gateway-ui.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/native/gateway-ui.tsnew file mode 100644index 000000000..2c1a0e043--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/native/gateway-ui.ts@@ -0,0 +1,142 @@+import { appendFile, access, mkdir, readFile, rename, rm } from 'node:fs/promises';+import path from 'node:path';+import { log } from '@main/lib/logger';+import type { LocalServerAdminPages } from '@shared/core/managed-switch-server/managed-switch-server';+import { CORE_ENV_FILE } from './core-process';+import type { NativeLayout } from './native-paths';+import { runCommand } from './run-command';++/**+ * The gateway's built pages (the admin dashboard) for a native local server.+ *+ * switch-core serves them itself, on its own address, when `GATEWAY_UI_DIR`+ * names a directory holding a build — the published image does exactly that.+ * A native server has no image, so the build comes from wherever its+ * switch-core did: the app's bundle, the checkout it runs from, or (dev builds+ * only) built from the source a start downloaded. switch-core refuses to start+ * when `GATEWAY_UI_DIR` names a directory with no `index.html`, so a directory+ * is only ever handed over once that file is seen.+ */++/** Where an install keeps its copy of the pages, beside its `src/` and `venv/`. */+export const GATEWAY_UI_DIR_NAME = 'gateway-ui';++/** The variable switch-core reads the pages' directory from. */+export const GATEWAY_UI_ENV = 'GATEWAY_UI_DIR';++const BUILD_TIMEOUT_MS = 15 * 60 * 1000;++/** Whether `dir` holds a build of the pages switch-core will accept. */+export async function hasGatewayUiBuild(dir: string): Promise<boolean> {+ try {+ await access(path.join(dir, 'index.html'));+ return true;+ } catch {+ return false;+ }+}++/** `dir` when it holds a build, else null. */+export async function gatewayUiOrNull(dir: string): Promise<string | null> {+ return (await hasGatewayUiBuild(dir)) ? dir : null;+}++/** The checkout's own build of the pages (`just gateway-build`), or null when+ * it has none. Used as it is, so a rebuild shows at the next start. */+export function checkoutGatewayUi(checkoutRoot: string): Promise<string | null> {+ return gatewayUiOrNull(path.join(checkoutRoot, 'gateway', 'dist'));+}++/** `npm`, as something `spawn` can run on this platform: Windows' npm is a+ * `.cmd` script, which Node only runs through a shell. */+function npmCommand(args: string[]): [string, string[]] {+ if (process.platform === 'win32') return ['cmd.exe', ['/d', '/s', '/c', 'npm', ...args]];+ return ['npm', args];+}++/**+ * Build the pages from a downloaded Switch source tree into `destination`.+ * For dev builds only, which have Node and npm to hand; never fatal: the+ * server is better started without its admin pages than not at all, so a+ * failure is logged and reported, and null returned. The packages it installs+ * are removed again: only the build is kept.+ */+export async function buildGatewayUi(opts: {+ layout: NativeLayout;+ sourceRoot: string;+ destination: string;+ onMessage: (message: string) => void;+}): Promise<string | null> {+ const { layout, sourceRoot, destination, onMessage } = opts;+ const project = path.join(sourceRoot, 'gateway');+ try {+ await access(path.join(project, 'package.json'));+ } catch {+ log.warn(`local-switch-server: no gateway source in ${sourceRoot}; no admin pages`);+ return null;+ }+ onMessage('Building the admin pages (first start of this version)…');+ await mkdir(layout.logs, { recursive: true });+ const buildLog = path.join(layout.logs, 'gateway-build.log');+ const lines: string[] = [];+ // The build tools are dev dependencies, which npm leaves out under+ // NODE_ENV=production; the build sets its own mode.+ const env: NodeJS.ProcessEnv = { ...process.env };+ delete env.NODE_ENV;+ const run = (args: string[]) => {+ const [command, commandArgs] = npmCommand(args);+ return runCommand(command, commandArgs, {+ cwd: project,+ env,+ onLine: (line) => lines.push(line),+ timeoutMs: BUILD_TIMEOUT_MS,+ });+ };+ try {+ await appendFile(buildLog, `\n# build ${project} (${new Date().toISOString()})\n`);+ await run(['ci', '--no-audit', '--no-fund']);+ await run(['run', 'build']);+ await rm(destination, { recursive: true, force: true });+ await rename(path.join(project, 'dist'), destination);+ } catch (error) {+ const reason = error instanceof Error ? error.message : String(error);+ log.warn('local-switch-server: could not build the admin pages', { error: reason });+ onMessage(`Could not build the admin pages, so the server starts without them (${buildLog})`);+ return null;+ } finally {+ await appendFile(buildLog, `${lines.join('\n')}\n`).catch(() => undefined);+ await rm(path.join(project, 'node_modules'), { recursive: true, force: true }).catch(+ () => undefined+ );+ }+ return gatewayUiOrNull(destination);+}++/** Whether the running switch-core was started with the pages, read off the+ * environment it was started with: it refuses to start with a directory that+ * holds none, so one named there is one it serves. */+export async function runningServesAdminPages(layout: NativeLayout): Promise<boolean> {+ try {+ const env = await readFile(path.join(layout.run, CORE_ENV_FILE), 'utf8');+ return env.split('\n').some((line) => {+ if (!line.startsWith(`${GATEWAY_UI_ENV}=`)) return false;+ return line.slice(GATEWAY_UI_ENV.length + 1).trim() !== '';+ });+ } catch {+ return false;+ }+}++/**+ * What a running native server's admin pages are doing: served, or not yet+ * and a restart would bring them (a server started before this Console+ * shipped them keeps running without them across the update), or not and a+ * restart would not help either.+ */+export async function nativeAdminPages(+ layout: NativeLayout,+ restartWouldServe: () => Promise<boolean>+): Promise<LocalServerAdminPages> {+ if (await runningServesAdminPages(layout)) return 'served';+ return (await restartWouldServe()) ? 'restart' : 'unavailable';+}diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/native/native-stack.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/native/native-stack.tsindex be354cf27..2fef64e03 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/native/native-stack.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/native/native-stack.ts@@ -12,6 +12,7 @@ import { RELEASE_REPO_NAME, RELEASE_REPO_OWNER } from '@shared/app-identity';import {CHECKOUT_IMAGE_TAG,type DeployedTelemetry,+ type LocalServerAdminPages,type StartLocalServerResult,} from '@shared/core/managed-switch-server/managed-switch-server';import { MAX_START_FAILURE_LINE } from '@shared/core/managed-switch-server/start-failure';@@ -50,6 +51,7 @@ import {waitForCoreHealth,} from './core-process';import { buildNativeCoreSettings, nativeApiUrl } from './core-settings';+import { checkoutGatewayUi, nativeAdminPages } from './gateway-ui';import {mattermostCallbackBaseUrl,pullMattermostImage,@@ -363,6 +365,7 @@ export async function startNativeStack(opts: NativeStartOptions): Promise<Nativeowner: RELEASE_REPO_OWNER,repo: RELEASE_REPO_NAME,checkoutRoot,+ buildGatewayUiFromSource: import.meta.env.DEV,onMessage,});@@ -419,6 +422,7 @@ export async function startNativeStack(opts: NativeStartOptions): Promise<NativetelemetryEnvironment: currentFlintEnv(),telemetryInternal: (await currentInternalFlag()) === 'true',telemetryEndpoint: nativeServerTelemetryEndpoint(),+ gatewayUiDir: install.gatewayUiDir,});await writeDeployedVersion(layout, install.version);onMessage('Starting switch-core…');@@ -607,6 +611,31 @@ export function nativeServerTelemetryEndpoint(): string {return TELEMETRY_RELAY_ORIGIN;}+/**+ * Whether a start now would hand switch-core the gateway's pages: the+ * checkout has a build of them, this build's bundle ships them, or (dev+ * builds) a downloaded install would build them.+ */+export async function nativeAdminPagesOnRestart(+ checkoutRoot: string | null,+ bundleRoot: string | null+): Promise<boolean> {+ if (checkoutRoot !== null) return (await checkoutGatewayUi(checkoutRoot)) !== null;+ const bundle = await readLocalServerBundle(bundleRoot, managedSwitchVersion());+ if (bundle !== null) return bundle.gatewayUi !== null;+ return import.meta.env.DEV;+}++/** What the running native server's admin pages are doing, for its page to+ * show the links to them, or offer the restart that turns them on. */+export function readNativeAdminPages(+ layout: NativeLayout,+ checkoutRoot: string | null,+ bundleRoot: string | null+): Promise<LocalServerAdminPages> {+ return nativeAdminPages(layout, () => nativeAdminPagesOnRestart(checkoutRoot, bundleRoot));+}+export async function readNativeTelemetry(layout: NativeLayout): Promise<DeployedTelemetry> {try {const env = await readFile(path.join(layout.run, CORE_ENV_FILE), 'utf8');diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/native/native-toolchain.integration.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/native/native-toolchain.integration.test.tsindex e066d2789..93fd3f2b2 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/native/native-toolchain.integration.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/native/native-toolchain.integration.test.ts@@ -68,6 +68,7 @@ describe.skipIf(!process.env.SWITCH_NATIVE_INTEGRATION)('native toolchain', () =owner: 'sandbox-quantum',repo: 'switch',checkoutRoot: null,+ buildGatewayUiFromSource: false,onMessage: log,});@@ -88,6 +89,7 @@ describe.skipIf(!process.env.SWITCH_NATIVE_INTEGRATION)('native toolchain', () =telemetryEnvironment: 'local',telemetryInternal: false,telemetryEndpoint: 'https://relay.example.test',+ gatewayUiDir: install.gatewayUiDir,}));expect(await waitForHealth(nativeApiUrl(ports.api), { timeoutMs: 120_000 })).toBe(true);@@ -115,6 +117,7 @@ describe.skipIf(!process.env.SWITCH_NATIVE_INTEGRATION)('native toolchain', () =telemetryEnvironment: 'local',telemetryInternal: false,telemetryEndpoint: 'https://relay.example.test',+ gatewayUiDir: install.gatewayUiDir,}));expect(await waitForHealth(nativeApiUrl(ports.api), { timeoutMs: 120_000 })).toBe(true);diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/native/native.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/native/native.test.tsindex 8a6d1f5a0..800d7a889 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/native/native.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/native/native.test.ts@@ -36,6 +36,7 @@ describe('buildNativeCoreSettings', () => {telemetryEnvironment: 'local',telemetryInternal: false,telemetryEndpoint: 'https://relay.example.test',+ gatewayUiDir: null,});it('holds every listener to loopback', () => {diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/native/switch-core-install.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/native/switch-core-install.tsindex 9c54b430b..a19b3e479 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/native/switch-core-install.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/native/switch-core-install.ts@@ -6,6 +6,12 @@ import { log } from '@main/lib/logger';import { CHECKOUT_IMAGE_TAG } from '@shared/core/managed-switch-server/managed-switch-server';import type { LocalServerBundle } from './bundle';import { downloadFile, extractArchive } from './download';+import {+ buildGatewayUi,+ checkoutGatewayUi,+ GATEWAY_UI_DIR_NAME,+ gatewayUiOrNull,+} from './gateway-ui';import type { NativeLayout } from './native-paths';import { runCommand } from './run-command';import { SWITCH_CORE_PYTHON, switchSourceArchiveUrl } from './toolchain-pins';@@ -25,6 +31,9 @@ export type SwitchCoreInstall = {projectDir: string;/** The environment's Python interpreter. */python: string;+ /** The gateway's built pages for switch-core to serve, or null when there+ * are none to hand it (see gateway-ui.ts). */+ gatewayUiDir: string | null;};function venvPython(venv: string): string {@@ -82,8 +91,9 @@ async function uvSync(type Marker = { version?: unknown; source?: unknown; bundleRoot?: unknown; format?: unknown };/** Raised when how an install from the bundle is laid out changes, so one made- * the old way is redone (2: the bundle is reached as a site directory). */-const BUNDLE_INSTALL_FORMAT = '2';+ * the old way is redone (2: the bundle is reached as a site directory; 3: the+ * gateway's pages are copied beside the source). */+const BUNDLE_INSTALL_FORMAT = '3';/** What the install in `dir` was made from, or null when there is none. */async function readMarker(dir: string): Promise<Marker | null> {@@ -118,6 +128,10 @@ function markerMatches(* With `checkoutRoot` (dev builds only) the checkout's own `core/` is used* instead and re-synced on every start, so a start runs whatever is in the* working tree.+ *+ * The gateway's pages come along: copied from the bundle, the checkout's own+ * build, or — with `buildGatewayUiFromSource`, for dev builds — built from the+ * downloaded source once per version.*/export async function installSwitchCore(opts: {layout: NativeLayout;@@ -127,6 +141,9 @@ export async function installSwitchCore(opts: {owner: string;repo: string;checkoutRoot: string | null;+ /** Build the gateway's pages from a downloaded source when the install has+ * none: dev builds, which have Node and npm, only. */+ buildGatewayUiFromSource: boolean;onMessage: (message: string) => void;}): Promise<SwitchCoreInstall> {const { layout, uv, bundle, version, owner, repo, checkoutRoot, onMessage } = opts;@@ -136,11 +153,19 @@ export async function installSwitchCore(opts: {const venv = path.join(layout.switchCore, CHECKOUT_IMAGE_TAG, 'venv');onMessage(`Installing switch-core from ${checkoutRoot}…`);await uvSync(uv, layout, projectDir, venv);+ const gatewayUiDir = await checkoutGatewayUi(checkoutRoot);+ if (gatewayUiDir === null) {+ onMessage(+ 'The checkout has no build of the admin pages, so the server starts without them; ' ++ 'run `just gateway-build` and restart it to add them.'+ );+ }return {version: CHECKOUT_IMAGE_TAG,sourceRoot: checkoutRoot,projectDir,python: venvPython(venv),+ gatewayUiDir,};}@@ -149,22 +174,37 @@ export async function installSwitchCore(opts: {const projectDir = path.join(src, 'core');const venv = path.join(dir, 'venv');const python = venvPython(venv);+ const gatewayUi = path.join(dir, GATEWAY_UI_DIR_NAME);+ // A downloaded install whose pages are missing (a build that failed, or one+ // made before they were built) gets another go at them; a bundled one has+ // whatever its bundle shipped.+ const pagesFor = async (source: 'bundle' | 'download'): Promise<string | null> => {+ const existing = await gatewayUiOrNull(gatewayUi);+ if (existing !== null || source === 'bundle' || !opts.buildGatewayUiFromSource) {+ return existing;+ }+ return buildGatewayUi({ layout, sourceRoot: src, destination: gatewayUi, onMessage });+ };// Checked by running it, not by its file existing: an environment made from// the app's bundled Python stops working if the app moves.- if (markerMatches(await readMarker(dir), version, bundle) && (await runs(python))) {- return { version, sourceRoot: src, projectDir, python };+ const marker = await readMarker(dir);+ if (markerMatches(marker, version, bundle) && (await runs(python))) {+ const source = marker?.source === 'bundle' ? 'bundle' : 'download';+ return { version, sourceRoot: src, projectDir, python, gatewayUiDir: await pagesFor(source) };}if (bundle !== null) {onMessage(`Installing switch-core ${version}…`);await installFromBundle(layout, uv, bundle, src, venv);+ await rm(gatewayUi, { recursive: true, force: true });+ if (bundle.gatewayUi !== null) await cp(bundle.gatewayUi, gatewayUi, { recursive: true });await writeMarker(dir, {version,source: 'bundle',bundleRoot: bundle.root,format: BUNDLE_INSTALL_FORMAT,});- return { version, sourceRoot: src, projectDir, python };+ return { version, sourceRoot: src, projectDir, python, gatewayUiDir: await pagesFor('bundle') };}onMessage(`Downloading switch-core ${version}…`);@@ -182,7 +222,8 @@ export async function installSwitchCore(opts: {await rm(venv, { recursive: true, force: true });await uvSync(uv, layout, projectDir, venv);await writeMarker(dir, { version, source: 'download', uv: uv.version });- return { version, sourceRoot: src, projectDir, python };+ await rm(gatewayUi, { recursive: true, force: true });+ return { version, sourceRoot: src, projectDir, python, gatewayUiDir: await pagesFor('download') };}async function writeMarker(dir: string, marker: Record<string, string>): Promise<void> {@@ -300,6 +341,7 @@ export async function existingSwitchCoreInstall(sourceRoot: checkoutRoot,projectDir: path.join(checkoutRoot, 'core'),python,+ gatewayUiDir: await checkoutGatewayUi(checkoutRoot),}: null;}@@ -307,7 +349,13 @@ export async function existingSwitchCoreInstall(const src = path.join(dir, 'src');const python = venvPython(path.join(dir, 'venv'));if ((await readMarker(dir))?.version !== version || !(await runs(python))) return null;- return { version, sourceRoot: src, projectDir: path.join(src, 'core'), python };+ return {+ version,+ sourceRoot: src,+ projectDir: path.join(src, 'core'),+ python,+ gatewayUiDir: await gatewayUiOrNull(path.join(dir, GATEWAY_UI_DIR_NAME)),+ };}/** Remove installed releases other than `keep`, once a start on it hasdiff --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.tsxindex bd59669f8..ae87b5ed6 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,11 +3,16 @@ import React from 'react';import { MigrationSettingsPage } from '@renderer/features/agent-migration/migration-settings-page';import { DevicesSettingsPage } from '@renderer/features/machines/devices-settings-page';import { RemoteHostsSettingsPage } from '@renderer/features/remote-hosts/views/remote-hosts-view';+import { startManagedServer } from '@renderer/features/switch-servers/managed-server-actions';import { openServerPage } from '@renderer/features/switch-servers/open-server-page';-import { servesWebGateway } from '@renderer/features/switch-servers/server-gateway';+import {+ servesWebGateway,+ webGatewayNeedsRestart,+} from '@renderer/features/switch-servers/server-gateway';import { PageHeader } from '@renderer/lib/components/page-header';import { PageContent, PageLayout, PageSidebarSections } from '@renderer/lib/components/page-layout';import { useAnyServerFeatureFlag } from '@renderer/lib/hooks/useFeatureFlags';+import { useShowModal } from '@renderer/lib/modal/modal-provider';import { openExternalUrl } from '@renderer/lib/open-external';import { dashboardOrigin } from '@shared/core/switch-servers/switch-servers';import { SWITCH_CONSOLE_DOCS_URL } from '@shared/urls';@@ -79,9 +84,13 @@ export const SettingsPage = observer(function SettingsPage({// nothing to move to managed and nothing managed to look after.const agentManagement = useAnyServerFeatureFlag('agent_management');const { server, user } = settingsServer();+ const showConfirm = useShowModal('confirmActionModal');// Workspace settings are the gateway's, open to every member there. A- // Switch this Console runs without Docker serves no gateway.- const workspaceSettings = server !== null && user !== null && servesWebGateway(server);+ // Switch this Console runs without Docker serves it once started with its+ // pages; one an older Console started is offered the restart that does.+ const restartForGateway = server !== null && webGatewayNeedsRestart(server);+ const workspaceSettings =+ server !== null && user !== null && (servesWebGateway(server) || restartForGateway);const sections = settingsSections({hasServer: server !== null,agentManagement,@@ -93,7 +102,18 @@ export const SettingsPage = observer(function SettingsPage({if (id === 'docs') {void openExternalUrl(SWITCH_CONSOLE_DOCS_URL, 'Could not open the documentation');} else if (id === 'workspace-settings') {- if (server) void openServerPage(server.id, `${dashboardOrigin(server)}/workspace`);+ if (!server) return;+ if (restartForGateway) {+ showConfirm({+ title: 'Restart the local server?',+ description:+ 'Workspace settings are in the web gateway, which this server turns on when it restarts. Running agents reconnect once it is back.',+ confirmLabel: 'Restart',+ onSuccess: () => startManagedServer(server),+ });+ } else {+ void openServerPage(server.id, `${dashboardOrigin(server)}/workspace`);+ }} else {onTabChange(id);}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/local-server-store.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/local-server-store.tsindex fd8cde0a9..7fe27d118 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/local-server-store.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/local-server-store.ts@@ -11,6 +11,7 @@ import type {StartLocalServerResult,SwitchVersionDrift,} from '@shared/core/managed-switch-server/managed-switch-server';+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';import {localServerLogChannel,localServerStatusChannel,@@ -114,6 +115,22 @@ export class LocalServerStore {return this.runtime === 'native';}+ /** A running native server's admin pages, when known; null otherwise. */+ get adminPages(): LocalServerStatus['adminPages'] {+ return this.status?.adminPages ?? null;+ }++ /**+ * Whether `server` is this machine's native server and does not serve the+ * gateway's admin pages, so links into them would open nothing: one started+ * without them, or one not (yet) seen running. Every other server serves+ * them — a Docker one runs them beside switch-core.+ */+ lacksAdminPages(server: Pick<SwitchServer, 'managed' | 'managementKind'>): boolean {+ if (!server.managed || server.managementKind !== 'local' || !this.isNative) return false;+ return this.adminPages !== 'served';+ }+/*** Whether Mattermost is on for a native server: for a running one, whether* it is up or coming up, where that is known; otherwise whether the nextdiff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-gateway.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-gateway.tsindex ee35fe09f..4f10387d3 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-gateway.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-gateway.ts@@ -1,14 +1,24 @@import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';import { localServerStore } from './local-server-store';+type ServerKind = Pick<SwitchServer, 'managed' | 'managementKind'>;+/*** Whether a server serves its web gateway — the workspace and server settings* Console links out to. Every server does except a Switch this Console runs- * without Docker: switch-core runs there without the gateway's pages, so its- * address serves the API alone.+ * without Docker that is not serving the gateway's pages: one started without+ * them (by an older Console, or where they could not be built), or one not+ * seen running yet.+ */+export function servesWebGateway(server: ServerKind): boolean {+ return !localServerStore.lacksAdminPages(server);+}++/**+ * Whether a server would serve its web gateway after a restart: this+ * machine's native server, started without the pages by an older Console,+ * now that this one has them to give it.*/-export function servesWebGateway(- server: Pick<SwitchServer, 'managed' | 'managementKind'>-): boolean {- return !(server.managed && server.managementKind === 'local' && localServerStore.isNative);+export function webGatewayNeedsRestart(server: ServerKind): boolean {+ return localServerStore.lacksAdminPages(server) && localServerStore.adminPages === 'restart';}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.test.tsindex 2fa4cbed8..013cbf16f 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.test.ts@@ -35,7 +35,14 @@ vi.mock('@renderer/features/workspaces/workspaces-store', () => ({workspacesStore: workspaces,}));vi.mock('./switch-servers-store', () => ({ switchServersStore: serversStore }));-vi.mock('./local-server-store', () => ({ localServerStore: { isRunning: true } }));+const localServer = vi.hoisted(() => ({+ isRunning: true,+ withoutPages: new Set<string>(),+ lacksAdminPages(server: { id: string }) {+ return this.withoutPages.has(server.id);+ },+}));+vi.mock('./local-server-store', () => ({ localServerStore: localServer }));vi.mock('./remote-server-store', () => ({ remoteServerStore: { isRunning: () => true } }));const { SwitchRoomsStore } = await import('./switch-rooms-store');@@ -697,4 +704,18 @@ describe('dashboard links', () => {);expect(store.gatewayAgentUrl('srv-unknown', 'agent-1')).toBeNull();});++ it('has no links into a server that serves no admin pages', async () => {+ localServer.withoutPages.add('srv-a');+ try {+ const store = new SwitchRoomsStore();+ await store.loadRoomNames();++ expect(store.gatewayRoomUrl('room-a')).toBeNull();+ expect(store.gatewayAgentUrl('srv-a', 'agent-1')).toBeNull();+ expect(store.gatewayRoomUrl('room-b')).toBe('https://beta-gateway.example.com/rooms/room-b');+ } finally {+ localServer.withoutPages.clear();+ }+ });});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.tsindex 78c69d2d8..6ebe9ee37 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts@@ -10,6 +10,7 @@ import {} from '@shared/core/switch-servers/switch-servers';import { UNBRIDGED_FILTER_VALUE } from '@shared/view-state';import { serverAvailability } from './server-availability';+import { servesWebGateway } from './server-gateway';import { switchServersStore } from './switch-servers-store';/** Cache key for an agent's room membership: workspace + Switch agent id. */@@ -133,25 +134,26 @@ export class SwitchRoomsStore {/*** URL of a room's detail page in the gateway web app, or null if the room's- * owning server isn't known yet (names/workspaces are loaded by loadRoomNames).+ * owning server isn't known yet (names/workspaces are loaded by loadRoomNames)+ * or serves no web gateway (a native local server started without its pages).*/gatewayRoomUrl(roomId: string): string | null {const serverId = this.roomServerId(roomId);if (!serverId) return null;const server = switchServersStore.servers.find((s) => s.id === serverId);- if (!server) return null;+ if (!server || !servesWebGateway(server)) return null;const base = dashboardOrigin(server).replace(/\/+$/, '');return `${base}/rooms/${roomId}`;}/*** URL of an agent's detail page in the gateway web app, or null if the server- * isn't known. Unlike rooms, the caller supplies the server id directly (an- * agent carries its owning server on its config).+ * isn't known or serves no web gateway. Unlike rooms, the caller supplies+ * the server id directly (an agent carries its owning server on its config).*/gatewayAgentUrl(serverId: string, switchAgentId: string): string | null {const server = switchServersStore.servers.find((s) => s.id === serverId);- if (!server) return null;+ if (!server || !servesWebGateway(server)) return null;const base = dashboardOrigin(server).replace(/\/+$/, '');return `${base}/agents/${switchAgentId}`;}diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/settings-workspace-link.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/settings-workspace-link.test.tsxnew file mode 100644index 000000000..ffe402974--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/settings-workspace-link.test.tsx@@ -0,0 +1,159 @@+/**+ * Settings' "Workspace settings" link opens the web gateway, including the one+ * a Switch this Console runs without Docker serves. A server an older Console+ * started without the gateway's pages is offered the restart that turns them+ * on; one that cannot serve them shows no link.+ */+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';++vi.hoisted(() => {+ window.electronAPI ??= {+ invoke: () => Promise.resolve(undefined),+ eventOn: () => () => {},+ eventSend: () => {},+ } as unknown as typeof window.electronAPI;+});++const state = vi.hoisted(() => ({+ adminPages: null as 'served' | 'restart' | 'unavailable' | null,+ native: true,+ openPage: vi.fn(),+ start: vi.fn(),+ confirms: [] as { title: string; confirmLabel?: string; onSuccess: () => void }[],+}));++const LOCAL = vi.hoisted(() => ({+ id: 'local',+ name: 'Local server',+ url: 'http://localhost:41001',+ dashboardUrl: null,+ managed: true,+ managementKind: 'local' as const,+ sshHost: null,+}));++vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({+ switchServersStore: {+ activeServer: LOCAL,+ servers: [LOCAL],+ statusFor: () => ({ connected: true, user: { id: 'u', name: 'admin' } }),+ },+}));+vi.mock('@renderer/features/switch-servers/local-server-store', () => ({+ localServerStore: {+ get adminPages() {+ return state.adminPages;+ },+ lacksAdminPages: (server: { managed: boolean; managementKind: string }) =>+ server.managed &&+ server.managementKind === 'local' &&+ state.native &&+ state.adminPages !== 'served',+ },+}));+vi.mock('@renderer/features/switch-servers/managed-server-actions', () => ({+ startManagedServer: (...args: unknown[]) => state.start(...args),+}));+vi.mock('@renderer/features/switch-servers/open-server-page', () => ({+ openServerPage: (...args: unknown[]) => state.openPage(...args),+}));+vi.mock('@renderer/lib/modal/modal-provider', () => ({+ useShowModal: () => (args: (typeof state.confirms)[number]) => state.confirms.push(args),+}));+vi.mock('@renderer/lib/hooks/useFeatureFlags', () => ({ useAnyServerFeatureFlag: () => false }));+vi.mock('@renderer/features/settings/pages/account-page', () => ({+ AccountSettingsPage: () => null,+}));+vi.mock('@renderer/features/agent-migration/migration-settings-page', () => ({+ MigrationSettingsPage: () => null,+}));+vi.mock('@renderer/features/machines/devices-settings-page', () => ({+ DevicesSettingsPage: () => null,+}));+vi.mock('@renderer/features/remote-hosts/views/remote-hosts-view', () => ({+ RemoteHostsSettingsPage: () => null,+}));+vi.mock('@renderer/features/settings/agents-page/AgentsSettingsPage', () => ({+ AgentsSettingsPage: () => null,+}));+vi.mock('@renderer/features/settings/pages/api-keys-page', () => ({+ ApiKeysSettingsPage: () => null,+}));+vi.mock('@renderer/features/settings/pages/messaging-apps-page', () => ({+ MessagingAppsSettingsPage: () => null,+}));+vi.mock('@renderer/features/settings/pages/system-status-page', () => ({+ SystemStatusSettingsPage: () => null,+}));++import { SettingsPage } from '@renderer/features/settings/components/SettingsPage';+import '@renderer/index.css';++let container: HTMLDivElement | null = null;+let root: Root | null = null;++beforeEach(() => {+ state.adminPages = null;+ state.native = true;+ state.openPage.mockReset();+ state.start.mockReset();+ state.confirms.length = 0;+});++afterEach(async () => {+ await act(async () => root?.unmount());+ container?.remove();+ container = null;+ root = null;+});++async function render() {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ await act(async () => root!.render(<SettingsPage tab="account" onTabChange={() => {}} />));+}++function link(): HTMLElement | undefined {+ return [...document.querySelectorAll('button, a')].find((el) =>+ /Workspace settings/.test(el.textContent ?? '')+ ) as HTMLElement | undefined;+}++it('opens the gateway a native local server serves', async () => {+ state.adminPages = 'served';+ await render();++ await act(async () => link()?.click());+ expect(state.openPage).toHaveBeenCalledWith('local', 'http://localhost:41001/workspace');+ expect(state.confirms).toHaveLength(0);+});++it('offers a restart to a native server started without the gateway', async () => {+ state.adminPages = 'restart';+ await render();++ await act(async () => link()?.click());+ expect(state.openPage).not.toHaveBeenCalled();+ expect(state.confirms).toHaveLength(1);+ expect(state.confirms[0]!.confirmLabel).toBe('Restart');+ state.confirms[0]!.onSuccess();+ expect(state.start).toHaveBeenCalledWith(LOCAL);+});++it('shows no link where a native server cannot serve the gateway', async () => {+ state.adminPages = 'unavailable';+ await render();++ expect(link()).toBeUndefined();+});++it('opens the gateway of a server run with Docker', async () => {+ state.native = false;+ await render();++ await act(async () => link()?.click());+ expect(state.openPage).toHaveBeenCalledWith('local', 'http://localhost:41001/workspace');+});diff --git a/console/apps/switch-console-desktop/src/shared/core/managed-switch-server/managed-switch-server.ts b/console/apps/switch-console-desktop/src/shared/core/managed-switch-server/managed-switch-server.tsindex 6fe7ac298..b7546dc50 100644--- a/console/apps/switch-console-desktop/src/shared/core/managed-switch-server/managed-switch-server.ts+++ b/console/apps/switch-console-desktop/src/shared/core/managed-switch-server/managed-switch-server.ts@@ -15,6 +15,15 @@*/export type LocalServerRuntime = 'native' | 'docker';+/**+ * Whether a running native server serves the gateway's admin pages: `served`,+ * or not and a restart would turn them on (`restart`: a server started before+ * this Console shipped them runs on without them across the update), or not+ * and a restart would not help (`unavailable`: a checkout with no build of+ * them, say).+ */+export type LocalServerAdminPages = 'served' | 'restart' | 'unavailable';+/** Lifecycle phase of the managed local stack. */export type LocalServerPhase = 'stopped' | 'starting' | 'running' | 'stopping' | 'error';@@ -224,6 +233,9 @@ export type LocalServerStatus = {* up — a stopped server reports nothing, so there is nothing to be out of* step with. */deployedTelemetry: DeployedTelemetry | null;+ /** A running native server's admin pages; null when no native server is+ * running. A Docker server always serves them, so this is null there. */+ adminPages: LocalServerAdminPages | null;/** Human-readable current step (e.g. "Pulling images…"), or null. */message: string | null;/** Populated only when `phase === 'error'`. */diff --git a/console/apps/switch-console-desktop/src/shared/events/remoteSwitchServerEvents.ts b/console/apps/switch-console-desktop/src/shared/events/remoteSwitchServerEvents.tsindex 40fdd7bad..26ef40eaf 100644--- a/console/apps/switch-console-desktop/src/shared/events/remoteSwitchServerEvents.ts+++ b/console/apps/switch-console-desktop/src/shared/events/remoteSwitchServerEvents.ts@@ -9,7 +9,8 @@ import { defineEvent } from '@shared/lib/ipc/events';* runtime: a remote stack always runs on the host's Docker. */export type RemoteServerStatus = Omit<LocalServerStatus,- 'runtime' | 'mattermost' | 'mattermostState' | 'notice'+ // A remote server runs on Docker, which always serves the admin pages.+ 'runtime' | 'mattermost' | 'mattermostState' | 'notice' | 'adminPages'> & {sshHost: string;/** Something done to the stack from elsewhere (another Console, or the host